file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/234517039.c | int foo(void bar(int), int i) {
bar(i);
return ++i;
}
long x = 0;
void baz(int i) {
x += i;
}
int main(int args, char** argv) {
void (*p)(int) = &baz;
long long i = 0;
for(; i < 10; i++) {
baz(foo(*p, i));
}
if(x == 100) {
ERROR:
return 1;
}
return 0;
}
|
the_stack_data/100140066.c | #include <stdio.h>
#define MAX 101
#define BIG 10000
int graph[MAX][MAX];
int visited[MAX][MAX];
int M,N;
typedef struct Node{
int x;
int y;
}q;
q queue[BIG+1];
int rear = 0;
int front = 0;
int max = 0;
int vectX[4] = {0,0,1,-1};
int vectY[4] = {1,-1,0,0};
q dequeue()
{
q temp = queue[front];
front = (front + 1) % BIG;
return temp;
}
void enqueue(int x, int y)
{
q temp;
temp.x = x;
temp.y = y;
queue[rear] = temp;
rear = (rear + 1) % BIG;
}
void BFS()
{
int nextX, nextY;
while(front<rear)
{
q pop=dequeue();
for(int i=0;i<4;i++) //모든 방향으로 검사
{
nextX = vectX[i] + pop.x;
nextY = vectY[i] + pop.y;
if(nextX>=1 && nextX<=M && nextY>=1 && nextY<=N)
if(graph[nextX][nextY] && !visited[nextX][nextY])
{
//(M,N)에 도착하는 값이 항상 최소, 그 외의 값은 첫 if 조건에서 이미 걸러짐.
visited[nextX][nextY] = visited[pop.x][pop.y]+1;
enqueue(nextX,nextY);
}
}
}
}
int main(void)
{
scanf("%d %d", &M, &N);
for(int i=1; i<=M; i++)
for(int j=1; j<=N; j++)
scanf("%1d", &graph[i][j]); //하나씩 입력 받음
visited[1][1] = 1;
enqueue(1, 1);
BFS();
printf("%d\n", visited[M][N]);
} |
the_stack_data/92324004.c | /* Copyright (C) 2010-2020 The RetroArch team
*
* ---------------------------------------------------------------------------------------
* The following license statement only applies to this file (s16_to_float_neon.S).
* ---------------------------------------------------------------------------------------
*
* 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.
*/
#if defined(__ARM_NEON__) && !defined(DONT_WANT_ARM_OPTIMIZATIONS)
#if defined(__thumb__)
#define DECL_ARMMODE(x) " .align 2\n" " .global " x "\n" " .thumb\n" " .thumb_func\n" " .type " x ", %function\n" x ":\n"
#else
#define DECL_ARMMODE(x) " .align 4\n" " .global " x "\n" " .arm\n" x ":\n"
#endif
asm(
DECL_ARMMODE("convert_s16_float_asm")
DECL_ARMMODE("_convert_s16_float_asm")
"# convert_s16_float_asm(float *out, const int16_t *in, size_t samples, const float *gain)\n"
" # Hacky way to get a constant of 2^-15.\n"
" # Might be faster to just load a constant from memory.\n"
" # It's just done once however ...\n"
" vmov.f32 q8, #0.25\n"
" vmul.f32 q8, q8, q8\n"
" vmul.f32 q8, q8, q8\n"
" vmul.f32 q8, q8, q8\n"
" vadd.f32 q8, q8, q8\n"
"\n"
" # Apply gain\n"
" vld1.f32 {d6[0]}, [r3]\n"
" vmul.f32 q8, q8, d6[0]\n"
"\n"
"1:\n"
" # Preload here?\n"
" vld1.s16 {q0}, [r1]!\n"
"\n"
" # Widen to 32-bit\n"
" vmovl.s16 q1, d0\n"
" vmovl.s16 q2, d1\n"
"\n"
" # Convert to float\n"
" vcvt.f32.s32 q1, q1\n"
" vcvt.f32.s32 q2, q2\n"
"\n"
" vmul.f32 q1, q1, q8\n"
" vmul.f32 q2, q2, q8\n"
"\n"
" vst1.f32 {q1-q2}, [r0]!\n"
"\n"
" # Guaranteed to get samples in multiples of 8.\n"
" subs r2, r2, #8\n"
" bne 1b\n"
"\n"
" bx lr\n"
"\n"
);
#endif
|
the_stack_data/62608.c | // RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for'}}
#pragma omp target teams distribute parallel for
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for'}}
#pragma omp target teams distribute parallel for foo
void test_no_clause() {
int i;
#pragma omp target teams distribute parallel for
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{statement after '#pragma omp target teams distribute parallel for' must be a for loop}}
#pragma omp target teams distribute parallel for
++i;
}
void test_branch_protected_scope() {
int i = 0;
L1:
++i;
int x[24];
#pragma omp target teams distribute parallel for
for (i = 0; i < 16; ++i) {
if (i == 5)
goto L1; // expected-error {{use of undeclared label 'L1'}}
else if (i == 6)
return; // expected-error {{cannot return from OpenMP region}}
else if (i == 7)
goto L2;
else if (i == 8) {
L2:
x[i]++;
}
}
if (x[0] == 0)
goto L2; // expected-error {{use of undeclared label 'L2'}}
else if (x[1] == 1)
goto L1;
}
void test_invalid_clause() {
int i;
// expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for' are ignored}}
#pragma omp target teams distribute parallel for foo bar
for (i = 0; i < 16; ++i)
;
}
void test_non_identifiers() {
int i, x;
// expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for' are ignored}}
#pragma omp target teams distribute parallel for;
for (i = 0; i < 16; ++i)
;
// expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for' are ignored}}
#pragma omp target teams distribute parallel for private(x);
for (i = 0; i < 16; ++i)
;
// expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for' are ignored}}
#pragma omp target teams distribute parallel for, private(x);
for (i = 0; i < 16; ++i)
;
}
extern int foo();
void test_collapse() {
int i;
// expected-error@+1 {{expected '('}}
#pragma omp target teams distribute parallel for collapse
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp target teams distribute parallel for collapse(
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for collapse()
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp target teams distribute parallel for collapse(,
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp target teams distribute parallel for collapse(, )
for (i = 0; i < 16; ++i)
;
// expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute parallel for' are ignored}}
// expected-error@+1 {{expected '('}}
#pragma omp target teams distribute parallel for collapse 4)
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4,
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4, )
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4, , 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
#pragma omp target teams distribute parallel for collapse(4)
for (int i1 = 0; i1 < 16; ++i1)
for (int i2 = 0; i2 < 16; ++i2)
for (int i3 = 0; i3 < 16; ++i3)
for (int i4 = 0; i4 < 16; ++i4)
foo();
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp target teams distribute parallel for collapse(4, 8)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for', but found only 1}}
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp target teams distribute parallel for collapse(2.5)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp target teams distribute parallel for collapse(foo())
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp target teams distribute parallel for collapse(-5)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp target teams distribute parallel for collapse(0)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp target teams distribute parallel for collapse(5 - 5)
for (i = 0; i < 16; ++i)
;
// expected-error@+3 {{loop iteration variable in the associated loop of 'omp target teams distribute parallel for' directive may not be firstprivate, predetermined as private}}
// expected-note@+1 {{defined as firstprivate}}
#pragma omp target teams distribute parallel for collapse(2) firstprivate(i)
for (i = 0; i < 16; ++i)
for (int j = 0; j < 16; ++j)
#pragma omp parallel for reduction(+ : i, j)
for (int k = 0; k < 16; ++k)
i += j;
}
void test_private() {
int i;
// expected-error@+2 {{expected expression}}
// expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp target teams distribute parallel for private(
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for private(,
for (i = 0; i < 16; ++i)
;
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for private(, )
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for private()
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for private(int)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected variable name}}
#pragma omp target teams distribute parallel for private(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp target teams distribute parallel for private(x)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for private(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for private(x, y, z)
for (i = 0; i < 16; ++i) {
x = y * i + z;
}
}
void test_lastprivate() {
int i;
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for lastprivate(
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for lastprivate(,
for (i = 0; i < 16; ++i)
;
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for lastprivate(, )
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for lastprivate()
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for lastprivate(int)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected variable name}}
#pragma omp target teams distribute parallel for lastprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp target teams distribute parallel for lastprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for lastprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for lastprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_firstprivate() {
int i;
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for firstprivate(
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for firstprivate(,
for (i = 0; i < 16; ++i)
;
// expected-error@+1 2 {{expected expression}}
#pragma omp target teams distribute parallel for firstprivate(, )
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for firstprivate()
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected expression}}
#pragma omp target teams distribute parallel for firstprivate(int)
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{expected variable name}}
#pragma omp target teams distribute parallel for firstprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp target teams distribute parallel for lastprivate(x) firstprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for lastprivate(x, y) firstprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp target teams distribute parallel for lastprivate(x, y, z) firstprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_loop_messages() {
float a[100], b[100], c[100];
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp target teams distribute parallel for
for (float fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp target teams distribute parallel for
for (double fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
}
|
the_stack_data/107953337.c | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/mman.h>
int _create_DMA_buff(unsigned long *virtual_addr, unsigned long *physical_addr, size_t length){
int temp;
size_t contig_length;
void *v_addr;
unsigned int p_addr;
#ifdef __QNX__
// map and get 'virtual address' (address in calling processes memory space) for a zero filled memory region
// of size. This space can be used for DMA transfer of data.
v_addr = mmap( 0, length, PROT_READ|PROT_WRITE|PROT_NOCACHE, MAP_PHYS|MAP_ANON, NOFD, 0);
//v_addr = mmap( 0, length, PROT_READ|PROT_WRITE|PROT_NOCACHE, MAP_PHYS|MAP_ANON|MAP_BELOW16M, NOFD, 0);
if (virtual_addr == MAP_FAILED){
perror("Mapping of DMA buffer failed");
return -1;
}
// now get the phsical address of this memory space to be provided to the DMA bus master (PLX9656) for
// DMA transfer of the data from the bus master
mem_offset( v_addr, NOFD, length, &p_addr, &contig_length);
if (temp == -1){
perror("Cannot determine physical address of DMA buffer");
return -1;
}
/*if (contig_length < length){
perror("Cannot create DMA buffer of desired length");
printf("contig_len=%d\n", contig_length);
return -1;
}*/
*physical_addr=p_addr;
*virtual_addr=v_addr;
//printf("PHYSICAL ADDR= %x\n", *physical_addr);
//printf("VIRTUAL ADDR= %x\n", *virtual_addr);
//printf("CONTIG_LENGTH= %d\n", contig_length);
//printf("LENGTH= %d\n", length);
#endif
return 1;
}
|
the_stack_data/50136526.c | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
#define MAXLEN 512
#define MAXARGS 10
#define ARGLEN 30
#define PROMPT "HammadShell:- "
char* read_cmd(char*,FILE*);
char** tokenize(char* cmdline);
int execute(char* arglist[]);
int check_builtin(char* arglist[]);
int my_cd(char **args);
int my_help(char **args);
int my_exit(char **args);
char *blt_str[]={"cd","exit","help"};
int main(){
char *cmdline;
char** arglist;
char*prompt= PROMPT;
while((cmdline=read_cmd(prompt,stdin))!=NULL){
if( (arglist=tokenize(cmdline))!=NULL){
execute(arglist);
for(int j=0;j<MAXARGS+1;j++)
free(arglist[j]);
free(arglist);
free(cmdline);
}
}
printf("\n");
return 0;
}
int my_cd(char **args)
{
if (args[1] == NULL) {
fprintf(stderr, "not proper arguments\n");
} else {
if (chdir(args[1]) != 0) {
perror("cant change directory");
}
}
return 1;
}
int my_help(char **args)
{
int i;
printf("The following are built in:\n");
for (i = 0; i < 3; i++) {
printf(" %s\n", blt_str[i]);
}
return 1;
}
int my_exit(char **args)
{
exit(0);
}
int execute(char* arglist[])
{
int status;
if((check_builtin(arglist)) ==2){ //if not built in then return value is 2 and do normal work
int cpid=fork();
switch(cpid){
case -1:
perror("fork failed");
exit(1);
case 0:
execvp(arglist[0],arglist);
perror("Command not found...");
exit(1);
default:
waitpid(cpid,&status,0);
//printf("child exited with status : %d\n",status>>8);
return 0;
}
}
}
int check_builtin(char* arglist[]){
int num=-1;
for (int i = 0; i <3; i++) {
if (strcmp(arglist[0], blt_str[i]) == 0) {
num=i;
}
}
if(num==-1)
return 2;
else if(num==0)
return my_cd(arglist);
else if(num==1)
return my_exit(arglist);
else
return my_help(arglist);
}
char* read_cmd(char* prompt,FILE* fp)
{
printf("%s",prompt);
int c;
int pos=0;
char* cmdline=(char*) malloc(sizeof(char)*MAXLEN);
while((c=getc(fp)) !=EOF){
if(c=='\n')
break;
cmdline[pos++]=c;
}
if(c==EOF && pos==0)
return NULL;
cmdline[pos]='\0';
return cmdline;
}
char** tokenize(char* cmdline)
{
char** arglist=(char**) malloc(sizeof(char*)*(MAXARGS+1));
for(int i=0;i<MAXARGS+1;i++){
arglist[i]=(char*) malloc(sizeof(char)*ARGLEN);
bzero(arglist[i],ARGLEN);
}
char* cp=cmdline;
char* start;
int len;
int argnum=0;
while(*cp!='\0'){
while(*cp==' '||*cp=='\t')
cp++;
start=cp;
len=1;
while(*++cp !='\0' && !(*cp==' '||*cp=='\t'))
len++;
strncpy(arglist[argnum],start,len);
arglist[argnum][len]='\0';
argnum++;
}
arglist[argnum]=NULL;
return arglist;
}
|
the_stack_data/232955953.c | /*
* MIT License
*
* Copyright 2019 Ted Percival
*
* 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.
*/
#define _GNU_SOURCE 1
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sysinfo.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#define PORT_NUMBER 8081
// Define to a number of processes to run.
// If undefined, automatically uses all CPUs.
#define NCPUS 1
#define MAX_REQUEST_SIZE 65536
#define MAX_PIPELINED_REQUEST_DATA (MAX_REQUEST_SIZE * 4)
// Should be at least 2 to handle long-lived keep-alive connections dropped by
// middleboxes.
#define MAX_CONNECT_ATTEMPTS 2u
__attribute__((noreturn))
static void fatal_perror(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
static void cork(int sock, bool whether) {
const int value = whether ? 1 : 0;
if (setsockopt(sock, IPPROTO_TCP, TCP_CORK, &value, sizeof(value)) == -1)
perror("setsockopt(TCP_CORK)");
}
static void tcp_cork(int sock) {
cork(sock, true);
}
static void tcp_uncork(int sock) {
cork(sock, false);
}
struct streambuf {
char *data;
size_t len;
size_t cap;
};
struct endpoint {
int fd;
struct streambuf incoming, outgoing;
};
#if 0 // Don't need to parse out a request yet. Just pass the entire request buffer.
// Request;
// All fields are intended to point into a streambuf, the only special case
// is that the headers array itself needs to be dynamically allocated to allow
// it to hold any number of headers.
struct request {
char *method;
char *path; // path + query in RFC 3986 terms
char *headers[]; // NUL-terminated, dynamically allocated list.
};
void free_request_contents(struct request *req) {
// See description of `struct request` for why these pointers aren't freed.
req->method = NULL;
req->path = NULL;
free(req->headers);
req->headers = NULL;
}
#endif
enum state {
FRONTEND_READ_WAIT, // Wait for next request
BACKEND_WRITE_WAIT, // Wait to write to backend
BACKEND_READ_WAIT, // Wait for backend response
FRONTEND_WRITE_WAIT, // Wait to write to frontend
};
struct job {
struct endpoint client, backend;
// Backend request has to be kept in case we need to retry on a new
// connection. It should point into the client.incoming buffer and *not* be
// dynamically allocated.
struct {
const char *data;
size_t len;
size_t remaining_len; // how much remains to send on *this* connection attempt
// When using this field, start at data + (len - remaining_len) (sorry)
} backend_request;
unsigned connect_attempts;
};
// Advance the current data location / consume a block of data.
// Avoid doing small advances; repeated small advances are inefficient.
static void streambuf_advance(struct streambuf *streambuf, size_t amount) {
assert(amount <= streambuf->len);
streambuf->len -= amount;
if (streambuf->len == 0)
return; // nothing else to do :)
memmove(streambuf->data, streambuf->data + amount, streambuf->len);
}
static bool streambuf_init(struct streambuf *streambuf) {
streambuf->cap = 4096;
streambuf->data = malloc(streambuf->cap);
streambuf->len = 0;
return streambuf->data != NULL ? true : false;
}
static void streambuf_free_contents(struct streambuf *streambuf) {
free(streambuf->data);
streambuf->data = NULL;
streambuf->len = 0;
streambuf->cap = 0;
}
static void streambuf_clear_contents(struct streambuf *streambuf) {
streambuf->len = 0;
}
static bool endpoint_init(struct endpoint *ep) {
ep->fd = -1;
if (streambuf_init(&ep->incoming) == false)
return false;
if (streambuf_init(&ep->outgoing) == false) {
streambuf_free_contents(&ep->incoming);
return false;
}
return true;
}
static void endpoint_free_contents(struct endpoint *ep) {
if (ep->fd != -1) {
close(ep->fd);
ep->fd = -1;
}
streambuf_free_contents(&ep->incoming);
streambuf_free_contents(&ep->outgoing);
}
static void endpoint_clear_contents(struct endpoint *ep) {
ep->fd = -1;
streambuf_clear_contents(&ep->incoming);
streambuf_clear_contents(&ep->outgoing);
}
static int endpoint_flush(struct endpoint *ep) {
if (ep->outgoing.len == 0)
return 0;
ssize_t len = send(ep->fd, ep->outgoing.data, ep->outgoing.len, 0);
if (len == -1 && errno != EAGAIN && errno != EWOULDBLOCK) {
perror("endpoint_flush send");
return -1;
}
// Shift by however much was sent
memmove(ep->outgoing.data, ep->outgoing.data + len, ep->outgoing.len - len);
ep->outgoing.len -= len;
return len;
}
static int streambuf_ensure_capacity(struct streambuf *sb, size_t data_len) {
if (sb->cap - sb->len >= data_len)
return 0;
if (sb->len == 0) {
free(sb->data);
sb->data = malloc(data_len);
if (sb->data == NULL)
return -1;
sb->cap = data_len;
} else {
char *newbuf = realloc(sb->data, sb->len + data_len);
if (!newbuf)
return -1;
sb->data = newbuf;
sb->cap = sb->len + data_len;
}
return 0;
}
static ssize_t streambuf_enqueue(struct streambuf *sb, const void *data, size_t data_len) {
ssize_t out_len;
out_len = streambuf_ensure_capacity(sb, data_len);
if (out_len < 0)
return out_len;
memcpy(sb->data + sb->len, data, data_len);
sb->len += data_len;
return sb->len;
}
#define RECV_NO_LIMIT (-1)
// Read as much data as possible into a streambuf from a file descriptor.
// Return values the same as recv(), except that the length returned is the
// total length of available data (including any that was already buffered).
// limit parameter is the maximum amount of outstanding data that will be
// buffered before returning, or -1 for no limit.
// (Combining a limit with edge-triggered polling is likely to cause your end
// of a connection to hang; you'd better use level-triggering or close the
// connection if it exceeds your limit.)
static ssize_t streambuf_recv(struct streambuf *sb, int fd, ssize_t limit) {
ssize_t len;
size_t available;
do {
size_t new_capacity;
if (sb->len < 4096)
new_capacity = 4096;
else // TODO: Align to page size
new_capacity = sb->len * 2;
if (streambuf_ensure_capacity(sb, new_capacity) < 0)
return -1;
available = sb->cap - sb->len;
if (limit != -1 && available > limit)
available = limit;
len = recv(fd, sb->data + sb->len, available, 0);
if (len <= 0) {
if (sb->len > 0)
return sb->len;
return len;
}
sb->len += len;
if (limit != -1 && sb->len >= limit)
break;
} while (len == available);
return sb->len;
}
// Like send(2), but queues data if it cannot be sent immediately.
// Return values are as for send(2):
// Returns -1 on fatal error (eg. EBADF, ENOMEM)
// Returns >0 if data were successfully sent or queued;
// the return value is always data_len in this case.
// Returns 0 if the socket is closed on the remote end (?)
static ssize_t endpoint_send(struct endpoint *ep, const void *data, size_t data_len) {
if (ep->outgoing.len > 0)
return streambuf_enqueue(&ep->outgoing, data, data_len);
// Attempt immediate send
ssize_t sent_len = send(ep->fd, data, data_len, 0);
if (sent_len < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return streambuf_enqueue(&ep->outgoing, data, data_len);
return sent_len; // error
}
if (sent_len == 0)
return 0;
if (sent_len < data_len)
streambuf_enqueue(&ep->outgoing, data + sent_len, data_len - sent_len);
return data_len;
}
// Remember to check for EAGAIN/EWOULDBLOCK when this returns -1.
// If you set a limit, make sure you don't retry indefinitely because of data
// waiting on the socket that you're not willing to read.
static ssize_t endpoint_recv(struct endpoint *ep, ssize_t limit) {
return streambuf_recv(&ep->incoming, ep->fd, limit);
}
static int job_send_status(struct job *job, int code, const char *msg) {
char buf[512];
ssize_t len = snprintf(buf, sizeof(buf), "HTTP/1.1 %d %s\r\n", code, msg);
if (len < 0 || endpoint_send(&job->client, buf, len) == -1)
return -1;
return 0;
}
static int job_terminate_headers(struct job *job) {
char term[2] = { '\r', '\n' };
if (endpoint_send(&job->client, term, sizeof(term)) == -1)
return -1;
return 0;
}
static int job_respond_status_only(struct job *job, int code, const char *msg) {
int rc = -1;
tcp_cork(job->client.fd);
if (job_send_status(job, code, msg) == -1)
goto cleanup;
const size_t msglen = strlen(msg);
char content_headers[256];
int len = snprintf(content_headers, sizeof(content_headers),
"Content-Type: text/plain; charset=us-ascii\r\n"
"Content-Length: %zu\r\n", msglen + 1);
if (len != -1 && len != sizeof(content_headers)) {
if (endpoint_send(&job->client, content_headers, len) == -1)
goto cleanup;
}
if (job_terminate_headers(job) == -1)
goto cleanup;
if (endpoint_send(&job->client, msg, msglen) == -1)
goto cleanup;
const char nl = '\n';
if (endpoint_send(&job->client, &nl, sizeof(nl)) == -1)
goto cleanup;
rc = 0;
cleanup:
tcp_uncork(job->client.fd);
return rc;
}
static struct job *new_job(int client) {
struct job *j = calloc(1, sizeof(*j));
if (j == NULL)
return NULL;
j->connect_attempts = 0;
j->backend_request.data = NULL;
j->backend_request.len = 0;
j->backend_request.remaining_len = 0;
if (endpoint_init(&j->client) == false) {
free(j);
return NULL;
}
j->client.fd = client;
if (endpoint_init(&j->backend) == false) {
endpoint_free_contents(&j->client);
free(j);
return NULL;
}
return j;
}
struct cpool_node {
int fd;
struct cpool_node *next;
};
struct connection_pool {
struct cpool_node *head;
struct addrinfo *addrs;
unsigned in_use_count, idle_count;
};
static struct connection_pool backend_pool;
static void setup_connection_pool(struct connection_pool *pool) {
pool->in_use_count = 0;
pool->idle_count = 0;
pool->head = NULL;
pool->addrs = NULL;
const struct addrinfo hints = {
.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG,
.ai_family = AF_INET6,
.ai_socktype = SOCK_STREAM,
.ai_protocol = 0,
};
#define HOST "localhost"
#define SERVICE "23206"
int gaierr = getaddrinfo(HOST, SERVICE, &hints, &pool->addrs);
if (gaierr) {
fprintf(stderr, "Failed to resolve backend host: %s\n", gai_strerror(gaierr));
exit(1);
}
if (pool->addrs == NULL) {
fprintf(stderr, "No addresses\n");
exit(1);
}
}
static unsigned connection_pool_idle_count(struct connection_pool *pool) {
return pool->idle_count;
}
static void try_to_enable_fastopen_connect(int sock) {
#if defined(TCP_FASTOPEN_CONNECT)
const int yes = 1;
if (setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, &yes, sizeof(yes)) == -1)
fatal_perror("setsockopt(TCP_FASTOPEN_CONNECT)");
#endif
}
static ssize_t connect_and_try_to_send(
int sock,
const struct sockaddr *addr,
socklen_t addrlen,
const void *data,
size_t len)
{
#if defined(TCP_FASTOPEN_CONNECT)
return sendto(sock, data, len, MSG_FASTOPEN, addr, addrlen);
#else
return connect(sock, addr, addrlen);
#endif
}
static ssize_t pool_new_connection_fastopen(
struct connection_pool *pool,
const void *data,
size_t len,
int *fdp)
{
// FIXME: Iterate over addresses
// (a little tricker with non-blocking connect)
struct addrinfo *addr = pool->addrs;
int sock = socket(addr->ai_family, addr->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, addr->ai_protocol);
if (sock == -1) {
int save_errno = errno;
perror("Failed to allocate connection pool socket\n");
errno = save_errno;
return -1;
}
try_to_enable_fastopen_connect(sock);
// connect() (maybe TCP Fast Open)
ssize_t sent = connect_and_try_to_send(sock, addr->ai_addr, addr->ai_addrlen, data, len);
if (sent == -1 && (errno != EINPROGRESS && errno != EAGAIN && errno != EWOULDBLOCK)) {
int save_errno = errno;
#if defined(TCP_FASTOPEN_CONNECT)
perror("Failed to fastopen connect to backend");
#else
perror("Failed to connect to backend");
#endif
close(sock);
errno = save_errno;
return -1;
}
*fdp = sock;
++pool->in_use_count;
return sent;
}
// Optimized version of pool_delete_fd if the caller knows that the file was not
// on the idle list.
static void pool_delete_active_fd(struct connection_pool *pool, int fd __attribute__((unused))) {
--pool->in_use_count;
}
static int pool_get_idle_fd(struct connection_pool *pool) {
if (pool->head == NULL)
return -1;
--pool->idle_count;
struct cpool_node *n = pool->head;
pool->head = n->next;
int fd = n->fd;
free(n);
return fd;
}
static ssize_t pool_get_fd_fastopen(
struct connection_pool *pool,
const void *data,
size_t len,
int *fdp)
{
int fd = -1;
while ((fd = pool_get_idle_fd(pool)) != -1) {
ssize_t sent = send(fd, data, len, MSG_DONTWAIT);
if (sent >= 0 || (sent == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))) {
// Socket seems good.
++pool->in_use_count;
*fdp = fd;
return sent;
}
if (sent == -1) {
// fd is bad
pool_delete_active_fd(pool, fd);
close(fd);
fd = -1;
}
}
return pool_new_connection_fastopen(pool, data, len, fdp);
}
static void subscribe(int epfd, int fd) {
struct epoll_event event = {
.events = 0,
.data = {
.u64 = 0,
},
};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event) == -1)
fatal_perror("epoll_ctl subscribe");
}
static void unsubscribe(int epfd, int fd) {
if (epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL) == -1)
perror("epoll_ctl DEL");
}
// use get_backend_fd_and_send to correctly track unsent bytes;
// it calls this.
static ssize_t get_backend_fd_fastopen(
int epfd,
struct connection_pool *pool,
const void *data,
size_t len,
int *fdp)
{
ssize_t sent = pool_get_fd_fastopen(pool, data, len, fdp);
if (sent == -1 && errno != EINPROGRESS && errno != EAGAIN && errno != EWOULDBLOCK)
return -1;
int save_errno = errno;
subscribe(epfd, *fdp);
errno = save_errno;
return sent;
}
static void delete_backend_fd(int epfd, struct connection_pool *pool, int fd) {
unsubscribe(epfd, fd);
pool_delete_active_fd(pool, fd);
close(fd);
}
struct free_job_node {
struct job *job;
struct free_job_node *next;
};
struct free_job_node *free_jobs = NULL;
static void free_closed_jobs() {
if (free_jobs == NULL)
return;
struct free_job_node *next = NULL;
for (struct free_job_node *n = free_jobs; n != NULL; n = next) {
free(n->job);
next = n->next;
free(n);
}
free_jobs = NULL;
}
static void free_job_later(struct job *job) {
for (struct free_job_node *n = free_jobs; n != NULL; n = n->next) {
if (n->job == job)
return; // already queued
}
struct free_job_node *n = malloc(sizeof(*n));
n->job = job;
n->next = free_jobs;
free_jobs = n;
}
static void close_job(int epfd, struct job *job) {
if (job->client.fd != -1) {
unsubscribe(epfd, job->client.fd);
close(job->client.fd);
job->client.fd = -1;
}
endpoint_free_contents(&job->client);
if (job->backend.fd != -1) {
// Kill the backend connection, it's the only way to cancel the
// request in HTTP/1.1. Waiting for it and draining it is a waste
// of time (potentially bigger).
delete_backend_fd(epfd, &backend_pool, job->backend.fd);
job->backend.fd = -1;
}
endpoint_free_contents(&job->backend);
free_job_later(job);
}
static void to_next_state(int epfd, struct job *job);
static int get_backend_fd_and_send(int epfd, struct job *job) {
assert(job->connect_attempts <= MAX_CONNECT_ATTEMPTS);
if (job->connect_attempts >= MAX_CONNECT_ATTEMPTS)
return -1;
int fd = -1;
if (connection_pool_idle_count(&backend_pool) == 0) {
// Only if the idle pool was empty should we count this as a new
// connection attempt. Otherwise a bunch of idle connections with broken
// pipes would be pinned on us and fail the request.
++job->connect_attempts;
}
ssize_t sent = get_backend_fd_fastopen(
epfd,
&backend_pool,
job->backend_request.data,
job->backend_request.len,
&fd);
if (sent == -1) {
if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) {
assert(fd != -1);
return fd;
}
return -1;
}
assert(fd != -1);
job->backend_request.remaining_len -= sent;
return fd;
}
static struct cpool_node *new_pool_node(int fd) {
struct cpool_node *n = calloc(1, sizeof(*n));
n->fd = fd;
n->next = NULL;
return n;
}
static void pool_release_fd(struct connection_pool *pool, int fd) {
--pool->in_use_count;
++pool->idle_count;
// prepend node to list.
struct cpool_node *n = new_pool_node(fd);
n->next = pool->head;
pool->head = n;
}
static void release_backend_fd(int epfd, struct connection_pool *pool, int fd) {
unsubscribe(epfd, fd);
pool_release_fd(pool, fd);
}
// Prefer pool_delete_active_fd() if possible
__attribute__((unused))
static void pool_delete_fd(struct connection_pool *pool, int fd) {
// Figure out whether it was in use or idle
for (struct cpool_node *n = pool->head; n != NULL; n = n->next) {
if (n->fd == fd) {
--pool->idle_count;
return;
}
}
pool_delete_active_fd(pool, fd);
}
// Returns new length, or -1 on error
static ssize_t replace_string(char *buf, size_t buflen, size_t bufcap, const char *from, size_t fromlen, const char *to, size_t tolen) {
if (buflen - fromlen + tolen > bufcap)
return -1;
char *location = memmem(buf, buflen, from, fromlen);
if (location == NULL)
return -1;
const size_t trailer_len = buflen - (location - buf) - fromlen;
// shift keep-memory
memmove(location + tolen, location + fromlen, trailer_len);
// replace
memcpy(location, to, tolen);
return buflen - fromlen + tolen;
}
static void ep_mod_or_cleanup(int epfd, int fd, struct epoll_event *event) {
if (epoll_ctl(epfd, EPOLL_CTL_MOD, fd, event) == -1) {
perror("epoll_ctl MOD EPOLLOUT");
// This call might print spurious errors, but it's better than leaking.
close_job(epfd, (struct job*)event->data.ptr);
return;
}
}
static void setup_event(struct epoll_event *event, struct job *job, uint32_t events) {
event->events = events;
event->data.ptr = job;
}
static void notify_when_readable(int epfd, struct job *job, int fd) {
struct epoll_event event;
setup_event(&event, job, EPOLLIN | EPOLLONESHOT | EPOLLET);
ep_mod_or_cleanup(epfd, fd, &event);
}
static void notify_when_writable(int epfd, struct job *job, int fd) {
struct epoll_event event;
setup_event(&event, job, EPOLLOUT | EPOLLONESHOT);
ep_mod_or_cleanup(epfd, fd, &event);
}
static void clear_backend_request(struct job *job) {
job->backend_request.data = NULL;
job->backend_request.len = 0;
job->backend_request.remaining_len = 0;
}
static void discard_request_data(struct job *job) {
streambuf_advance(&job->client.incoming, job->backend_request.len);
clear_backend_request(job);
}
static enum state job_state(struct job *job) {
if (job->client.outgoing.len > 0)
return FRONTEND_WRITE_WAIT;
// This one is different; it writes straight from the backend_request
// pointer (which actually points into the client.incoming buffer).
if (job->backend_request.remaining_len > 0)
return BACKEND_WRITE_WAIT;
if (job->backend.fd != -1)
return BACKEND_READ_WAIT;
else
return FRONTEND_READ_WAIT;
}
static void poll_appropriate_fd(int epfd, struct job *job) {
switch (job_state(job)) {
case BACKEND_WRITE_WAIT:
notify_when_writable(epfd, job, job->backend.fd);
break;
case FRONTEND_WRITE_WAIT:
notify_when_writable(epfd, job, job->client.fd);
break;
case BACKEND_READ_WAIT:
notify_when_readable(epfd, job, job->backend.fd);
break;
case FRONTEND_READ_WAIT:
notify_when_readable(epfd, job, job->client.fd);
break;
}
}
// reset the job structure
static void finished_with_previous_request(int epfd, struct job *job) {
job->connect_attempts = 0;
discard_request_data(job);
// Don't accidentally close the backend fd, just unsubscribe.
if (job->backend.fd != -1) {
release_backend_fd(epfd, &backend_pool, job->backend.fd);
job->backend.fd = -1;
}
endpoint_clear_contents(&job->backend);
}
// This is meant to be a specialized, faster alternative to
// memmem(buf, len, "\r\n\r\n", 4) because memmem is really slow and we can make
// some educated guesses about the presence & location of newlines.
// Returns a pointer to the byte beyond the terminal "\n".
static char *find_end_of_header(char *buf, size_t len) {
char *last_nl = memrchr(buf, '\n', len);
if (last_nl == NULL)
return NULL;
// It's now safe to use rawmemchr() up to last_nl
// Linear search forward to the first "\n\r\n" (or "\n\n" to be permissive).
char *nl = NULL;
for (char *start = buf; (nl = rawmemchr(start, '\n')) != last_nl; start = nl + 1) {
if (nl[1] == '\n')
return nl + 2;
if (last_nl - nl >= 2) {
if (nl[1] == '\r' && nl[2] == '\n')
return nl + 3;
}
}
return NULL;
}
static void setup_backend_request(struct job *job, const char *end_of_request_header) {
job->backend_request.data = job->client.incoming.data;
job->backend_request.len = end_of_request_header - job->client.incoming.data;
job->backend_request.remaining_len = job->backend_request.len;
}
static void on_client_input(int epfd, struct job *job) {
ssize_t len = endpoint_recv(&job->client, MAX_PIPELINED_REQUEST_DATA);
if (len < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
perror("recv");
close_job(epfd, job);
return;
}
if (len == 0) {
// Client closed connection
close_job(epfd, job);
return;
}
if (len == MAX_PIPELINED_REQUEST_DATA) {
if (job_respond_status_only(job, 413, "Requests too big") == -1) {
close_job(epfd, job);
return;
}
close_job(epfd, job);
return;
}
// Beware that there might be a stack of pipelined requests waiting, so it's
// inappropriate to reject the connection for sending a request that's too
// big until we're sure it hasn't finished describing a single request yet.
char *end_of_request_header = find_end_of_header(job->client.incoming.data, job->client.incoming.len);
if (end_of_request_header == NULL) {
if (job->client.incoming.len > MAX_REQUEST_SIZE) {
if (job_respond_status_only(job, 413, "Request too big") == -1) {
close_job(epfd, job);
return;
}
// This is fairly abrupt, we try to tell the client that the request
// was too big, but they might not get the message if the socket
// wasn't ready. But they're misbehaving so we want to drop the
// ASAP.
close_job(epfd, job);
return;
}
// remains in client_read state; re-arm epoll
to_next_state(epfd, job);
return;
}
setup_backend_request(job, end_of_request_header);
// Grab a backend connection
endpoint_clear_contents(&job->backend);
job->backend.fd = get_backend_fd_and_send(epfd, job);
if (job->backend.fd == -1) {
clear_backend_request(job);
job_respond_status_only(job, 503, "Backend unavailable");
to_next_state(epfd, job);
return;
}
to_next_state(epfd, job);
}
static void send_backend_request(int epfd, struct job *job) {
ssize_t sent = send(
job->backend.fd,
job->backend_request.data + (job->backend_request.len - job->backend_request.remaining_len),
job->backend_request.remaining_len,
MSG_DONTWAIT);
if (sent == -1 && (errno != EAGAIN && errno != EWOULDBLOCK)) {
if (job_respond_status_only(job, 503, "Backend send failed") == -1) {
close_job(epfd, job);
return;
}
to_next_state(epfd, job);
return;
}
if (sent == -1)
return;
assert(sent <= job->backend_request.remaining_len);
job->backend_request.remaining_len -= sent;
}
static void state_to_backend_write(int epfd, struct job *job) {
poll_appropriate_fd(epfd, job);
}
static void state_to_backend_read(int epfd, struct job *job) {
poll_appropriate_fd(epfd, job);
}
static void state_to_client_write(int epfd, struct job *job) {
poll_appropriate_fd(epfd, job);
}
static void state_to_client_read(int epfd, struct job *job) {
finished_with_previous_request(epfd, job);
// If there's data in the pipe go inspect it to see if it contains a full
// request already (eg. pipelined request).
if (job->client.incoming.len > 0) {
on_client_input(epfd, job);
return;
}
poll_appropriate_fd(epfd, job);
}
static void to_next_state(int epfd, struct job *job) {
assert(job->client.fd != -1);
switch (job_state(job)) {
case FRONTEND_WRITE_WAIT:
state_to_client_write(epfd, job);
break;
case BACKEND_WRITE_WAIT:
state_to_backend_write(epfd, job);
break;
case BACKEND_READ_WAIT:
state_to_backend_read(epfd, job);
break;
case FRONTEND_READ_WAIT:
state_to_client_read(epfd, job);
break;
}
}
// The transformation invalidates any pointers to the given buffer.
static ssize_t transform_response_body(struct streambuf *buf) {
const char from[] = "http://watch.sling.com";
const size_t fromlen = sizeof(from) - 1;
const char to[] = "http://hahaha.com";
const size_t tolen = sizeof(to) - 1;
if (tolen > fromlen) {
if (streambuf_ensure_capacity(buf, tolen - fromlen) < 0)
return -1;
}
ssize_t new_len = replace_string(buf->data, buf->len, buf->cap, from, fromlen, to, tolen);
if (new_len >= 0)
buf->len = new_len;
return new_len;
}
static ssize_t make_response_header(char *buf, size_t buflen, size_t content_length) {
int len = snprintf(buf, buflen,
"HTTP/1.1 200 OK\r\n"
"Server: Proxymoron\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %zu\r\n"
"\r\n", content_length);
if (len == buflen)
return -1; // truncated string
return len;
}
static void write_client_response(int epfd, struct job *job) {
tcp_cork(job->client.fd);
char header_buf[4096];
bool ok = false;
ssize_t len = make_response_header(header_buf, sizeof(header_buf), job->backend.incoming.len);
if (!len) {
if (job_respond_status_only(job, 500, "Failed to render response header") == -1)
goto cleanup;
// managed to inform the client that we had a problem,
// so don't disconnect the client.
ok = true;
goto cleanup;
}
if (endpoint_send(&job->client, header_buf, len) == -1)
goto cleanup;
if (endpoint_send(&job->client, job->backend.incoming.data, job->backend.incoming.len) == -1)
goto cleanup;
ok = true;
cleanup:
tcp_uncork(job->client.fd);
if (ok)
to_next_state(epfd, job);
else
close_job(epfd, job);
}
static void read_backend_response(int epfd, struct job *job) {
ssize_t len = endpoint_recv(&job->backend, RECV_NO_LIMIT);
if (len == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
// No data yet.
to_next_state(epfd, job);
return;
}
if (len == -1 || len == 0) {
fprintf(stderr, "Backend fd %d was trash (%s); replacing\n",
job->backend.fd,
len == 0 ? "connection closed" : strerror(errno));
delete_backend_fd(epfd, &backend_pool, job->backend.fd);
job->backend_request.remaining_len = job->backend_request.len;
job->backend.fd = get_backend_fd_and_send(epfd, job);
if (job->backend.fd == -1) {
clear_backend_request(job);
if (job_respond_status_only(job, 503, "Backend unavailable (for real)") == -1) {
close_job(epfd, job);
return;
}
to_next_state(epfd, job);
return;
}
to_next_state(epfd, job);
return;
}
char *end_of_header = find_end_of_header(job->backend.incoming.data, job->backend.incoming.len);
if (end_of_header == NULL) {
// re-arm fd
to_next_state(epfd, job);
return;
}
// FIXME: Parse out Content-Length so we know when we've received the full
// response.
// TODO: If the response contained "Connection: close", close it and
// prepare a replacement connection, but don't throw away the response
// that we got.
// Finished with the backend fd.
release_backend_fd(epfd, &backend_pool, job->backend.fd);
job->backend.fd = -1;
// Throw away response headers (later: store them off for use in the client
// response).
streambuf_advance(&job->backend.incoming, end_of_header - job->backend.incoming.data);
if (transform_response_body(&job->backend.incoming) == -1) {
job_respond_status_only(job, 500, "Transformation failed");
to_next_state(epfd, job);
return;
}
write_client_response(epfd, job);
}
static void read_event(int epfd, struct job *job) {
switch (job_state(job)) {
case FRONTEND_READ_WAIT:
on_client_input(epfd, job);
break;
case BACKEND_READ_WAIT:
read_backend_response(epfd, job);
break;
default:
abort();
return;
}
}
static void write_event(int epfd, const struct epoll_event *event) {
struct job *job = event->data.ptr;
if (job->client.outgoing.len > 0)
endpoint_flush(&job->client);
if (job->backend_request.remaining_len > 0)
send_backend_request(epfd, job);
if (job->client.fd == -1) {
close_job(epfd, job);
return;
}
to_next_state(epfd, job);
}
static void new_client(int epfd, struct job *listen_job) {
int client = accept4(listen_job->client.fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (client == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// other process probably got it.
return;
}
perror("accept4");
return;
}
struct job *job = new_job(client);
if (job == NULL) {
perror("failed to allocate job");
char msg[] = "HTTP/1.1 503 Service Unavailable\r\n\r\n";
send(client, msg, sizeof(msg) - 1, MSG_DONTWAIT);
close(client);
return;
}
// Here we don't want to subscribe to any events because we'll immediately
// do a socket read, *then* subscribe to read events (or go straight to
// BACKEND_WRITE_WAIT), but we need the client FD to be part of the epoll
// set (so we can do a CTL_MOD later).
struct epoll_event revent = {
.events = 0 | EPOLLET | EPOLLONESHOT,
.data = {
.ptr = job,
},
};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, client, &revent) == -1) {
perror("epoll_ctl ADD");
if (close(client) == -1)
perror("close");
}
// Optimize for TCP_FASTOPEN and/or TCP_DEFER_ACCEPT, wherein data
// (a request) will be waiting immediately upon connection receipt.
on_client_input(epfd, job);
}
static void dispatch(int epfd, const struct epoll_event *event, int listensock) {
if (event->events & EPOLLIN) {
struct job *job = event->data.ptr;
if (job->client.fd == listensock)
new_client(epfd, job);
else
read_event(epfd, job);
} else if (event->events & EPOLLOUT) {
write_event(epfd, event);
}
struct job *job = event->data.ptr;
if (job->client.fd == -1) {
// Client already closed
return;
}
}
static void multiply() {
int ncpus;
#if defined(NCPUS)
ncpus = NCPUS;
#else
ncpus = get_nprocs_conf();
#endif
fprintf(stderr, "Using %d processes\n", ncpus);
// parent keeps running too
for (unsigned i = 1; i < ncpus; ++i) {
pid_t pid = fork();
if (pid == -1)
perror("fork");
if (pid == 0)
return;
}
}
__attribute__((unused))
static void enable_defer_accept(int sock) {
#if defined (TCP_DEFER_ACCEPT)
const int seconds = 2;
if (setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &seconds, sizeof(seconds)) == -1)
perror("setsockopt TCP_DEFER_ACCEPT");
#endif
}
static void enable_fastopen_on_listener(int sock) {
#if defined(TCP_FASTOPEN)
const int queue_len = 100;
if (setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN, &queue_len, sizeof(queue_len)) == -1)
perror("setsockopt(TCP_FASTOPEN)");
#endif
}
static void reuseport(int sock) {
const int yes = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)) == -1)
perror("setsockopt(SO_REUSEPORT)");
}
static int server_socket(void) {
int sock = socket(PF_INET6, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (sock == -1)
fatal_perror("socket");
reuseport(sock);
const struct sockaddr_in6 bind_addr = {
.sin6_family = AF_INET6,
.sin6_port = htons(PORT_NUMBER),
.sin6_flowinfo = 0,
.sin6_addr = in6addr_any,
.sin6_scope_id = 0,
};
if (bind(sock, (const struct sockaddr*)&bind_addr, sizeof(bind_addr)) == -1)
fatal_perror("bind");
// This is slightly slower in this case, but probably want to enable it on a
// real server. Might be faster once we do an immediate read on a new
// socket.
enable_defer_accept(sock);
// nodelay seems to reduce throughput. leave it off for now.
//enable_nodelay(sock);
enable_fastopen_on_listener(sock);
if (listen(sock, 1000) == -1)
fatal_perror("listen");
return sock;
}
static void quiesce_signals(void) {
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
fatal_perror("signal(SIGPIPE)");
}
// Dummy `struct job` to store the listen sock for epoll.
static struct job listen_sock_job;
static int setup_epoll_fd(int listen_sock) {
int epfd = epoll_create1(EPOLL_CLOEXEC);
if (epfd == -1)
fatal_perror("epoll_create");
listen_sock_job.client.fd = listen_sock;
struct epoll_event event = {
.events = EPOLLIN,
.data = {
.ptr = &listen_sock_job,
},
};
if (event.data.ptr == NULL)
fatal_perror("Failed to create epoll wrapper for listen socket");
#if defined(EPOLLEXCLUSIVE)
event.events |= EPOLLEXCLUSIVE;
#endif
if (epoll_ctl(epfd, EPOLL_CTL_ADD, listen_sock, &event) == -1)
fatal_perror("epoll_ctl add");
return epfd;
}
static void event_loop_iteration(int epfd, int listen_sock) {
struct epoll_event events[10];
int count = epoll_wait(epfd, events, sizeof(events) / sizeof(events[0]), -1);
if (count == -1)
fatal_perror("epoll_wait");
if (count == 0)
return;
for (unsigned i = 0; i < count; ++i)
dispatch(epfd, &events[i], listen_sock);
free_closed_jobs();
}
static void event_loop(int epfd, int listen_sock) {
for (;;)
event_loop_iteration(epfd, listen_sock);
}
static int serve(void) {
int s = server_socket();
int epfd = setup_epoll_fd(s);
setup_connection_pool(&backend_pool);
event_loop(epfd, s);
close(epfd);
close(s);
return EXIT_SUCCESS;
}
int main(void) {
quiesce_signals();
multiply();
return serve();
}
|
the_stack_data/996656.c | /* csinhf.c */
/*
Contributed by Danny Smith
2004-12-24
*/
#include <math.h>
#include <complex.h>
/* csinh (x + I * y) = sinh (x) * cos (y)
+ I * (cosh (x) * sin (y)) */
float complex csinhf (float complex Z)
{
float complex Res;
__real__ Res = sinhf (__real__ Z) * cosf (__imag__ Z);
__imag__ Res = coshf (__real__ Z) * sinf (__imag__ Z);
return Res;
}
|
the_stack_data/63580.c | #include <sched.h>
#include <stdio.h>
#include <stdlib.h>
void die_usage(void)
{
fprintf(stderr, "Usage: sched_yield\n");
exit(1);
}
int main(int argc, char const *argv[])
{
if (argc > 1) {
die_usage();
}
int res = sched_yield();
if (res == -1) {
perror("sched_yield");
exit(1);
}
return 0;
}
|
the_stack_data/977098.c | /*
** 2007 May 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
**
** This file implements an integration between the ICU library
** ("International Components for Unicode", an open-source library
** for handling unicode data) and SQLite. The integration uses
** ICU to provide the following to SQLite:
**
** * An implementation of the SQL regexp() function (and hence REGEXP
** operator) using the ICU uregex_XX() APIs.
**
** * Implementations of the SQL scalar upper() and lower() functions
** for case mapping.
**
** * Integration of ICU and SQLite collation sequences.
**
** * An implementation of the LIKE operator that uses ICU to
** provide case-independent matching.
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
/* Include ICU headers */
#include <unicode/utypes.h>
#include <unicode/uregex.h>
#include <unicode/ustring.h>
#include <unicode/ucol.h>
#include <assert.h>
#ifndef SQLITE_CORE
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#else
#include "sqlite3.h"
#endif
/*
** Maximum length (in bytes) of the pattern in a LIKE or GLOB
** operator.
*/
#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
#endif
/*
** Version of sqlite3_free() that is always a function, never a macro.
*/
static void xFree(void *p){
sqlite3_free(p);
}
/*
** Compare two UTF-8 strings for equality where the first string is
** a "LIKE" expression. Return true (1) if they are the same and
** false (0) if they are different.
*/
static int icuLikeCompare(
const uint8_t *zPattern, /* LIKE pattern */
const uint8_t *zString, /* The UTF-8 string to compare against */
const UChar32 uEsc /* The escape character */
){
static const int MATCH_ONE = (UChar32)'_';
static const int MATCH_ALL = (UChar32)'%';
int iPattern = 0; /* Current byte index in zPattern */
int iString = 0; /* Current byte index in zString */
int prevEscape = 0; /* True if the previous character was uEsc */
while( zPattern[iPattern]!=0 ){
/* Read (and consume) the next character from the input pattern. */
UChar32 uPattern;
U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
assert(uPattern!=0);
/* There are now 4 possibilities:
**
** 1. uPattern is an unescaped match-all character "%",
** 2. uPattern is an unescaped match-one character "_",
** 3. uPattern is an unescaped escape character, or
** 4. uPattern is to be handled as an ordinary character
*/
if( !prevEscape && uPattern==MATCH_ALL ){
/* Case 1. */
uint8_t c;
/* Skip any MATCH_ALL or MATCH_ONE characters that follow a
** MATCH_ALL. For each MATCH_ONE, skip one character in the
** test string.
*/
while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
if( c==MATCH_ONE ){
if( zString[iString]==0 ) return 0;
U8_FWD_1_UNSAFE(zString, iString);
}
iPattern++;
}
if( zPattern[iPattern]==0 ) return 1;
while( zString[iString] ){
if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
return 1;
}
U8_FWD_1_UNSAFE(zString, iString);
}
return 0;
}else if( !prevEscape && uPattern==MATCH_ONE ){
/* Case 2. */
if( zString[iString]==0 ) return 0;
U8_FWD_1_UNSAFE(zString, iString);
}else if( !prevEscape && uPattern==uEsc){
/* Case 3. */
prevEscape = 1;
}else{
/* Case 4. */
UChar32 uString;
U8_NEXT_UNSAFE(zString, iString, uString);
uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
if( uString!=uPattern ){
return 0;
}
prevEscape = 0;
}
}
return zString[iString]==0;
}
/*
** Implementation of the like() SQL function. This function implements
** the build-in LIKE operator. The first argument to the function is the
** pattern and the second argument is the string. So, the SQL statements:
**
** A LIKE B
**
** is implemented as like(B, A). If there is an escape character E,
**
** A LIKE B ESCAPE E
**
** is mapped to like(B, A, E).
*/
static void icuLikeFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const unsigned char *zA = sqlite3_value_text(argv[0]);
const unsigned char *zB = sqlite3_value_text(argv[1]);
UChar32 uEsc = 0;
/* Limit the length of the LIKE or GLOB pattern to avoid problems
** of deep recursion and N*N behavior in patternCompare().
*/
if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
return;
}
if( argc==3 ){
/* The escape character string must consist of a single UTF-8 character.
** Otherwise, return an error.
*/
int nE= sqlite3_value_bytes(argv[2]);
const unsigned char *zE = sqlite3_value_text(argv[2]);
int i = 0;
if( zE==0 ) return;
U8_NEXT(zE, i, nE, uEsc);
if( i!=nE){
sqlite3_result_error(context,
"ESCAPE expression must be a single character", -1);
return;
}
}
if( zA && zB ){
sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
}
}
/*
** This function is called when an ICU function called from within
** the implementation of an SQL scalar function returns an error.
**
** The scalar function context passed as the first argument is
** loaded with an error message based on the following two args.
*/
static void icuFunctionError(
sqlite3_context *pCtx, /* SQLite scalar function context */
const char *zName, /* Name of ICU function that failed */
UErrorCode e /* Error code returned by ICU function */
){
char zBuf[128];
sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
zBuf[127] = '\0';
sqlite3_result_error(pCtx, zBuf, -1);
}
/*
** Function to delete compiled regexp objects. Registered as
** a destructor function with sqlite3_set_auxdata().
*/
static void icuRegexpDelete(void *p){
URegularExpression *pExpr = (URegularExpression *)p;
uregex_close(pExpr);
}
/*
** Implementation of SQLite REGEXP operator. This scalar function takes
** two arguments. The first is a regular expression pattern to compile
** the second is a string to match against that pattern. If either
** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
** is 1 if the string matches the pattern, or 0 otherwise.
**
** SQLite maps the regexp() function to the regexp() operator such
** that the following two are equivalent:
**
** zString REGEXP zPattern
** regexp(zPattern, zString)
**
** Uses the following ICU regexp APIs:
**
** uregex_open()
** uregex_matches()
** uregex_close()
*/
static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
UErrorCode status = U_ZERO_ERROR;
URegularExpression *pExpr;
UBool res;
const UChar *zString = sqlite3_value_text16(apArg[1]);
(void)nArg; /* Unused parameter */
/* If the left hand side of the regexp operator is NULL,
** then the result is also NULL.
*/
if( !zString ){
return;
}
pExpr = sqlite3_get_auxdata(p, 0);
if( !pExpr ){
const UChar *zPattern = sqlite3_value_text16(apArg[0]);
if( !zPattern ){
return;
}
pExpr = uregex_open(zPattern, -1, 0, 0, &status);
if( U_SUCCESS(status) ){
sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
}else{
assert(!pExpr);
icuFunctionError(p, "uregex_open", status);
return;
}
}
/* Configure the text that the regular expression operates on. */
uregex_setText(pExpr, zString, -1, &status);
if( !U_SUCCESS(status) ){
icuFunctionError(p, "uregex_setText", status);
return;
}
/* Attempt the match */
res = uregex_matches(pExpr, 0, &status);
if( !U_SUCCESS(status) ){
icuFunctionError(p, "uregex_matches", status);
return;
}
/* Set the text that the regular expression operates on to a NULL
** pointer. This is not really necessary, but it is tidier than
** leaving the regular expression object configured with an invalid
** pointer after this function returns.
*/
uregex_setText(pExpr, 0, 0, &status);
/* Return 1 or 0. */
sqlite3_result_int(p, res ? 1 : 0);
}
/*
** Implementations of scalar functions for case mapping - upper() and
** lower(). Function upper() converts its input to upper-case (ABC).
** Function lower() converts to lower-case (abc).
**
** ICU provides two types of case mapping, "general" case mapping and
** "language specific". Refer to ICU documentation for the differences
** between the two.
**
** To utilise "general" case mapping, the upper() or lower() scalar
** functions are invoked with one argument:
**
** upper('ABC') -> 'abc'
** lower('abc') -> 'ABC'
**
** To access ICU "language specific" case mapping, upper() or lower()
** should be invoked with two arguments. The second argument is the name
** of the locale to use. Passing an empty string ("") or SQL NULL value
** as the second argument is the same as invoking the 1 argument version
** of upper() or lower().
**
** lower('I', 'en_us') -> 'i'
** lower('I', 'tr_tr') -> 'ı' (small dotless i)
**
** http://www.icu-project.org/userguide/posix.html#case_mappings
*/
static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
const UChar *zInput;
UChar *zOutput;
int nInput;
int nOutput;
UErrorCode status = U_ZERO_ERROR;
const char *zLocale = 0;
assert(nArg==1 || nArg==2);
if( nArg==2 ){
zLocale = (const char *)sqlite3_value_text(apArg[1]);
}
zInput = sqlite3_value_text16(apArg[0]);
if( !zInput ){
return;
}
nInput = sqlite3_value_bytes16(apArg[0]);
nOutput = nInput * 2 + 2;
zOutput = sqlite3_malloc(nOutput);
if( !zOutput ){
return;
}
if( sqlite3_user_data(p) ){
u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
}else{
u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
}
if( !U_SUCCESS(status) ){
icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
return;
}
sqlite3_result_text16(p, zOutput, -1, xFree);
}
/*
** Collation sequence destructor function. The pCtx argument points to
** a UCollator structure previously allocated using ucol_open().
*/
static void icuCollationDel(void *pCtx){
UCollator *p = (UCollator *)pCtx;
ucol_close(p);
}
/*
** Collation sequence comparison function. The pCtx argument points to
** a UCollator structure previously allocated using ucol_open().
*/
static int icuCollationColl(
void *pCtx,
int nLeft,
const void *zLeft,
int nRight,
const void *zRight
){
UCollationResult res;
UCollator *p = (UCollator *)pCtx;
res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
switch( res ){
case UCOL_LESS: return -1;
case UCOL_GREATER: return +1;
case UCOL_EQUAL: return 0;
}
assert(!"Unexpected return value from ucol_strcoll()");
return 0;
}
/*
** Implementation of the scalar function icu_load_collation().
**
** This scalar function is used to add ICU collation based collation
** types to an SQLite database connection. It is intended to be called
** as follows:
**
** SELECT icu_load_collation(<locale>, <collation-name>);
**
** Where <locale> is a string containing an ICU locale identifier (i.e.
** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
** collation sequence to create.
*/
static void icuLoadCollation(
sqlite3_context *p,
int nArg,
sqlite3_value **apArg
){
sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
UErrorCode status = U_ZERO_ERROR;
const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
const char *zName; /* SQL Collation sequence name (eg. "japanese") */
UCollator *pUCollator; /* ICU library collation object */
int rc; /* Return code from sqlite3_create_collation_x() */
assert(nArg==2);
zLocale = (const char *)sqlite3_value_text(apArg[0]);
zName = (const char *)sqlite3_value_text(apArg[1]);
if( !zLocale || !zName ){
return;
}
pUCollator = ucol_open(zLocale, &status);
if( !U_SUCCESS(status) ){
icuFunctionError(p, "ucol_open", status);
return;
}
assert(p);
rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
icuCollationColl, icuCollationDel
);
if( rc!=SQLITE_OK ){
ucol_close(pUCollator);
sqlite3_result_error(p, "Error registering collation function", -1);
}
}
/*
** Register the ICU extension functions with database db.
*/
int sqlite3IcuInit(sqlite3 *db){
struct IcuScalar {
const char *zName; /* Function name */
int nArg; /* Number of arguments */
int enc; /* Optimal text encoding */
void *pContext; /* sqlite3_user_data() context */
void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
} scalars[] = {
{"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
{"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
{"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
{"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
{"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
{"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
{"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
{"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
{"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
{"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
{"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
{"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
};
int rc = SQLITE_OK;
int i;
for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
struct IcuScalar *p = &scalars[i];
rc = sqlite3_create_function(
db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
);
}
return rc;
}
#if !SQLITE_CORE
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_icu_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
SQLITE_EXTENSION_INIT2(pApi)
return sqlite3IcuInit(db);
}
#endif
#endif
|
the_stack_data/474920.c | /* FNA3D - 3D Graphics Library for FNA
*
* Copyright (c) 2020 Ethan Lee
*
* 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.
*
* Ethan "flibitijibibo" Lee <[email protected]>
*
*/
#if FNA3D_DRIVER_D3D11
#include "FNA3D_Driver.h"
#include "FNA3D_PipelineCache.h"
#include "FNA3D_Driver_D3D11.h"
#include <SDL.h>
#include <SDL_syswm.h>
/* D3D11 Libraries */
#if defined(_WIN32)
#define D3DCOMPILER_DLL "d3dcompiler_47.dll"
#define D3D11_DLL "d3d11.dll"
#define DXGI_DLL "dxgi.dll"
#elif defined(__APPLE__)
#define D3DCOMPILER_DLL "libd3dcompiler.dylib"
#define D3D11_DLL "libd3d11.dylib"
#define DXGI_DLL "libdxgi.dylib"
#else
#define D3DCOMPILER_DLL "libd3dcompiler.so"
#define D3D11_DLL "libd3d11.so"
#define DXGI_DLL "libdxgi.so"
#endif
#ifdef __WINRT__
#include <dxgi1_2.h>
#include <d3dcompiler.h>
#else
#include <dxgi.h>
#endif
#define ERROR_CHECK(msg) \
if (FAILED(res)) \
{ \
FNA3D_LogError("%s! Error Code: %08X", msg, res); \
}
#define ERROR_CHECK_RETURN(msg, ret) \
if (FAILED(res)) \
{ \
FNA3D_LogError("%s! Error Code: %08X", msg, res); \
return ret; \
}
#define ERROR_CHECK_UNLOCK_RETURN(msg, ret) \
if (FAILED(res)) \
{ \
FNA3D_LogError("%s! Error Code: %08X", msg, res); \
SDL_UnlockMutex(renderer->ctxLock); \
return ret; \
}
/* Internal Structures */
typedef struct D3D11Texture /* Cast FNA3D_Texture* to this! */
{
/* D3D Handles */
ID3D11Resource *handle; /* ID3D11Texture2D or ID3D11Texture3D */
ID3D11ShaderResourceView *shaderView;
/* Basic Info */
int32_t levelCount;
uint8_t isRenderTarget;
FNA3D_SurfaceFormat format;
/* Dimensions */
uint8_t rtType;
FNA3DNAMELESS union
{
struct
{
int32_t width;
int32_t height;
ID3D11RenderTargetView *rtView;
} twod;
struct
{
int32_t width;
int32_t height;
int32_t depth;
} threed;
struct
{
int32_t size;
ID3D11RenderTargetView **rtViews;
} cube;
};
ID3D11Resource *staging; /* ID3D11Texture2D or ID3D11Texture3D */
} D3D11Texture;
static D3D11Texture NullTexture =
{
NULL,
NULL,
1,
0,
FNA3D_SURFACEFORMAT_COLOR,
0,
{
{ 0, 0 }
},
NULL
};
typedef struct D3D11Renderbuffer /* Cast FNA3D_Renderbuffer* to this! */
{
ID3D11Texture2D *handle;
int32_t multiSampleCount;
#define RENDERBUFFER_COLOR 0
#define RENDERBUFFER_DEPTH 1
uint8_t type;
FNA3DNAMELESS union
{
struct
{
FNA3D_SurfaceFormat format;
ID3D11RenderTargetView *rtView;
} color;
struct
{
FNA3D_DepthFormat format;
ID3D11DepthStencilView *dsView;
} depth;
};
} D3D11Renderbuffer;
typedef struct D3D11Buffer /* Cast FNA3D_Buffer* to this! */
{
ID3D11Buffer *handle;
uint8_t dynamic;
int32_t size;
} D3D11Buffer;
typedef struct D3D11Effect /* Cast FNA3D_Effect* to this! */
{
MOJOSHADER_effect *effect;
} D3D11Effect;
typedef struct D3D11Query /* Cast FNA3D_Query* to this! */
{
ID3D11Query *handle;
} D3D11Query;
typedef struct D3D11Renderer /* Cast FNA3D_Renderer* to this! */
{
/* Persistent D3D11 Objects */
ID3D11Device *device;
ID3D11DeviceContext *context;
void* d3d11_dll;
void* dxgi_dll;
void* factory; /* IDXGIFactory1 or IDXGIFactory2 */
IDXGIAdapter1 *adapter;
IDXGISwapChain *swapchain;
ID3DUserDefinedAnnotation *annotation;
SDL_mutex *ctxLock;
/* The Faux-Backbuffer */
struct
{
int32_t width;
int32_t height;
/* Color */
FNA3D_SurfaceFormat surfaceFormat;
ID3D11Texture2D *colorBuffer;
ID3D11RenderTargetView *colorView;
ID3D11ShaderResourceView *shaderView;
ID3D11Texture2D *stagingBuffer;
/* Depth Stencil */
FNA3D_DepthFormat depthFormat;
ID3D11Texture2D *depthStencilBuffer;
ID3D11DepthStencilView *depthStencilView;
/* Multisample */
int32_t multiSampleCount;
ID3D11Texture2D *resolveBuffer;
} backbuffer;
uint8_t backbufferSizeChanged;
FNA3D_Rect prevSrcRect;
FNA3D_Rect prevDstRect;
ID3D11VertexShader *fauxBlitVS;
ID3D11PixelShader *fauxBlitPS;
ID3D11SamplerState *fauxBlitSampler;
ID3D11Buffer *fauxBlitVertexBuffer;
ID3D11Buffer *fauxBlitIndexBuffer;
ID3D11InputLayout *fauxBlitLayout;
ID3D11RasterizerState *fauxRasterizer;
ID3D11BlendState *fauxBlendState;
/* Capabilities */
uint8_t debugMode;
uint32_t supportsDxt1;
uint32_t supportsS3tc;
int32_t maxMultiSampleCount;
D3D_FEATURE_LEVEL featureLevel;
/* Presentation */
uint8_t syncInterval;
/* Blend State */
ID3D11BlendState *blendState;
FNA3D_Color blendFactor;
int32_t multiSampleMask;
/* Depth Stencil State */
ID3D11DepthStencilState *depthStencilState;
int32_t stencilRef;
/* Rasterizer State */
FNA3D_Viewport viewport;
FNA3D_Rect scissorRect;
ID3D11RasterizerState *rasterizerState;
/* Textures */
D3D11Texture *textures[MAX_TOTAL_SAMPLERS];
ID3D11SamplerState *samplers[MAX_TOTAL_SAMPLERS];
/* Input Assembly */
ID3D11InputLayout *inputLayout;
FNA3D_PrimitiveType topology;
ID3D11Buffer *vertexBuffers[MAX_BOUND_VERTEX_BUFFERS];
uint32_t vertexBufferOffsets[MAX_BOUND_VERTEX_BUFFERS];
uint32_t vertexBufferStrides[MAX_BOUND_VERTEX_BUFFERS];
ID3D11Buffer *indexBuffer;
FNA3D_IndexElementSize indexElementSize;
/* Resource Caches */
PackedStateArray blendStateCache;
PackedStateArray depthStencilStateCache;
PackedStateArray rasterizerStateCache;
PackedStateArray samplerStateCache;
PackedVertexBufferBindingsArray inputLayoutCache;
/* Render Targets */
int32_t numRenderTargets;
ID3D11RenderTargetView *swapchainRTView;
ID3D11RenderTargetView *renderTargetViews[MAX_RENDERTARGET_BINDINGS];
ID3D11DepthStencilView *depthStencilView;
FNA3D_DepthFormat currentDepthFormat;
/* MojoShader Interop */
MOJOSHADER_effect *currentEffect;
const MOJOSHADER_effectTechnique *currentTechnique;
uint32_t currentPass;
uint8_t effectApplied;
} D3D11Renderer;
/* XNA->D3D11 Translation Arrays */
static DXGI_FORMAT XNAToD3D_TextureFormat[] =
{
DXGI_FORMAT_R8G8B8A8_UNORM, /* SurfaceFormat.Color */
DXGI_FORMAT_B5G6R5_UNORM, /* SurfaceFormat.Bgr565 */
DXGI_FORMAT_B5G5R5A1_UNORM, /* SurfaceFormat.Bgra5551 */
DXGI_FORMAT_B4G4R4A4_UNORM, /* SurfaceFormat.Bgra4444 */
DXGI_FORMAT_BC1_UNORM, /* SurfaceFormat.Dxt1 */
DXGI_FORMAT_BC2_UNORM, /* SurfaceFormat.Dxt3 */
DXGI_FORMAT_BC3_UNORM, /* SurfaceFormat.Dxt5 */
DXGI_FORMAT_R8G8_SNORM, /* SurfaceFormat.NormalizedByte2 */
DXGI_FORMAT_R8G8B8A8_SNORM, /* SurfaceFormat.NormalizedByte4 */
DXGI_FORMAT_R10G10B10A2_UNORM, /* SurfaceFormat.Rgba1010102 */
DXGI_FORMAT_R16G16_UNORM, /* SurfaceFormat.Rg32 */
DXGI_FORMAT_R16G16B16A16_UNORM, /* SurfaceFormat.Rgba64 */
DXGI_FORMAT_A8_UNORM, /* SurfaceFormat.Alpha8 */
DXGI_FORMAT_R32_FLOAT, /* SurfaceFormat.Single */
DXGI_FORMAT_R32G32_FLOAT, /* SurfaceFormat.Vector2 */
DXGI_FORMAT_R32G32B32A32_FLOAT, /* SurfaceFormat.Vector4 */
DXGI_FORMAT_R16_FLOAT, /* SurfaceFormat.HalfSingle */
DXGI_FORMAT_R16G16_FLOAT, /* SurfaceFormat.HalfVector2 */
DXGI_FORMAT_R16G16B16A16_FLOAT, /* SurfaceFormat.HalfVector4 */
DXGI_FORMAT_R16G16B16A16_FLOAT, /* SurfaceFormat.HdrBlendable */
DXGI_FORMAT_B8G8R8A8_UNORM, /* SurfaceFormat.ColorBgraEXT */
};
static DXGI_FORMAT XNAToD3D_DepthFormat[] =
{
DXGI_FORMAT_UNKNOWN, /* DepthFormat.None */
DXGI_FORMAT_D16_UNORM, /* DepthFormat.Depth16 */
DXGI_FORMAT_D24_UNORM_S8_UINT, /* DepthFormat.Depth24 */
DXGI_FORMAT_D24_UNORM_S8_UINT /* DepthFormat.Depth24Stencil8 */
};
static LPCSTR XNAToD3D_VertexAttribSemanticName[] =
{
"POSITION", /* VertexElementUsage.Position */
"COLOR", /* VertexElementUsage.Color */
"TEXCOORD", /* VertexElementUsage.TextureCoordinate */
"NORMAL", /* VertexElementUsage.Normal */
"BINORMAL", /* VertexElementUsage.Binormal */
"TANGENT", /* VertexElementUsage.Tangent */
"BLENDINDICES", /* VertexElementUsage.BlendIndices */
"BLENDWEIGHT", /* VertexElementUsage.BlendWeight */
"SV_DEPTH", /* VertexElementUsage.Depth */
"FOG", /* VertexElementUsage.Fog */
"PSIZE", /* VertexElementUsage.PointSize */
"SV_SampleIndex", /* VertexElementUsage.Sample */
"TESSFACTOR" /* VertexElementUsage.TessellateFactor */
};
static DXGI_FORMAT XNAToD3D_VertexAttribFormat[] =
{
DXGI_FORMAT_R32_FLOAT, /* VertexElementFormat.Single */
DXGI_FORMAT_R32G32_FLOAT, /* VertexElementFormat.Vector2 */
DXGI_FORMAT_R32G32B32_FLOAT, /* VertexElementFormat.Vector3 */
DXGI_FORMAT_R32G32B32A32_FLOAT, /* VertexElementFormat.Vector4 */
DXGI_FORMAT_R8G8B8A8_UNORM, /* VertexElementFormat.Color */
DXGI_FORMAT_R8G8B8A8_UINT, /* VertexElementFormat.Byte4 */
DXGI_FORMAT_R16G16_SINT, /* VertexElementFormat.Short2 */
DXGI_FORMAT_R16G16B16A16_SINT, /* VertexElementFormat.Short4 */
DXGI_FORMAT_R16G16_SNORM, /* VertexElementFormat.NormalizedShort2 */
DXGI_FORMAT_R16G16B16A16_SNORM, /* VertexElementFormat.NormalizedShort4 */
DXGI_FORMAT_R16G16_FLOAT, /* VertexElementFormat.HalfVector2 */
DXGI_FORMAT_R16G16B16A16_FLOAT /* VertexElementFormat.HalfVector4 */
};
static DXGI_FORMAT XNAToD3D_IndexType[] =
{
DXGI_FORMAT_R16_UINT, /* IndexElementSize.SixteenBits */
DXGI_FORMAT_R32_UINT /* IndexElementSize.ThirtyTwoBits */
};
static D3D11_BLEND XNAToD3D_BlendMode[] =
{
D3D11_BLEND_ONE, /* Blend.One */
D3D11_BLEND_ZERO, /* Blend.Zero */
D3D11_BLEND_SRC_COLOR, /* Blend.SourceColor */
D3D11_BLEND_INV_SRC_COLOR, /* Blend.InverseSourceColor */
D3D11_BLEND_SRC_ALPHA, /* Blend.SourceAlpha */
D3D11_BLEND_INV_SRC_ALPHA, /* Blend.InverseSourceAlpha */
D3D11_BLEND_DEST_COLOR, /* Blend.DestinationColor */
D3D11_BLEND_INV_DEST_COLOR, /* Blend.InverseDestinationColor */
D3D11_BLEND_DEST_ALPHA, /* Blend.DestinationAlpha */
D3D11_BLEND_INV_DEST_ALPHA, /* Blend.InverseDestinationAlpha */
D3D11_BLEND_BLEND_FACTOR, /* Blend.BlendFactor */
D3D11_BLEND_INV_BLEND_FACTOR, /* Blend.InverseBlendFactor */
D3D11_BLEND_SRC_ALPHA_SAT /* Blend.SourceAlphaSaturation */
};
static D3D11_BLEND XNAToD3D_BlendModeAlpha[] =
{
D3D11_BLEND_ONE, /* Blend.One */
D3D11_BLEND_ZERO, /* Blend.Zero */
D3D11_BLEND_SRC_ALPHA, /* Blend.SourceColor */
D3D11_BLEND_INV_SRC_ALPHA, /* Blend.InverseSourceColor */
D3D11_BLEND_SRC_ALPHA, /* Blend.SourceAlpha */
D3D11_BLEND_INV_SRC_ALPHA, /* Blend.InverseSourceAlpha */
D3D11_BLEND_DEST_ALPHA, /* Blend.DestinationColor */
D3D11_BLEND_INV_DEST_ALPHA, /* Blend.InverseDestinationColor */
D3D11_BLEND_DEST_ALPHA, /* Blend.DestinationAlpha */
D3D11_BLEND_INV_DEST_ALPHA, /* Blend.InverseDestinationAlpha */
D3D11_BLEND_BLEND_FACTOR, /* Blend.BlendFactor */
D3D11_BLEND_INV_BLEND_FACTOR, /* Blend.InverseBlendFactor */
D3D11_BLEND_SRC_ALPHA_SAT /* Blend.SourceAlphaSaturation */
};
static D3D11_BLEND_OP XNAToD3D_BlendOperation[] =
{
D3D11_BLEND_OP_ADD, /* BlendFunction.Add */
D3D11_BLEND_OP_SUBTRACT, /* BlendFunction.Subtract */
D3D11_BLEND_OP_REV_SUBTRACT, /* BlendFunction.ReverseSubtract */
D3D11_BLEND_OP_MAX, /* BlendFunction.Max */
D3D11_BLEND_OP_MIN /* BlendFunction.Min */
};
static D3D11_COMPARISON_FUNC XNAToD3D_CompareFunc[] =
{
D3D11_COMPARISON_ALWAYS, /* CompareFunction.Always */
D3D11_COMPARISON_NEVER, /* CompareFunction.Never */
D3D11_COMPARISON_LESS, /* CompareFunction.Less */
D3D11_COMPARISON_LESS_EQUAL, /* CompareFunction.LessEqual */
D3D11_COMPARISON_EQUAL, /* CompareFunction.Equal */
D3D11_COMPARISON_GREATER_EQUAL, /* CompareFunction.GreaterEqual */
D3D11_COMPARISON_GREATER, /* CompareFunction.Greater */
D3D11_COMPARISON_NOT_EQUAL /* CompareFunction.NotEqual */
};
static D3D11_STENCIL_OP XNAToD3D_StencilOp[] =
{
D3D11_STENCIL_OP_KEEP, /* StencilOperation.Keep */
D3D11_STENCIL_OP_ZERO, /* StencilOperation.Zero */
D3D11_STENCIL_OP_REPLACE, /* StencilOperation.Replace */
D3D11_STENCIL_OP_INCR, /* StencilOperation.Increment */
D3D11_STENCIL_OP_DECR, /* StencilOperation.Decrement */
D3D11_STENCIL_OP_INCR_SAT, /* StencilOperation.IncrementSaturation */
D3D11_STENCIL_OP_DECR_SAT, /* StencilOperation.DecrementSaturation */
D3D11_STENCIL_OP_INVERT /* StencilOperation.Invert */
};
static D3D11_FILL_MODE XNAToD3D_FillMode[] =
{
D3D11_FILL_SOLID, /* FillMode.Solid */
D3D11_FILL_WIREFRAME /* FillMode.WireFrame */
};
static float XNAToD3D_DepthBiasScale[] =
{
0.0f, /* DepthFormat.None */
(float) ((1 << 16) - 1), /* DepthFormat.Depth16 */
(float) ((1 << 24) - 1), /* DepthFormat.Depth24 */
(float) ((1 << 24) - 1) /* DepthFormat.Depth24Stencil8 */
};
static D3D11_CULL_MODE XNAToD3D_CullMode[] =
{
D3D11_CULL_NONE, /* CullMode.None */
D3D11_CULL_BACK, /* CullMode.CullClockwiseFace */
D3D11_CULL_FRONT /* CullMode.CullCounterClockwiseFace */
};
static D3D11_TEXTURE_ADDRESS_MODE XNAToD3D_Wrap[] =
{
D3D11_TEXTURE_ADDRESS_WRAP, /* TextureAddressMode.Wrap */
D3D11_TEXTURE_ADDRESS_CLAMP, /* TextureAddressMode.Clamp */
D3D11_TEXTURE_ADDRESS_MIRROR /* TextureAddressMode.Mirror */
};
static D3D11_FILTER XNAToD3D_Filter[] =
{
D3D11_FILTER_MIN_MAG_MIP_LINEAR, /* TextureFilter.Linear */
D3D11_FILTER_MIN_MAG_MIP_POINT, /* TextureFilter.Point */
D3D11_FILTER_ANISOTROPIC, /* TextureFilter.Anisotropic */
D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT, /* TextureFilter.LinearMipPoint */
D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR, /* TextureFilter.PointMipLinear */
D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, /* TextureFilter.MinLinearMagPointMipLinear */
D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT, /* TextureFilter.MinLinearMagPointMipPoint */
D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR, /* TextureFilter.MinPointMagLinearMipLinear */
D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT /* TextureFilter.MinPointMagLinearMipPoint */
};
static D3D_PRIMITIVE_TOPOLOGY XNAToD3D_Primitive[] =
{
D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, /* PrimitiveType.TriangleList */
D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, /* PrimitiveType.TriangleStrip */
D3D_PRIMITIVE_TOPOLOGY_LINELIST, /* PrimitiveType.LineList */
D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, /* PrimitiveType.LineStrip */
D3D_PRIMITIVE_TOPOLOGY_POINTLIST /* PrimitiveType.PointListEXT */
};
/* Faux-Backbuffer Blit Shader Sources */
static const char* FAUX_BLIT_VERTEX_SHADER =
"void main("
" inout float4 position : SV_POSITION,"
" inout float2 texcoord : TEXCOORD0"
") {"
" position.y *= -1;"
" position.zw = float2(0.0f, 1.0f);"
"}";
static const char* FAUX_BLIT_PIXEL_SHADER =
"Texture2D Texture : register(t0);"
"sampler TextureSampler : register(s0);"
"float4 main("
" float4 position : SV_POSITION,"
" float2 texcoord : TEXCOORD0"
") : SV_TARGET {"
" return Texture.Sample(TextureSampler, texcoord);"
"}";
/* Helper Functions */
static inline uint32_t D3D11_INTERNAL_CalcSubresource(
uint32_t mipLevel,
uint32_t arraySlice,
uint32_t numLevels
) {
return mipLevel + (arraySlice * numLevels);
}
static uint8_t D3D11_INTERNAL_BlendEquals(
FNA3D_Color *a,
FNA3D_Color *b
) {
return SDL_memcmp(a, b, sizeof(FNA3D_Color)) == 0;
}
/* Pipeline State Object Caching */
static ID3D11BlendState* D3D11_INTERNAL_FetchBlendState(
D3D11Renderer *renderer,
FNA3D_BlendState *state
) {
PackedState packedState;
D3D11_BLEND_DESC desc = {0};
ID3D11BlendState *result;
HRESULT res;
/* Can we just reuse an existing state? */
packedState = GetPackedBlendState(*state);
result = (ID3D11BlendState*) PackedStateArray_Fetch(
renderer->blendStateCache,
packedState
);
if (result != NULL)
{
/* The state is already cached! */
return result;
}
/* We need to make a new blend state... */
desc.AlphaToCoverageEnable = 0;
desc.IndependentBlendEnable = 0;
desc.RenderTarget[0].BlendEnable = !(
state->colorSourceBlend == FNA3D_BLEND_ONE &&
state->colorDestinationBlend == FNA3D_BLEND_ZERO &&
state->alphaSourceBlend == FNA3D_BLEND_ONE &&
state->alphaDestinationBlend == FNA3D_BLEND_ZERO
);
if (desc.RenderTarget[0].BlendEnable)
{
desc.RenderTarget[0].BlendOp = XNAToD3D_BlendOperation[
state->colorBlendFunction
];
desc.RenderTarget[0].BlendOpAlpha = XNAToD3D_BlendOperation[
state->alphaBlendFunction
];
desc.RenderTarget[0].DestBlend = XNAToD3D_BlendMode[
state->colorDestinationBlend
];
desc.RenderTarget[0].DestBlendAlpha = XNAToD3D_BlendModeAlpha[
state->alphaDestinationBlend
];
desc.RenderTarget[0].SrcBlend = XNAToD3D_BlendMode[
state->colorSourceBlend
];
desc.RenderTarget[0].SrcBlendAlpha = XNAToD3D_BlendModeAlpha[
state->alphaSourceBlend
];
}
/* All other states should match for all targets... */
desc.RenderTarget[1] = desc.RenderTarget[0];
desc.RenderTarget[2] = desc.RenderTarget[0];
desc.RenderTarget[3] = desc.RenderTarget[0];
/* ... except RenderTargetWriteMask. */
desc.RenderTarget[0].RenderTargetWriteMask = (
(uint32_t) state->colorWriteEnable
);
desc.RenderTarget[1].RenderTargetWriteMask = (
(uint32_t) state->colorWriteEnable1
);
desc.RenderTarget[2].RenderTargetWriteMask = (
(uint32_t) state->colorWriteEnable2
);
desc.RenderTarget[3].RenderTargetWriteMask = (
(uint32_t) state->colorWriteEnable3
);
/* Bake the state! */
res = ID3D11Device_CreateBlendState(
renderer->device,
&desc,
&result
);
ERROR_CHECK_RETURN("Blend state creation failed", NULL)
PackedStateArray_Insert(
&renderer->blendStateCache,
packedState,
result
);
/* Return the state! */
return result;
}
static ID3D11DepthStencilState* D3D11_INTERNAL_FetchDepthStencilState(
D3D11Renderer *renderer,
FNA3D_DepthStencilState *state
) {
PackedState packedState;
D3D11_DEPTH_STENCIL_DESC desc;
D3D11_DEPTH_STENCILOP_DESC front, back;
ID3D11DepthStencilState *result;
HRESULT res;
/* Can we just reuse an existing state? */
packedState = GetPackedDepthStencilState(*state);
result = (ID3D11DepthStencilState*) PackedStateArray_Fetch(
renderer->depthStencilStateCache,
packedState
);
if (result != NULL)
{
/* The state is already cached! */
return result;
}
/* We have to make a new depth stencil state... */
desc.DepthEnable = state->depthBufferEnable;
desc.DepthWriteMask = (
state->depthBufferEnable && state->depthBufferWriteEnable ?
D3D11_DEPTH_WRITE_MASK_ALL :
D3D11_DEPTH_WRITE_MASK_ZERO
);
desc.DepthFunc = XNAToD3D_CompareFunc[
state->depthBufferFunction
];
desc.StencilEnable = state->stencilEnable;
desc.StencilReadMask = (uint8_t) state->stencilMask;
desc.StencilWriteMask = (uint8_t) state->stencilWriteMask;
front.StencilDepthFailOp = XNAToD3D_StencilOp[
state->stencilDepthBufferFail
];
front.StencilFailOp = XNAToD3D_StencilOp[
state->stencilFail
];
front.StencilFunc = XNAToD3D_CompareFunc[
state->stencilFunction
];
front.StencilPassOp = XNAToD3D_StencilOp[
state->stencilPass
];
if (state->twoSidedStencilMode)
{
back.StencilDepthFailOp = XNAToD3D_StencilOp[
state->ccwStencilDepthBufferFail
];
back.StencilFailOp = XNAToD3D_StencilOp[
state->ccwStencilFail
];
back.StencilFunc = XNAToD3D_CompareFunc[
state->ccwStencilFunction
];
back.StencilPassOp = XNAToD3D_StencilOp[
state->ccwStencilPass
];
}
else
{
back = front;
}
desc.FrontFace = front;
desc.BackFace = back;
/* Bake the state! */
res = ID3D11Device_CreateDepthStencilState(
renderer->device,
&desc,
&result
);
ERROR_CHECK_RETURN("Depth-stencil state creation failed", NULL)
PackedStateArray_Insert(
&renderer->depthStencilStateCache,
packedState,
result
);
/* Return the state! */
return result;
}
static ID3D11RasterizerState* D3D11_INTERNAL_FetchRasterizerState(
D3D11Renderer *renderer,
FNA3D_RasterizerState *state
) {
PackedState packedState;
float depthBias;
D3D11_RASTERIZER_DESC desc;
ID3D11RasterizerState *result;
HRESULT res;
depthBias = state->depthBias * XNAToD3D_DepthBiasScale[
renderer->currentDepthFormat
];
/* Can we just reuse an existing state? */
packedState = GetPackedRasterizerState(*state, depthBias);
result = (ID3D11RasterizerState*) PackedStateArray_Fetch(
renderer->rasterizerStateCache,
packedState
);
if (result != NULL)
{
/* The state is already cached! */
return result;
}
/* We have to make a new rasterizer state... */
desc.AntialiasedLineEnable = 0;
desc.CullMode = XNAToD3D_CullMode[state->cullMode];
desc.DepthBias = (int32_t) depthBias;
desc.DepthBiasClamp = D3D11_FLOAT32_MAX;
desc.DepthClipEnable = 1;
desc.FillMode = XNAToD3D_FillMode[state->fillMode];
desc.FrontCounterClockwise = 1;
desc.MultisampleEnable = state->multiSampleAntiAlias;
desc.ScissorEnable = state->scissorTestEnable;
desc.SlopeScaledDepthBias = state->slopeScaleDepthBias;
/* Bake the state! */
res = ID3D11Device_CreateRasterizerState(
renderer->device,
&desc,
&result
);
ERROR_CHECK_RETURN("Rasterizer state creation failed", NULL)
PackedStateArray_Insert(
&renderer->rasterizerStateCache,
packedState,
result
);
/* Return the state! */
return result;
}
static ID3D11SamplerState* D3D11_INTERNAL_FetchSamplerState(
D3D11Renderer *renderer,
FNA3D_SamplerState *state
) {
PackedState packedState;
D3D11_SAMPLER_DESC desc;
ID3D11SamplerState *result;
HRESULT res;
/* Can we just reuse an existing state? */
packedState = GetPackedSamplerState(*state);
result = (ID3D11SamplerState*) PackedStateArray_Fetch(
renderer->samplerStateCache,
packedState
);
if (result != NULL)
{
/* The state is already cached! */
return result;
}
/* We have to make a new sampler state... */
desc.AddressU = XNAToD3D_Wrap[state->addressU];
desc.AddressV = XNAToD3D_Wrap[state->addressV];
desc.AddressW = XNAToD3D_Wrap[state->addressW];
desc.BorderColor[0] = 1.0f;
desc.BorderColor[1] = 1.0f;
desc.BorderColor[2] = 1.0f;
desc.BorderColor[3] = 1.0f;
desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
desc.Filter = XNAToD3D_Filter[state->filter];
desc.MaxAnisotropy = (uint32_t) state->maxAnisotropy;
desc.MaxLOD = D3D11_FLOAT32_MAX;
desc.MinLOD = (float) state->maxMipLevel;
desc.MipLODBias = state->mipMapLevelOfDetailBias;
/* Bake the state! */
res = ID3D11Device_CreateSamplerState(
renderer->device,
&desc,
&result
);
ERROR_CHECK_RETURN("Sampler state creation failed", NULL)
PackedStateArray_Insert(
&renderer->samplerStateCache,
packedState,
result
);
/* Return the state! */
return result;
}
static ID3D11InputLayout* D3D11_INTERNAL_FetchBindingsInputLayout(
D3D11Renderer *renderer,
FNA3D_VertexBufferBinding *bindings,
int32_t numBindings,
uint32_t *hash
) {
int32_t numElements, i, j, k, usage, index, attribLoc, bindingsIndex;
uint8_t attrUse[MOJOSHADER_USAGE_TOTAL][16];
D3D11_INPUT_ELEMENT_DESC elements[16]; /* D3DCAPS9 MaxStreams <= 16 */
D3D11_INPUT_ELEMENT_DESC *d3dElement;
MOJOSHADER_d3d11Shader *vertexShader, *blah;
void *bytecode;
int32_t bytecodeLength;
HRESULT res;
ID3D11InputLayout *result;
/* We need the vertex shader... */
MOJOSHADER_d3d11GetBoundShaders(&vertexShader, &blah);
/* Can we just reuse an existing input layout? */
result = (ID3D11InputLayout*) PackedVertexBufferBindingsArray_Fetch(
renderer->inputLayoutCache,
bindings,
numBindings,
vertexShader,
&bindingsIndex,
hash
);
if (result != NULL)
{
/* This input layout has already been cached! */
return result;
}
/* We have to make a new input layout... */
/* There's this weird case where you can have overlapping
* vertex usage/index combinations. It seems like the first
* attrib gets priority, so whenever a duplicate attribute
* exists, give it the next available index. If that fails, we
* have to crash :/
* -flibit
*/
SDL_zero(attrUse);
/* Determine how many elements are actually in use */
numElements = 0;
for (i = 0; i < numBindings; i += 1)
{
/* Describe vertex attributes */
const FNA3D_VertexBufferBinding *binding = &bindings[i];
for (j = 0; j < binding->vertexDeclaration.elementCount; j += 1)
{
const FNA3D_VertexElement *element = &binding->vertexDeclaration.elements[j];
usage = element->vertexElementUsage;
index = element->usageIndex;
if (attrUse[usage][index])
{
index = -1;
for (k = 0; k < 16; k += 1)
{
if (!attrUse[usage][k])
{
index = k;
break;
}
}
if (index < 0)
{
FNA3D_LogError(
"Vertex usage collision!"
);
}
}
attrUse[usage][index] = 1;
attribLoc = MOJOSHADER_d3d11GetVertexAttribLocation(
vertexShader,
VertexAttribUsage(usage),
index
);
if (attribLoc == -1)
{
/* Stream not in use! */
continue;
}
numElements += 1;
d3dElement = &elements[attribLoc];
d3dElement->SemanticName = XNAToD3D_VertexAttribSemanticName[usage];
d3dElement->SemanticIndex = index;
d3dElement->Format = XNAToD3D_VertexAttribFormat[
element->vertexElementFormat
];
d3dElement->InputSlot = i;
d3dElement->AlignedByteOffset = element->offset;
d3dElement->InputSlotClass = (
binding->instanceFrequency > 0 ?
D3D11_INPUT_PER_INSTANCE_DATA :
D3D11_INPUT_PER_VERTEX_DATA
);
d3dElement->InstanceDataStepRate = (
binding->instanceFrequency > 0 ?
binding->instanceFrequency :
0
);
}
}
MOJOSHADER_d3d11CompileVertexShader(
(unsigned long long) *hash,
elements,
numElements,
&bytecode,
&bytecodeLength
);
res = ID3D11Device_CreateInputLayout(
renderer->device,
elements,
numElements,
bytecode,
bytecodeLength,
&result
);
/* Check for errors now that elements is freed */
ERROR_CHECK_RETURN("Could not compile input layout", NULL)
/* Return the new input layout! */
PackedVertexBufferBindingsArray_Insert(
&renderer->inputLayoutCache,
bindings,
numBindings,
vertexShader,
result
);
return result;
}
/* Forward Declarations */
static void D3D11_INTERNAL_DestroyFramebuffer(D3D11Renderer *renderer);
static void D3D11_SetRenderTargets(
FNA3D_Renderer *driverData,
FNA3D_RenderTargetBinding *renderTargets,
int32_t numRenderTargets,
FNA3D_Renderbuffer *depthStencilBuffer,
FNA3D_DepthFormat depthFormat,
uint8_t preserveTargetContents
);
static void D3D11_GetTextureData2D(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
int32_t level,
void* data,
int32_t dataLength
);
static void D3D11_GetDrawableSize(void *window, int32_t *w, int32_t *h);
static void* D3D11_PLATFORM_LoadD3D11();
static void D3D11_PLATFORM_UnloadD3D11(void* module);
static PFN_D3D11_CREATE_DEVICE D3D11_PLATFORM_GetCreateDeviceFunc(void* module);
static void* D3D11_PLATFORM_LoadCompiler();
static void D3D11_PLATFORM_UnloadCompiler(void* module);
static PFN_D3DCOMPILE D3D11_PLATFORM_GetCompileFunc(void* module);
static HRESULT D3D11_PLATFORM_CreateDXGIFactory(
void** module,
void** factory
);
static void D3D11_PLATFORM_UnloadDXGI(void* module);
static void D3D11_PLATFORM_GetDefaultAdapter(
void* factory,
IDXGIAdapter1 **adapter
);
static void D3D11_PLATFORM_CreateSwapChain(
D3D11Renderer *renderer,
FNA3D_PresentationParameters *pp
);
/* Renderer Implementation */
/* Quit */
static void D3D11_DestroyDevice(FNA3D_Device *device)
{
D3D11Renderer* renderer = (D3D11Renderer*) device->driverData;
int32_t i;
/* Unbind all render objects */
ID3D11DeviceContext_ClearState(renderer->context);
/* Release faux backbuffer and swapchain */
D3D11_INTERNAL_DestroyFramebuffer(renderer);
ID3D11BlendState_Release(renderer->fauxBlendState);
ID3D11Buffer_Release(renderer->fauxBlitIndexBuffer);
ID3D11InputLayout_Release(renderer->fauxBlitLayout);
ID3D11PixelShader_Release(renderer->fauxBlitPS);
ID3D11SamplerState_Release(renderer->fauxBlitSampler);
ID3D11VertexShader_Release(renderer->fauxBlitVS);
ID3D11RasterizerState_Release(renderer->fauxRasterizer);
ID3D11Buffer_Release(renderer->fauxBlitVertexBuffer);
IDXGISwapChain_Release(renderer->swapchain);
/* Release blend states */
for (i = 0; i < renderer->blendStateCache.count; i += 1)
{
ID3D11BlendState_Release(
(ID3D11BlendState*) renderer->blendStateCache.elements[i].value
);
}
SDL_free(renderer->blendStateCache.elements);
/* Release depth stencil states */
for (i = 0; i < renderer->depthStencilStateCache.count; i += 1)
{
ID3D11DepthStencilState_Release(
(ID3D11DepthStencilState*) renderer->depthStencilStateCache.elements[i].value
);
}
SDL_free(renderer->depthStencilStateCache.elements);
/* Release rasterizer states */
for (i = 0; i < renderer->rasterizerStateCache.count; i += 1)
{
ID3D11RasterizerState_Release(
(ID3D11RasterizerState*) renderer->rasterizerStateCache.elements[i].value
);
}
SDL_free(renderer->rasterizerStateCache.elements);
/* Release sampler states */
for (i = 0; i < renderer->samplerStateCache.count; i += 1)
{
ID3D11SamplerState_Release(
(ID3D11SamplerState*) renderer->samplerStateCache.elements[i].value
);
}
SDL_free(renderer->samplerStateCache.elements);
/* Release input layouts */
for (i = 0; i < renderer->inputLayoutCache.count; i += 1)
{
ID3D11InputLayout_Release(
(ID3D11InputLayout*) renderer->inputLayoutCache.elements[i].value
);
}
SDL_free(renderer->inputLayoutCache.elements);
/* Release the annotation, if applicable */
if (renderer->annotation != NULL)
{
ID3DUserDefinedAnnotation_Release(renderer->annotation);
}
/* Release the factory */
IUnknown_Release((IUnknown*) renderer->factory);
/* Release the MojoShader context */
MOJOSHADER_d3d11DestroyContext();
/* Release the device */
ID3D11DeviceContext_Release(renderer->context);
ID3D11Device_Release(renderer->device);
/* Release the DLLs */
D3D11_PLATFORM_UnloadD3D11(renderer->d3d11_dll);
D3D11_PLATFORM_UnloadDXGI(renderer->dxgi_dll);
SDL_DestroyMutex(renderer->ctxLock);
SDL_free(renderer);
SDL_free(device);
}
/* Presentation */
static void D3D11_INTERNAL_UpdateBackbufferVertexBuffer(
D3D11Renderer *renderer,
FNA3D_Rect *srcRect,
FNA3D_Rect *dstRect,
int32_t drawableWidth,
int32_t drawableHeight
) {
float backbufferWidth = (float) renderer->backbuffer.width;
float backbufferHeight = (float) renderer->backbuffer.height;
float sx0, sy0, sx1, sy1;
float dx0, dy0, dx1, dy1;
float data[16];
D3D11_MAPPED_SUBRESOURCE mappedBuffer;
HRESULT res;
/* Cache the new info */
renderer->backbufferSizeChanged = 0;
renderer->prevSrcRect = *srcRect;
renderer->prevDstRect = *dstRect;
/* Scale the texture coordinates to (0, 1) */
sx0 = srcRect->x / backbufferWidth;
sy0 = srcRect->y / backbufferHeight;
sx1 = (srcRect->x + srcRect->w) / backbufferWidth;
sy1 = (srcRect->y + srcRect->h) / backbufferHeight;
/* Scale the position coordinates to (-1, 1) */
dx0 = (dstRect->x / (float) drawableWidth) * 2.0f - 1.0f;
dy0 = (dstRect->y / (float) drawableHeight) * 2.0f - 1.0f;
dx1 = ((dstRect->x + dstRect->w) / (float) drawableWidth) * 2.0f - 1.0f;
dy1 = ((dstRect->y + dstRect->h) / (float) drawableHeight) * 2.0f - 1.0f;
/* Stuff the data into an array */
data[0] = dx0;
data[1] = dy0;
data[2] = sx0;
data[3] = sy0;
data[4] = dx1;
data[5] = dy0;
data[6] = sx1;
data[7] = sy0;
data[8] = dx1;
data[9] = dy1;
data[10] = sx1;
data[11] = sy1;
data[12] = dx0;
data[13] = dy1;
data[14] = sx0;
data[15] = sy1;
/* Copy the data into the buffer */
mappedBuffer.pData = NULL;
mappedBuffer.DepthPitch = 0;
mappedBuffer.RowPitch = 0;
SDL_LockMutex(renderer->ctxLock);
res = ID3D11DeviceContext_Map(
renderer->context,
(ID3D11Resource*) renderer->fauxBlitVertexBuffer,
0,
D3D11_MAP_WRITE_DISCARD,
0,
&mappedBuffer
);
ERROR_CHECK_UNLOCK_RETURN("Could not map backbuffer vertex buffer for writing",)
SDL_memcpy(mappedBuffer.pData, data, sizeof(data));
ID3D11DeviceContext_Unmap(
renderer->context,
(ID3D11Resource*) renderer->fauxBlitVertexBuffer,
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_INTERNAL_BlitFramebuffer(
D3D11Renderer *renderer,
int32_t drawableWidth,
int32_t drawableHeight
) {
DXGI_SWAP_CHAIN_DESC swapchainDesc;
D3D11_VIEWPORT tempViewport;
const uint32_t vertexStride = 16;
const uint32_t offsets[] = { 0 };
float blendFactor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
ID3D11VertexShader *oldVertexShader;
ID3D11PixelShader *oldPixelShader;
ID3D11ClassInstance *whatever;
uint32_t noReallyWhatever = 0;
D3D11_VIEWPORT origViewport =
{
(float) renderer->viewport.x,
(float) renderer->viewport.y,
(float) renderer->viewport.w,
(float) renderer->viewport.h,
renderer->viewport.minDepth,
renderer->viewport.maxDepth
};
SDL_LockMutex(renderer->ctxLock);
/* HACK ahead: During a window resize operation, the swapchain size does not necessarily
* match the size of the drawable. As a result, we need to set our viewport to match the
* size of the swapchain instead of the size of the drawable.
* If we don't do this, during the resize the damaged area will contain garbage pixels and
* the framebuffer will be drawn at the incorrect size as well.
* The result of this hack is that the framebuffer is scaled up to match whatever the size
* of the drawable happens to be (this will introduce some blurring, and does not match
* the behavior of OpenGL/Vulkan - just show black pixels in the damaged area - but is
* better than the alternatives.)
* The ideal solution would be to resize the swapchain to fit, but resizing a swapchain
* requires us to first release any references to its backbuffers, so attempting to
* resize it here will always fail.
*/
IDXGISwapChain_GetDesc(renderer->swapchain, &swapchainDesc);
tempViewport.TopLeftX = 0;
tempViewport.TopLeftY = 0;
tempViewport.Width = (float) swapchainDesc.BufferDesc.Width;
tempViewport.Height = (float) swapchainDesc.BufferDesc.Height;
tempViewport.MinDepth = 0;
tempViewport.MaxDepth = 1;
/* Push the current shader state */
ID3D11DeviceContext_VSGetShader(
renderer->context,
&oldVertexShader,
&whatever,
&noReallyWhatever
);
ID3D11DeviceContext_PSGetShader(
renderer->context,
&oldPixelShader,
&whatever,
&noReallyWhatever
);
/* Bind the swapchain render target */
ID3D11DeviceContext_OMSetRenderTargets(
renderer->context,
1,
&renderer->swapchainRTView,
NULL
);
/* Bind the vertex and index buffers */
ID3D11DeviceContext_IASetVertexBuffers(
renderer->context,
0,
1,
&renderer->fauxBlitVertexBuffer,
&vertexStride,
offsets
);
ID3D11DeviceContext_IASetIndexBuffer(
renderer->context,
renderer->fauxBlitIndexBuffer,
DXGI_FORMAT_R16_UINT,
0
);
/* Set the rest of the pipeline state */
ID3D11DeviceContext_RSSetViewports(
renderer->context,
1,
&tempViewport
);
ID3D11DeviceContext_OMSetBlendState(
renderer->context,
renderer->fauxBlendState,
blendFactor,
0xffffffff
);
ID3D11DeviceContext_OMSetDepthStencilState(
renderer->context,
NULL,
0
);
ID3D11DeviceContext_RSSetState(
renderer->context,
renderer->fauxRasterizer
);
ID3D11DeviceContext_IASetInputLayout(
renderer->context,
renderer->fauxBlitLayout
);
ID3D11DeviceContext_VSSetShader(
renderer->context,
renderer->fauxBlitVS,
NULL,
0
);
ID3D11DeviceContext_PSSetShader(
renderer->context,
renderer->fauxBlitPS,
NULL,
0
);
ID3D11DeviceContext_PSSetShaderResources(
renderer->context,
0,
1,
&renderer->backbuffer.shaderView
);
ID3D11DeviceContext_PSSetSamplers(
renderer->context,
0,
1,
&renderer->fauxBlitSampler
);
if (renderer->topology != FNA3D_PRIMITIVETYPE_TRIANGLELIST)
{
renderer->topology = FNA3D_PRIMITIVETYPE_TRIANGLELIST;
ID3D11DeviceContext_IASetPrimitiveTopology(
renderer->context,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST
);
}
/* Draw the faux backbuffer! */
ID3D11DeviceContext_DrawIndexed(renderer->context, 6, 0, 0);
/* Restore the old state */
blendFactor[0] = renderer->blendFactor.r / 255.0f;
blendFactor[1] = renderer->blendFactor.g / 255.0f;
blendFactor[2] = renderer->blendFactor.b / 255.0f;
blendFactor[3] = renderer->blendFactor.a / 255.0f;
ID3D11DeviceContext_RSSetViewports(
renderer->context,
1,
&origViewport
);
ID3D11DeviceContext_OMSetBlendState(
renderer->context,
renderer->blendState,
blendFactor,
renderer->multiSampleMask
);
ID3D11DeviceContext_OMSetDepthStencilState(
renderer->context,
renderer->depthStencilState,
renderer->stencilRef
);
ID3D11DeviceContext_RSSetState(
renderer->context,
renderer->rasterizerState
);
ID3D11DeviceContext_IASetInputLayout(
renderer->context,
renderer->inputLayout
);
ID3D11DeviceContext_VSSetShader(
renderer->context,
oldVertexShader,
NULL,
0
);
ID3D11DeviceContext_PSSetShader(
renderer->context,
oldPixelShader,
NULL,
0
);
if (oldVertexShader != NULL)
{
ID3D11VertexShader_Release(oldVertexShader);
}
if (oldPixelShader != NULL)
{
ID3D11PixelShader_Release(oldPixelShader);
}
ID3D11DeviceContext_IASetVertexBuffers(
renderer->context,
0,
MAX_BOUND_VERTEX_BUFFERS,
renderer->vertexBuffers,
renderer->vertexBufferStrides,
renderer->vertexBufferOffsets
);
ID3D11DeviceContext_IASetIndexBuffer(
renderer->context,
renderer->indexBuffer,
XNAToD3D_IndexType[renderer->indexElementSize],
0
);
ID3D11DeviceContext_PSSetShaderResources(
renderer->context,
0,
1,
&renderer->textures[0]->shaderView
);
ID3D11DeviceContext_PSSetSamplers(
renderer->context,
0,
1,
&renderer->samplers[0]
);
/* Bind the faux-backbuffer */
D3D11_SetRenderTargets(
(FNA3D_Renderer*) renderer,
NULL,
0,
NULL,
FNA3D_DEPTHFORMAT_NONE,
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_SwapBuffers(
FNA3D_Renderer *driverData,
FNA3D_Rect *sourceRectangle,
FNA3D_Rect *destinationRectangle,
void* overrideWindowHandle
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
int32_t drawableWidth, drawableHeight;
FNA3D_Rect srcRect, dstRect;
/* Determine the regions to present */
D3D11_GetDrawableSize(
overrideWindowHandle,
&drawableWidth,
&drawableHeight
);
if (sourceRectangle != NULL)
{
srcRect.x = sourceRectangle->x;
srcRect.y = sourceRectangle->y;
srcRect.w = sourceRectangle->w;
srcRect.h = sourceRectangle->h;
}
else
{
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = renderer->backbuffer.width;
srcRect.h = renderer->backbuffer.height;
}
if (destinationRectangle != NULL)
{
dstRect.x = destinationRectangle->x;
dstRect.y = destinationRectangle->y;
dstRect.w = destinationRectangle->w;
dstRect.h = destinationRectangle->h;
}
else
{
dstRect.x = 0;
dstRect.y = 0;
dstRect.w = drawableWidth;
dstRect.h = drawableHeight;
}
/* Update the cached vertex buffer, if needed */
if ( renderer->backbufferSizeChanged ||
renderer->prevSrcRect.x != srcRect.x ||
renderer->prevSrcRect.y != srcRect.y ||
renderer->prevSrcRect.w != srcRect.w ||
renderer->prevSrcRect.h != srcRect.h ||
renderer->prevDstRect.x != dstRect.x ||
renderer->prevDstRect.y != dstRect.y ||
renderer->prevDstRect.w != dstRect.w ||
renderer->prevDstRect.h != dstRect.h )
{
D3D11_INTERNAL_UpdateBackbufferVertexBuffer(
renderer,
&srcRect,
&dstRect,
drawableWidth,
drawableHeight
);
}
SDL_LockMutex(renderer->ctxLock);
/* Resolve the faux-backbuffer if needed */
if (renderer->backbuffer.multiSampleCount > 1)
{
ID3D11DeviceContext_ResolveSubresource(
renderer->context,
(ID3D11Resource*) renderer->backbuffer.resolveBuffer,
0,
(ID3D11Resource*) renderer->backbuffer.colorBuffer,
0,
XNAToD3D_TextureFormat[renderer->backbuffer.surfaceFormat]
);
}
/* "Blit" the faux-backbuffer to the swapchain image */
D3D11_INTERNAL_BlitFramebuffer(renderer, drawableWidth, drawableHeight);
SDL_UnlockMutex(renderer->ctxLock);
/* Present! */
IDXGISwapChain_Present(renderer->swapchain, renderer->syncInterval, 0);
}
/* Drawing */
static void D3D11_Clear(
FNA3D_Renderer *driverData,
FNA3D_ClearOptions options,
FNA3D_Vec4 *color,
float depth,
int32_t stencil
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
int32_t i;
uint32_t dsClearFlags;
float clearColor[4] = {color->x, color->y, color->z, color->w};
SDL_LockMutex(renderer->ctxLock);
/* Clear color? */
if (options & FNA3D_CLEAROPTIONS_TARGET)
{
for (i = 0; i < renderer->numRenderTargets; i += 1)
{
/* Clear! */
ID3D11DeviceContext_ClearRenderTargetView(
renderer->context,
renderer->renderTargetViews[i],
clearColor
);
}
}
/* Clear depth/stencil? */
dsClearFlags = 0;
if (options & FNA3D_CLEAROPTIONS_DEPTHBUFFER)
{
dsClearFlags |= D3D11_CLEAR_DEPTH;
}
if (options & FNA3D_CLEAROPTIONS_STENCIL)
{
dsClearFlags |= D3D11_CLEAR_STENCIL;
}
if (dsClearFlags != 0 && renderer->depthStencilView != NULL)
{
/* Clear! */
ID3D11DeviceContext_ClearDepthStencilView(
renderer->context,
renderer->depthStencilView,
dsClearFlags,
depth,
(uint8_t) stencil
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_DrawIndexedPrimitives(
FNA3D_Renderer *driverData,
FNA3D_PrimitiveType primitiveType,
int32_t baseVertex,
int32_t minVertexIndex,
int32_t numVertices,
int32_t startIndex,
int32_t primitiveCount,
FNA3D_Buffer *indices,
FNA3D_IndexElementSize indexElementSize
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dIndices = (D3D11Buffer*) indices;
SDL_LockMutex(renderer->ctxLock);
/* Bind index buffer */
if ( renderer->indexBuffer != d3dIndices->handle ||
renderer->indexElementSize != indexElementSize )
{
renderer->indexBuffer = d3dIndices->handle;
renderer->indexElementSize = indexElementSize;
ID3D11DeviceContext_IASetIndexBuffer(
renderer->context,
d3dIndices->handle,
XNAToD3D_IndexType[indexElementSize],
0
);
}
/* Set up draw state */
if (renderer->topology != primitiveType)
{
renderer->topology = primitiveType;
ID3D11DeviceContext_IASetPrimitiveTopology(
renderer->context,
XNAToD3D_Primitive[primitiveType]
);
}
/* Draw! */
ID3D11DeviceContext_DrawIndexed(
renderer->context,
PrimitiveVerts(primitiveType, primitiveCount),
(uint32_t) startIndex,
baseVertex
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_DrawInstancedPrimitives(
FNA3D_Renderer *driverData,
FNA3D_PrimitiveType primitiveType,
int32_t baseVertex,
int32_t minVertexIndex,
int32_t numVertices,
int32_t startIndex,
int32_t primitiveCount,
int32_t instanceCount,
FNA3D_Buffer *indices,
FNA3D_IndexElementSize indexElementSize
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dIndices = (D3D11Buffer*) indices;
SDL_LockMutex(renderer->ctxLock);
/* Bind index buffer */
if ( renderer->indexBuffer != d3dIndices->handle ||
renderer->indexElementSize != indexElementSize )
{
renderer->indexBuffer = d3dIndices->handle;
renderer->indexElementSize = indexElementSize;
ID3D11DeviceContext_IASetIndexBuffer(
renderer->context,
d3dIndices->handle,
XNAToD3D_IndexType[indexElementSize],
0
);
}
/* Set up draw state */
if (renderer->topology != primitiveType)
{
renderer->topology = primitiveType;
ID3D11DeviceContext_IASetPrimitiveTopology(
renderer->context,
XNAToD3D_Primitive[primitiveType]
);
}
/* Draw! */
ID3D11DeviceContext_DrawIndexedInstanced(
renderer->context,
PrimitiveVerts(primitiveType, primitiveCount),
instanceCount,
(uint32_t) startIndex,
baseVertex,
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_DrawPrimitives(
FNA3D_Renderer *driverData,
FNA3D_PrimitiveType primitiveType,
int32_t vertexStart,
int32_t primitiveCount
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
SDL_LockMutex(renderer->ctxLock);
/* Bind draw state */
if (renderer->topology != primitiveType)
{
renderer->topology = primitiveType;
ID3D11DeviceContext_IASetPrimitiveTopology(
renderer->context,
XNAToD3D_Primitive[primitiveType]
);
}
/* Draw! */
ID3D11DeviceContext_Draw(
renderer->context,
(uint32_t) PrimitiveVerts(primitiveType, primitiveCount),
(uint32_t) vertexStart
);
SDL_UnlockMutex(renderer->ctxLock);
}
/* Mutable Render States */
static void D3D11_SetViewport(FNA3D_Renderer *driverData, FNA3D_Viewport *viewport)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11_VIEWPORT vp =
{
(float) viewport->x,
(float) viewport->y,
(float) viewport->w,
(float) viewport->h,
viewport->minDepth,
viewport->maxDepth
};
if ( renderer->viewport.x != viewport->x ||
renderer->viewport.y != viewport->y ||
renderer->viewport.w != viewport->w ||
renderer->viewport.h != viewport->h ||
renderer->viewport.minDepth != viewport->minDepth ||
renderer->viewport.maxDepth != viewport->maxDepth )
{
SDL_LockMutex(renderer->ctxLock);
SDL_memcpy(&renderer->viewport, viewport, sizeof(FNA3D_Viewport));
ID3D11DeviceContext_RSSetViewports(
renderer->context,
1,
&vp
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_SetScissorRect(FNA3D_Renderer *driverData, FNA3D_Rect *scissor)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11_RECT rect =
{
scissor->x,
scissor->y,
scissor->x + scissor->w,
scissor->y + scissor->h
};
if ( renderer->scissorRect.x != scissor->x ||
renderer->scissorRect.y != scissor->y ||
renderer->scissorRect.w != scissor->w ||
renderer->scissorRect.h != scissor->h )
{
SDL_LockMutex(renderer->ctxLock);
SDL_memcpy(&renderer->scissorRect, scissor, sizeof(FNA3D_Rect));
ID3D11DeviceContext_RSSetScissorRects(
renderer->context,
1,
&rect
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_GetBlendFactor(
FNA3D_Renderer *driverData,
FNA3D_Color *blendFactor
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
*blendFactor = renderer->blendFactor;
}
static void D3D11_SetBlendFactor(
FNA3D_Renderer *driverData,
FNA3D_Color *blendFactor
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
float factor[4];
if (!D3D11_INTERNAL_BlendEquals(&renderer->blendFactor, blendFactor))
{
factor[0] = blendFactor->r / 255.0f;
factor[1] = blendFactor->g / 255.0f;
factor[2] = blendFactor->b / 255.0f;
factor[3] = blendFactor->a / 255.0f;
renderer->blendFactor = *blendFactor;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetBlendState(
renderer->context,
renderer->blendState,
factor,
renderer->multiSampleMask
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static int32_t D3D11_GetMultiSampleMask(FNA3D_Renderer *driverData)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
return renderer->multiSampleMask;
}
static void D3D11_SetMultiSampleMask(FNA3D_Renderer *driverData, int32_t mask)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
float factor[4];
if (renderer->multiSampleMask != mask)
{
renderer->multiSampleMask = mask;
factor[0] = renderer->blendFactor.r / 255.0f;
factor[1] = renderer->blendFactor.g / 255.0f;
factor[2] = renderer->blendFactor.b / 255.0f;
factor[3] = renderer->blendFactor.a / 255.0f;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetBlendState(
renderer->context,
renderer->blendState,
factor,
renderer->multiSampleMask
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static int32_t D3D11_GetReferenceStencil(FNA3D_Renderer *driverData)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
return renderer->stencilRef;
}
static void D3D11_SetReferenceStencil(FNA3D_Renderer *driverData, int32_t ref)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
if (renderer->stencilRef != ref)
{
renderer->stencilRef = ref;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetDepthStencilState(
renderer->context,
renderer->depthStencilState,
(uint32_t) renderer->stencilRef
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
/* Immutable Render States */
static void D3D11_SetBlendState(
FNA3D_Renderer *driverData,
FNA3D_BlendState *blendState
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
ID3D11BlendState *bs = D3D11_INTERNAL_FetchBlendState(renderer, blendState);
float factor[4];
if ( renderer->blendState != bs ||
!D3D11_INTERNAL_BlendEquals(&renderer->blendFactor, &blendState->blendFactor) ||
renderer->multiSampleMask != blendState->multiSampleMask )
{
renderer->blendState = bs;
factor[0] = blendState->blendFactor.r / 255.0f;
factor[1] = blendState->blendFactor.g / 255.0f;
factor[2] = blendState->blendFactor.b / 255.0f;
factor[3] = blendState->blendFactor.a / 255.0f;
renderer->blendFactor = blendState->blendFactor;
renderer->multiSampleMask = blendState->multiSampleMask;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetBlendState(
renderer->context,
bs,
factor,
(uint32_t) renderer->multiSampleMask
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_SetDepthStencilState(
FNA3D_Renderer *driverData,
FNA3D_DepthStencilState *depthStencilState
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
ID3D11DepthStencilState *ds = D3D11_INTERNAL_FetchDepthStencilState(
renderer,
depthStencilState
);
if ( renderer->depthStencilState != ds ||
renderer->stencilRef != depthStencilState->referenceStencil )
{
renderer->depthStencilState = ds;
renderer->stencilRef = depthStencilState->referenceStencil;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetDepthStencilState(
renderer->context,
ds,
(uint32_t) renderer->stencilRef
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_ApplyRasterizerState(
FNA3D_Renderer *driverData,
FNA3D_RasterizerState *rasterizerState
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
ID3D11RasterizerState *rs = D3D11_INTERNAL_FetchRasterizerState(
renderer,
rasterizerState
);
if (renderer->rasterizerState != rs)
{
renderer->rasterizerState = rs;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_RSSetState(
renderer->context,
rs
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_VerifySampler(
FNA3D_Renderer *driverData,
int32_t index,
FNA3D_Texture *texture,
FNA3D_SamplerState *sampler
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *d3dTexture = (D3D11Texture*) texture;
ID3D11SamplerState *d3dSamplerState;
if (texture == NULL)
{
if (renderer->textures[index] != &NullTexture)
{
renderer->textures[index] = &NullTexture;
renderer->samplers[index] = NULL;
SDL_LockMutex(renderer->ctxLock);
if (index < MAX_TEXTURE_SAMPLERS)
{
ID3D11DeviceContext_PSSetShaderResources(
renderer->context,
index,
1,
&NullTexture.shaderView
);
ID3D11DeviceContext_PSSetSamplers(
renderer->context,
index,
1,
&renderer->samplers[index]
);
}
else
{
ID3D11DeviceContext_VSSetShaderResources(
renderer->context,
index - MAX_TEXTURE_SAMPLERS,
1,
&NullTexture.shaderView
);
ID3D11DeviceContext_VSSetSamplers(
renderer->context,
index - MAX_TEXTURE_SAMPLERS,
1,
&renderer->samplers[index]
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
return;
}
/* Bind the correct texture */
if (d3dTexture != renderer->textures[index])
{
renderer->textures[index] = d3dTexture;
SDL_LockMutex(renderer->ctxLock);
if (index < MAX_TEXTURE_SAMPLERS)
{
ID3D11DeviceContext_PSSetShaderResources(
renderer->context,
index,
1,
&d3dTexture->shaderView
);
}
else
{
ID3D11DeviceContext_VSSetShaderResources(
renderer->context,
index - MAX_TEXTURE_SAMPLERS,
1,
&d3dTexture->shaderView
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
/* Update the sampler state, if needed */
d3dSamplerState = D3D11_INTERNAL_FetchSamplerState(
renderer,
sampler
);
if (d3dSamplerState != renderer->samplers[index])
{
renderer->samplers[index] = d3dSamplerState;
SDL_LockMutex(renderer->ctxLock);
if (index < MAX_TEXTURE_SAMPLERS)
{
ID3D11DeviceContext_PSSetSamplers(
renderer->context,
index,
1,
&d3dSamplerState
);
}
else
{
ID3D11DeviceContext_VSSetSamplers(
renderer->context,
index - MAX_TEXTURE_SAMPLERS,
1,
&d3dSamplerState
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
}
static void D3D11_VerifyVertexSampler(
FNA3D_Renderer *driverData,
int32_t index,
FNA3D_Texture *texture,
FNA3D_SamplerState *sampler
) {
D3D11_VerifySampler(
driverData,
MAX_TEXTURE_SAMPLERS + index,
texture,
sampler
);
}
static void D3D11_ApplyVertexBufferBindings(
FNA3D_Renderer *driverData,
FNA3D_VertexBufferBinding *bindings,
int32_t numBindings,
uint8_t bindingsUpdated,
int32_t baseVertex
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *vertexBuffer;
ID3D11InputLayout *inputLayout;
int32_t i, stride, offset;
uint32_t hash;
if (!bindingsUpdated && !renderer->effectApplied)
{
return;
}
/* Translate the bindings array into an input layout */
inputLayout = D3D11_INTERNAL_FetchBindingsInputLayout(
renderer,
bindings,
numBindings,
&hash
);
SDL_LockMutex(renderer->ctxLock);
if (renderer->inputLayout != inputLayout)
{
renderer->inputLayout = inputLayout;
ID3D11DeviceContext_IASetInputLayout(
renderer->context,
inputLayout
);
}
/* Bind the vertex buffers */
for (i = 0; i < numBindings; i += 1)
{
vertexBuffer = (D3D11Buffer*) bindings[i].vertexBuffer;
stride = bindings[i].vertexDeclaration.vertexStride;
if ( renderer->vertexBuffers[i] != vertexBuffer->handle ||
renderer->vertexBufferStrides[i] != stride ||
renderer->vertexBufferOffsets[i] != bindings[i].vertexOffset )
{
renderer->vertexBuffers[i] = vertexBuffer->handle;
if (vertexBuffer == NULL)
{
renderer->vertexBufferStrides[i] = 0;
renderer->vertexBufferOffsets[i] = 0;
continue;
}
offset = bindings[i].vertexOffset * stride;
ID3D11DeviceContext_IASetVertexBuffers(
renderer->context,
i,
1,
&vertexBuffer->handle,
(uint32_t*) &stride,
(uint32_t*) &offset
);
renderer->vertexBufferOffsets[i] = offset;
renderer->vertexBufferStrides[i] = stride;
}
}
SDL_UnlockMutex(renderer->ctxLock);
MOJOSHADER_d3d11ProgramReady((unsigned long long) hash);
renderer->effectApplied = 0;
}
/* Render Targets */
static void D3D11_INTERNAL_RestoreTargetTextures(D3D11Renderer *renderer)
{
/* For textures that were bound while this target was active, rebind.
* D3D11 implicitly unsets these to prevent simultaneous read/write.
* -flibit
*/
int32_t i, j, k;
uint8_t bound;
for (i = 0; i < renderer->numRenderTargets; i += 1)
{
const ID3D11RenderTargetView *view = renderer->renderTargetViews[i];
for (j = 0; j < MAX_TOTAL_SAMPLERS; j += 1)
{
const D3D11Texture *texture = renderer->textures[j];
if (!texture->isRenderTarget)
{
continue;
}
if (texture->rtType == FNA3D_RENDERTARGET_TYPE_2D)
{
bound = (texture->twod.rtView == view);
}
else
{
bound = 0;
for (k = 0; k < 6; k += 1)
{
if (texture->cube.rtViews[k] == view)
{
bound = 1;
break;
}
}
}
if (bound)
{
if (j < MAX_TEXTURE_SAMPLERS)
{
ID3D11DeviceContext_PSSetShaderResources(
renderer->context,
j,
1,
&texture->shaderView
);
ID3D11DeviceContext_PSSetSamplers(
renderer->context,
j,
1,
&renderer->samplers[j]
);
}
else
{
ID3D11DeviceContext_VSSetShaderResources(
renderer->context,
j - MAX_TEXTURE_SAMPLERS,
1,
&texture->shaderView
);
ID3D11DeviceContext_VSSetSamplers(
renderer->context,
j - MAX_TEXTURE_SAMPLERS,
1,
&renderer->samplers[j]
);
}
}
}
}
}
static void D3D11_SetRenderTargets(
FNA3D_Renderer *driverData,
FNA3D_RenderTargetBinding *renderTargets,
int32_t numRenderTargets,
FNA3D_Renderbuffer *depthStencilBuffer,
FNA3D_DepthFormat depthFormat,
uint8_t preserveTargetContents
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *tex;
D3D11Renderbuffer *rb;
ID3D11RenderTargetView *views[MAX_RENDERTARGET_BINDINGS];
int32_t i;
/* Bind the backbuffer, if applicable */
if (renderTargets == NULL)
{
views[0] = renderer->backbuffer.colorView;
renderer->currentDepthFormat = renderer->backbuffer.depthFormat;
renderer->depthStencilView = renderer->backbuffer.depthStencilView;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetRenderTargets(
renderer->context,
1,
views,
renderer->depthStencilView
);
D3D11_INTERNAL_RestoreTargetTextures(renderer);
SDL_UnlockMutex(renderer->ctxLock);
renderer->renderTargetViews[0] = views[0];
for (i = 1; i < MAX_RENDERTARGET_BINDINGS; i += 1)
{
renderer->renderTargetViews[i] = NULL;
}
renderer->numRenderTargets = 1;
return;
}
/* Update color buffers */
for (i = 0; i < numRenderTargets; i += 1)
{
if (renderTargets[i].colorBuffer != NULL)
{
rb = (D3D11Renderbuffer*) renderTargets[i].colorBuffer;
views[i] = rb->color.rtView;
}
else
{
tex = (D3D11Texture*) renderTargets[i].texture;
if (tex->rtType == FNA3D_RENDERTARGET_TYPE_2D)
{
views[i] = tex->twod.rtView;
}
else if (tex->rtType == FNA3D_RENDERTARGET_TYPE_CUBE)
{
views[i] = tex->cube.rtViews[
renderTargets[i].cube.face
];
}
}
}
while (i < MAX_RENDERTARGET_BINDINGS)
{
views[i++] = NULL;
}
/* Update depth stencil buffer */
renderer->depthStencilView = (
depthStencilBuffer == NULL ?
NULL :
((D3D11Renderbuffer*) depthStencilBuffer)->depth.dsView
);
renderer->currentDepthFormat = (
depthStencilBuffer == NULL ?
FNA3D_DEPTHFORMAT_NONE :
depthFormat
);
/* Actually set the render targets, finally. */
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_OMSetRenderTargets(
renderer->context,
numRenderTargets,
views,
renderer->depthStencilView
);
D3D11_INTERNAL_RestoreTargetTextures(renderer);
SDL_UnlockMutex(renderer->ctxLock);
/* Remember color attachments */
SDL_memcpy(renderer->renderTargetViews, views, sizeof(views));
renderer->numRenderTargets = numRenderTargets;
}
static void D3D11_ResolveTarget(
FNA3D_Renderer *driverData,
FNA3D_RenderTargetBinding *target
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *tex = (D3D11Texture*) target->texture;
D3D11Renderbuffer *rb = (D3D11Renderbuffer*) target->colorBuffer;
uint32_t slice = 0;
SDL_LockMutex(renderer->ctxLock);
if (target->multiSampleCount > 0)
{
if (target->type == FNA3D_RENDERTARGET_TYPE_CUBE)
{
slice = target->cube.face;
}
ID3D11DeviceContext_ResolveSubresource(
renderer->context,
(ID3D11Resource*) tex->handle,
D3D11_INTERNAL_CalcSubresource(0, slice, tex->levelCount),
(ID3D11Resource*) rb->handle,
0,
XNAToD3D_TextureFormat[tex->format]
);
}
/* If the target has mipmaps, regenerate them now */
if (target->levelCount > 1)
{
ID3D11DeviceContext_GenerateMips(
renderer->context,
tex->shaderView
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
/* Backbuffer Functions */
static void D3D11_INTERNAL_CreateFramebuffer(
D3D11Renderer *renderer,
FNA3D_PresentationParameters *presentationParameters
) {
int32_t w, h;
HRESULT res;
D3D11_TEXTURE2D_DESC colorBufferDesc;
D3D11_RENDER_TARGET_VIEW_DESC colorViewDesc;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderViewDesc;
D3D11_TEXTURE2D_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_RENDER_TARGET_VIEW_DESC swapchainViewDesc;
ID3D11Texture2D *swapchainTexture;
#define BB renderer->backbuffer
/* Update the backbuffer size */
w = presentationParameters->backBufferWidth;
h = presentationParameters->backBufferHeight;
if (BB.width != w || BB.height != h)
{
renderer->backbufferSizeChanged = 1;
}
BB.width = w;
BB.height = h;
/* Update other presentation parameters */
BB.surfaceFormat = presentationParameters->backBufferFormat;
BB.depthFormat = presentationParameters->depthStencilFormat;
BB.multiSampleCount = presentationParameters->multiSampleCount;
/* Update color buffer to the new resolution */
colorBufferDesc.Width = BB.width;
colorBufferDesc.Height = BB.height;
colorBufferDesc.MipLevels = 1;
colorBufferDesc.ArraySize = 1;
colorBufferDesc.Format = XNAToD3D_TextureFormat[BB.surfaceFormat];
colorBufferDesc.SampleDesc.Count = (BB.multiSampleCount > 1 ? BB.multiSampleCount : 1);
colorBufferDesc.SampleDesc.Quality = 0;
colorBufferDesc.Usage = D3D11_USAGE_DEFAULT;
colorBufferDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
if (BB.multiSampleCount <= 1)
{
colorBufferDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
}
colorBufferDesc.CPUAccessFlags = 0;
colorBufferDesc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&colorBufferDesc,
NULL,
&BB.colorBuffer
);
ERROR_CHECK_RETURN("Backbuffer color buffer creation failed",)
/* Update color buffer view */
colorViewDesc.Format = colorBufferDesc.Format;
if (BB.multiSampleCount > 1)
{
colorViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
}
else
{
colorViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
colorViewDesc.Texture2D.MipSlice = 0;
}
res = ID3D11Device_CreateRenderTargetView(
renderer->device,
(ID3D11Resource*) BB.colorBuffer,
&colorViewDesc,
&BB.colorView
);
ERROR_CHECK_RETURN("Backbuffer color buffer RT view creation failed",)
/* Update resolve texture, if applicable */
if (BB.multiSampleCount > 1)
{
colorBufferDesc.Width = BB.width;
colorBufferDesc.Height = BB.height;
colorBufferDesc.MipLevels = 1;
colorBufferDesc.ArraySize = 1;
colorBufferDesc.Format = XNAToD3D_TextureFormat[BB.surfaceFormat];
colorBufferDesc.SampleDesc.Count = 1;
colorBufferDesc.SampleDesc.Quality = 0;
colorBufferDesc.Usage = D3D11_USAGE_DEFAULT;
colorBufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
colorBufferDesc.CPUAccessFlags = 0;
colorBufferDesc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&colorBufferDesc,
NULL,
&BB.resolveBuffer
);
ERROR_CHECK_RETURN("Backbuffer multisample resolve buffer creation failed",)
}
/* Update shader resource view */
shaderViewDesc.Format = colorBufferDesc.Format;
shaderViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderViewDesc.Texture2D.MipLevels = 1;
shaderViewDesc.Texture2D.MostDetailedMip = 0;
res = ID3D11Device_CreateShaderResourceView(
renderer->device,
(ID3D11Resource*) ((BB.multiSampleCount > 1) ? BB.resolveBuffer : BB.colorBuffer),
&shaderViewDesc,
&BB.shaderView
);
ERROR_CHECK_RETURN("Backbuffer shader view creation failed",)
/* Update the depth/stencil buffer, if applicable */
if (BB.depthFormat != FNA3D_DEPTHFORMAT_NONE)
{
depthStencilDesc.Width = BB.width;
depthStencilDesc.Height = BB.height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = XNAToD3D_DepthFormat[BB.depthFormat];
depthStencilDesc.SampleDesc.Count = (BB.multiSampleCount > 1 ? BB.multiSampleCount : 1);
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&depthStencilDesc,
NULL,
&BB.depthStencilBuffer
);
ERROR_CHECK_RETURN("Backbuffer depth-stencil buffer creation failed",)
/* Update the depth-stencil view */
depthStencilViewDesc.Format = depthStencilDesc.Format;
depthStencilViewDesc.Flags = 0;
if (BB.multiSampleCount > 1)
{
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
}
else
{
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
}
res = ID3D11Device_CreateDepthStencilView(
renderer->device,
(ID3D11Resource*) BB.depthStencilBuffer,
&depthStencilViewDesc,
&BB.depthStencilView
);
ERROR_CHECK_RETURN("Backbuffer depth-stencil view creation failed",)
}
/* Create the swapchain */
if (renderer->swapchain == NULL)
{
D3D11_PLATFORM_CreateSwapChain(renderer, presentationParameters);
}
else
{
/* Resize the swapchain to the new window size */
res = IDXGISwapChain_ResizeBuffers(
renderer->swapchain,
0, /* keep # of buffers the same */
0, /* get width from window */
0, /* get height from window */
DXGI_FORMAT_UNKNOWN, /* keep the old format */
0
);
ERROR_CHECK_RETURN("Could not resize swapchain",)
}
/* Create a render target view for the swapchain */
swapchainViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapchainViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
swapchainViewDesc.Texture2D.MipSlice = 0;
res = IDXGISwapChain_GetBuffer(
renderer->swapchain,
0,
&D3D_IID_ID3D11Texture2D,
(void**) &swapchainTexture
);
ERROR_CHECK_RETURN("Could not get buffer from swapchain",)
res = ID3D11Device_CreateRenderTargetView(
renderer->device,
(ID3D11Resource*) swapchainTexture,
&swapchainViewDesc,
&renderer->swapchainRTView
);
ERROR_CHECK_RETURN("Swapchain RT view creation failed",)
/* Cleanup is required for any GetBuffer call! */
ID3D11Texture2D_Release(swapchainTexture);
swapchainTexture = NULL;
/* This is the default render target */
D3D11_SetRenderTargets(
(FNA3D_Renderer*) renderer,
NULL,
0,
NULL,
FNA3D_DEPTHFORMAT_NONE,
0
);
#undef BB
}
static void D3D11_INTERNAL_DestroyFramebuffer(D3D11Renderer *renderer)
{
#define BB renderer->backbuffer
if (BB.colorBuffer != NULL)
{
ID3D11RenderTargetView_Release(BB.colorView);
BB.colorView = NULL;
ID3D11ShaderResourceView_Release(BB.shaderView);
BB.shaderView = NULL;
ID3D11Texture2D_Release(BB.colorBuffer);
BB.colorBuffer = NULL;
}
if (BB.stagingBuffer != NULL)
{
ID3D11Texture2D_Release(BB.stagingBuffer);
BB.stagingBuffer = NULL;
}
if (BB.depthStencilBuffer != NULL)
{
ID3D11DepthStencilView_Release(BB.depthStencilView);
BB.depthStencilView = NULL;
ID3D11Texture2D_Release(BB.depthStencilBuffer);
BB.depthStencilBuffer = NULL;
}
if (BB.resolveBuffer != NULL)
{
ID3D11Texture2D_Release(BB.resolveBuffer);
BB.resolveBuffer = NULL;
}
if (renderer->swapchainRTView != NULL)
{
ID3D11RenderTargetView_Release(renderer->swapchainRTView);
renderer->swapchainRTView = NULL;
}
#undef BB
}
static void D3D11_INTERNAL_SetPresentationInterval(
D3D11Renderer *renderer,
FNA3D_PresentInterval presentInterval
) {
if ( presentInterval == FNA3D_PRESENTINTERVAL_DEFAULT ||
presentInterval == FNA3D_PRESENTINTERVAL_ONE )
{
renderer->syncInterval = 1;
}
else if (presentInterval == FNA3D_PRESENTINTERVAL_TWO)
{
renderer->syncInterval = 2;
}
else if (presentInterval == FNA3D_PRESENTINTERVAL_IMMEDIATE)
{
renderer->syncInterval = 0;
}
else
{
FNA3D_LogError(
"Unrecognized PresentInterval: %d",
presentInterval
);
}
}
static void D3D11_ResetBackbuffer(
FNA3D_Renderer *driverData,
FNA3D_PresentationParameters *presentationParameters
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11_INTERNAL_DestroyFramebuffer(renderer);
D3D11_INTERNAL_CreateFramebuffer(
renderer,
presentationParameters
);
D3D11_INTERNAL_SetPresentationInterval(
renderer,
presentationParameters->presentationInterval
);
}
static void D3D11_ReadBackbuffer(
FNA3D_Renderer *driverData,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture backbufferTexture;
if (renderer->backbuffer.multiSampleCount > 1)
{
/* We have to resolve the backbuffer first. */
ID3D11DeviceContext_ResolveSubresource(
renderer->context,
(ID3D11Resource*) renderer->backbuffer.resolveBuffer,
0,
(ID3D11Resource*) renderer->backbuffer.colorBuffer,
0,
XNAToD3D_TextureFormat[renderer->backbuffer.surfaceFormat]
);
}
/* Create a pseudo-texture we can feed to GetTextureData2D.
* These are the only members we need to initialize.
* -caleb
*/
backbufferTexture.twod.width = renderer->backbuffer.width;
backbufferTexture.twod.height = renderer->backbuffer.height;
backbufferTexture.format = renderer->backbuffer.surfaceFormat;
backbufferTexture.levelCount = 1;
backbufferTexture.handle = (
renderer->backbuffer.multiSampleCount > 1 ?
(ID3D11Resource*) renderer->backbuffer.resolveBuffer :
(ID3D11Resource*) renderer->backbuffer.colorBuffer
);
backbufferTexture.staging = (ID3D11Resource*) renderer->backbuffer.stagingBuffer;
D3D11_GetTextureData2D(
driverData,
(FNA3D_Texture*) &backbufferTexture,
x,
y,
w,
h,
0,
data,
dataLength
);
}
static void D3D11_GetBackbufferSize(
FNA3D_Renderer *driverData,
int32_t *w,
int32_t *h
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
*w = renderer->backbuffer.width;
*h = renderer->backbuffer.height;
}
static FNA3D_SurfaceFormat D3D11_GetBackbufferSurfaceFormat(
FNA3D_Renderer *driverData
) {
return ((D3D11Renderer*) driverData)->backbuffer.surfaceFormat;
}
static FNA3D_DepthFormat D3D11_GetBackbufferDepthFormat(
FNA3D_Renderer *driverData
) {
return ((D3D11Renderer*) driverData)->backbuffer.depthFormat;
}
static int32_t D3D11_GetBackbufferMultiSampleCount(
FNA3D_Renderer *driverData
) {
return ((D3D11Renderer*) driverData)->backbuffer.multiSampleCount;
}
/* Textures */
static FNA3D_Texture* D3D11_CreateTexture2D(
FNA3D_Renderer *driverData,
FNA3D_SurfaceFormat format,
int32_t width,
int32_t height,
int32_t levelCount,
uint8_t isRenderTarget
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *result;
ID3D11Texture2D *texture;
D3D11_TEXTURE2D_DESC desc;
D3D11_RENDER_TARGET_VIEW_DESC rtViewDesc;
HRESULT res;
/* Initialize descriptor */
desc.Width = width;
desc.Height = height;
desc.MipLevels = levelCount;
desc.ArraySize = 1;
desc.Format = XNAToD3D_TextureFormat[format];
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
if (isRenderTarget)
{
desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
}
/* Create the texture */
res = ID3D11Device_CreateTexture2D(
renderer->device,
&desc,
NULL,
&texture
);
ERROR_CHECK_RETURN("Texture2D creation failed", NULL)
/* Initialize D3D11Texture */
result = (D3D11Texture*) SDL_malloc(sizeof(D3D11Texture));
SDL_memset(result, '\0', sizeof(D3D11Texture));
result->handle = (ID3D11Resource*) texture;
result->levelCount = levelCount;
result->isRenderTarget = isRenderTarget;
result->format = format;
result->twod.width = width;
result->twod.height = height;
/* Create the shader resource view */
res = ID3D11Device_CreateShaderResourceView(
renderer->device,
result->handle,
NULL,
&result->shaderView
);
ERROR_CHECK_RETURN("Texture2D shader view creation failed", NULL)
/* Create the render target view, if applicable */
if (isRenderTarget)
{
result->rtType = FNA3D_RENDERTARGET_TYPE_2D;
rtViewDesc.Format = desc.Format;
rtViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
rtViewDesc.Texture2D.MipSlice = 0;
res = ID3D11Device_CreateRenderTargetView(
renderer->device,
result->handle,
&rtViewDesc,
&result->twod.rtView
);
ERROR_CHECK_RETURN("Texture2D render target creation failed", NULL)
}
return (FNA3D_Texture*) result;
}
static FNA3D_Texture* D3D11_CreateTexture3D(
FNA3D_Renderer *driverData,
FNA3D_SurfaceFormat format,
int32_t width,
int32_t height,
int32_t depth,
int32_t levelCount
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *result;
ID3D11Texture3D *texture;
D3D11_TEXTURE3D_DESC desc;
HRESULT res;
/* Initialize descriptor */
desc.Width = width;
desc.Height = height;
desc.Depth = depth;
desc.MipLevels = levelCount;
desc.Format = XNAToD3D_TextureFormat[format];
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
/* Create the texture */
res = ID3D11Device_CreateTexture3D(
renderer->device,
&desc,
NULL,
&texture
);
ERROR_CHECK_RETURN("Texture3D creation failed", NULL)
/* Initialize D3D11Texture */
result = (D3D11Texture*) SDL_malloc(sizeof(D3D11Texture));
SDL_memset(result, '\0', sizeof(D3D11Texture));
result->handle = (ID3D11Resource*) texture;
result->levelCount = levelCount;
result->isRenderTarget = 0;
result->format = format;
result->threed.width = width;
result->threed.height = height;
result->threed.depth = depth;
/* Create the shader resource view */
res = ID3D11Device_CreateShaderResourceView(
renderer->device,
result->handle,
NULL,
&result->shaderView
);
ERROR_CHECK_RETURN("Texture3D shader view creation failed", NULL)
return (FNA3D_Texture*) result;
}
static FNA3D_Texture* D3D11_CreateTextureCube(
FNA3D_Renderer *driverData,
FNA3D_SurfaceFormat format,
int32_t size,
int32_t levelCount,
uint8_t isRenderTarget
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *result;
ID3D11Texture2D *texture;
D3D11_TEXTURE2D_DESC desc;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
D3D11_RENDER_TARGET_VIEW_DESC rtViewDesc;
int32_t i;
HRESULT res;
/* Initialize descriptor */
desc.Width = size;
desc.Height = size;
desc.MipLevels = levelCount;
desc.ArraySize = 6;
desc.Format = XNAToD3D_TextureFormat[format];
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
if (isRenderTarget)
{
desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
desc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
}
/* Create the texture */
res = ID3D11Device_CreateTexture2D(
renderer->device,
&desc,
NULL,
&texture
);
ERROR_CHECK_RETURN("TextureCube creation failed", NULL)
/* Initialize D3D11Texture */
result = (D3D11Texture*) SDL_malloc(sizeof(D3D11Texture));
SDL_memset(result, '\0', sizeof(D3D11Texture));
result->handle = (ID3D11Resource*) texture;
result->levelCount = levelCount;
result->isRenderTarget = isRenderTarget;
result->format = format;
result->cube.size = size;
/* Create the shader resource view */
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
srvDesc.TextureCube.MipLevels = levelCount;
srvDesc.TextureCube.MostDetailedMip = 0;
res = ID3D11Device_CreateShaderResourceView(
renderer->device,
result->handle,
&srvDesc,
&result->shaderView
);
ERROR_CHECK_RETURN("TextureCube shader view creation failed", NULL)
/* Create the render target view, if applicable */
if (isRenderTarget)
{
result->rtType = FNA3D_RENDERTARGET_TYPE_CUBE;
result->cube.rtViews = (ID3D11RenderTargetView**) SDL_malloc(
6 * sizeof(ID3D11RenderTargetView*)
);
rtViewDesc.Format = desc.Format;
rtViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
rtViewDesc.Texture2DArray.ArraySize = 1; /* One slice per view */
rtViewDesc.Texture2DArray.MipSlice = 0;
for (i = 0; i < 6; i += 1)
{
rtViewDesc.Texture2DArray.FirstArraySlice = i;
res = ID3D11Device_CreateRenderTargetView(
renderer->device,
result->handle,
&rtViewDesc,
&result->cube.rtViews[i]
);
ERROR_CHECK_RETURN("TextureCube render target view creation failed", NULL)
}
}
return (FNA3D_Texture*) result;
}
static void D3D11_AddDisposeTexture(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *tex = (D3D11Texture*) texture;
int32_t i, j;
/* Unbind the texture */
for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1)
{
if (renderer->textures[i] == tex)
{
renderer->textures[i] = &NullTexture;
}
}
/* Unbind and release the render target views, if applicable */
if (tex->isRenderTarget)
{
for (i = 0; i < renderer->numRenderTargets; i += 1)
{
if (tex->rtType == FNA3D_RENDERTARGET_TYPE_2D)
{
if (tex->twod.rtView == renderer->renderTargetViews[i])
{
renderer->renderTargetViews[i] = NULL;
}
}
else if (tex->rtType == FNA3D_RENDERTARGET_TYPE_CUBE)
{
for (j = 0; j < 6; j += 1)
{
if (tex->cube.rtViews[j] == renderer->renderTargetViews[i])
{
renderer->renderTargetViews[i] = NULL;
}
}
}
}
if (tex->rtType == FNA3D_RENDERTARGET_TYPE_2D)
{
ID3D11RenderTargetView_Release(tex->twod.rtView);
}
else if (tex->rtType == FNA3D_RENDERTARGET_TYPE_CUBE)
{
for (i = 0; i < 6; i += 1)
{
ID3D11RenderTargetView_Release(tex->cube.rtViews[i]);
}
SDL_free(tex->cube.rtViews);
}
}
/* Release the shader resource view and texture */
ID3D11ShaderResourceView_Release(tex->shaderView);
IUnknown_Release(tex->handle);
SDL_free(texture);
}
static void D3D11_SetTextureData2D(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
int32_t level,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *d3dTexture = (D3D11Texture*) texture;
D3D11_BOX dstBox;
/* DXT formats require w and h to be multiples of 4 */
if ( d3dTexture->format == FNA3D_SURFACEFORMAT_DXT1 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT3 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT5 )
{
w = (w + 3) & ~3;
h = (h + 3) & ~3;
}
dstBox.left = x;
dstBox.top = y;
dstBox.front = 0;
dstBox.right = x + w;
dstBox.bottom = y + h;
dstBox.back = 1;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dTexture->handle,
D3D11_INTERNAL_CalcSubresource(level, 0, d3dTexture->levelCount),
&dstBox,
data,
BytesPerRow(w, d3dTexture->format),
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_SetTextureData3D(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t z,
int32_t w,
int32_t h,
int32_t d,
int32_t level,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *d3dTexture = (D3D11Texture*) texture;
D3D11_BOX dstBox;
/* DXT formats require w and h to be multiples of 4 */
if ( d3dTexture->format == FNA3D_SURFACEFORMAT_DXT1 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT3 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT5 )
{
w = (w + 3) & ~3;
h = (h + 3) & ~3;
}
dstBox.left = x;
dstBox.top = y;
dstBox.front = z;
dstBox.right = x + w;
dstBox.bottom = y + h;
dstBox.back = z + d;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dTexture->handle,
D3D11_INTERNAL_CalcSubresource(level, 0, d3dTexture->levelCount),
&dstBox,
data,
BytesPerRow(w, d3dTexture->format),
BytesPerImage(w, h, d3dTexture->format)
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_SetTextureDataCube(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
FNA3D_CubeMapFace cubeMapFace,
int32_t level,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *d3dTexture = (D3D11Texture*) texture;
D3D11_BOX dstBox;
/* DXT formats require w and h to be multiples of 4 */
if ( d3dTexture->format == FNA3D_SURFACEFORMAT_DXT1 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT3 ||
d3dTexture->format == FNA3D_SURFACEFORMAT_DXT5 )
{
w = (w + 3) & ~3;
h = (h + 3) & ~3;
}
dstBox.left = x;
dstBox.top = y;
dstBox.front = 0;
dstBox.right = x + w;
dstBox.bottom = y + h;
dstBox.back = 1;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dTexture->handle,
D3D11_INTERNAL_CalcSubresource(
level,
cubeMapFace,
d3dTexture->levelCount
),
&dstBox,
data,
BytesPerRow(w, d3dTexture->format),
BytesPerImage(w, h, d3dTexture->format)
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_SetTextureDataYUV(
FNA3D_Renderer *driverData,
FNA3D_Texture *y,
FNA3D_Texture *u,
FNA3D_Texture *v,
int32_t yWidth,
int32_t yHeight,
int32_t uvWidth,
int32_t uvHeight,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *d3dY = (D3D11Texture*) y;
D3D11Texture *d3dU = (D3D11Texture*) u;
D3D11Texture *d3dV = (D3D11Texture*) v;
D3D11_BOX yBox = {0, 0, 0, yWidth, yHeight, 1};
D3D11_BOX uvBox = {0, 0, 0, uvWidth, uvHeight, 1};
int32_t yRow, uvRow;
uint8_t *dataPtr = (uint8_t*) data;
yRow = BytesPerRow(yWidth, FNA3D_SURFACEFORMAT_ALPHA8);
uvRow = BytesPerRow(uvWidth, FNA3D_SURFACEFORMAT_ALPHA8);
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dY->handle,
0,
&yBox,
dataPtr,
yRow,
0
);
dataPtr += yWidth * yHeight;
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dU->handle,
0,
&uvBox,
dataPtr,
uvRow,
0
);
dataPtr += uvWidth * uvHeight;
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
d3dV->handle,
0,
&uvBox,
dataPtr,
uvRow,
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_GetTextureData2D(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
int32_t level,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *tex = (D3D11Texture*) texture;
D3D11_TEXTURE2D_DESC stagingDesc;
ID3D11Resource *stagingTexture;
uint32_t subresourceIndex = D3D11_INTERNAL_CalcSubresource(
level,
0,
tex->levelCount
);
int32_t texW = tex->twod.width >> level;
int32_t texH = tex->twod.height >> level;
D3D11_BOX srcBox = {0, 0, 0, texW, texH, 1};
D3D11_MAPPED_SUBRESOURCE subresource;
uint8_t *dataPtr = (uint8_t*) data;
int32_t row;
int32_t formatSize = Texture_GetFormatSize(tex->format);
HRESULT res;
if ( tex->format == FNA3D_SURFACEFORMAT_DXT1 ||
tex->format == FNA3D_SURFACEFORMAT_DXT3 ||
tex->format == FNA3D_SURFACEFORMAT_DXT5 )
{
FNA3D_LogError(
"GetData with compressed textures unsupported!"
);
return;
}
/* Create staging texture if needed */
if (tex->isRenderTarget)
{
stagingTexture = tex->staging;
}
else
{
stagingTexture = NULL;
}
if (stagingTexture == NULL)
{
stagingDesc.Width = tex->twod.width;
stagingDesc.Height = tex->twod.height;
stagingDesc.MipLevels = tex->levelCount;
stagingDesc.ArraySize = 1;
stagingDesc.Format = XNAToD3D_TextureFormat[tex->format];
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&stagingDesc,
NULL,
(ID3D11Texture2D**) &stagingTexture
);
ERROR_CHECK_RETURN("Texture2D staging buffer creation failed",)
/* Targets will probably call this a lot, so try to keep this all the time */
if (tex->isRenderTarget)
{
tex->staging = stagingTexture;
}
}
SDL_LockMutex(renderer->ctxLock);
/* Copy data into staging texture */
ID3D11DeviceContext_CopySubresourceRegion(
renderer->context,
stagingTexture,
subresourceIndex,
0,
0,
0,
tex->handle,
subresourceIndex,
&srcBox
);
/* Read from the staging texture */
res = ID3D11DeviceContext_Map(
renderer->context,
stagingTexture,
subresourceIndex,
D3D11_MAP_READ,
0,
&subresource
);
ERROR_CHECK_UNLOCK_RETURN("Could not map Texture2D for reading",)
for (row = y; row < y + h; row += 1)
{
SDL_memcpy(
dataPtr,
(uint8_t*) subresource.pData + (row * subresource.RowPitch) + (x * formatSize),
formatSize * w
);
dataPtr += formatSize * w;
}
ID3D11DeviceContext_Unmap(
renderer->context,
stagingTexture,
subresourceIndex
);
SDL_UnlockMutex(renderer->ctxLock);
if (!tex->isRenderTarget)
{
ID3D11Resource_Release(stagingTexture);
}
}
static void D3D11_GetTextureData3D(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t z,
int32_t w,
int32_t h,
int32_t d,
int32_t level,
void* data,
int32_t dataLength
) {
FNA3D_LogError(
"GetTextureData3D is unsupported!"
);
}
static void D3D11_GetTextureDataCube(
FNA3D_Renderer *driverData,
FNA3D_Texture *texture,
int32_t x,
int32_t y,
int32_t w,
int32_t h,
FNA3D_CubeMapFace cubeMapFace,
int32_t level,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Texture *tex = (D3D11Texture*) texture;
D3D11_TEXTURE2D_DESC stagingDesc;
ID3D11Resource *stagingTexture;
uint32_t srcSubresourceIndex = D3D11_INTERNAL_CalcSubresource(
level,
cubeMapFace,
tex->levelCount
);
uint32_t dstSubresourceIndex = D3D11_INTERNAL_CalcSubresource(
level,
0,
tex->levelCount
);
int32_t texSize = tex->cube.size >> level;
D3D11_BOX srcBox = {0, 0, 0, texSize, texSize, 1};
D3D11_MAPPED_SUBRESOURCE subresource;
uint8_t *dataPtr = (uint8_t*) data;
int32_t row;
int32_t formatSize = Texture_GetFormatSize(tex->format);
HRESULT res;
if ( tex->format == FNA3D_SURFACEFORMAT_DXT1 ||
tex->format == FNA3D_SURFACEFORMAT_DXT3 ||
tex->format == FNA3D_SURFACEFORMAT_DXT5 )
{
FNA3D_LogError(
"GetData with compressed textures unsupported!"
);
return;
}
/* Create staging texture if needed */
if (tex->isRenderTarget)
{
stagingTexture = tex->staging;
}
else
{
stagingTexture = NULL;
}
if (stagingTexture == NULL)
{
stagingDesc.Width = tex->cube.size;
stagingDesc.Height = tex->cube.size;
stagingDesc.MipLevels = tex->levelCount;
stagingDesc.ArraySize = 1;
stagingDesc.Format = XNAToD3D_TextureFormat[tex->format];
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&stagingDesc,
NULL,
(ID3D11Texture2D**) &stagingTexture
);
ERROR_CHECK_RETURN("TextureCube staging buffer creation failed",)
/* Targets will probably call this a lot, so try to keep this all the time */
if (tex->isRenderTarget)
{
tex->staging = stagingTexture;
}
}
SDL_LockMutex(renderer->ctxLock);
/* Copy data into staging texture */
ID3D11DeviceContext_CopySubresourceRegion(
renderer->context,
stagingTexture,
dstSubresourceIndex,
0,
0,
0,
tex->handle,
srcSubresourceIndex,
&srcBox
);
/* Read from the staging texture */
res = ID3D11DeviceContext_Map(
renderer->context,
stagingTexture,
dstSubresourceIndex,
D3D11_MAP_READ,
0,
&subresource
);
ERROR_CHECK_UNLOCK_RETURN("Could not map TextureCube for reading",)
for (row = y; row < y + h; row += 1)
{
SDL_memcpy(
dataPtr,
(uint8_t*) subresource.pData + (row * subresource.RowPitch) + (x * formatSize),
formatSize * w
);
dataPtr += formatSize * w;
}
ID3D11DeviceContext_Unmap(
renderer->context,
stagingTexture,
dstSubresourceIndex
);
SDL_UnlockMutex(renderer->ctxLock);
if (!tex->isRenderTarget)
{
ID3D11Resource_Release(stagingTexture);
}
}
/* Renderbuffers */
static FNA3D_Renderbuffer* D3D11_GenColorRenderbuffer(
FNA3D_Renderer *driverData,
int32_t width,
int32_t height,
FNA3D_SurfaceFormat format,
int32_t multiSampleCount,
FNA3D_Texture *texture
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11_TEXTURE2D_DESC desc;
D3D11Renderbuffer *result;
HRESULT res;
/* Initialize the renderbuffer */
result = (D3D11Renderbuffer*) SDL_malloc(sizeof(D3D11Renderbuffer));
SDL_memset(result, '\0', sizeof(D3D11Renderbuffer));
result->multiSampleCount = multiSampleCount;
result->type = RENDERBUFFER_COLOR;
result->color.format = format;
/* Create the backing texture */
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = XNAToD3D_TextureFormat[format];
desc.SampleDesc.Count = multiSampleCount;
desc.SampleDesc.Quality = D3D11_STANDARD_MULTISAMPLE_PATTERN;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_RENDER_TARGET;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&desc,
NULL,
&result->handle
);
ERROR_CHECK_RETURN("Color renderbuffer creation failed", NULL)
/* Create the render target view */
res = ID3D11Device_CreateRenderTargetView(
renderer->device,
(ID3D11Resource*) result->handle,
NULL,
&result->color.rtView
);
ERROR_CHECK_RETURN("Color renderbuffer RT view creation failed", NULL)
return (FNA3D_Renderbuffer*) result;
}
static FNA3D_Renderbuffer* D3D11_GenDepthStencilRenderbuffer(
FNA3D_Renderer *driverData,
int32_t width,
int32_t height,
FNA3D_DepthFormat format,
int32_t multiSampleCount
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11_TEXTURE2D_DESC desc;
D3D11Renderbuffer *result;
HRESULT res;
/* Initialize the renderbuffer */
result = (D3D11Renderbuffer*) SDL_malloc(sizeof(D3D11Renderbuffer));
SDL_memset(result, '\0', sizeof(D3D11Renderbuffer));
result->multiSampleCount = multiSampleCount;
result->type = RENDERBUFFER_DEPTH;
result->depth.format = format;
/* Create the backing texture */
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = XNAToD3D_DepthFormat[format];
desc.SampleDesc.Count = (multiSampleCount > 1 ? multiSampleCount : 1);
desc.SampleDesc.Quality = (
multiSampleCount > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0
);
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
res = ID3D11Device_CreateTexture2D(
renderer->device,
&desc,
NULL,
&result->handle
);
ERROR_CHECK_RETURN("Depth-stencil renderbuffer creation failed", NULL)
/* Create the render target view */
res = ID3D11Device_CreateDepthStencilView(
renderer->device,
(ID3D11Resource*) result->handle,
NULL,
&result->depth.dsView
);
ERROR_CHECK_RETURN("Depth-stencil renderbuffer RT view creation failed", NULL)
return (FNA3D_Renderbuffer*) result;
}
static void D3D11_AddDisposeRenderbuffer(
FNA3D_Renderer *driverData,
FNA3D_Renderbuffer *renderbuffer
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Renderbuffer *d3dRenderbuffer = (D3D11Renderbuffer*) renderbuffer;
int32_t i;
if (d3dRenderbuffer->type == RENDERBUFFER_DEPTH)
{
if (d3dRenderbuffer->depth.dsView == renderer->depthStencilView)
{
renderer->depthStencilView = NULL;
}
ID3D11DepthStencilView_Release(d3dRenderbuffer->depth.dsView);
d3dRenderbuffer->depth.dsView = NULL;
}
else
{
for (i = 0; i < MAX_RENDERTARGET_BINDINGS; i += 1)
{
if (d3dRenderbuffer->color.rtView == renderer->renderTargetViews[i])
{
renderer->renderTargetViews[i] = NULL;
}
}
ID3D11RenderTargetView_Release(d3dRenderbuffer->color.rtView);
}
ID3D11Texture2D_Release(d3dRenderbuffer->handle);
d3dRenderbuffer->handle = NULL;
SDL_free(renderbuffer);
}
/* Vertex Buffers */
static FNA3D_Buffer* D3D11_GenVertexBuffer(
FNA3D_Renderer *driverData,
uint8_t dynamic,
FNA3D_BufferUsage usage,
int32_t sizeInBytes
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *result = (D3D11Buffer*) SDL_malloc(sizeof(D3D11Buffer));
D3D11_BUFFER_DESC desc;
HRESULT res;
/* Initialize the descriptor */
desc.ByteWidth = sizeInBytes;
desc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
/* Make the buffer */
res = ID3D11Device_CreateBuffer(
renderer->device,
&desc,
NULL,
&result->handle
);
ERROR_CHECK_RETURN("Vertex buffer creation failed", NULL)
/* Return the result */
result->dynamic = dynamic;
result->size = desc.ByteWidth;
return (FNA3D_Buffer*) result;
}
static void D3D11_AddDisposeVertexBuffer(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
ID3D11Buffer *nullVertexBuffers[] = {NULL};
uint32_t whatever[1] = {0};
int32_t i;
for (i = 0; i < MAX_BOUND_VERTEX_BUFFERS; i += 1)
{
if (renderer->vertexBuffers[i] == d3dBuffer->handle)
{
renderer->vertexBuffers[i] = NULL;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_IASetVertexBuffers(
renderer->context,
i,
1,
nullVertexBuffers,
whatever,
whatever
);
SDL_UnlockMutex(renderer->ctxLock);
}
}
ID3D11Buffer_Release(d3dBuffer->handle);
SDL_free(buffer);
}
static void D3D11_SetVertexBufferData(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer,
int32_t offsetInBytes,
void* data,
int32_t elementCount,
int32_t elementSizeInBytes,
int32_t vertexStride,
FNA3D_SetDataOptions options
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
D3D11_MAPPED_SUBRESOURCE subres = {0, 0, 0};
int32_t dataLen = vertexStride * elementCount;
D3D11_BOX dstBox = {offsetInBytes, 0, 0, offsetInBytes + dataLen, 1, 1};
HRESULT res;
SDL_LockMutex(renderer->ctxLock);
if (d3dBuffer->dynamic)
{
if ( renderer->debugMode &&
options == FNA3D_SETDATAOPTIONS_NONE &&
dataLen < d3dBuffer->size )
{
FNA3D_LogWarn(
"Dynamic buffer using SetDataOptions.None, expect bad performance and broken output!"
);
}
res = ID3D11DeviceContext_Map(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0,
options == FNA3D_SETDATAOPTIONS_NOOVERWRITE ?
D3D11_MAP_WRITE_NO_OVERWRITE :
D3D11_MAP_WRITE_DISCARD,
0,
&subres
);
ERROR_CHECK_UNLOCK_RETURN("Could not map vertex buffer for writing",)
SDL_memcpy(
(uint8_t*) subres.pData + offsetInBytes,
data,
dataLen
);
ID3D11DeviceContext_Unmap(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0
);
}
else
{
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0,
&dstBox,
data,
dataLen,
dataLen
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_GetVertexBufferData(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer,
int32_t offsetInBytes,
void* data,
int32_t elementCount,
int32_t elementSizeInBytes,
int32_t vertexStride
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
D3D11_BUFFER_DESC desc;
ID3D11Resource *stagingBuffer;
int32_t dataLength = vertexStride * elementCount;
uint8_t *src, *dst;
int32_t i;
D3D11_MAPPED_SUBRESOURCE subres;
D3D11_BOX srcBox = {offsetInBytes, 0, 0, offsetInBytes + dataLength, 1, 1};
HRESULT res;
/* Create staging buffer */
desc.ByteWidth = d3dBuffer->size;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
res = ID3D11Device_CreateBuffer(
renderer->device,
&desc,
NULL,
(ID3D11Buffer**) &stagingBuffer
);
ERROR_CHECK_RETURN("Could not create vertex buffer staging buffer",)
SDL_LockMutex(renderer->ctxLock);
/* Copy data into staging buffer */
ID3D11DeviceContext_CopySubresourceRegion(
renderer->context,
stagingBuffer,
0,
0,
0,
0,
(ID3D11Resource*) d3dBuffer->handle,
0,
&srcBox
);
/* Read from the staging buffer */
res = ID3D11DeviceContext_Map(
renderer->context,
stagingBuffer,
0,
D3D11_MAP_READ,
0,
&subres
);
ERROR_CHECK_UNLOCK_RETURN("Could not map vertex buffer for reading",)
if (elementSizeInBytes < vertexStride)
{
dst = (uint8_t*) data;
src = (uint8_t*) subres.pData;
for (i = 0; i < elementCount; i += 1)
{
SDL_memcpy(dst, src, elementSizeInBytes);
dst += elementSizeInBytes;
src += vertexStride;
}
}
else
{
SDL_memcpy(
data,
subres.pData,
dataLength
);
}
ID3D11DeviceContext_Unmap(
renderer->context,
stagingBuffer,
0
);
SDL_UnlockMutex(renderer->ctxLock);
ID3D11Resource_Release(stagingBuffer);
}
/* Index Buffers */
static FNA3D_Buffer* D3D11_GenIndexBuffer(
FNA3D_Renderer *driverData,
uint8_t dynamic,
FNA3D_BufferUsage usage,
int32_t sizeInBytes
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *result = (D3D11Buffer*) SDL_malloc(sizeof(D3D11Buffer));
D3D11_BUFFER_DESC desc;
HRESULT res;
/* Initialize the descriptor */
desc.ByteWidth = sizeInBytes;
desc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
/* Make the buffer */
res = ID3D11Device_CreateBuffer(
renderer->device,
&desc,
NULL,
&result->handle
);
ERROR_CHECK_RETURN("Index buffer creation failed", NULL)
/* Return the result */
result->dynamic = dynamic;
result->size = desc.ByteWidth;
return (FNA3D_Buffer*) result;
}
static void D3D11_AddDisposeIndexBuffer(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
if (d3dBuffer->handle == renderer->indexBuffer)
{
renderer->indexBuffer = NULL;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_IASetIndexBuffer(
renderer->context,
NULL,
DXGI_FORMAT_R16_UINT,
0
);
SDL_UnlockMutex(renderer->ctxLock);
}
ID3D11Buffer_Release(d3dBuffer->handle);
SDL_free(buffer);
}
static void D3D11_SetIndexBufferData(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer,
int32_t offsetInBytes,
void* data,
int32_t dataLength,
FNA3D_SetDataOptions options
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
D3D11_MAPPED_SUBRESOURCE subres = {0, 0, 0};
D3D11_BOX dstBox = {offsetInBytes, 0, 0, offsetInBytes + dataLength, 1, 1};
HRESULT res;
SDL_LockMutex(renderer->ctxLock);
if (d3dBuffer->dynamic)
{
if ( renderer->debugMode &&
options == FNA3D_SETDATAOPTIONS_NONE &&
dataLength < d3dBuffer->size )
{
FNA3D_LogWarn(
"Dynamic buffer using SetDataOptions.None, expect bad performance and broken output!"
);
}
res = ID3D11DeviceContext_Map(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0,
options == FNA3D_SETDATAOPTIONS_NOOVERWRITE ?
D3D11_MAP_WRITE_NO_OVERWRITE :
D3D11_MAP_WRITE_DISCARD,
0,
&subres
);
ERROR_CHECK_UNLOCK_RETURN("Could not map index buffer for writing",)
SDL_memcpy(
(uint8_t*) subres.pData + offsetInBytes,
data,
dataLength
);
ID3D11DeviceContext_Unmap(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0
);
}
else
{
ID3D11DeviceContext_UpdateSubresource(
renderer->context,
(ID3D11Resource*) d3dBuffer->handle,
0,
&dstBox,
data,
dataLength,
dataLength
);
}
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_GetIndexBufferData(
FNA3D_Renderer *driverData,
FNA3D_Buffer *buffer,
int32_t offsetInBytes,
void* data,
int32_t dataLength
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Buffer *d3dBuffer = (D3D11Buffer*) buffer;
D3D11_BUFFER_DESC desc;
ID3D11Resource *stagingBuffer;
D3D11_MAPPED_SUBRESOURCE subres;
D3D11_BOX srcBox = {offsetInBytes, 0, 0, offsetInBytes + dataLength, 1, 1};
HRESULT res;
/* Create staging buffer */
desc.ByteWidth = d3dBuffer->size;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
res = ID3D11Device_CreateBuffer(
renderer->device,
&desc,
NULL,
(ID3D11Buffer**) &stagingBuffer
);
ERROR_CHECK_RETURN("Index buffer staging buffer creation failed",)
SDL_LockMutex(renderer->ctxLock);
/* Copy data into staging buffer */
ID3D11DeviceContext_CopySubresourceRegion(
renderer->context,
stagingBuffer,
0,
0,
0,
0,
(ID3D11Resource*) d3dBuffer->handle,
0,
&srcBox
);
/* Read from the staging buffer */
res = ID3D11DeviceContext_Map(
renderer->context,
stagingBuffer,
0,
D3D11_MAP_READ,
0,
&subres
);
ERROR_CHECK_UNLOCK_RETURN("Could not map index buffer for reading",)
SDL_memcpy(
data,
subres.pData,
dataLength
);
ID3D11DeviceContext_Unmap(
renderer->context,
stagingBuffer,
0
);
SDL_UnlockMutex(renderer->ctxLock);
ID3D11Resource_Release(stagingBuffer);
}
/* Effects */
static void D3D11_CreateEffect(
FNA3D_Renderer *driverData,
uint8_t *effectCode,
uint32_t effectCodeLength,
FNA3D_Effect **effect,
MOJOSHADER_effect **effectData
) {
int32_t i;
MOJOSHADER_effectShaderContext shaderBackend;
D3D11Effect *result;
shaderBackend.compileShader = (MOJOSHADER_compileShaderFunc) MOJOSHADER_d3d11CompileShader;
shaderBackend.shaderAddRef = (MOJOSHADER_shaderAddRefFunc) MOJOSHADER_d3d11ShaderAddRef;
shaderBackend.deleteShader = (MOJOSHADER_deleteShaderFunc) MOJOSHADER_d3d11DeleteShader;
shaderBackend.getParseData = (MOJOSHADER_getParseDataFunc) MOJOSHADER_d3d11GetShaderParseData;
shaderBackend.bindShaders = (MOJOSHADER_bindShadersFunc) MOJOSHADER_d3d11BindShaders;
shaderBackend.getBoundShaders = (MOJOSHADER_getBoundShadersFunc) MOJOSHADER_d3d11GetBoundShaders;
shaderBackend.mapUniformBufferMemory = MOJOSHADER_d3d11MapUniformBufferMemory;
shaderBackend.unmapUniformBufferMemory = MOJOSHADER_d3d11UnmapUniformBufferMemory;
shaderBackend.getError = MOJOSHADER_d3d11GetError;
shaderBackend.m = NULL;
shaderBackend.f = NULL;
shaderBackend.malloc_data = NULL;
*effectData = MOJOSHADER_compileEffect(
effectCode,
effectCodeLength,
NULL,
0,
NULL,
0,
&shaderBackend
);
for (i = 0; i < (*effectData)->error_count; i += 1)
{
FNA3D_LogError(
"MOJOSHADER_compileEffect Error: %s",
(*effectData)->errors[i].error
);
}
result = (D3D11Effect*) SDL_malloc(sizeof(D3D11Effect));
result->effect = *effectData;
*effect = (FNA3D_Effect*) result;
}
static void D3D11_CloneEffect(
FNA3D_Renderer *driverData,
FNA3D_Effect *cloneSource,
FNA3D_Effect **effect,
MOJOSHADER_effect **effectData
) {
D3D11Effect *d3dCloneSource = (D3D11Effect*) cloneSource;
D3D11Effect *result;
*effectData = MOJOSHADER_cloneEffect(d3dCloneSource->effect);
if (*effectData == NULL)
{
FNA3D_LogError(
"%s", MOJOSHADER_d3d11GetError()
);
}
result = (D3D11Effect*) SDL_malloc(sizeof(D3D11Effect));
result->effect = *effectData;
*effect = (FNA3D_Effect*) result;
}
static void D3D11_AddDisposeEffect(
FNA3D_Renderer *driverData,
FNA3D_Effect *effect
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
MOJOSHADER_effect *effectData = ((D3D11Effect*) effect)->effect;
SDL_LockMutex(renderer->ctxLock);
if (effectData == renderer->currentEffect)
{
MOJOSHADER_effectEndPass(renderer->currentEffect);
MOJOSHADER_effectEnd(renderer->currentEffect);
renderer->currentEffect = NULL;
renderer->currentTechnique = NULL;
renderer->currentPass = 0;
renderer->effectApplied = 1;
}
MOJOSHADER_deleteEffect(effectData);
SDL_UnlockMutex(renderer->ctxLock);
SDL_free(effect);
}
static void D3D11_SetEffectTechnique(
FNA3D_Renderer *driverData,
FNA3D_Effect *effect,
MOJOSHADER_effectTechnique *technique
) {
/* FIXME: Why doesn't this function do anything? */
D3D11Effect *d3dEffect = (D3D11Effect*) effect;
MOJOSHADER_effectSetTechnique(d3dEffect->effect, technique);
}
static void D3D11_ApplyEffect(
FNA3D_Renderer *driverData,
FNA3D_Effect *effect,
uint32_t pass,
MOJOSHADER_effectStateChanges *stateChanges
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
MOJOSHADER_effect *effectData = ((D3D11Effect*) effect)->effect;
const MOJOSHADER_effectTechnique *technique = effectData->current_technique;
uint32_t whatever;
renderer->effectApplied = 1;
SDL_LockMutex(renderer->ctxLock);
if (effectData == renderer->currentEffect)
{
if ( technique == renderer->currentTechnique &&
pass == renderer->currentPass )
{
MOJOSHADER_effectCommitChanges(
renderer->currentEffect
);
SDL_UnlockMutex(renderer->ctxLock);
return;
}
MOJOSHADER_effectEndPass(renderer->currentEffect);
MOJOSHADER_effectBeginPass(renderer->currentEffect, pass);
renderer->currentTechnique = technique;
renderer->currentPass = pass;
SDL_UnlockMutex(renderer->ctxLock);
return;
}
else if (renderer->currentEffect != NULL)
{
MOJOSHADER_effectEndPass(renderer->currentEffect);
MOJOSHADER_effectEnd(renderer->currentEffect);
}
MOJOSHADER_effectBegin(
effectData,
&whatever,
0,
stateChanges
);
MOJOSHADER_effectBeginPass(effectData, pass);
SDL_UnlockMutex(renderer->ctxLock);
renderer->currentEffect = effectData;
renderer->currentTechnique = technique;
renderer->currentPass = pass;
}
static void D3D11_BeginPassRestore(
FNA3D_Renderer *driverData,
FNA3D_Effect *effect,
MOJOSHADER_effectStateChanges *stateChanges
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
MOJOSHADER_effect *effectData = ((D3D11Effect*) effect)->effect;
uint32_t whatever;
SDL_LockMutex(renderer->ctxLock);
MOJOSHADER_effectBegin(
effectData,
&whatever,
1,
stateChanges
);
MOJOSHADER_effectBeginPass(effectData, 0);
SDL_UnlockMutex(renderer->ctxLock);
renderer->effectApplied = 1;
}
static void D3D11_EndPassRestore(
FNA3D_Renderer *driverData,
FNA3D_Effect *effect
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
MOJOSHADER_effect *effectData = ((D3D11Effect*) effect)->effect;
SDL_LockMutex(renderer->ctxLock);
MOJOSHADER_effectEndPass(effectData);
MOJOSHADER_effectEnd(effectData);
SDL_UnlockMutex(renderer->ctxLock);
renderer->effectApplied = 1;
}
/* Queries */
static FNA3D_Query* D3D11_CreateQuery(FNA3D_Renderer *driverData)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Query *query = (D3D11Query*) SDL_malloc(sizeof(D3D11Query));
D3D11_QUERY_DESC desc;
HRESULT res;
desc.Query = D3D11_QUERY_OCCLUSION;
desc.MiscFlags = 0;
res = ID3D11Device_CreateQuery(
renderer->device,
&desc,
&query->handle
);
ERROR_CHECK_RETURN("Query creation failed", NULL)
return (FNA3D_Query*) query;
}
static void D3D11_AddDisposeQuery(
FNA3D_Renderer *driverData,
FNA3D_Query *query
) {
D3D11Query *d3dQuery = (D3D11Query*) query;
ID3D11Query_Release(d3dQuery->handle);
SDL_free(query);
}
static void D3D11_QueryBegin(FNA3D_Renderer *driverData, FNA3D_Query *query)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Query *d3dQuery = (D3D11Query*) query;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_Begin(
renderer->context,
(ID3D11Asynchronous*) d3dQuery->handle
);
SDL_UnlockMutex(renderer->ctxLock);
}
static void D3D11_QueryEnd(FNA3D_Renderer *driverData, FNA3D_Query *query)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Query *d3dQuery = (D3D11Query*) query;
SDL_LockMutex(renderer->ctxLock);
ID3D11DeviceContext_End(
renderer->context,
(ID3D11Asynchronous*) d3dQuery->handle
);
SDL_UnlockMutex(renderer->ctxLock);
}
static uint8_t D3D11_QueryComplete(
FNA3D_Renderer *driverData,
FNA3D_Query *query
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Query *d3dQuery = (D3D11Query*) query;
uint8_t result;
SDL_LockMutex(renderer->ctxLock);
result = ID3D11DeviceContext_GetData(
renderer->context,
(ID3D11Asynchronous*) d3dQuery->handle,
NULL,
0,
0
) == S_OK;
SDL_UnlockMutex(renderer->ctxLock);
return result;
}
static int32_t D3D11_QueryPixelCount(
FNA3D_Renderer *driverData,
FNA3D_Query *query
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
D3D11Query *d3dQuery = (D3D11Query*) query;
uint64_t result;
HRESULT res;
SDL_LockMutex(renderer->ctxLock);
res = ID3D11DeviceContext_GetData(
renderer->context,
(ID3D11Asynchronous*) d3dQuery->handle,
&result,
sizeof(result),
0
);
ERROR_CHECK("QueryPixelCount failed")
SDL_UnlockMutex(renderer->ctxLock);
return (int32_t) result;
}
/* Feature Queries */
static uint8_t D3D11_SupportsDXT1(FNA3D_Renderer *driverData)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
return renderer->supportsDxt1;
}
static uint8_t D3D11_SupportsS3TC(FNA3D_Renderer *driverData)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
return renderer->supportsS3tc;
}
static uint8_t D3D11_SupportsHardwareInstancing(FNA3D_Renderer *driverData)
{
return 1;
}
static uint8_t D3D11_SupportsNoOverwrite(FNA3D_Renderer *driverData)
{
return 1;
}
static void D3D11_GetMaxTextureSlots(
FNA3D_Renderer *driverData,
int32_t *textures,
int32_t *vertexTextures
) {
*textures = D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
*vertexTextures = D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
}
static int32_t D3D11_GetMaxMultiSampleCount(
FNA3D_Renderer *driverData,
FNA3D_SurfaceFormat format,
int32_t multiSampleCount
) {
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
uint32_t levels;
do
{
/* FIXME: This returns a result code, but the
* docs don't say if/when it can fail...
*/
ID3D11Device_CheckMultisampleQualityLevels(
renderer->device,
XNAToD3D_TextureFormat[format],
multiSampleCount,
&levels
);
if (levels > 0)
{
break;
}
multiSampleCount >>= 1;
} while (multiSampleCount > 0);
return multiSampleCount;
}
/* Debugging */
static void D3D11_SetStringMarker(FNA3D_Renderer *driverData, const char *text)
{
D3D11Renderer *renderer = (D3D11Renderer*) driverData;
wchar_t wstr[256];
MultiByteToWideChar(CP_ACP, 0, text, -1, wstr, 256);
ID3DUserDefinedAnnotation_SetMarker(
renderer->annotation,
wstr
);
}
/* Driver */
static uint8_t D3D11_PrepareWindowAttributes(uint32_t *flags)
{
void* module = NULL;
PFN_D3D11_CREATE_DEVICE D3D11CreateDeviceFunc;
D3D_FEATURE_LEVEL levels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
HRESULT res;
module = D3D11_PLATFORM_LoadD3D11();
if (module == NULL)
{
return 0;
}
D3D11CreateDeviceFunc = D3D11_PLATFORM_GetCreateDeviceFunc(module);
if (D3D11CreateDeviceFunc == NULL)
{
SDL_UnloadObject(module);
return 0;
}
res = D3D11CreateDeviceFunc(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
levels,
SDL_arraysize(levels),
D3D11_SDK_VERSION,
NULL,
NULL,
NULL
);
D3D11_PLATFORM_UnloadD3D11(module);
if (FAILED(res))
{
FNA3D_LogWarn("D3D11 is unsupported! Error Code: %08X", res);
return 0;
}
/* No window flags required */
SDL_SetHint(SDL_HINT_VIDEO_EXTERNAL_CONTEXT, "1");
return 1;
}
static void D3D11_GetDrawableSize(void* window, int32_t *w, int32_t *h)
{
SDL_GetWindowSize((SDL_Window*) window, w, h);
}
static void D3D11_INTERNAL_InitializeFauxBackbuffer(
D3D11Renderer *renderer,
uint8_t scaleNearest
) {
void* d3dCompilerModule;
PFN_D3DCOMPILE D3DCompileFunc;
ID3DBlob *blob;
D3D11_INPUT_ELEMENT_DESC ePosition;
D3D11_INPUT_ELEMENT_DESC eTexcoord;
D3D11_INPUT_ELEMENT_DESC elements[2];
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC vbufDesc;
uint16_t indices[] =
{
0, 1, 3,
1, 2, 3
};
D3D11_SUBRESOURCE_DATA indicesData;
D3D11_BUFFER_DESC ibufDesc;
D3D11_RASTERIZER_DESC rastDesc;
D3D11_BLEND_DESC blendDesc;
HRESULT res;
/* Load the D3DCompile function */
d3dCompilerModule = D3D11_PLATFORM_LoadCompiler();
if (d3dCompilerModule == NULL)
{
FNA3D_LogError("Could not find " D3DCOMPILER_DLL);
}
D3DCompileFunc = D3D11_PLATFORM_GetCompileFunc(d3dCompilerModule);
if (D3DCompileFunc == NULL)
{
FNA3D_LogError("Could not load function D3DCompile!");
}
/* Compile and create the vertex shader */
res = D3DCompileFunc(
FAUX_BLIT_VERTEX_SHADER, SDL_strlen(FAUX_BLIT_VERTEX_SHADER),
"Faux-Backbuffer Blit Vertex Shader", NULL, NULL,
"main", "vs_4_0", 0, 0, &blob, &blob
);
ERROR_CHECK_RETURN("Backbuffer vshader failed to compile",)
res = ID3D11Device_CreateVertexShader(
renderer->device,
ID3D10Blob_GetBufferPointer(blob),
ID3D10Blob_GetBufferSize(blob),
NULL,
&renderer->fauxBlitVS
);
ERROR_CHECK_RETURN("Backbuffer vshader creation failed",)
/* Create the vertex shader input layout */
ePosition.SemanticName = "SV_POSITION";
ePosition.SemanticIndex = 0;
ePosition.Format = DXGI_FORMAT_R32G32_FLOAT;
ePosition.InputSlot = 0;
ePosition.AlignedByteOffset = 0;
ePosition.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
ePosition.InstanceDataStepRate = 0;
eTexcoord.SemanticName = "TEXCOORD";
eTexcoord.SemanticIndex = 0;
eTexcoord.Format = DXGI_FORMAT_R32G32_FLOAT;
eTexcoord.InputSlot = 0;
eTexcoord.AlignedByteOffset = sizeof(float) * 2;
eTexcoord.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
eTexcoord.InstanceDataStepRate = 0;
elements[0] = ePosition;
elements[1] = eTexcoord;
res = ID3D11Device_CreateInputLayout(
renderer->device,
elements,
2,
ID3D10Blob_GetBufferPointer(blob),
ID3D10Blob_GetBufferSize(blob),
&renderer->fauxBlitLayout
);
ERROR_CHECK_RETURN("Backbuffer input layout creation failed",)
/* Compile and create the pixel shader */
res = D3DCompileFunc(
FAUX_BLIT_PIXEL_SHADER, SDL_strlen(FAUX_BLIT_PIXEL_SHADER),
"Faux-Backbuffer Blit Pixel Shader", NULL, NULL,
"main", "ps_4_0", 0, 0, &blob, &blob
);
ERROR_CHECK_RETURN("Backbuffer pshader failed to compile",)
ID3D11Device_CreatePixelShader(
renderer->device,
ID3D10Blob_GetBufferPointer(blob),
ID3D10Blob_GetBufferSize(blob),
NULL,
&renderer->fauxBlitPS
);
ERROR_CHECK_RETURN("Backbuffer pshader creation failed",)
/* We're done with the compiler now */
D3D11_PLATFORM_UnloadCompiler(d3dCompilerModule);
/* Create the faux backbuffer sampler state */
samplerDesc.Filter = (
scaleNearest ?
D3D11_FILTER_MIN_MAG_MIP_POINT :
D3D11_FILTER_MIN_MAG_MIP_LINEAR
);
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = 0;
res = ID3D11Device_CreateSamplerState(
renderer->device,
&samplerDesc,
&renderer->fauxBlitSampler
);
ERROR_CHECK_RETURN("Backbuffer sampler state creation failed",)
/* Create the faux backbuffer vertex buffer */
vbufDesc.ByteWidth = 16 * sizeof(float);
vbufDesc.Usage = D3D11_USAGE_DYNAMIC;
vbufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbufDesc.MiscFlags = 0;
vbufDesc.StructureByteStride = 0;
res = ID3D11Device_CreateBuffer(
renderer->device,
&vbufDesc,
NULL,
&renderer->fauxBlitVertexBuffer
);
ERROR_CHECK_RETURN("Backbuffer vertex buffer creation failed",)
/* Initialize faux backbuffer index data */
indicesData.pSysMem = &indices[0];
indicesData.SysMemPitch = 0;
indicesData.SysMemSlicePitch = 0;
/* Create the faux backbuffer index buffer */
ibufDesc.ByteWidth = 6 * sizeof(uint16_t);
ibufDesc.Usage = D3D11_USAGE_IMMUTABLE;
ibufDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibufDesc.CPUAccessFlags = 0;
ibufDesc.MiscFlags = 0;
ibufDesc.StructureByteStride = 0;
res = ID3D11Device_CreateBuffer(
renderer->device,
&ibufDesc,
&indicesData,
&renderer->fauxBlitIndexBuffer
);
ERROR_CHECK_RETURN("Backbuffer index buffer creation failed",)
/* Create the faux backbuffer rasterizer state */
rastDesc.AntialiasedLineEnable = 0;
rastDesc.CullMode = D3D11_CULL_NONE;
rastDesc.DepthBias = 0;
rastDesc.DepthBiasClamp = 0;
rastDesc.DepthClipEnable = 1;
rastDesc.FillMode = D3D11_FILL_SOLID;
rastDesc.FrontCounterClockwise = 0;
rastDesc.MultisampleEnable = 0;
rastDesc.ScissorEnable = 0;
rastDesc.SlopeScaledDepthBias = 0;
res = ID3D11Device_CreateRasterizerState(
renderer->device,
&rastDesc,
&renderer->fauxRasterizer
);
ERROR_CHECK_RETURN("Backbuffer rasterizer state creation failed",)
/* Create the faux backbuffer blend state */
SDL_zero(blendDesc);
blendDesc.AlphaToCoverageEnable = 0;
blendDesc.IndependentBlendEnable = 0;
blendDesc.RenderTarget[0].BlendEnable = 0;
blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
res = ID3D11Device_CreateBlendState(
renderer->device,
&blendDesc,
&renderer->fauxBlendState
);
ERROR_CHECK_RETURN("Backbuffer blend state creation failed",)
}
static FNA3D_Device* D3D11_CreateDevice(
FNA3D_PresentationParameters *presentationParameters,
uint8_t debugMode
) {
FNA3D_Device *result;
D3D11Renderer *renderer;
DXGI_ADAPTER_DESC1 adapterDesc;
PFN_D3D11_CREATE_DEVICE D3D11CreateDeviceFunc;
D3D_FEATURE_LEVEL levels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
uint32_t flags, supportsDxt3, supportsDxt5;
int32_t i;
HRESULT res;
/* Allocate and zero out the renderer */
renderer = (D3D11Renderer*) SDL_malloc(sizeof(D3D11Renderer));
SDL_memset(renderer, '\0', sizeof(D3D11Renderer));
/* Load CreateDXGIFactory1 */
res = D3D11_PLATFORM_CreateDXGIFactory(
&renderer->dxgi_dll,
&renderer->factory
);
ERROR_CHECK_RETURN("Could not create DXGIFactory", NULL)
D3D11_PLATFORM_GetDefaultAdapter(
renderer->factory,
&renderer->adapter
);
IDXGIAdapter1_GetDesc1(renderer->adapter, &adapterDesc);
/* Load D3D11CreateDevice */
renderer->d3d11_dll = D3D11_PLATFORM_LoadD3D11();
if (renderer->d3d11_dll == NULL)
{
FNA3D_LogError("Could not find " D3D11_DLL);
return NULL;
}
D3D11CreateDeviceFunc = D3D11_PLATFORM_GetCreateDeviceFunc(
renderer->d3d11_dll
);
if (D3D11CreateDeviceFunc == NULL)
{
FNA3D_LogError("Could not load function D3D11CreateDevice!");
return NULL;
}
/* Create the D3D11Device */
flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
if (debugMode)
{
flags |= D3D11_CREATE_DEVICE_DEBUG;
}
try_create_device:
res = D3D11CreateDeviceFunc(
NULL, /* FIXME: Should be renderer->adapter! */
D3D_DRIVER_TYPE_HARDWARE,
NULL,
flags,
levels,
SDL_arraysize(levels),
D3D11_SDK_VERSION,
&renderer->device,
&renderer->featureLevel,
&renderer->context
);
if (FAILED(res) && debugMode)
{
/* Creating a debug mode device will fail on some systems due to the necessary
* debug infrastructure not being available. Remove the debug flag and retry. */
FNA3D_LogWarn("Creating device in debug mode failed with error %08X. Trying non-debug.", res);
flags ^= D3D11_CREATE_DEVICE_DEBUG;
debugMode = 0;
goto try_create_device;
}
ERROR_CHECK_RETURN("Could not create D3D11Device", NULL)
/* Print driver info */
FNA3D_LogInfo("FNA3D Driver: D3D11");
FNA3D_LogInfo("D3D11 Adapter: %S", adapterDesc.Description);
/* Determine DXT/S3TC support.
* Note that we do NOT error check the return values!
*/
ID3D11Device_CheckFormatSupport(
renderer->device,
XNAToD3D_TextureFormat[FNA3D_SURFACEFORMAT_DXT1],
&renderer->supportsDxt1
);
ID3D11Device_CheckFormatSupport(
renderer->device,
XNAToD3D_TextureFormat[FNA3D_SURFACEFORMAT_DXT3],
&supportsDxt3
);
ID3D11Device_CheckFormatSupport(
renderer->device,
XNAToD3D_TextureFormat[FNA3D_SURFACEFORMAT_DXT5],
&supportsDxt5
);
renderer->supportsS3tc = (supportsDxt3 || supportsDxt5);
/* Initialize MojoShader context */
MOJOSHADER_d3d11CreateContext(
renderer->device,
renderer->context,
NULL,
NULL,
NULL
);
/* Initialize texture and sampler collections */
for (i = 0; i < MAX_TOTAL_SAMPLERS; i += 1)
{
renderer->textures[i] = &NullTexture;
renderer->samplers[i] = NULL;
}
/* Initialize SetStringMarker support, if available */
if (renderer->featureLevel == D3D_FEATURE_LEVEL_11_1)
{
res = ID3D11DeviceContext_QueryInterface(
renderer->context,
&D3D_IID_ID3DUserDefinedAnnotation,
(void**) &renderer->annotation
);
ERROR_CHECK("Could not get UserDefinedAnnotation")
}
else
{
FNA3D_LogInfo("SetStringMarker not supported!");
}
/* Initialize renderer members not covered by SDL_memset('\0') */
renderer->debugMode = debugMode;
renderer->blendFactor.r = 0xFF;
renderer->blendFactor.g = 0xFF;
renderer->blendFactor.b = 0xFF;
renderer->blendFactor.a = 0xFF;
renderer->multiSampleMask = -1; /* AKA 0xFFFFFFFF, ugh -flibit */
renderer->topology = (FNA3D_PrimitiveType) -1; /* Force an update */
/* Create and initialize the faux-backbuffer */
D3D11_INTERNAL_CreateFramebuffer(
renderer,
presentationParameters
);
D3D11_INTERNAL_InitializeFauxBackbuffer(
renderer,
SDL_GetHintBoolean("FNA3D_BACKBUFFER_SCALE_NEAREST", SDL_FALSE)
);
D3D11_INTERNAL_SetPresentationInterval(
renderer,
presentationParameters->presentationInterval
);
/* A mutex, for ID3D11Context */
renderer->ctxLock = SDL_CreateMutex();
/* Create and return the FNA3D_Device */
result = (FNA3D_Device*) SDL_malloc(sizeof(FNA3D_Device));
result->driverData = (FNA3D_Renderer*) renderer;
ASSIGN_DRIVER(D3D11)
return result;
}
#ifdef __WINRT__
/* WinRT Platform Implementation */
static void* D3D11_PLATFORM_LoadD3D11()
{
return (size_t) 69420;
}
static void D3D11_PLATFORM_UnloadD3D11(void* module)
{
/* No-op */
}
static PFN_D3D11_CREATE_DEVICE D3D11_PLATFORM_GetCreateDeviceFunc(void* module)
{
return D3D11CreateDevice;
}
static void* D3D11_PLATFORM_LoadCompiler()
{
return (size_t) 42069;
}
static void D3D11_PLATFORM_UnloadCompiler(void* module)
{
/* No-op */
}
static PFN_D3DCOMPILE D3D11_PLATFORM_GetCompileFunc(void* module)
{
return D3DCompile;
}
static HRESULT D3D11_PLATFORM_CreateDXGIFactory(
void** module,
void** factory
) {
return CreateDXGIFactory1(
&D3D_IID_IDXGIFactory2,
factory
);
}
static void D3D11_PLATFORM_UnloadDXGI(void* module)
{
/* No-op */
}
static void D3D11_PLATFORM_GetDefaultAdapter(
void* factory,
IDXGIAdapter1 **adapter
) {
IDXGIFactory2_EnumAdapters1(
(IDXGIFactory2*) factory,
0,
adapter
);
}
static void D3D11_PLATFORM_CreateSwapChain(
D3D11Renderer *renderer,
FNA3D_PresentationParameters *pp
) {
DXGI_SWAP_CHAIN_DESC1 swapchainDesc;
HRESULT res;
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
SDL_GetWindowWMInfo((SDL_Window*) pp->deviceWindowHandle, &info);
/* Initialize swapchain descriptor */
swapchainDesc.Width = 0;
swapchainDesc.Height = 0;
swapchainDesc.Format = XNAToD3D_TextureFormat[pp->backBufferFormat];
swapchainDesc.Stereo = 0;
swapchainDesc.SampleDesc.Count = 1;
swapchainDesc.SampleDesc.Quality = 0;
swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapchainDesc.BufferCount = 3;
swapchainDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
swapchainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
swapchainDesc.Flags = 0;
/* Create the swap chain! */
res = IDXGIFactory2_CreateSwapChainForCoreWindow(
(IDXGIFactory2*) renderer->factory,
(IUnknown*) renderer->device,
(IUnknown*) info.info.winrt.window,
&swapchainDesc,
NULL,
(IDXGISwapChain1**) &renderer->swapchain
);
ERROR_CHECK("Could not create swapchain")
}
#else
/* Win32 Platform Implementation */
static void* D3D11_PLATFORM_LoadD3D11()
{
return SDL_LoadObject(D3D11_DLL);
}
static void D3D11_PLATFORM_UnloadD3D11(void* module)
{
SDL_UnloadObject(module);
}
static PFN_D3D11_CREATE_DEVICE D3D11_PLATFORM_GetCreateDeviceFunc(void* module)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
return (PFN_D3D11_CREATE_DEVICE) SDL_LoadFunction(
module,
"D3D11CreateDevice"
);
#pragma GCC diagnostic pop
}
static void* D3D11_PLATFORM_LoadCompiler()
{
return SDL_LoadObject(D3DCOMPILER_DLL);
}
static void D3D11_PLATFORM_UnloadCompiler(void* module)
{
SDL_UnloadObject(module);
}
static PFN_D3DCOMPILE D3D11_PLATFORM_GetCompileFunc(void* module)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
return (PFN_D3DCOMPILE) SDL_LoadFunction(module, "D3DCompile");
#pragma GCC diagnostic pop
}
static HRESULT D3D11_PLATFORM_CreateDXGIFactory(
void** module,
void** factory
) {
typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY)(const GUID *riid, void **ppFactory);
PFN_CREATE_DXGI_FACTORY CreateDXGIFactoryFunc;
/* Load DXGI... */
*module = SDL_LoadObject(DXGI_DLL);
if (*module == NULL)
{
FNA3D_LogError("Could not find " DXGI_DLL);
return -1;
}
/* Load CreateFactory... */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
CreateDXGIFactoryFunc = (PFN_CREATE_DXGI_FACTORY) SDL_LoadFunction(
*module,
"CreateDXGIFactory1"
);
#pragma GCC diagnostic pop
if (CreateDXGIFactoryFunc == NULL)
{
FNA3D_LogError("Could not load function CreateDXGIFactory1!");
return -1;
}
/* ... Create, finally. */
return CreateDXGIFactoryFunc(
&D3D_IID_IDXGIFactory1,
factory
);
}
static void D3D11_PLATFORM_UnloadDXGI(void* module)
{
SDL_UnloadObject(module);
}
static void D3D11_PLATFORM_GetDefaultAdapter(
void* factory,
IDXGIAdapter1 **adapter
) {
IDXGIFactory1_EnumAdapters1(
(IDXGIFactory1*) factory,
0,
adapter
);
}
static inline void* GetDXGIHandle(SDL_Window *window)
{
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
SDL_GetWindowWMInfo((SDL_Window*) window, &info);
return (void*) info.info.win.window; /* HWND */
}
static void D3D11_PLATFORM_CreateSwapChain(
D3D11Renderer *renderer,
FNA3D_PresentationParameters *pp
) {
IDXGIOutput *output;
DXGI_SWAP_CHAIN_DESC swapchainDesc;
DXGI_MODE_DESC swapchainBufferDesc;
HRESULT res;
/* Initialize swapchain buffer descriptor */
swapchainBufferDesc.Width = 0;
swapchainBufferDesc.Height = 0;
swapchainBufferDesc.RefreshRate.Numerator = 0;
swapchainBufferDesc.RefreshRate.Denominator = 0;
swapchainBufferDesc.Format = XNAToD3D_TextureFormat[pp->backBufferFormat];
swapchainBufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapchainBufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
IDXGIAdapter_EnumOutputs(
(IDXGIAdapter*) renderer->adapter,
0,
&output
);
IDXGIOutput_FindClosestMatchingMode(
output,
&swapchainBufferDesc,
&swapchainDesc.BufferDesc,
(IUnknown*) renderer->device
);
/* Initialize the swapchain descriptor */
swapchainDesc.BufferDesc = swapchainBufferDesc;
swapchainDesc.SampleDesc.Count = 1;
swapchainDesc.SampleDesc.Quality = 0;
swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapchainDesc.BufferCount = 3;
swapchainDesc.OutputWindow = (HWND) GetDXGIHandle((SDL_Window*) pp->deviceWindowHandle);
swapchainDesc.Windowed = 1;
swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapchainDesc.Flags = 0;
/* Create the swapchain! */
res = IDXGIFactory1_CreateSwapChain(
(IDXGIFactory1*) renderer->factory,
(IUnknown*) renderer->device,
&swapchainDesc,
&renderer->swapchain
);
ERROR_CHECK("Could not create swapchain")
}
#endif
FNA3D_Driver D3D11Driver = {
"D3D11",
D3D11_PrepareWindowAttributes,
D3D11_GetDrawableSize,
D3D11_CreateDevice
};
#else
extern int this_tu_is_empty;
#endif /* FNA3D_DRIVER_D3D11 */
/* vim: set noexpandtab shiftwidth=8 tabstop=8: */
|
the_stack_data/2105.c | // combine_node_alloc_1.c
// "Out of memory" problem
struct node {
struct node *link;
};
struct node *list[1] = {
((struct node *) 0)
};
|
the_stack_data/29825450.c | /*
Writing into a file
Write a program that prints the text "Hello world!" into the file "hello.usr".
The file does not exist, so it must be created. Finally, the program must print
a message on the screen indicating that writing to the file was successful.
The text printed to the file must exactly match the assignment.
*/
#include<stdio.h>
int main()
{
FILE *file_handle= fopen("hello.usr","w");
fprintf(file_handle,"Hello world!");
fclose(file_handle);
printf("Writing to the file was successful.n");
printf("Closing the program.n");
return 0;
}
|
the_stack_data/293890.c | #include <stdio.h>
#include <stdlib.h>
#define g 12
#define o 12
int main(){
int n,c=0,l=0,r=0,q=0,m=0,t=0,cont1=0;
char nom;
int i,j;
double q1=0,q2=0,q3=0,q4=0;
double matriz [g][o];
n=12;
m=n;
scanf("%c",&nom);
for (j=0;j<n;j++){
m--;
for(i=0;i<n;i++){
scanf("%lf",&matriz [j] [i]);
if(i>j && i>m){
q1+=matriz [j][i];
cont1++;
}
}
}
if(nom=='S'){
printf("%0.1lf\n",q1);
}
if(nom=='M'){
printf("%0.1lf\n",q1/cont1);
}
return 0;
}
|
the_stack_data/193893586.c | // 约瑟夫环
int lastRemaining(int n, int m)
{
// f(n - 1, m) = x
// f(n, m) = ((m - 1) % n + x + 1) % m = (m + x) % n
int x = 0;
int i;
for (i = 2; i <= n; i++) {
x = (m + x) % i;
}
return x;
} |
the_stack_data/12638732.c | static int testfunc(int i) {
return i-6;
}
int TestNano(void) {
int (*f) (int);
f = &testfunc;
if (f) {
return f(6);
}
else {
return 1;
}
}
|
the_stack_data/772603.c | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
int main() {
int __BLAST_NONDET;
int x;
int y;
x = __BLAST_NONDET;
y = __BLAST_NONDET;
if (x != y) {
ERROR:
goto ERROR;
}
}
|
the_stack_data/1025617.c | #include<stdio.h>
int main()
{
int i,j=0,f=0;
char s[100],a[5]="hello";
scanf("%s",s);
for(i=0;i<5;i++)
{
while(s[j]!='\0')
{
if(a[i]==s[j])
{
f++;
j++;
break;
}
else
j++;
}
}
if(f==5)
printf("YES");
else
printf("NO");
return 0;
}
|
the_stack_data/12637724.c | #include<stdio.h>
#include<string.h>
#include <unistd.h>
int main() {
int quantProcessos;
printf("Quantidade de processos: ");
scanf("%d", &quantProcessos);
char cpu[10][10];
int tempoExecucao[10], tempoEspera[10], timer = 3, tempoProcessamento[10], rt;
int i, j, totalTempoEspera = 0, aux;
float tempoEstimado;
// Lendo dados
for(i = 0; i < quantProcessos; i++) {
printf("Nome do processo : ");
scanf("%s", cpu[i]);
printf("Tempo do processo : ");
scanf("%d", &tempoProcessamento[i]);
sleep(2);
printf("\nProcessando %s ...\n\n", cpu[i]);
sleep(2);
}
aux = quantProcessos;
tempoEspera[0] = 0;
i = 0;
do {
if(tempoProcessamento[i] > timer) {
rt = tempoProcessamento[i] - timer;
strcpy(cpu[quantProcessos], cpu[i]);
tempoProcessamento[quantProcessos] = rt;
tempoExecucao[i] = timer;
quantProcessos++;
} else {
tempoExecucao[i] = tempoProcessamento[i];
}
i++;
tempoEspera[i] = tempoEspera[i-1] + tempoExecucao[i-1];
} while(i < quantProcessos);
int achado = 0, soma = 0;
for(i = 0; i < aux; i++) {
for(j = i+1; j <= quantProcessos; j++) {
if(strcmp(cpu[i], cpu[j]) == 0) {
soma++;
achado = j;
}
}
if(achado != 0) {
tempoEspera[i] = tempoEspera[achado] - (soma * timer);
soma = 0;
achado = 0;
}
}
for(i = 0; i < aux; i++) {
totalTempoEspera += tempoEspera[i];
}
tempoEstimado = (float)totalTempoEspera/aux;
for(i = 0; i < aux; i++) {
printf("\n####################");
printf("\nNomeProcesso: %s", cpu[i]);
printf("\nTempoProcesso: %d", tempoProcessamento[i]);
printf("\nTempoEsperando: %d", tempoEspera[i]);
}
printf("\n####################");
printf("\nTotal de tempo esperando: %d\n", totalTempoEspera);
printf("Tempo esperando estimado: %f\n", tempoEstimado);
return 0;
} |
the_stack_data/92214.c | #include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i)
{
// condition for nonprime number
if (n % i == 0)
{
flag = 1;
break;
}
}
if (n == 1)
{
printf("1 is neither a prime nor a composite number.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
} |
the_stack_data/694326.c | /* $Id: ctatv.c,v 1.1.1.1 2006/04/21 20:56:15 peachey Exp $
*----------------------------------------------------------------------
*
* Routine name: CTATV
*
* Programmer and Completion Date:
* Lloyd Rawley - S.T.X. - 07/28/89
* (Retyped by Masaki Mori - 04/19/96)
* (Converted to C for bary, optimized,
* corrected following Faithead & Bretagnon 1990, A&A 229, 240
* by Arnold Rots - 1997-11-20)
*
* Function: Computes the cumulative relativistic time correction to
* earth-based clocks, TDB-TDT, for a given time. Routine
* furnished by the Bureau des Longitudes, modified by
* removal of terms much smaller than 0.1 microsecond.
*
* Calling Sequence: tdbdt = ctacv(jdno, fjdno)
* Argument Type I/O Description
* -------- ---- --- ----------------------------------------
* jdno long I Julian day number of lookup
* fjdno double I Fractional part of Julian day number
* tdbtdt double O Time difference TDB-TDT (seconds)
*
* Called by: TTtoTDB
*
* Calls: none
*
* COMMON use: none
*
* Significant Local Variables:
* Variable Type Ini. Val. Description
* -------- ---- --------- ----------------------------------
* t double - Time since 2000.0 (millennia)
* tt double - Square of T
*
* Logical Units Used: none
*
* Method:
* Convert input time to millennia since 2000.0
* For each sinusoidal term of sufficient amplitude
* Compute value of term at input time
* End for
* Add together all terms and convert from microseconds to seconds
* End CTATV
*
* Note for the retyped version:
* Results of this routine has been confirmed up to (1E-10)microsecond
* level compared with the calculation by the IBM machine: this seems
* to be within the 64-bit precision allowance, but still the original
* hardcopy should be kept as the right one. (M.M.)
*
* Note for the C version: the accuracy is guaranteed to 100 ns.
*
*---------------------------------------------------------------------------*/
#include <math.h>
double ctatv (long jdno, double fjdno)
{
/* Masaharu Hirayama 1 November 2008: Commented out variable 't31' in the
following line because it is not used in any part of this function. */
double t, tt, t1, t2, t3, t4, t5, t24, t25, t29, t30/*, t31*/ ;
t = ((jdno-2451545) + fjdno)/(365250.0) ;
tt = t*t ;
t1 = 1656.674564 * sin( 6283.075943033*t + 6.240054195)
+ 22.417471 * sin( 5753.384970095*t + 4.296977442)
+ 13.839792 * sin( 12566.151886066*t + 6.196904410)
+ 4.770086 * sin( 529.690965095*t + 0.444401603)
+ 4.676740 * sin( 6069.776754553*t + 4.021195093)
+ 2.256707 * sin( 213.299095438*t + 5.543113262)
+ 1.694205 * sin( -3.523118349*t + 5.025132748)
+ 1.554905 * sin( 77713.772618729*t + 5.198467090)
+ 1.276839 * sin( 7860.419392439*t + 5.988822341)
+ 1.193379 * sin( 5223.693919802*t + 3.649823730)
+ 1.115322 * sin( 3930.209696220*t + 1.422745069)
+ 0.794185 * sin( 11506.769769794*t + 2.322313077)
+ 0.600309 * sin( 1577.343542448*t + 2.678271909)
+ 0.496817 * sin( 6208.294251424*t + 5.696701824)
+ 0.486306 * sin( 5884.926846583*t + 0.520007179)
+ 0.468597 * sin( 6244.942814354*t + 5.866398759)
+ 0.447061 * sin( 26.298319800*t + 3.615796498)
+ 0.435206 * sin( -398.149003408*t + 4.349338347)
+ 0.432392 * sin( 74.781598567*t + 2.435898309)
+ 0.375510 * sin( 5507.553238667*t + 4.103476804) ;
t2 = 0.243085 * sin( -775.522611324*t + 3.651837925)
+ 0.230685 * sin( 5856.477659115*t + 4.773852582)
+ 0.203747 * sin( 12036.460734888*t + 4.333987818)
+ 0.173435 * sin( 18849.227549974*t + 6.153743485)
+ 0.159080 * sin( 10977.078804699*t + 1.890075226)
+ 0.143935 * sin( -796.298006816*t + 5.957517795)
+ 0.137927 * sin( 11790.629088659*t + 1.135934669)
+ 0.119979 * sin( 38.133035638*t + 4.551585768)
+ 0.118971 * sin( 5486.777843175*t + 1.914547226)
+ 0.116120 * sin( 1059.381930189*t + 0.873504123)
+ 0.101868 * sin( -5573.142801634*t + 5.984503847)
+ 0.098358 * sin( 2544.314419883*t + 0.092793886)
+ 0.080164 * sin( 206.185548437*t + 2.095377709)
+ 0.079645 * sin( 4694.002954708*t + 2.949233637)
+ 0.075019 * sin( 2942.463423292*t + 4.980931759)
+ 0.064397 * sin( 5746.271337896*t + 1.280308748)
+ 0.063814 * sin( 5760.498431898*t + 4.167901731)
+ 0.062617 * sin( 20.775395492*t + 2.654394814)
+ 0.058844 * sin( 426.598190876*t + 4.839650148)
+ 0.054139 * sin( 17260.154654690*t + 3.411091093) ;
t3 = 0.048373 * sin( 155.420399434*t + 2.251573730)
+ 0.048042 * sin( 2146.165416475*t + 1.495846011)
+ 0.046551 * sin( -0.980321068*t + 0.921573539)
+ 0.042732 * sin( 632.783739313*t + 5.720622217)
+ 0.042560 * sin(161000.685737473*t + 1.270837679)
+ 0.042411 * sin( 6275.962302991*t + 2.869567043)
+ 0.040759 * sin( 12352.852604545*t + 3.981496998)
+ 0.040480 * sin( 15720.838784878*t + 2.546610123)
+ 0.040184 * sin( -7.113547001*t + 3.565975565)
+ 0.036955 * sin( 3154.687084896*t + 5.071801441)
+ 0.036564 * sin( 5088.628839767*t + 3.324679049)
+ 0.036507 * sin( 801.820931124*t + 6.248866009)
+ 0.034867 * sin( 522.577418094*t + 5.210064075)
+ 0.033529 * sin( 9437.762934887*t + 2.404714239)
+ 0.033477 * sin( 6062.663207553*t + 4.144987272)
+ 0.032438 * sin( 6076.890301554*t + 0.749317412)
+ 0.032423 * sin( 8827.390269875*t + 5.541473556)
+ 0.030215 * sin( 7084.896781115*t + 3.389610345)
+ 0.029862 * sin( 12139.553509107*t + 1.770181024)
+ 0.029247 * sin(-71430.695617928*t + 4.183178762) ;
t4 = 0.028244 * sin( -6286.598968340*t + 5.069663519)
+ 0.027567 * sin( 6279.552731642*t + 5.040846034)
+ 0.025196 * sin( 1748.016413067*t + 2.901883301)
+ 0.024816 * sin( -1194.447010225*t + 1.087136918)
+ 0.022567 * sin( 6133.512652857*t + 3.307984806)
+ 0.022509 * sin( 10447.387839604*t + 1.460726241)
+ 0.021691 * sin( 14143.495242431*t + 5.952658009)
+ 0.020937 * sin( 8429.241266467*t + 0.652303414)
+ 0.020322 * sin( 419.484643875*t + 3.735430632)
+ 0.017673 * sin( 6812.766815086*t + 3.186129845)
+ 0.017806 * sin( 73.297125859*t + 3.475975097)
+ 0.016155 * sin( 10213.285546211*t + 1.331103168)
+ 0.015974 * sin( -2352.866153772*t + 6.145309371)
+ 0.015949 * sin( -220.412642439*t + 4.005298270)
+ 0.015078 * sin( 19651.048481098*t + 3.969480770)
+ 0.014751 * sin( 1349.867409659*t + 4.308933301)
+ 0.014318 * sin( 16730.463689596*t + 3.016058075)
+ 0.014223 * sin( 17789.845619785*t + 2.104551349)
+ 0.013671 * sin( -536.804512095*t + 5.971672571)
+ 0.012462 * sin( 103.092774219*t + 1.737438797) ;
t5 = 0.012420 * sin( 4690.479836359*t + 4.734090399)
+ 0.011942 * sin( 8031.092263058*t + 2.053414715)
+ 0.011847 * sin( 5643.178563677*t + 5.489005403)
+ 0.011707 * sin( -4705.732307544*t + 2.654125618)
+ 0.011622 * sin( 5120.601145584*t + 4.863931876)
+ 0.010962 * sin( 3.590428652*t + 2.196567739)
+ 0.010825 * sin( 553.569402842*t + 0.842715011)
+ 0.010396 * sin( 951.718406251*t + 5.717799605)
+ 0.010453 * sin( 5863.591206116*t + 1.913704550)
+ 0.010099 * sin( 283.859318865*t + 1.942176992)
+ 0.009858 * sin( 6309.374169791*t + 1.061816410)
+ 0.009963 * sin( 149.563197135*t + 4.870690598)
+ 0.009370 * sin(149854.400135205*t + 0.673880395) ;
t24 = t * ( 102.156724 * sin( 6283.075849991*t + 4.249032005)
+ 1.706807 * sin( 12566.151699983*t + 4.205904248)
+ 0.269668 * sin( 213.299095438*t + 3.400290479)
+ 0.265919 * sin( 529.690965095*t + 5.836047367)
+ 0.210568 * sin( -3.523118349*t + 6.262738348)
+ 0.077996 * sin( 5223.693919802*t + 4.670344204) ) ;
t25 = t * ( 0.059146 * sin( 26.298319800*t + 1.083044735)
+ 0.054764 * sin( 1577.343542448*t + 4.534800170)
+ 0.034420 * sin( -398.149003408*t + 5.980077351)
+ 0.033595 * sin( 5507.553238667*t + 5.980162321)
+ 0.032088 * sin( 18849.227549974*t + 4.162913471)
+ 0.029198 * sin( 5856.477659115*t + 0.623811863)
+ 0.027764 * sin( 155.420399434*t + 3.745318113)
+ 0.025190 * sin( 5746.271337896*t + 2.980330535)
+ 0.024976 * sin( 5760.498431898*t + 2.467913690)
+ 0.022997 * sin( -796.298006816*t + 1.174411803)
+ 0.021774 * sin( 206.185548437*t + 3.854787540)
+ 0.017925 * sin( -775.522611324*t + 1.092065955)
+ 0.013794 * sin( 426.598190876*t + 2.699831988)
+ 0.013276 * sin( 6062.663207553*t + 5.845801920)
+ 0.012869 * sin( 6076.890301554*t + 5.333425680)
+ 0.012152 * sin( 1059.381930189*t + 6.222874454)
+ 0.011774 * sin( 12036.460734888*t + 2.292832062)
+ 0.011081 * sin( -7.113547001*t + 5.154724984)
+ 0.010143 * sin( 4694.002954708*t + 4.044013795)
+ 0.010084 * sin( 522.577418094*t + 0.749320262)
+ 0.009357 * sin( 5486.777843175*t + 3.416081409) ) ;
t29 = tt * ( 0.370115 * sin( 4.712388980)
+ 4.322990 * sin( 6283.075849991*t + 2.642893748)
+ 0.122605 * sin( 12566.151699983*t + 2.438140634)
+ 0.019476 * sin( 213.299095438*t + 1.642186981)
+ 0.016916 * sin( 529.690965095*t + 4.510959344)
+ 0.013374 * sin( -3.523118349*t + 1.502210314) ) ;
t30 = t * tt * 0.143388 * sin( 6283.075849991*t + 1.131453581) ;
return (t1+t2+t3+t4+t5+t24+t25+t29+t30) * 1.0e-6 ;
}
|
the_stack_data/72752.c | #include <stdio.h>
unsigned long int fat(unsigned int n) {
int fatorial = 1;
for (int i = 1; i <= n; i++) fatorial *= i;
return fatorial;
}
int main() {
int numero;
scanf("%d", &numero);
printf("%d! = %ld", numero, fat(numero));
}
//https://pt.stackoverflow.com/q/330965/101
|
the_stack_data/218893546.c | #include <stdio.h>
int main()
{
union {
struct
{
int a : 3;
int b : 3;
int c : 2;
} x;
unsigned char y;
} z;
z.x.a = 6;
z.x.b = 5;
z.x.c = 2;
printf("%i\n", z.y); // despliega 174 (en binario: 10101110)
} |
the_stack_data/55014.c | #include <stdio.h>
#define Debug
#ifdef Debug
#define MAX_N 1000
#else
#define MAX_N 5000
#endif
int main() {
printf("MAX_N = %d\n", MAX_N);
return 0;
}
|
the_stack_data/156394396.c | /*
(c) copyright 1988 by the Vrije Universiteit, Amsterdam, The Netherlands.
See the copyright notice in the ACK home directory, in the file "Copyright".
*/
/*
Module: Dummy priority routines
Author: Ceriel J.H. Jacobs
Version: $Header: /cvsup/minix/src/lib/libm2/stackprio.c,v 1.1.1.1 2005/04/21 14:56:22 beng Exp $
*/
static unsigned prio = 0;
stackprio(n)
unsigned n;
{
unsigned old = prio;
if (n > prio) prio = n;
return old;
}
unstackprio(n)
unsigned n;
{
prio = n;
}
|
the_stack_data/164027.c | //Question 1
#include <stdio.h>
int main(void){
//Variable declaration
char roomType, payMethod, con = 'N';
int numOfRooms, night;
double rate = 0, discount = 0, total;
printf("Room Type \t Description \t\t Rate per Night \n");
printf(" D \t\t Deluxe \t\t 31000.00 \n");
printf(" S \t\t Superior Deluxe \t 35000.00 \n");
printf(" C \t\t Club Suites \t\t 50000.00 \n");
printf(" E \t\t Executive Suites \t 75000.00 \n");
printf(" P \t\t Presidential Suite \t 100000.00 \n\n");
do{
printf("Input room type : ");
scanf(" %c", &roomType);
printf("Input number of rooms : ");
scanf("%d", &numOfRooms);
printf("Input no of nights : ");
scanf("%d", &night);
printf("Input Payment method : ");
scanf(" %c", &payMethod);
switch (roomType){
case 'D': rate = 31000;
break;
case 'S': rate = 35000;
break;
case 'C': rate = 50000;
break;
case 'E': rate = 75000;
break;
case 'P': rate = 100000;
break;
default: printf("Invalid type !!!");
}
total = rate * night * numOfRooms;
if (payMethod == 'C' || payMethod == 'c'){
discount = total * 0.1;
}
total -= discount;
printf("Your total amount : %.2f\n", total);
printf("Do you want to continue ? (Y/N)\n");
scanf(" %c", &con);
}while (con == 'Y' || con == 'y');
}
|
the_stack_data/143761.c | #include<stdio.h>
// In the case of function calls, the values separated by commas are evaluated right to left
int i=2;
main()
{
void add();
add(i++,--i);
printf("\ni=%d \n",i);
}
void add(int a ,int b)
{
printf("\na=%d b=%d",a,b);
}
|
the_stack_data/999640.c | /*
* Simple sound playback using ALSA API and libasound.
*
* Compile:
* $ cc -o play sound_playback.c -lasound
*
* Usage:
* $ ./play <sample_rate> <channels> <seconds> < <file>
*
* Examples:
* $ ./play 44100 2 5 < /dev/urandom
* $ ./play 22050 1 8 < /path/to/file.wav
*
* Copyright (C) 2009 Alessandro Ghedini <[email protected]>
* --------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Alessandro Ghedini wrote this file. As long as you retain this
* notice you can do whatever you want with this stuff. If we
* meet some day, and you think this stuff is worth it, you can
* buy me a beer in return.
* --------------------------------------------------------------
*/
#include <alsa/asoundlib.h>
#include <stdio.h>
#define PCM_DEVICE "default"
int main(int argc, char **argv) {
unsigned int pcm, tmp;
int rate, channels, seconds;
snd_pcm_t *pcm_handle;
snd_pcm_hw_params_t *params;
snd_pcm_uframes_t frames;
char *buff;
int buff_size, loops;
if (argc < 4) {
printf("Usage: %s <sample_rate> <channels> <seconds>\n",
argv[0]);
return -1;
}
rate = atoi(argv[1]);
channels = atoi(argv[2]);
seconds = atoi(argv[3]);
/* Open the PCM device in playback mode */
if (pcm = snd_pcm_open(&pcm_handle, PCM_DEVICE,
SND_PCM_STREAM_PLAYBACK, 0) < 0)
printf("ERROR: Can't open \"%s\" PCM device. %s\n",
PCM_DEVICE, snd_strerror(pcm));
/* Allocate parameters object and fill it with default values*/
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(pcm_handle, params);
/* Set parameters */
if (pcm = snd_pcm_hw_params_set_access(pcm_handle, params,
SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
printf("ERROR: Can't set interleaved mode. %s\n", snd_strerror(pcm));
if (pcm = snd_pcm_hw_params_set_format(pcm_handle, params,
SND_PCM_FORMAT_S16_LE) < 0)
printf("ERROR: Can't set format. %s\n", snd_strerror(pcm));
if (pcm = snd_pcm_hw_params_set_channels(pcm_handle, params, channels) < 0)
printf("ERROR: Can't set channels number. %s\n", snd_strerror(pcm));
if (pcm = snd_pcm_hw_params_set_rate_near(pcm_handle, params, &rate, 0) < 0)
printf("ERROR: Can't set rate. %s\n", snd_strerror(pcm));
/* Write parameters */
if (pcm = snd_pcm_hw_params(pcm_handle, params) < 0)
printf("ERROR: Can't set harware parameters. %s\n", snd_strerror(pcm));
/* Resume information */
printf("PCM name: '%s'\n", snd_pcm_name(pcm_handle));
printf("PCM state: %s\n", snd_pcm_state_name(snd_pcm_state(pcm_handle)));
snd_pcm_hw_params_get_channels(params, &tmp);
printf("channels: %i ", tmp);
if (tmp == 1)
printf("(mono)\n");
else if (tmp == 2)
printf("(stereo)\n");
snd_pcm_hw_params_get_rate(params, &tmp, 0);
printf("rate: %d bps\n", tmp);
printf("seconds: %d\n", seconds);
/* Allocate buffer to hold single period */
snd_pcm_hw_params_get_period_size(params, &frames, 0);
buff_size = frames * channels * 2 /* 2 -> sample size */;
buff = (char *) malloc(buff_size);
snd_pcm_hw_params_get_period_time(params, &tmp, NULL);
for (loops = (seconds * 1000000) / tmp; loops > 0; loops--) {
if (pcm = read(0, buff, buff_size) == 0) {
printf("Early end of file.\n");
return 0;
}
if (pcm = snd_pcm_writei(pcm_handle, buff, frames) == -EPIPE) {
printf("XRUN.\n");
snd_pcm_prepare(pcm_handle);
} else if (pcm < 0) {
printf("ERROR. Can't write to PCM device. %s\n", snd_strerror(pcm));
}
}
snd_pcm_drain(pcm_handle);
snd_pcm_close(pcm_handle);
free(buff);
return 0;
} |
the_stack_data/225142057.c | // [ACM] #10161 - Ant on a Chessboard
// Problem Status CPU Date&Time(UTC) ID Best CPU
// 10161 Accepted 0.010 2008-10-15 04:19:08 6725567 0.000
#include<stdio.h>
int main(void)
{
long long int i, n, t, k;
while(scanf("%lld" , &n) != EOF)
{
if(n == 0)
break;
k = 0;
t = 1;
for(i = 1; ; )
{
if(i - t + 1 <= n && n <= i + t - 1)
{
if(n == i)
printf("%lld %lld\n" , t, t);
else
{
if(t % 2 == 0)
{
if(i - t + 1 <= n && n < i)
printf("%lld %lld\n" , t - i + n, t);
else
printf("%lld %lld\n" , t, t - n + i);
}
else
{
if(i - t + 1 <= n && n < i)
printf("%lld %lld\n" , t, t - i + n);
else
printf("%lld %lld\n" , t - n + i, t);
}
}
break;
}
k += 2;
i += k;
t ++;
}
}
return 0;
}
|
the_stack_data/11075355.c | #include <stdio.h>
#include <math.h>
int main(void)
{
int num;
double a;
double b;
double c;
double hipotenusa;
double x1;
double x2;
double delta;
double raiz;
double expo = 2;
double rest = 0;
double dividendo;
double divisor;
double resultado;
int n;
int contador;
int fatorial;
do
{
printf("1 - calcular a hipotenusa (Pitágoras).\n");
printf("2 - calcular as raízes reais usando a fórmula de Bháskara.\n");
printf("3 - calcular o resto de uma divisão de dois números reais.\n");
printf("4 - calcule o fatorial de um número inteiro menor que 10.\n");
printf("5 - sair do programa.\n");
printf("Digite qual funcao voce quer: ");
scanf("%d", &num);
if (num == 1)
{
printf("1 - calcular a hipotenusa (Pitágoras).\n");
printf("Digite um valor do cateto 1:");
scanf("%lf", &a);
printf("Digite um valor do cateto 2:");
scanf("%lf", &b);
c = pow(a, expo) + pow(b, expo);
hipotenusa = sqrt(c);
printf("A hipotenusa é %.2lf \n", hipotenusa);
}
else if (num == 2)
{
printf("2 - calcular as raízes reais usando a fórmula de Bháskara.\n");
printf("Digite o valor de A: ");
scanf("%lf", &a);
printf("Digite o valor de B: ");
scanf("%lf", &b);
printf("Digite o valor de C: ");
scanf("%lf", &c);
delta = pow(b, expo) - 4 * a * c;
if (delta < 0)
{
printf("Nao tem raiz negativa!! \n");
}
else
{
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("O valor de X1 = %.2lf e de X2 = %.2lf \n", x1, x2);
}
}
else if (num == 3)
{
printf("3 - calcular o resto de uma divisão de dois números reais.\n");
printf("Digite o dividendo: ");
scanf("%lf", ÷ndo);
printf("Digite o dividendo: ");
scanf("%lf", &divisor);
if (divisor == 0)
{
printf("Divisor é 0!! \n");
}
else
{
resultado = dividendo / divisor;
printf("O resultado da divisao de %.2lf // %.2lf = %.0lf\n", dividendo, divisor, resultado);
}
}
else if (num == 4)
{
printf("4 - calcule o fatorial de um número inteiro menor que 10. \n");
printf("Digite um inteiro nao-negativo: ");
scanf("%d", &n);
fatorial = 1;
contador = 2;
while (contador <= n)
{
fatorial = fatorial * contador;
contador = contador + 1;
}
printf("O valor de %d: %d \n", n, fatorial);
}
} while (num != 5);
return 0;
} |
the_stack_data/37636843.c | /** since the arguments of main is never used, they would
* be removed by the general transformer.
* This example should pass.
*/
int sum(int k){
return (1+k)*k/2;
}
int main(int argc, char* argv[]){
int a=9;
a = sum(a);
return 0;
}
|
the_stack_data/23892.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define true 1
#define false 0
void printGrid(int grid[9][9]) {
int i, j;
printf("|-------|-------|-------|\n");
for (i = 0; i < 9; i++) {
printf("| ");
for (j = 0; j < 9; j++) {
printf("%d ", grid[i][j]);
if ((j + 1) % 3 == 0 && j > 0) {
printf("| ");
}
}
printf("\n");
if ((i + 1) % 3 == 0) {
printf("|-------|-------|-------|\n");
}
}
}
int inCol(int num, int col, int grid[9][9]) {
int i;
int total = 0;
for (i = 0; i < 9; i++) {
if (grid[i][col] == num) {
total++;
}
}
return total;
}
int inRow(int num, int row, int grid[9][9]) {
int i;
int total = 0;
for (i = 0; i < 9; i++) {
if (grid[row][i] == num) {
total++;
}
}
return total;
}
int checkBoxRow(int num, int row, int col, int grid[9][9]) {
return (grid[row][col] == num) + (grid[row][col + 1] == num) + (grid[row][col + 2] == num);
}
int checkBoxCol(int num, int row, int col, int grid[9][9]) {
return (grid[row][col] == num) + (grid[row + 1][col] == num) + (grid[row + 2][col] == num);
}
int inBox(int num, int row, int col, int grid[9][9]) {
int cRow = (row / 3) * 3;
int cCol = (col / 3) * 3;
int sum =
checkBoxRow(num, cRow, cCol, grid) +
checkBoxRow(num, cRow + 1, cCol, grid) +
checkBoxRow(num, cRow + 2, cCol, grid) +
checkBoxCol(num, cRow, cCol, grid) +
checkBoxCol(num, cRow, cCol + 1, grid) +
checkBoxCol(num, cRow, cCol + 2, grid);
return sum / 2;
}
int goodRow(int row, int grid[9][9]) {
int num;
for (num = 1; num < 10; num++) {
if (inRow(num, row, grid) != 1) {
return false;
}
}
return true;
}
int goodCol(int col, int grid[9][9]) {
int num;
for (num = 1; num < 10; num++) {
if (inCol(num, col, grid) != 1) {
return false;
}
}
return true;
}
int goodRows(int grid[9][9]) {
int row;
for (row = 0; row < 9; row++) {
if (!goodRow(row, grid)) {
return false;
}
}
return true;
}
int goodCols(int grid[9][9]) {
int col;
for (col = 0; col < 9; col++) {
if (!goodCol(col, grid)) {
return false;
}
}
return true;
}
int goodBox(int row, int col, int grid[9][9]) {
// Must be provided the boxes upper left indexes
int num;
for (num = 1; num < 10; num++) {
if (inBox(num, row, col, grid) != 1) {
return false;
}
}
return true;
}
int goodBoxes(int grid[9][9]) {
int n1 = 1;
int n2;
int row, col;
for (row = 0; row < 9; row = 3*n1) {
n2 = 1;
for (col = 0; col < 9; col = 3*n2) {
if (!goodBox(row, col, grid)) {
return false;
}
n2++;
}
printf("\n");
n1++;
}
return true;
}
int isSolved(int grid[9][9]) {
int row, col;
for (row = 0; row < 9; row++) {
for (col = 0; col < 9; col++) {
if (grid[row][col] == 0) {
return false;
}
}
}
return goodRows(grid) && goodCols(grid) && goodBoxes(grid);
}
int recurseSolve(int row, int col, int orig[9][9], int grid[9][9]) {
// Can't change cell
/*printGrid(grid);*/
if (row == 9) {
return isSolved(grid);
}
if (orig[row][col] != 0) {
if (col == 8) {
return recurseSolve(row + 1, 0, orig, grid);
}
else {
return recurseSolve(row, col + 1, orig, grid);
}
}
// Can Change Cell
else {
int num;
for (num = 1; num < 10; num++) {
if (!inRow(num, row, grid) && !inCol(num, col, grid) && !inBox(num, row, col, grid)) {
grid[row][col] = num;
if (col == 8) {
if (recurseSolve(row + 1, 0, orig, grid)) {
return true;
}
}
else {
if (recurseSolve(row, col + 1, orig, grid)) {
return true;
}
}
}
}
grid[row][col] = 0;
return false;
}
}
void write_grid_solution2(double time_spent, int grid[9][9]) {
char filename[64];
time_t now;
struct tm *time = gmtime(&now);
snprintf(filename, sizeof(char)*64, "./solution_%lu.txt", (long unsigned) now);
/*snprintf(filename, sizeof(char)*64, "./solution_%d.txt", (int) now);*/
FILE *output = fopen(filename, "w");
// Start Writing
fprintf(output, "Time: %fs\n", time_spent);
int i, j;
fprintf(output, "|-------|-------|-------|\n");
for (i = 0; i < 9; i++) {
fprintf(output, "| ");
for (j = 0; j < 9; j++) {
fprintf(output, "%d ", grid[i][j]);
if ((j + 1) % 3 == 0 && j > 0) {
fprintf(output, "| ");
}
}
fprintf(output, "\n");
if ((i + 1) % 3 == 0) {
fprintf(output, "|-------|-------|-------|\n");
}
}
fclose(output);
}
void write_grid_solution(int num, double time_spent, int grid[9][9]) {
char filename[64];
snprintf(filename, sizeof(char)*64, "./solutions/grid%d_solution.txt", num);
FILE *output = fopen(filename, "w");
// Start Writing
fprintf(output, "Time: %fs\n", time_spent);
int i, j;
fprintf(output, "|-------|-------|-------|\n");
for (i = 0; i < 9; i++) {
fprintf(output, "| ");
for (j = 0; j < 9; j++) {
fprintf(output, "%d ", grid[i][j]);
if ((j + 1) % 3 == 0 && j > 0) {
fprintf(output, "| ");
}
}
fprintf(output, "\n");
if ((i + 1) % 3 == 0) {
fprintf(output, "|-------|-------|-------|\n");
}
}
fclose(output);
}
int main(int argc, char **argv) {
// Initial Variable
if (argc == 2) {
FILE *input = fopen(argv[1], "r");
int num;
int grid[9][9];
int orig[9][9];
int scanned;
int total = 0;
clock_t begin, end;
// While read the grid num
while (1 == fscanf(input, "Grid %d", &num)) {
printf("Grid %d\n", num);
// Read in array
int x, y;
char digit;
for (y = 0; y < 9; y++) {
for (x = 0; x < 9; x++) {
// Read in char
scanned = fscanf(input, " %c ", &digit);
grid[y][x] = digit - '0';
}
}
// Copy Over
memcpy(orig, grid, sizeof(int)*81);
// Display Grid
/*solvePuzzle(orig, grid);*/
printGrid(grid);
begin = clock();
int solved = recurseSolve(0, 0, orig, grid);
end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Solved: %d\t%f\n", num, time_spent);
write_grid_solution(num, time_spent, grid);
printGrid(grid);
total += 100*grid[0][0] + 10*grid[0][1] + grid[0][2];
}
fclose(input);
printf("Summed Total: %d\n", total);
}
else {
int i;
int grid[9][9];
int orig[9][9];
char buffer[11];
clock_t begin, end;
int row = 0;
printf("Input row where blanks are 0's with no spaces!\n");
while (row < 9) {
scanf("%s", buffer);
for (i = 0; i < 9; i++) {
grid[row][i] = (int) buffer[i] - '0';
}
row++;
}
memcpy(orig, grid, sizeof(int)*81);
// Display Grid
/*solvePuzzle(orig, grid);*/
printGrid(grid);
begin = clock();
int solved = recurseSolve(0, 0, orig, grid);
end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Solved: %fs\n", time_spent);
write_grid_solution2(time_spent, grid);
printGrid(grid);
}
return 0;
}
|
the_stack_data/20649.c | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h> // needed for memset
#include <sys/types.h>
#include <dirent.h>
#include <stdbool.h>
#include <time.h>
#include <sys/ioctl.h>
#include <ctype.h>
#include <glob.h>
#define RETURNCODE int
#define OK 0
/****************************************************************************
globals
*****************************************************************************/
unsigned int iSerialDeviceCtr = 0;
unsigned int iActiveDevice = -1;
char serialDeviceNames[256][256];
char buf[256];
char workbuff[512];
unsigned char delayms;
int tty_fd;
long chksum;
unsigned int byteCtr;
unsigned long szBuf;
/****************************************************************************
stuff to put in a utility library - START
*****************************************************************************/
char* stristr( const char* str1, const char* str2 )
{
const char* p1 = str1 ;
const char* p2 = str2 ;
const char* r = *p2 == 0 ? str1 : 0 ;
while( *p1 != 0 && *p2 != 0 ){
if( tolower( (unsigned char)*p1 ) == tolower( (unsigned char)*p2 ) ){
if( r == 0 ){
r = p1 ;
}
p2++ ;
}
else{
p2 = str2 ;
if( r != 0 ){
p1 = r + 1 ;
}
if( tolower( (unsigned char)*p1 ) == tolower( (unsigned char)*p2 ) ){
r = p1 ;
p2++ ;
}
else{
r = 0 ;
}
}
p1++ ;
}
return *p2 == 0 ? (char*)r : 0 ;
}
int stricmp(const char *a, const char *b, int x) {
int ca, cb,c;
c=0;
do {
ca = (unsigned char) *a++;
cb = (unsigned char) *b++;
ca = tolower(toupper(ca));
cb = tolower(toupper(cb));
c++;
} while (c < x && ca == cb && ca != '\0');
return ca - cb;
}
int EndsWith(const char *str, const char *suffix)
{
if (!str || !suffix)
return 0;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
return 0;
return stricmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
void String_Upper(char string[])
{
int i = 0;
while (string[i] != '\0')
{
if (string[i] >= 'a' && string[i] <= 'z') {
string[i] = string[i] - 32;
}
i++;
}
}
void String_Lower(char string[])
{
int i = 0;
while (string[i] != '\0')
{
if (string[i] >= 'A' && string[i] <= 'Z') {
string[i] = string[i] + 32;
}
i++;
}
}
bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : stricmp(pre, str, lenpre) == 0;
}
/****************************************************************************
stuff to put in a utility library - END
*****************************************************************************/
RETURNCODE getSerialDevices(char* desiredDevice) {
DIR *dp;
struct dirent *ep;
printf("Searching for non-bluetooth tty devices...\n");
memset(&serialDeviceNames,0x0,256*256);
dp = opendir("/dev");
if(dp != NULL) {
while((ep = readdir(dp)) != NULL) {
strcpy(buf,ep->d_name);
//String_Upper(buf);
if(startsWith("TTY.",buf)) {
if(stristr(buf,"BLUE") == NULL) {
strcat(serialDeviceNames[iSerialDeviceCtr], ep->d_name);
if(stricmp(desiredDevice, buf, strlen(desiredDevice)) == 0)
iActiveDevice = iSerialDeviceCtr;
iSerialDeviceCtr++;
if(iSerialDeviceCtr > 255) {
closedir(dp);
perror("Too many serial devices!\n");
return -2;
}
}
else {
printf("...ignoring bluetooth device: %s ...\n",ep->d_name);
}
}
}
closedir(dp);
}
else {
perror("Couldn't open device directory /dev");
return -1;
}
return OK;
}
void listDeviceChoices() {
printf("Your choices: \n");
for(int i=0;i<iSerialDeviceCtr;i++) {
printf(" %s\n",serialDeviceNames[i]);
}
printf("\n");
}
RETURNCODE getDevicesAndHandleErrors(char* desiredDevice) {
if(getSerialDevices(desiredDevice) < OK) {
perror("Problem getting serial devices! Exiting.");
return -1;
}
printf("\nFound %d valid serial device(s).\n", iSerialDeviceCtr);
if(iSerialDeviceCtr < 1) {
printf("Unable to continue. No usable devices.\n");
return -2;
}
if(iSerialDeviceCtr == 1) {
iActiveDevice = 0;
printf("Defaulting to serial device: %s\n", serialDeviceNames[iActiveDevice]);
}
else {
if(strlen(desiredDevice) == 0) {
printf("You must specify a desired device name, when there is more than one serial device.\n");
listDeviceChoices();
return -3;
}
if(iActiveDevice == -1) {
printf("You attempted to specify a desired device, but it was not found. Try again.\n");
listDeviceChoices();
return -4;
}
printf("Unexpected error.\n");
return -5;
}
return 0;
}
void sleep_ms(int milliseconds) {
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
}
void sendByte(char b) {
chksum += b;
byteCtr++;
write(tty_fd,&b,1);
tcdrain(tty_fd);
sleep_ms(delayms);
}
void sendString(char* s) {
char c;
int x;
x = strlen(s);
for(int i=0;i<x;i++) {
c=*(s+i);
sendByte(c);
}
}
void sendResponse(char* s) {
sendString(s);
sendByte(13);
}
void lsResponse(char* s) {
DIR *dp;
struct dirent *ep;
char c;
int status;
time_t now;
time_t later;
struct dirent **namelist;
int n;
chksum = 0;
byteCtr = 0;
time(&now);
char *token = strtok(s, " "); // command itself
token = strtok(NULL, " "); // wildcard path sent
if(token == NULL) {
strcpy(buf,"*");
token = buf;
}
sprintf(workbuff,"%s",token);
String_Lower(workbuff);
glob_t globbuf;
int r1, r2;
r1 = glob(token, 0, NULL, &globbuf);
r2 = glob(workbuff, GLOB_APPEND, NULL, &globbuf);
if(r1 == 0 || r2 == 0)
{
int i;
printf("%zu matching file entries...", globbuf.gl_pathc);
for(i = 0; i < globbuf.gl_pathc; i++) {
strcpy(buf,globbuf.gl_pathv[i]);
String_Upper(buf);
sendString(buf);
sendByte(':');
}
globfree(&globbuf);
}
sendByte(13);
time(&later);
double seconds = difftime(later, now);
if(seconds == 0)
seconds = 1;
printf(" Checksum: %ld\n",chksum);
printf(" Bytes sent: %d\n", byteCtr);
printf(" Duration: %d\n", (int)seconds);
printf(" Bps: %d\n", byteCtr/(int)seconds);
}
int
set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
perror ("error from tcgetattr");
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= CRTSCTS;
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
//tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
perror ("error from tcsetattr");
return -1;
}
return 0;
}
void
set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
perror ("error from tggetattr");
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
perror ("error setting term attributes");
}
void handleSetDelay(char* s) {
char *token = strtok(s, " "); // command itself
token = strtok(NULL, " "); // numeric value
if(token == NULL) {
sendResponse("NO_VALUE_SPECIFIED");
return;
}
int val = atoi(token);
if(val == 0) {
sendResponse("BAD_NUMERIC_VALUE");
return;
}
delayms = val;
sendResponse("OK");
}
char* getCommand() {
unsigned char c;
int iCtr = 0;
c = 0x0;
while( c != 13) {
if(read(tty_fd, &c, 1) > 0) {
if(c != 13) {
workbuff[iCtr] = c;
workbuff[iCtr+1] = 0x0;
iCtr++;
}
}
else
sleep_ms(1);
}
return workbuff;
}
char* base64Encode( char* in, int iLen, char* out) {
size_t sz;
typedef unsigned long UL;
unsigned char c[4];
UL u, len;
const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
//printf("a\n");
FILE* fpIn = fmemopen(in, iLen, "rb");
if(fpIn == NULL) {
printf(" base64 encoding failure, fmemopen\n");
return 0;
}
//printf("b\n");
FILE* fpOut = open_memstream (&out, &sz);
if(fpOut == NULL) {
printf(" base64 encoding failure, open_memstream\n");
return 0;
}
//printf("c\n");
//printf("len: %d\n", iLen);
do {
//printf("x\n");
c[1] = c[2] = 0;
//printf("x\n");
if (!(len = fread(&c, 1, 3, fpIn))) break;
//printf("y, len=%zu\n",len);
//printf("c[0]=%d, c[1]=%d, c[2]=%d, c[3]=%d\n", c[0], c[1], c[2], c[3]);
u = (UL)c[0]<<16 | (UL)c[1]<<8 | (UL)c[2];
//printf("z\n");
//printf("u=%zu\n",(u>>18));
fputc(alpha[u>>18], fpOut);
//fflush(fpOut);
//printf("size: %zu\n",sz);
fputc(alpha[u>>12 & 63], fpOut);
//fflush(fpOut);
//printf("size: %zu\n",sz);
fputc(len < 2 ? '=' : alpha[u>>6 & 63], fpOut);
//fflush(fpOut);
//printf("size: %zu\n",sz);
fputc(len < 3 ? '=' : alpha[u & 63], fpOut);
//fflush(fpOut);
//printf("size: %zu\n",sz);
} while (len == 3);
fputc(0,fpOut);
fflush(fpOut);
//printf("d\n");
fclose(fpIn);
//printf("e\n");
fclose(fpOut);
//printf("f\n");
//for(int i=0;i<sz;i++) {
// putchar(*(out+i));
//}
//printf("\n");
//printf(" base64 ptr in func: %p\n", out);
szBuf = sz;
return out;
}
void handleLoadCommand(char* s) {
FILE *fp;
char *base64Buff;
char tempbuff[512];
char responseBuff[2048];
char blocktype;
unsigned char b;
int len;
unsigned long cksum;
unsigned long bytesRead;
unsigned short address;
unsigned long bytePercentage;
double f;
char *token = strtok(s, " "); // command itself
token = strtok(NULL, " "); // file name
if(token == NULL) {
sendResponse("ERROR_NO_FILE_SPECIFIED");
return;
}
if(EndsWith(token,".CMD") == 0) {
sendResponse("ERROR_FILE_NOT_CMD_FORMAT");
return;
}
fp = fopen(token, "rb");
if(fp == NULL) {
sendResponse("ERROR_UNABLE_TO_OPEN_FILE");
return;
}
bytesRead = 0;
fseek(fp, 0L, SEEK_END);
long szFile = ftell(fp);
rewind(fp);
for(;;) {
if(!fread(tempbuff,1,1,fp)) // EOF
break;
bytesRead++;
blocktype = *(tempbuff);
if(blocktype == 0x0) {
// ignore blocktype 0x00
}
else
if(blocktype == 0x01) {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
//printf("len read: %d\n",len);
if(len<3) // compensate for special values 0,1, and 2.
len+=256;
//printf("adjusted len: %d\n",len);
fread(&address,1,2,fp); // read 16-bit load-address
bytesRead+=2;
len=len-2;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Reading Object block, addr 0x%x, length = %d (%d percent complete)\n",address,len, (int)f);
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
cksum = 0;
for(int i=0;i<len;i++) {
b = *(tempbuff+i);
cksum+=b;
//printf(" %ld ",cksum);
}
//printf("\n cksum=%ld\n", cksum);
base64Buff = base64Encode(tempbuff, len, base64Buff);
f = f / 100;
f = f * 64;
bytePercentage = (int)f;
if(bytePercentage == 0)
bytePercentage = 1;
sprintf(responseBuff,"OBJ %04X %04lX %04lX %s", address, bytePercentage, cksum, base64Buff);
//printf(" %s\n", responseBuff);
free(base64Buff);
int iResendCtr = 0;
do {
sendResponse(responseBuff);
getCommand();
iResendCtr++;
}
while(stricmp(workbuff, "RESEND", strlen(workbuff)) == 0 && iResendCtr < 5);
if(iResendCtr >= 5) {
printf(" too many resends. Forcing stop.\n");
break;
}
if(stricmp(workbuff, "WRITE_FAILED_HIT_CLIENT_BUFFER", strlen(workbuff)) == 0) {
printf(" WRITE_FAILED_HIT_CLIENT_BUFFER while sending object blocks, terminating GET request.");
break;
}
if(stricmp(workbuff, "OK", strlen(workbuff)) != 0) {
printf(" problem sending object block: %s, continuing loop.\n", workbuff);
}
}
else if(blocktype == 0x02) {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Reading Transfer Address, block length = %u, (%d percent complete).\n",len, (int)f);
fread(&address,1,len,fp);
bytesRead+=len;
printf(" Entry point is 0x%x (%d)\n",address,address);
sprintf(responseBuff,"ENTPT %X",address);
sendResponse(responseBuff);
getCommand();
if(stricmp(workbuff, "OK", strlen(workbuff)) != 0) {
printf(" problem sending transfer address: %s\n", workbuff);
}
}
else if(blocktype == 0x03) {
printf("Read End Of File Mark -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0)
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x04) {
printf("Read End of ISAM mark -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x05) {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
//printf("%X\n",len);
if(len == 0 )
len = 256;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Reading Load Module Header, block length = %d (%d percent complete).\n",len,(int)f);
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
printf(" %s\n",tempbuff);
}
else if(blocktype == 0x06) {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Reading PDS Header, block length = %d (%d percent complete).\n",len,(int)f);
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
//printf(" %s\n",tempbuff);
}
else if(blocktype == 0x07) {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Reading Patch Name Header, block length = %u (%d percent complete).\n",len,(int)f);
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
//printf(" %s\n",tempbuff);
}
else if(blocktype == 0x08) {
printf("Read ISAM directory entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x0a) {
printf("Read End of ISAM directory entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x0c) {
printf("Read PDS directory entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x0e) {
printf("Read End of PDS directory entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x10) {
printf("Read Yanked Load Block entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else if(blocktype == 0x1f) {
printf("Read Copyright Block entry -- skipping.\n");
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
if(len == 0 )
len = 256;
memset(tempbuff, 0x0, sizeof(tempbuff));
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
else {
fread(tempbuff,1,1,fp);
bytesRead++;
len=*(tempbuff+0);
len = len & 0x000000ff;
f = (double)bytesRead * (double)100.0 / (double)szFile;
printf("Unknown block type 0x%x, length = %u (%d percent complete).\n",blocktype,len, (int)f);
fread(tempbuff,1,len,fp);
bytesRead+=len;
}
}
fclose(fp);
sendResponse("GET_DONE");
}
int main(int argc,char** argv)
{
char desiredDevice[256];
RETURNCODE r;
struct termios tio;
setbuf(stdout, NULL);
delayms = 4;
printf("Starting...\n");
memset(desiredDevice,0x0,sizeof(desiredDevice));
if(argc > 1) {
strcpy(desiredDevice,argv[1]);
}
printf("Getting devices...\n");
r = getDevicesAndHandleErrors(desiredDevice);
if(r != OK)
exit(r);
printf("Opening...\n");
strcpy(buf,"/dev/");
strcat(buf,serialDeviceNames[iActiveDevice]);
tty_fd = open(buf, O_RDWR | O_NOCTTY | O_NDELAY);
if(tty_fd < 0) {
printf("Unable to open device: %s, rc=%d\n", buf, tty_fd);
exit(-5);
}
set_interface_attribs(tty_fd, B57600, 0);
set_blocking(tty_fd, 0);
bool bRunning = true;
while(bRunning == true) {
workbuff[0]=0x0;
printf("Waiting for command.\n");
getCommand();
if(startsWith("LS",workbuff)) {
printf("Received LS command.\n");
lsResponse(workbuff);
printf("Response sent.\n\n");
}
else if(startsWith("SETDELAY",workbuff)) {
printf("Transmit Delay change requested...");
handleSetDelay(workbuff);
printf("Delay changed to %d.\n\n",delayms);
}
else if(stricmp(workbuff, "KILL", strlen(workbuff)) == 0) {
printf("Received KILL command.\n");
sendResponse("OK");
bRunning = false;
printf("Goodbye cruel world.");
}
else if(startsWith("GET",workbuff)) {
printf("Get Command requested...\n");
printf(" %s\n",workbuff);
handleLoadCommand(workbuff);
printf("Get Command completed.\n\n");
}
else if(startsWith("OK",workbuff)) {
printf("Received spurious OK command. Ignoring.\n");
}
else {
printf("Received unknown command: %s\n",workbuff);
sendResponse("UNKNOWN_COMMAND");
printf("Sent UNKNOWN_COMMAND\n");
}
}
close(tty_fd);
printf("Done!\n\n");
return 0;
}
|
the_stack_data/151704586.c | /*
* shared_ptr.c
*
* Copyright 2017 chehw <chehw@chehw-HP8200>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <search.h>
#include <assert.h>
#include <pthread.h>
typedef struct shared_ptr_ctx
{
void * ptr;
size_t size;
long refs;
void (* cleanup)(void *);
}shared_ptr_ctx_t;
static void * shared_ptr_root;
pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;
static inline void lock() { pthread_mutex_lock(&s_mutex); }
static inline void unlock() { pthread_mutex_unlock(&s_mutex); }
static int shared_ptr_compare(const void * l, const void * r)
{
long addr1 = (long)((shared_ptr_ctx_t *)l)->ptr;
long addr2 = (long)((shared_ptr_ctx_t *)r)->ptr;
if(addr1 > addr2) return 1;
else if(addr1 < addr2) return -1;
return 0;
}
static void shared_ptr_cleanup(void * node)
{
shared_ptr_ctx_t * sptr = (shared_ptr_ctx_t *)node;
if(sptr)
{
if(sptr->cleanup) sptr->cleanup(sptr->ptr);
else free(sptr->ptr);
}
free(sptr);
}
void * shared_ptr_new(void * ptr, void (* cleanup)(void *))
{
if(NULL == ptr) return NULL;
shared_ptr_ctx_t * sptr = calloc(1, sizeof(shared_ptr_ctx_t));
void ** p_node = NULL;
assert(NULL != sptr);
lock();
sptr->ptr = ptr;
if(cleanup) sptr->cleanup = cleanup;
p_node = tsearch(sptr, &shared_ptr_root, shared_ptr_compare);
if(NULL == p_node) {
unlock();
return NULL;
}
if(*(shared_ptr_ctx_t **)p_node != sptr)
{
free(sptr);
sptr = *(shared_ptr_ctx_t **)p_node;
}
++sptr->refs;
unlock();
return ptr;
}
void * shared_ptr_malloc(size_t size)
{
void * ptr = malloc(size);
assert(NULL != ptr);
return shared_ptr_new(ptr, free);
}
void shared_ptr_free(void * ptr)
{
shared_ptr_ctx_t pattern = {
.ptr = ptr
};
void *p_node;
shared_ptr_ctx_t * sptr;
lock();
p_node = tfind(&pattern, &shared_ptr_root, shared_ptr_compare);
if(p_node)
{
sptr = *(shared_ptr_ctx_t **)p_node;
}
if(sptr)
{
if(sptr->refs > 0) --sptr->refs;
if(0 == sptr->refs)
{
tdelete(&pattern, &shared_ptr_root, shared_ptr_compare);
shared_ptr_cleanup(sptr);
// free(sptr);
}
}
unlock();
return;
}
long shared_ptr_get_refs_count(void * ptr)
{
long count = -1;
lock();
shared_ptr_ctx_t pattern = {
.ptr = ptr
};
void *p_node;
shared_ptr_ctx_t * sptr;
lock();
p_node = tfind(&pattern, &shared_ptr_root, shared_ptr_compare);
if(p_node)
{
sptr = *(shared_ptr_ctx_t **)p_node;
if(sptr)
{
count = sptr->refs;
}
}
unlock();
return count;
}
long shared_ptr_ref(void *ptr)
{
long count = -1;
lock();
shared_ptr_ctx_t pattern = {
.ptr = ptr
};
void *p_node;
shared_ptr_ctx_t * sptr;
lock();
p_node = tfind(&pattern, &shared_ptr_root, shared_ptr_compare);
if(p_node)
{
sptr = *(shared_ptr_ctx_t **)p_node;
if(sptr)
{
count = ++sptr->refs;
}
}
unlock();
return count;
}
long shared_ptr_unref(void * ptr)
{
long count = -1;
lock();
shared_ptr_ctx_t pattern = {
.ptr = ptr
};
void *p_node;
shared_ptr_ctx_t * sptr;
lock();
p_node = tfind(&pattern, &shared_ptr_root, shared_ptr_compare);
if(p_node)
{
sptr = *(shared_ptr_ctx_t **)p_node;
if(sptr && sptr->refs > 0)
{
count = --sptr->refs;
if(0 == sptr->refs)
{
tdelete(&pattern, &shared_ptr_root, shared_ptr_compare);
// free(sptr);
}
}
}
unlock();
if(0 == count) shared_ptr_cleanup(sptr);
return count;
}
void shared_ptr_global_init()
{
pthread_mutex_init(&s_mutex, NULL);
}
void shared_ptr_global_cleanup()
{
tdestroy(&shared_ptr_root, shared_ptr_cleanup);
pthread_mutex_destroy(&s_mutex);
}
|
the_stack_data/934351.c | #include <stdio.h>
#include <ctype.h>
int main() {
char str[80], *p;
printf("Enter a string:");
gets(str);
p = str;
while (*p) {
*p = toupper(*p);
p++;
}
printf("%s\n", str); //uppercase string
p = str; // reset p
while (*p) {
*p = tolower(*p);
p++;
}
printf("%s\n", str); // lowercase string
return 0;
} |
the_stack_data/125139419.c | /*
* who01.c
* open, read UTMP file and show results
* bugs: couldn't convert time right
*/
#include <stdio.h>
#include <utmp.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define SHOWHOST
void show_info(struct utmp* utbufp);
void showtime(const long int timeval);
int main(){
struct utmp current_record; // read info into utmp struct
int utmpfd; // open utmp file with file identifier
int reclen = sizeof(current_record);
if ((utmpfd = open(UTMP_FILE, O_RDONLY)) == -1){
perror(UTMP_FILE);
exit(1);
}
while (read(utmpfd, ¤t_record, reclen) == reclen)
{
show_info(¤t_record);
}
close(utmpfd);
return 0;
}
void show_info(struct utmp* utbufp)
{
if ( utbufp->ut_type != USER_PROCESS)
return;
printf("%-8.8s", utbufp->ut_user);
printf(" ");
printf("%-8.8s", utbufp->ut_line);
printf(" ");
showtime(utbufp->ut_tv.tv_sec);
printf(" ");
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host);
#endif
printf("\n");
}
void showtime(const long int timeval)
{
char *cp;
cp = ctime(&timeval);
printf("%12.12s", cp+4);
} |
the_stack_data/761982.c | /*
** EPITECH PROJECT, 2021
** PSU_2017_malloc
** File description:
** Created by rectoria
*/
#include <pthread.h>
#include <signal.h>
static pthread_mutex_t g_mutex_m = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t g_mutex_r = PTHREAD_MUTEX_INITIALIZER;
void lock_thread(int flag)
{
if (!flag) {
if (pthread_mutex_lock(&g_mutex_m))
raise(SIGABRT);
} else if (flag == 1) {
if (pthread_mutex_lock(&g_mutex_r))
raise(SIGABRT);
}
}
void unlock_thread(int flag)
{
if (!flag) {
if (pthread_mutex_unlock(&g_mutex_m))
raise(SIGABRT);
} else if (flag == 1) {
if (pthread_mutex_unlock(&g_mutex_r))
raise(SIGABRT);
}
}
|
the_stack_data/129070.c | /*
*/
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
float x;
int y;
int main (int argc, char * argv[])
{
#ifdef _OPENMP
omp_set_num_threads(4);
#endif
x=1.0;
y=1;
#pragma omp parallel private(x)
{
printf("x=%f, y=%d\n",x,y);
}
return 0;
}
|
the_stack_data/18043.c | /* Example code for Software Systems at Olin College.
Instructions:
1) Fill in the body of endswith so it passes the tests.
You can use any of the functions in string.h
https://www.tutorialspoint.com/c_standard_library/string_h.htm
2) Remove the TODO comment.
Copyright 2017 Allen Downey
License: Creative Commons Attribution-ShareAlike 3.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/* endswith: Checks whether s ends with suffix.
s: string
suffix: string
returns: 1 if true, 0 otherwise
*/
int endswith(char *s, char *suffix)
{
// Get final inds
int i = strlen(s)-1;
int j = strlen(suffix)-1;
//Iterate from the back and check matching
while (i >= 0 && j >= 0 && s[i] == suffix[j]){
i--;
j--;
}
// If j == -1 the suffix matched the end of the string entirely
// If j is larger then either the string is longer than the suffix, or they didn't match
return j == -1;
}
/* test_endswith
*/
void test_endswith(char *s1, char *s2, int expected) {
int got = endswith(s1, s2);
printf("%s\n%s\n%d\n\n",s1,s2,got);
assert(got == expected);
}
int main (int argc, char *argv[])
{
test_endswith("endswith", "swith", 1);
test_endswith("endswith", "ends", 0);
test_endswith("endswith", "offendswith", 0);
// what's the right answer?
test_endswith("endswith", "", 1);
printf("All tests passed\n");
}
|
the_stack_data/103264596.c |
// source: http://billor.chsh.chc.edu.tw/IT/C/BigInteger.htm
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXDIGITS 100 /* maximum length bignum */
#define PLUS 1 /* positive sign bit */
#define MINUS -1 /* negative sign bit */
#define max(a, b) ((a > b) ? a : b)
#ifndef strlcpy
#define strlcpy(dst, src, sz) snprintf((dst), (sz), "%s", (src))
#endif
typedef struct {
char digits[MAXDIGITS]; /* represent the number */
int signbit; /* 1 if positive, -1 if negative */
int lastdigit; /* index of high-order digit */
} bignum;
int add_bignum(bignum *a, bignum *b, bignum *c);
int compare_bignum(bignum *a, bignum *b);
int subtract_bignum(bignum *a, bignum *b, bignum *c);
void print_bignum(bignum *n);
void int_to_bignum(int s, bignum *n);
void initialize_bignum(bignum *n);
int add_bignum(bignum *a, bignum *b, bignum *c);
int subtract_bignum(bignum *a, bignum *b, bignum *c);
int compare_bignum(bignum *a, bignum *b);
/* ************************************** */
/* print a Big integer */
/* Input : A big integer pointer */
/* Return : None */
/* ************************************** */
void print_bignum(bignum *n)
{
if (n->signbit == MINUS)
printf("-");
printf("%s\n", n->digits);
}
/* *********************************************** */
/* Convert an integer into big integer */
/* Input : A integer and a big integer */
/* pointer */
/* Return : None */
/* *********************************************** */
void int_to_bignum(int s, bignum *n)
{
if (s >= 0)
n->signbit = PLUS;
else
n->signbit = MINUS;
int t = abs(s);
snprintf(n->digits, sizeof(n->digits), "%d", t);
n->lastdigit = strlen(n->digits);
}
/* **************************************** */
/* Inatilize a zero integer */
/* Input : A big integer pointer */
/* Return : None */
/* **************************************** */
void initialize_bignum(bignum *n)
{
int_to_bignum(0, n);
}
/* *********************************************************** */
/* Add two big integer */
/* Input : Three big integer pointer a,b,c */
/* where a & b is argument of addition */
/* and c is the result. c = a + b */
/* Return : Number of carry */
/* *********************************************************** */
int add_bignum(bignum *a, bignum *b, bignum *c)
{
int carry; /* carry digit */
int i, j;
; /* counter */
int n_carry;
initialize_bignum(c);
if (a->signbit == b->signbit)
c->signbit = a->signbit;
else {
if (a->signbit == MINUS) {
a->signbit = PLUS;
n_carry = subtract_bignum(b, a, c);
a->signbit = MINUS;
} else {
b->signbit = PLUS;
n_carry = subtract_bignum(a, b, c);
b->signbit = MINUS;
}
return n_carry;
}
if (a->lastdigit < b->lastdigit)
return add_bignum(b, a, c);
int k = c->lastdigit = a->lastdigit + 1;
c->digits[k--] = '\0';
carry = 0;
n_carry = 0;
for (i = b->lastdigit - 1, j = a->lastdigit - 1; i >= 0; i--, j--) {
carry = b->digits[i] - '0' + a->digits[j] - '0' + carry;
c->digits[k--] = (carry % 10) + '0';
carry = carry / 10;
if (carry)
n_carry++;
}
for (; j >= 0; j--) {
carry = a->digits[j] - '0' + carry;
c->digits[k--] = (carry % 10) + '0';
carry = carry / 10;
if (carry)
n_carry++;
}
if (carry)
c->digits[k] = carry + '0';
else {
char string[MAXDIGITS];
strlcpy(string, &c->digits[1], MAXDIGITS);
strlcpy(c->digits, string, MAXDIGITS);
c->lastdigit = c->lastdigit - k - 1;
}
return n_carry;
}
/* ************************************************************ */
/* Subtract two big integer */
/* Input : Three big integer pointer a,b,c */
/* where a & b is argument of subtraction */
/* and c is the result. */
/* Return : Number of borrow */
/* ************************************************************ */
int subtract_bignum(bignum *a, bignum *b, bignum *c)
{
register int i, j, op = 0; /* counter */
int n_borrow;
int temp;
c->signbit = PLUS;
if ((a->signbit == MINUS) || (b->signbit == MINUS))
{
b->signbit = -1 * b->signbit;
n_borrow = add_bignum(a, b, c);
b->signbit = -1 * b->signbit;
return n_borrow;
}
if (compare_bignum(a, b) == PLUS) {
n_borrow = subtract_bignum(b, a, c);
c->signbit = MINUS;
return n_borrow;
}
int k = c->lastdigit = max(a->lastdigit, b->lastdigit);
n_borrow = 0;
c->digits[k--] = '\0';
for (i = a->lastdigit - 1, j = b->lastdigit - 1; j >= 0; i--, j--) {
temp = a->digits[i] - '0' - (b->digits[j] - '0' + op);
if (temp < 0) {
temp += 10;
op = 1;
n_borrow++;
} else
op = 0;
c->digits[k--] = temp + '0';
}
while (op) {
temp = a->digits[i--] - op - '0';
if (temp < 0) {
temp += 10;
op = 1;
n_borrow++;
} else
op = 0;
c->digits[k--] = temp + '0';
}
for (; i >= 0; i--)
c->digits[k--] = a->digits[i];
for (i = 0; !(c->digits[i] - '0'); i++)
;
c->lastdigit = c->lastdigit - i;
if (i == a->lastdigit)
strlcpy(c->digits, "0", MAXDIGITS);
else {
char string[MAXDIGITS];
strlcpy(string, &c->digits[i], MAXDIGITS);
strlcpy(c->digits, string, MAXDIGITS);
}
return n_borrow;
}
/* **************************************************** */
/* Compare two big integer */
/* Input : Two big integer pointer a,b */
/* Return : 0,1 or -1, */
/* 0 for a=b */
/* 1 for a < b */
/* -1 for a>b */
/* **************************************************** */
int compare_bignum(bignum *a, bignum *b)
{
int i; /* counter */
if ((a->signbit == MINUS) && (b->signbit == PLUS))
return (PLUS);
if ((a->signbit == PLUS) && (b->signbit == MINUS))
return (MINUS);
if (b->lastdigit > a->lastdigit)
return (PLUS * a->signbit);
if (a->lastdigit > b->lastdigit)
return (MINUS * a->signbit);
for (i = 0; i < a->lastdigit; i++) {
if (a->digits[i] > b->digits[i])
return (MINUS * a->signbit);
if (b->digits[i] > a->digits[i])
return (PLUS * a->signbit);
}
return (0);
}
/* *************************************************************** */
/* Multiply two big integer */
/* Input : Three big integer pointer a,b,c */
/* where a & b is argument of multiplication */
/* and c is the result. */
/* Return : Number of borrow */
/* *************************************************************** */
void multiply_bignum(bignum *a, bignum *b, bignum *c)
{
// long int n_d;
register long int i, j, k;
short int num1[MAXDIGITS], num2[MAXDIGITS], of = 0, res[MAXDIGITS] = {0};
// n_d = (a->lastdigit < b->lastdigit) ? b->lastdigit : a->lastdigit;
// n_d++;
for (i = 0, j = a->lastdigit - 1; i < a->lastdigit; i++, j--)
num1[i] = a->digits[j] - 48;
for (i = 0, j = b->lastdigit - 1; i < b->lastdigit; j--, i++)
num2[i] = b->digits[j] - 48;
res[0] = 0;
for (j = 0; j < b->lastdigit; j++) {
for (i = 0, k = j; i < a->lastdigit || of; k++, i++) {
if (i < a->lastdigit)
res[k] += num1[i] * num2[j] + of;
else
res[k] += of;
of = res[k] / 10;
res[k] = res[k] % 10;
}
}
for (i = k - 1, j = 0; i >= 0; i--, j++)
c->digits[j] = res[i] + 48;
c->digits[j] = '\0';
c->lastdigit = k;
c->signbit = a->signbit * b->signbit;
}
/* ******************************************************* */
/* Copy one big integer into another */
/* Input : Two big integer pointer a,b */
/* where a is destinition & b source */
/* Return : None */
/* ******************************************************* */
void copy(bignum *a, bignum *b)
{
a->lastdigit = b->lastdigit;
a->signbit = b->signbit;
strlcpy(a->digits, b->digits, MAXDIGITS);
}
// n is fib param, implement fib by fast method
int main()
{
bignum a, b;
// fib param
unsigned long long n = 95;
bignum two;
int_to_bignum(0, &a);
int_to_bignum(1, &b);
int_to_bignum(2, &two);
for (int i = 31 - __builtin_clz(n); i >= 0; i--) {
bignum t1, t2;
bignum tmp1, tmp2;
// t1 = a * (b * 2 - a);
multiply_bignum(&b, &two, &tmp1);
subtract_bignum(&tmp1, &a, &tmp2);
multiply_bignum(&a, &tmp2, &t1);
// t2 = b * b + a * a;
multiply_bignum(&a, &a, &tmp1);
multiply_bignum(&b, &b, &tmp2);
add_bignum(&tmp1, &tmp2, &t2);
// a = t1; des = source
// b = t2;
copy(&a, &t1);
copy(&b, &t2);
if ((n & (1 << i)) > 0) {
// t1 = a + b;
add_bignum(&a, &b, &t1);
// a = b;
// b = t1;
copy(&a, &b);
copy(&b, &t1);
}
}
print_bignum(&a);
} |
the_stack_data/71989.c | /*
* Generated with test/generate_buildtest.pl, to check that such a simple
* program builds.
*/
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_STDIO
# include <stdio.h>
#endif
#ifndef OPENSSL_NO_SHA
# include <openssl/sha.h>
#endif
int main(void)
{
return 0;
}
|
the_stack_data/28262771.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
/*
"One good way to synthesize declarations is
in small steps with typedef, ..."
- K&R book Chapter 5.12
*/
/* Complicated Function Declarations */
/* Use typedef to make declarations simpler */
int main()
{
return 0;
} |
the_stack_data/98574746.c | #include <stdio.h>
#include <math.h>
int main()
{
int i, num, tnum, digit, sum = 0;
long int satisfyingNumberSum = 0;
for ( i = 2; i <= 236196; ++i )
{
num = tnum = i;
sum = 0;
do
{
digit = tnum % 10;
tnum /= 10;
sum = sum + pow ( digit , 5 );
}while( tnum );
if ( num == sum )
{
satisfyingNumberSum += num;
}
}
printf( "\nResult Sum = %ld", satisfyingNumberSum );
return 0;
}
//( ( exp - 1 ) * ( 9 ^ exp ) )
|
the_stack_data/36075131.c | /**********************************************************************************************************************************/
/* Module : BAS2TAP.C */
/* Executable : BAS2TAP.EXE */
/* Doc file : BAS2TAP.DOC */
/* Version type : Single file */
/* Last changed : 20-01-2013 16:00 */
/* Update count : 18 */
/* OS type : Generic */
/* Watcom C = wcl386 -mf -fp3 -fpi -3r -oxnt -w4 -we bas2tap.c */
/* MS C = cl /Ox /G2 /AS bas2tap.c /F 1000 */
/* gcc = gcc -Wall -O2 bas2tap.c -o bas2tap -lm ; strip bas2tap */
/* SAS/C = sc link math=ieee bas2tap.c */
/* Libs needed : math */
/* Description : Convert ASCII BASIC file to TAP tape image emulator file */
/* */
/* Notes : There's a check for a define "__DEBUG__", which generates tons of output if defined. */
/* */
/* Copyleft (C) 1998-2013 ThunderWare Research Center, written by Martijn van der Heide. */
/* */
/* 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 <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
/**********************************************************************************************************************************/
/* Some compilers don't define the following things, so I define them here... */
/**********************************************************************************************************************************/
#ifdef __WATCOMC__
#define x_strnicmp(_S1,_S2,_Len) strnicmp (_S1, _S2, _Len)
#define x_log2(_X) log2 (_X)
#else
int x_strnicmp (char *_S1, char *_S2, int _Len) /* Case independant partial string compare */
{
for ( ; _Len && *_S1 && *_S2 && toupper (*_S1) == toupper (*_S2) ; _S1 ++, _S2 ++, _Len --)
;
return (_Len ? (int)toupper (*_S1) - (int)toupper (*_S2) : 0);
}
#define x_log2(_X) (log (_X) / log (2.0)) /* If your compiler doesn't know the 'log2' function */
#endif
//#define __DEBUG__
typedef unsigned char byte;
#ifndef FALSE
typedef unsigned char bool; /* If your compiler doesn't know this variable type yet */
#define TRUE 1
#define FALSE 0
#endif
/**********************************************************************************************************************************/
/* Define the global variables */
/**********************************************************************************************************************************/
struct TokenMap_s
{
char *Token;
byte TokenType;
/* Type 0 = No special meaning */
/* Type 1 = Always keyword */
/* Type 2 = Can be both keyword and non-keyword (colour parameters) */
/* Type 3 = Numeric expression token */
/* Type 4 = String expression token */
/* Type 5 = May only appear in (L)PRINT statements (AT and TAB) */
/* Type 6 = Type-less (normal ASCII or expression token) */
byte KeywordClass[8]; /* The class this keyword belongs to, as defined in the Spectrum ROM */
/* This table is used by expression tokens as well. Class 12 was added for this purpose */
/* Class 0 = No further operands */
/* Class 1 = Used in LET. A variable is required */
/* Class 2 = Used in LET. An expression, numeric or string, must follow */
/* Class 3 = A numeric expression may follow. Zero to be used in case of default */
/* Class 4 = A single character variable must follow */
/* Class 5 = A set of items may be given */
/* Class 6 = A numeric expression must follow */
/* Class 7 = Handles colour items */
/* Class 8 = Two numeric expressions, separated by a comma, must follow */
/* Class 9 = As for class 8 but colour items may precede the expression */
/* Class 10 = A string expression must follow */
/* Class 11 = Handles cassette routines */
/* The following classes are not available in the ROM but were needed */
/* Class 12 = One or more string expressions, separated by commas, must follow */
/* Class 13 = One or more expressions, separated by commas, must follow */
/* Class 14 = One or more variables, separated by commas, must follow (READ) */
/* Class 15 = DEF FN */
} TokenMap[256] = {
/* Everything below ASCII 32 */
{NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }},
{NULL, 6, { 0 }}, /* Print ' */
{NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }},
{"(eoln)", 6, { 0 }}, /* CR */
{NULL, 6, { 0 }}, /* Number */
{NULL, 6, { 0 }},
{NULL, 6, { 0 }}, /* INK */
{NULL, 6, { 0 }}, /* PAPER */
{NULL, 6, { 0 }}, /* FLASH */
{NULL, 6, { 0 }}, /* BRIGHT */
{NULL, 6, { 0 }}, /* INVERSE */
{NULL, 6, { 0 }}, /* OVER */
{NULL, 6, { 0 }}, /* AT */
{NULL, 6, { 0 }}, /* TAB */
{NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }}, {NULL, 6, { 0 }},
{NULL, 6, { 0 }},
/* Normal ASCII set */
{"\x20", 6, { 0 }}, {"\x21", 6, { 0 }}, {"\x22", 6, { 0 }}, {"\x23", 6, { 0 }}, {"\x24", 6, { 0 }}, {"\x25", 6, { 0 }},
{"\x26", 6, { 0 }}, {"\x27", 6, { 0 }}, {"\x28", 6, { 0 }}, {"\x29", 6, { 0 }}, {"\x2A", 6, { 0 }}, {"\x2B", 6, { 0 }},
{"\x2C", 6, { 0 }}, {"\x2D", 6, { 0 }}, {"\x2E", 6, { 0 }}, {"\x2F", 6, { 0 }}, {"\x30", 6, { 0 }}, {"\x31", 6, { 0 }},
{"\x32", 6, { 0 }}, {"\x33", 6, { 0 }}, {"\x34", 6, { 0 }}, {"\x35", 6, { 0 }}, {"\x36", 6, { 0 }}, {"\x37", 6, { 0 }},
{"\x38", 6, { 0 }}, {"\x39", 6, { 0 }}, {"\x3A", 2, { 0 }}, {"\x3B", 6, { 0 }}, {"\x3C", 6, { 0 }}, {"\x3D", 6, { 0 }},
{"\x3E", 6, { 0 }}, {"\x3F", 6, { 0 }}, {"\x40", 6, { 0 }}, {"\x41", 6, { 0 }}, {"\x42", 6, { 0 }}, {"\x43", 6, { 0 }},
{"\x44", 6, { 0 }}, {"\x45", 6, { 0 }}, {"\x46", 6, { 0 }}, {"\x47", 6, { 0 }}, {"\x48", 6, { 0 }}, {"\x49", 6, { 0 }},
{"\x4A", 6, { 0 }}, {"\x4B", 6, { 0 }}, {"\x4C", 6, { 0 }}, {"\x4D", 6, { 0 }}, {"\x4E", 6, { 0 }}, {"\x4F", 6, { 0 }},
{"\x50", 6, { 0 }}, {"\x51", 6, { 0 }}, {"\x52", 6, { 0 }}, {"\x53", 6, { 0 }}, {"\x54", 6, { 0 }}, {"\x55", 6, { 0 }},
{"\x56", 6, { 0 }}, {"\x57", 6, { 0 }}, {"\x58", 6, { 0 }}, {"\x59", 6, { 0 }}, {"\x5A", 6, { 0 }}, {"\x5B", 6, { 0 }},
{"\x5C", 6, { 0 }}, {"\x5D", 6, { 0 }}, {"\x5E", 6, { 0 }}, {"\x5F", 6, { 0 }}, {"\x60", 6, { 0 }}, {"\x61", 6, { 0 }},
{"\x62", 6, { 0 }}, {"\x63", 6, { 0 }}, {"\x64", 6, { 0 }}, {"\x65", 6, { 0 }}, {"\x66", 6, { 0 }}, {"\x67", 6, { 0 }},
{"\x68", 6, { 0 }}, {"\x69", 6, { 0 }}, {"\x6A", 6, { 0 }}, {"\x6B", 6, { 0 }}, {"\x6C", 6, { 0 }}, {"\x6D", 6, { 0 }},
{"\x6E", 6, { 0 }}, {"\x6F", 6, { 0 }}, {"\x70", 6, { 0 }}, {"\x71", 6, { 0 }}, {"\x72", 6, { 0 }}, {"\x73", 6, { 0 }},
{"\x74", 6, { 0 }}, {"\x75", 6, { 0 }}, {"\x76", 6, { 0 }}, {"\x77", 6, { 0 }}, {"\x78", 6, { 0 }}, {"\x79", 6, { 0 }},
{"\x7A", 6, { 0 }}, {"\x7B", 6, { 0 }}, {"\x7C", 6, { 0 }}, {"\x7D", 6, { 0 }}, {"\x7E", 6, { 0 }}, {"\x7F", 6, { 0 }},
/* Block graphics without shift */
{"\x80", 6, { 0 }}, {"\x81", 6, { 0 }}, {"\x82", 6, { 0 }}, {"\x83", 6, { 0 }}, {"\x84", 6, { 0 }}, {"\x85", 6, { 0 }},
{"\x86", 6, { 0 }}, {"\x87", 6, { 0 }},
/* Block graphics with shift */
{"\x88", 6, { 0 }}, {"\x89", 6, { 0 }}, {"\x8A", 6, { 0 }}, {"\x8B", 6, { 0 }}, {"\x8C", 6, { 0 }}, {"\x8D", 6, { 0 }},
{"\x8E", 6, { 0 }}, {"\x8F", 6, { 0 }},
/* UDGs */
{"\x90", 6, { 0 }}, {"\x91", 6, { 0 }}, {"\x92", 6, { 0 }}, {"\x93", 6, { 0 }}, {"\x94", 6, { 0 }}, {"\x95", 6, { 0 }},
{"\x96", 6, { 0 }}, {"\x97", 6, { 0 }}, {"\x98", 6, { 0 }}, {"\x99", 6, { 0 }}, {"\x9A", 6, { 0 }}, {"\x9B", 6, { 0 }},
{"\x9C", 6, { 0 }}, {"\x9D", 6, { 0 }}, {"\x9E", 6, { 0 }}, {"\x9F", 6, { 0 }}, {"\xA0", 6, { 0 }}, {"\xA1", 6, { 0 }},
{"\xA2", 6, { 0 }},
{"SPECTRUM", 1, { 0 }}, /* For Spectrum 128 */
{"PLAY", 1, { 12 }},
/* BASIC tokens - expression */
{"RND", 3, { 0 }},
{"INKEY$", 4, { 0 }},
{"PI", 3, { 0 }},
{"FN", 3, { 1, '(', 13, ')', 0 }},
{"POINT", 3, { '(', 8, ')', 0 }},
{"SCREEN$", 4, { '(', 8, ')', 0 }},
{"ATTR", 3, { '(', 8, ')', 0 }},
{"AT", 5, { 8, 0 }},
{"TAB", 5, { 6, 0 }},
{"VAL$", 4, { 10, 0 }},
{"CODE", 3, { 10, 0 }},
{"VAL", 3, { 10, 0 }},
{"LEN", 3, { 10, 0 }},
{"SIN", 3, { 6, 0 }},
{"COS", 3, { 6, 0 }},
{"TAN", 3, { 6, 0 }},
{"ASN", 3, { 6, 0 }},
{"ACS", 3, { 6, 0 }},
{"ATN", 3, { 6, 0 }},
{"LN", 3, { 6, 0 }},
{"EXP", 3, { 6, 0 }},
{"INT", 3, { 6, 0 }},
{"SQR", 3, { 6, 0 }},
{"SGN", 3, { 6, 0 }},
{"ABS", 3, { 6, 0 }},
{"PEEK", 3, { 6, 0 }},
{"IN", 3, { 6, 0 }},
{"USR", 3, { 6, 0 }},
{"STR$", 4, { 6, 0 }},
{"CHR$", 4, { 6, 0 }},
{"NOT", 3, { 6, 0 }},
{"BIN", 6, { 0 }},
{"OR", 6, { 5, 0 }}, /* -\ */
{"AND", 6, { 5, 0 }}, /* | */
{"<=", 6, { 5, 0 }}, /* | These are handled directly within ScanExpression */
{">=", 6, { 5, 0 }}, /* | */
{"<>", 6, { 5, 0 }}, /* -/ */
{"LINE", 6, { 0 }},
{"THEN", 6, { 0 }},
{"TO", 6, { 0 }},
{"STEP", 6, { 0 }},
/* BASIC tokens - keywords */
{"DEF FN", 1, { 15, 0 }}, /* Special treatment - insertion of call-by-value room required for the evaluator */
{"CAT", 1, { 11, 0 }},
{"FORMAT", 1, { 11, 0 }},
{"MOVE", 1, { 11, 0 }},
{"ERASE", 1, { 11, 0 }},
{"OPEN #", 1, { 11, 0 }},
{"CLOSE #", 1, { 11, 0 }},
{"MERGE", 1, { 11, 0 }},
{"VERIFY", 1, { 11, 0 }},
{"BEEP", 1, { 8, 0 }},
{"CIRCLE", 1, { 9, ',', 6, 0 }},
{"INK", 2, { 7, 0 }},
{"PAPER", 2, { 7, 0 }},
{"FLASH", 2, { 7, 0 }},
{"BRIGHT", 2, { 7, 0 }},
{"INVERSE", 2, { 7, 0 }},
{"OVER", 2, { 7, 0 }},
{"OUT", 1, { 8, 0 }},
{"LPRINT", 1, { 5, 0 }},
{"LLIST", 1, { 3, 0 }},
{"STOP", 1, { 0 }},
{"READ", 1, { 14, 0 }},
{"DATA", 2, { 13, 0 }},
{"RESTORE", 1, { 3, 0 }},
{"NEW", 1, { 0 }},
{"BORDER", 1, { 6, 0 }},
{"CONTINUE", 1, { 0 }},
{"DIM", 1, { 1, '(', 13, ')', 0 }},
{"REM", 1, { 5, 0 }}, /* (Special: taken out separately) */
{"FOR", 1, { 4, '=', 6, 0xCC, 6, 0xCD, 6, 0 }}, /* (Special: STEP (0xCD) is not required) */
{"GO TO", 1, { 6, 0 }},
{"GO SUB", 1, { 6, 0 }},
{"INPUT", 1, { 5, 0 }},
{"LOAD", 1, { 11, 0 }},
{"LIST", 1, { 3, 0 }},
{"LET", 1, { 1, '=', 2, 0 }},
{"PAUSE", 1, { 6, 0 }},
{"NEXT", 1, { 4, 0 }},
{"POKE", 1, { 8, 0 }},
{"PRINT", 1, { 5, 0 }},
{"PLOT", 1, { 9, 0 }},
{"RUN", 1, { 3, 0 }},
{"SAVE", 1, { 11, 0 }},
{"RANDOMIZE", 1, { 3, 0 }},
{"IF", 1, { 6, 0xCB, 0 }},
{"CLS", 1, { 0 }},
{"DRAW", 1, { 9, ',', 6, 0 }},
{"CLEAR", 1, { 3, 0 }},
{"RETURN", 1, { 0 }},
{"COPY", 1, { 0 }}};
#define MAXLINELENGTH 1024
char ConvertedSpectrumLine[MAXLINELENGTH + 1];
byte ResultingLine[MAXLINELENGTH + 1];
struct TapeHeader_s
{
byte LenLo1;
byte LenHi1;
byte Flag1;
byte HType;
char HName[10];
byte HLenLo;
byte HLenHi;
byte HStartLo;
byte HStartHi;
byte HBasLenLo;
byte HBasLenHi;
byte Parity1;
byte LenLo2;
byte LenHi2;
byte Flag2;
} TapeHeader = {19, 0, /* Len header */
0, /* Flag header */
0, {32, 32, 32, 32, 32, 32, 32, 32, 32, 32}, 0, 0, 0, 128, 0, 0, /* The header itself */
0, /* Parity header */
0, 0, /* Len converted BASIC */
255}; /* Flag converted BASIC */
int Is48KProgram = -1; /* -1 = unknown */
/* 1 = 48K */
/* 0 = 128K */
int UsesInterface1 = -1; /* -1 = unknown */
/* 0 = either Interface1 or Opus Discovery */
/* 1 = Interface1 */
/* 2 = Opus Discovery */
bool CaseIndependant = FALSE;
bool Quiet = FALSE; /* Suppress banner and progress indication if TRUE */
bool NoWarnings = FALSE; /* Suppress warnings if TRUE */
bool DoCheckSyntax = TRUE;
bool TokenBracket = FALSE;
bool HandlingDEFFN = FALSE; /* Exceptional instruction */
bool InsideDEFFN = FALSE;
#define DEFFN 0xCE
FILE *ErrStream;
/**********************************************************************************************************************************/
/* Let's be lazy and define a very commonly used error message.... */
/**********************************************************************************************************************************/
#define BADTOKEN(_Exp,_Got) fprintf (ErrStream, "ERROR in line %d, statement %d - Expected %s, but got \"%s\"\n", \
BasicLineNo, StatementNo, _Exp, _Got)
/**********************************************************************************************************************************/
/* And let's generate tons of debugging info too.... */
/**********************************************************************************************************************************/
#ifdef __DEBUG__
char ListSpaces[20];
int RecurseLevel;
#endif
/**********************************************************************************************************************************/
/* Prototype all functions */
/**********************************************************************************************************************************/
int GetLineNumber (char **FirstAfter);
int MatchToken (int BasicLineNo, bool WantKeyword, char **LineIndex, byte *Token);
int HandleNumbers (int BasicLineNo, char **BasicLine, byte **SpectrumLine);
int HandleBIN (int BasicLineNo, char **BasicLine, byte **SpectrumLine);
int ExpandSequences (int BasicLineNo, char **BasicLine, byte **SpectrumLine, bool StripSpaces);
int PrepareLine (char *LineIn, int FileLineNo, char **FirstToken);
bool ScanVariable (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type, int *NameLen, int AllowSlicing);
bool SliceDirectString (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool ScanStream (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool ScanChannel (int BasicLineNo, int StatementNo, int Keyword, byte **Index, byte *WhichChannel);
bool SignalInterface1 (int BasicLineNo, int StatementNo, int NewMode);
bool CheckEnd (int BasicLineNo, int StatementNo, byte **Index);
bool ScanExpression (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type, int Level);
bool HandleClass01 (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type);
bool HandleClass02 (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool Type);
bool HandleClass03 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass04 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass05 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass06 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass07 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass08 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass09 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass10 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass11 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass12 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass13 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass14 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool HandleClass15 (int BasicLineNo, int StatementNo, int Keyword, byte **Index);
bool CheckSyntax (int BasicLineNo, byte *Line);
/**********************************************************************************************************************************/
/* Start of the program */
/**********************************************************************************************************************************/
int GetLineNumber (char **FirstAfter)
/**********************************************************************************************************************************/
/* Pre : The line must have been prepared into (global) `ConvertedSpectrumLine'. */
/* Post : The BASIC line number has been returned, or -1 if there was none. */
/* Import: None. */
/**********************************************************************************************************************************/
{
int LineNo = 0;
char *LineIndex;
bool SkipSpaces = TRUE;
bool Continue = TRUE;
LineIndex = ConvertedSpectrumLine;
while (*LineIndex && Continue)
if (*LineIndex == ' ') /* Skip leading spaces */
{
if (SkipSpaces)
LineIndex ++;
else
Continue = FALSE;
}
else if (isdigit (*LineIndex)) /* Process number */
{
LineNo = LineNo * 10 + *(LineIndex ++) - '0';
SkipSpaces = FALSE;
}
else
Continue = FALSE;
*FirstAfter = LineIndex;
if (SkipSpaces) /* Nothing found yet ? */
return (-1);
else
while ((**FirstAfter) == ' ') /* Skip trailing spaces */
(*FirstAfter) ++;
return (LineNo);
}
int MatchToken (int BasicLineNo, bool WantKeyword, char **LineIndex, byte *Token)
/**********************************************************************************************************************************/
/* Pre : `WantKeyword' is TRUE if we need in keyword match, `LineIndex' holds the position to match. */
/* Post : If there was a match, the token value is returned in `Token' and `LineIndex' is pointing after the string plus any */
/* any trailing space. */
/* The return value is 0 for no match, -2 for an error, -1 for a match of the wrong type, 1 for a good match. */
/* Import: None. */
/**********************************************************************************************************************************/
{
int Cnt;
size_t Length;
size_t LongestMatch = 0;
bool Match = FALSE;
bool Match2;
if ((**LineIndex) == ':') /* Special exception */
{
LongestMatch = 1;
Match = TRUE;
*Token = ':';
}
else for (Cnt = 0xA3 ; Cnt <= 0xFF ; Cnt ++) /* (Keywords start after the UDGs) */
{
Length = strlen (TokenMap[Cnt].Token);
if (CaseIndependant)
Match2 = !x_strnicmp (*LineIndex, TokenMap[Cnt].Token, Length);
else
Match2 = !strncmp (*LineIndex, TokenMap[Cnt].Token, Length);
if (Match2)
if (Length > LongestMatch)
{
LongestMatch = Length;
Match = TRUE;
*Token = Cnt;
}
}
if (!Match)
return (0); /* Signal: no match */
if (isalpha (*(*LineIndex + LongestMatch - 1)) && isalpha (*(*LineIndex + LongestMatch))) /* Continueing alpha string ? */
return (0); /* Then there's no match after all! (eg. 'INT' must not match 'INTER') */
*LineIndex += LongestMatch; /* Go past the token */
while ((**LineIndex) == ' ') /* Skip trailing spaces */
(*LineIndex) ++;
if (*Token == 0xA3 || *Token == 0xA4) /* 'SPECTRUM' or 'PLAY' ? */
switch (Is48KProgram) /* Then the program must be 128K */
{
case -1 : Is48KProgram = 0; break; /* Set the flag */
case 1 : fprintf (ErrStream, "ERROR - Line %d contains a 128K keyword, but the program\n"
"also uses UDGs \'T\' and/or \'U\'\n", BasicLineNo);
return (-2);
case 0 : break;
}
if ((WantKeyword && TokenMap[*Token].TokenType == 0) || /* Wanted keyword but got something else */
(!WantKeyword && TokenMap[*Token].TokenType == 1)) /* Did not want a keyword but got one nonetheless */
return (-1); /* Signal: match, but of wrong type */
else
return (1); /* Signal: match! */
}
int HandleNumbers (int BasicLineNo, char **BasicLine, byte **SpectrumLine)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the current BASIC line number, `BasicLine' points into the line, `SpectrumLine' points to the */
/* TAPped Spectrum line. */
/* Post : If there was a (floating point) number at this position, it has been processed into `SpectrumLine' and `LineIndex' is */
/* pointing after the number. */
/* The return value is: 0 = no number, 1 = number done, -1 = number error (already reported). */
/* Import: None. */
/**********************************************************************************************************************************/
{
#define SHIFT31BITS (double)2147483648.0 /* (= 2^31) */
char *StartOfNumber;
double Value = 0.0;
double Divider = 1.0;
double Exp = 0.0;
int IntValue;
byte Sign = 0x00;
unsigned long Mantissa;
if (!isdigit (**BasicLine) && /* Current character is not a digit ? */
(**BasicLine) != '.') /* And not a decimal point (eg. '.5') ? */
return (0); /* Then it can hardly be a number */
StartOfNumber = *BasicLine;
while (isdigit (**BasicLine)) /* First read the integer part */
Value = Value * 10 + *((*BasicLine) ++) - '0';
if ((**BasicLine) == '.') /* Decimal point ? */
{ /* Read the decimal part */
(*BasicLine) ++;
while (isdigit (**BasicLine))
Value = Value + (Divider /= 10) * (*((*BasicLine) ++) - '0');
}
if ((**BasicLine) == 'e' || (**BasicLine) == 'E') /* Exponent ? */
{
(*BasicLine) ++;
if ((**BasicLine) == '+') /* Both "Ex" and "E+x" do the same thing */
(*BasicLine) ++;
else if ((**BasicLine) == '-') /* Negative exponent */
{
Sign = 0xFF;
(*BasicLine) ++;
}
while (isdigit (**BasicLine)) /* Read the exponent value */
Exp = Exp * 10 + *((*BasicLine) ++) - '0';
if (Sign == 0x00) /* Raise the resulting value to the read exponent */
Value = Value * pow (10.0, Exp);
else
Value = Value / pow (10.0, Exp);
}
strncpy ((char *)*SpectrumLine, StartOfNumber, *BasicLine - StartOfNumber); /* Insert the ASCII value first */
(*SpectrumLine) += (*BasicLine - StartOfNumber);
IntValue = (int)floor (Value);
if (Value == IntValue && Value >= -65536 && Value < 65536) /* Small integer ? */
{
*((*SpectrumLine) ++) = 0x0E; /* Insert number marker */
*((*SpectrumLine) ++) = 0x00;
if (IntValue >= 0) /* Insert sign */
*((*SpectrumLine) ++) = 0x00;
else
{
*((*SpectrumLine) ++) = 0xFF;
IntValue += 65536; /* Maintain bug in Spectrum ROM - INT(-65536) will result in -1 */
}
*((*SpectrumLine) ++) = (byte)(IntValue & 0xFF);
*((*SpectrumLine) ++) = (byte)(IntValue >> 8);
*((*SpectrumLine) ++) = 0x00;
}
else /* Need to store in full floating point format */
{
if (Value < 0)
{
Sign = 0x80; /* Sign bit is high bit of byte 2 */
Value = -Value;
}
else
Sign = 0x00;
Exp = floor (x_log2 (Value));
if (Exp < -129 || Exp > 126)
{
fprintf (ErrStream, "ERROR - Number too big in line %d\n", BasicLineNo);
return (-1);
}
Mantissa = (unsigned long)floor ((Value / pow (2.0, Exp) - 1.0) * SHIFT31BITS + 0.5); /* Calculate mantissa */
*((*SpectrumLine) ++) = 0x0E; /* Insert number marker */
*((*SpectrumLine) ++) = (byte)Exp + 0x81; /* Insert exponent */
*((*SpectrumLine) ++) = (byte)((Mantissa >> 24) & 0x7F) | Sign; /* Insert mantissa */
*((*SpectrumLine) ++) = (byte)((Mantissa >> 16) & 0xFF); /* (Big endian!) */
*((*SpectrumLine) ++) = (byte)((Mantissa >> 8) & 0xFF);
*((*SpectrumLine) ++) = (byte)(Mantissa & 0xFF);
}
return (1);
}
int HandleBIN (int BasicLineNo, char **BasicLine, byte **SpectrumLine)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the current BASIC line number, `BasicLine' points into the line just past the BIN token, */
/* `SpectrumLine' points to the TAPped Spectrum line. */
/* Post : If there was a BINary number at this position, it has been processed into `SpectrumLine' and `LineIndex' is pointing */
/* after the number. */
/* The return value is: 1 = number done, -1 = number error (already reported). */
/* Import: None. */
/**********************************************************************************************************************************/
{
int Value = 0;
while ((**BasicLine) == '0' || (**BasicLine) == '1') /* Read only binary digits */
{
Value = Value * 2 + **BasicLine - '0';
if (Value > 65535)
{
fprintf (ErrStream, "ERROR - Number too big in line %d\n", BasicLineNo);
return (-1);
}
*((*SpectrumLine) ++) = *((*BasicLine) ++); /* (Copy digit across) */
}
*((*SpectrumLine) ++) = 0x0E; /* Insert number marker */
*((*SpectrumLine) ++) = 0x00; /* (A small integer by definition) */
*((*SpectrumLine) ++) = 0x00;
*((*SpectrumLine) ++) = (byte)(Value & 0xFF);
*((*SpectrumLine) ++) = (byte)(Value >> 8);
*((*SpectrumLine) ++) = 0x00;
return (1);
}
int ExpandSequences (int BasicLineNo, char **BasicLine, byte **SpectrumLine, bool StripSpaces)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the current BASIC line number, `BasicLine' points into the line, `SpectrumLine' points to the */
/* TAPped Spectrum line. */
/* Post : If there was an expandable '{...}' sequence at this position, it has been processed into `SpectrumLine', `LineIndex' */
/* is pointing after the sequence. Returned is -1 for error, 0 for no expansion, 1 for expansion. */
/* Import: None. */
/**********************************************************************************************************************************/
{
char *StartOfSequence;
byte Attribute = 0;
byte AttributeLength = 0;
byte AttributeVal1 = 0;
byte AttributeVal2 = 0;
byte OldCharacter;
int Cnt;
if (**BasicLine != '{')
return (0);
StartOfSequence = (*BasicLine) + 1;
/* 'CODE' and 'CAT' were added for the sole purpuse of allowing them to be OPEN #'ed as channels! */
if (!x_strnicmp (StartOfSequence, "CODE}", 5)) /* Special: 'CODE' */
{
*((*SpectrumLine) ++) = 0xAF;
(*BasicLine) += 6;
return (1);
}
if (!x_strnicmp (StartOfSequence, "CAT}", 4)) /* Special: 'CAT' */
{
*((*SpectrumLine) ++) = 0xCF;
(*BasicLine) += 5;
return (1);
}
if (!x_strnicmp (StartOfSequence, "(C)}", 4))
{ /* Form "{(C)}" -> copyright sign */
*((*SpectrumLine) ++) = 0x7F;
(*BasicLine) += 5;
if (StripSpaces)
while ((**BasicLine) == ' ') /* Skip trailing spaces */
(*BasicLine) ++;
return (1);
}
if (*StartOfSequence == '+' && *(StartOfSequence + 1) >= '1' && *(StartOfSequence + 1) <= '8' && *(StartOfSequence + 2) == '}')
{ /* Form "{+X}" -> block graphics with shift */
*((*SpectrumLine) ++) = 0x88 + (((*(StartOfSequence + 1) - '0') % 8) ^ 7);
(*BasicLine) += 4;
if (StripSpaces)
while ((**BasicLine) == ' ')
(*BasicLine) ++;
return (1);
}
if (*StartOfSequence == '-' && *(StartOfSequence + 1) >= '1' && *(StartOfSequence + 1) <= '8' && *(StartOfSequence + 2) == '}')
{ /* Form "{-X}" -> block graphics without shift */
*((*SpectrumLine) ++) = 0x80 + (*(StartOfSequence + 1) - '0') % 8;
(*BasicLine) += 4;
if (StripSpaces)
while ((**BasicLine) == ' ')
(*BasicLine) ++;
return (1);
}
if (toupper (*StartOfSequence) >= 'A' && toupper (*StartOfSequence) <= 'U' && *(StartOfSequence + 1) == '}')
{ /* Form "{X}" -> UDG */
if (toupper (*StartOfSequence) == 'T' || toupper (*StartOfSequence) == 'U') /* 'T' or 'U' ? */
switch (Is48KProgram) /* Then the program must be 48K */
{
case -1 : Is48KProgram = 1; break; /* Set the flag */
case 0 : fprintf (ErrStream, "ERROR - Line %d contains UDGs \'T\' and/or \'U\'\n"
"but the program was already marked 128K\n", BasicLineNo);
return (-1);
case 1 : break;
}
*((*SpectrumLine) ++) = 0x90 + toupper (*StartOfSequence) - 'A';
(*BasicLine) += 3;
if (StripSpaces)
while ((**BasicLine) == ' ')
(*BasicLine) ++;
return (1);
}
if (isxdigit (*StartOfSequence) && isxdigit (*(StartOfSequence + 1)) && *(StartOfSequence + 2) == '}')
{ /* Form "{XX}" -> below 32 */
if (*StartOfSequence <= '9')
(**SpectrumLine) = *StartOfSequence - '0';
else
(**SpectrumLine) = toupper (*StartOfSequence) - 'A' + 10;
if (*(StartOfSequence + 1) <= '9')
(**SpectrumLine) = (**SpectrumLine) * 16 + *(StartOfSequence + 1) - '0';
else
(**SpectrumLine) = (**SpectrumLine) * 16 + toupper (*(StartOfSequence + 1)) - 'A' + 10;
(*SpectrumLine) ++;
(*BasicLine) += 4;
if (StripSpaces)
while ((**BasicLine) == ' ')
(*BasicLine) ++;
return (1);
}
if (!x_strnicmp (StartOfSequence, "INK", 3))
{
Attribute = 0x10;
AttributeLength = 3;
}
else if (!x_strnicmp (StartOfSequence, "PAPER", 5))
{
Attribute = 0x11;
AttributeLength = 5;
}
else if (!x_strnicmp (StartOfSequence, "FLASH", 5))
{
Attribute = 0x12;
AttributeLength = 5;
}
else if (!x_strnicmp (StartOfSequence, "BRIGHT", 6))
{
Attribute = 0x13;
AttributeLength = 6;
}
else if (!x_strnicmp (StartOfSequence, "INVERSE", 7))
{
Attribute = 0x14;
AttributeLength = 7;
}
else if (!x_strnicmp (StartOfSequence, "OVER", 4))
{
Attribute = 0x15;
AttributeLength = 4;
}
else if (!x_strnicmp (StartOfSequence, "AT", 2))
{
Attribute = 0x16;
AttributeLength = 2;
}
else if (!x_strnicmp (StartOfSequence, "TAB", 3))
{
Attribute = 0x17;
AttributeLength = 3;
}
if (Attribute > 0)
{
StartOfSequence += AttributeLength;
while (*StartOfSequence == ' ')
StartOfSequence ++;
while (isdigit (*StartOfSequence))
AttributeVal1 = AttributeVal1 * 10 + *(StartOfSequence ++) - '0';
if (Attribute == 0x16 || Attribute == 0x17)
{
if (*StartOfSequence != ',')
Attribute = 0;
else
{
StartOfSequence ++; /* (Step past the comma) */
while (*StartOfSequence == ' ')
StartOfSequence ++;
while (isdigit (*StartOfSequence))
AttributeVal2 = AttributeVal2 * 10 + *(StartOfSequence ++) - '0';
}
}
if (*StartOfSequence != '}') /* Need closing bracket */
Attribute = 0;
if (Attribute > 0)
{
*((*SpectrumLine) ++) = Attribute;
*((*SpectrumLine) ++) = AttributeVal1;
if (Attribute == 0x16 || Attribute == 0x17)
*((*SpectrumLine) ++) = AttributeVal2;
(*BasicLine) = StartOfSequence + 1;
if (StripSpaces)
while ((**BasicLine) == ' ')
(*BasicLine) ++;
return (1);
}
}
if (!NoWarnings)
{
for (Cnt = 0 ; *((*BasicLine) + Cnt) && *((*BasicLine) + Cnt) != '}' ; Cnt ++)
;
if (*((*BasicLine) + Cnt) == '}')
{
OldCharacter = *((*BasicLine) + Cnt + 1);
*((*BasicLine) + Cnt + 1) = '\0';
printf ("WARNING - Unexpandable sequence \"%s\" in line %d\n", (*BasicLine), BasicLineNo);
*((*BasicLine) + Cnt + 1) = OldCharacter;
return (0);
}
}
return (0);
}
int PrepareLine (char *LineIn, int FileLineNo, char **FirstToken)
/**********************************************************************************************************************************/
/* Pre : `LineIn' points to the read line, `FileLineNo' holds the real line number. */
/* Post : Multiple spaces have been removed (unless within a string), the BASIC line number has been found and `FirstToken' is */
/* pointing at the first non-whitespace character after the line number. */
/* Bad characters are reported, as well as any other error. The return value is the BASIC line number, -1 if error, or */
/* -2 if the (empty!) line should be skipped. */
/* Import: GetLineNumber. */
/**********************************************************************************************************************************/
{
char *IndexIn;
char *IndexOut;
bool InString = FALSE;
bool SingleSeparator = FALSE;
bool StillOk = TRUE;
bool DoingREM = FALSE;
int BasicLineNo = -1;
static int PreviousBasicLineNo = -1;
IndexIn = LineIn;
IndexOut = ConvertedSpectrumLine;
while (*IndexIn && StillOk)
{
if (*IndexIn == '\t') /* EXCEPTION: Print ' */
{
*(IndexOut ++) = 0x06;
IndexIn ++;
}
else if (*IndexIn < 32 || *IndexIn >= 127) /* (Exclude copyright sign as well) */
StillOk = FALSE;
else
{
if (!DoingREM)
if (!x_strnicmp (IndexIn, " REM ", 5) || /* Going through REM statement ? */
!x_strnicmp (IndexIn, ":REM ", 5))
DoingREM = TRUE; /* Signal: copy anything and everything ASCII */
if (InString || DoingREM)
*(IndexOut ++) = *IndexIn;
else
{
if (*IndexIn == ' ')
{
if (!SingleSeparator) /* Remove multiple spaces */
{
SingleSeparator = TRUE;
*(IndexOut ++) = *IndexIn;
}
}
else
{
SingleSeparator = FALSE;
*(IndexOut ++) = *IndexIn;
}
}
if (*IndexIn == '\"' && !DoingREM)
InString = !InString;
IndexIn ++;
}
}
*IndexOut = '\0';
if (!StillOk)
if (*IndexIn == 0x0D || *IndexIn == 0x0A) /* 'Correct' for end-of-line */
StillOk = TRUE; /* (Accept CR and/or LF as end-of-line) */
BasicLineNo = GetLineNumber (FirstToken);
if (InString)
fprintf (ErrStream, "ERROR - %s line %d misses terminating quote\n",
BasicLineNo < 0 ? "ASCII" : "BASIC", BasicLineNo < 0 ? FileLineNo : BasicLineNo);
else if (!StillOk)
fprintf (ErrStream, "ERROR - %s line %d contains a bad character (code %02Xh)\n",
BasicLineNo < 0 ? "ASCII" : "BASIC", BasicLineNo < 0 ? FileLineNo : BasicLineNo, *IndexIn);
else if (BasicLineNo < 0) /* Could not read line number */
{
if (!(**FirstToken)) /* Line is completely empty ? */
{
if (!NoWarnings)
printf ("WARNING - Skipping empty ASCII line %d\n", FileLineNo);
return (-2); /* Signal: skip entire line */
}
else
{
fprintf (ErrStream, "ERROR - Missing line number in ASCII line %d\n", FileLineNo);
StillOk = FALSE;
}
}
else if (PreviousBasicLineNo >= 0) /* Not the first line ? */
{
if (BasicLineNo < PreviousBasicLineNo) /* This line number smaller than previous ? */
{
fprintf (ErrStream, "ERROR - Line number %d is smaller than previous line number %d\n", BasicLineNo, PreviousBasicLineNo);
StillOk = FALSE;
}
else if (BasicLineNo == PreviousBasicLineNo && !NoWarnings) /* Same line number as previous ? */
printf ("WARNING - Duplicate use of line number %d\n", BasicLineNo); /* (BASIC can handle it after all...) */
}
else if (!(**FirstToken)) /* Line contains only a line number ? */
{
fprintf (ErrStream, "ERROR - Line %d contains no statements!\n", BasicLineNo);
StillOk = FALSE;
}
PreviousBasicLineNo = BasicLineNo; /* Remember this line number */
if (!InString && StillOk)
return (BasicLineNo);
else
return (-1);
}
bool CheckEnd (int BasicLineNo, int StatementNo, byte **Index)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Index' the current position in the line. */
/* Post : A check is made whether the end of the current statement has been reached. */
/* If so, an error is reported and TRUE is returned (so FALSE indicates that everything is still fine and dandy). */
/* Import: none. */
/**********************************************************************************************************************************/
{
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of statement\n", BasicLineNo, StatementNo);
return (TRUE);
}
return (FALSE);
}
bool ScanVariable (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type, int *NameLen, int AllowSlicing)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Keyword' the keyword to which this operand */
/* belongs, `Index' the current position in the line. */
/* `AllocSlicing' is one of the following values: */
/* -1 = Don't check for slicing/indexing (used by DEF FN) */
/* 0 = No slicing/indexing allowed */
/* 1 = Either slicing or indexing may follow (indices being numeric) */
/* 2 = Only numeric indexing may follow (used by LET and READ) */
/* Post : A check has been made whether there's a variable at the current position. If so, it has been skipped. */
/* Slicing is handled here as well, but notice that this is not necessarily correct! */
/* Single letter string variables can be either flat or array and both possibilities are considered here. */
/* Both "a$(1 TO 10)" and "a$(1, 2)" are correct to BASIC, but depend on whether a "DIM" statement was used. */
/* The length of the found string (without any '$') is returned in `NameLen', its type is returned in `Type' (TRUE for */
/* numeric and FALSE for string variables). The return value is TRUE is all went well. Errors have already been reported. */
/* The return value is FALSE either when no variable is at this point or an error was found. */
/* `NameLen' is returned 0 if no variable was detected here, or > 0 if in error. */
/* Import: ScanExpression. */
/**********************************************************************************************************************************/
{
bool SubType;
bool IsArray = FALSE;
bool SetTokenBracket = FALSE;
Keyword = Keyword; /* (Keep compilers happy) */
*Type = TRUE; /* Assume it will be numeric */
*NameLen = 0;
if (!isalpha (**Index)) /* The first character must be alphabetic for a variable */
return (FALSE);
*NameLen = 1;
while (isalnum (*(++ (*Index)))) /* Read on, until end of the word */
(*NameLen) ++;
if (**Index == '$') /* It's a string variable ? */
{
if (*NameLen > 1) /* String variables can only have a single character name */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - String variables can only have single character names\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
*Type = FALSE;
}
#ifdef __DEBUG__
printf ("DEBUG - %sScanVariable, Type is %s\n", ListSpaces, *Type ? "NUM" : "ALPHA");
#endif
if (AllowSlicing >= 0 && **Index == '(') /* Slice the string ? */
{
#ifdef __DEBUG__
printf ("DEBUG - %sScanVariable, reading index\n", ListSpaces);
#endif
if (*NameLen > 1) /* Arrays can only have a single character name */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Arrays can only have single character names\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (AllowSlicing == 0) /* Slicing/Indexing not allowed ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Slicing/Indexing not allowed\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++; /* (Skip the bracket) */
if (**Index == ')') /* Empty slice "a$()" is not ok */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty array index not allowed\n", BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index == 0xCC) /* "a$( TO num)" or "a$( TO )" */
{
if (AllowSlicing == 2)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Slicing token \"TO\" inappropriate for arrays\n",
BasicLineNo, StatementNo);
return (FALSE);
}
}
else /* Not "a$( TO num)" nor "a$( TO )" */
{
if (!TokenBracket)
{
TokenBracket = TRUE; /* Allow complex expression */
SetTokenBracket = TRUE;
}
if (!ScanExpression (BasicLineNo, StatementNo, '(', Index, &SubType, 0)) /* First parameter */
return (FALSE);
if (SetTokenBracket)
TokenBracket = FALSE;
if (!SubType) /* Must be numeric */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Variables indices must be numeric\n", BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index == ')') /* "a$(num)" is ok */
{
(*Index) ++;
#ifdef __DEBUG__
printf ("DEBUG - %sScanVariable, index ending, next char is \"%s\"\n", ListSpaces, TokenMap[**Index].Token);
#endif
return (TRUE);
}
}
if (**Index != 0xCC && **Index != ',') /* Either an array or a slice */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected index character \"%c\"\n",
BasicLineNo, StatementNo, **Index);
return (FALSE);
}
if (**Index == ',')
IsArray = TRUE;
else
{
if (AllowSlicing == 2)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Slicing token \"TO\" inappropriate for arrays\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (*Type) /* Only character strings can be sliced */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Only character strings can be sliced\n", BasicLineNo, StatementNo);
return (FALSE);
}
}
do
{
(*Index) ++; /* Skip each "," (or the "TO" for non-arrays) */
if (!TokenBracket)
{
TokenBracket = TRUE;
SetTokenBracket = TRUE;
}
if (!ScanExpression (BasicLineNo, StatementNo, '(', Index, &SubType, 0)) /* Second or further parameter */
return (FALSE);
if (SetTokenBracket)
TokenBracket = FALSE;
if (!SubType) /* Must be numeric */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Variables indices must be numeric\n", BasicLineNo, StatementNo);
return (FALSE);
}
if (!IsArray && **Index != ')')
{
BADTOKEN ("\")\"", TokenMap[**Index].Token);
return (FALSE);
}
else if (IsArray && **Index != ',' && **Index != ')' && **Index != 0xCC)
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
while (**Index != ')');
(*Index) ++; /* (Step past closing bracket) */
#ifdef __DEBUG__
printf ("DEBUG - %sScanVariable, index ending, next char is \"%s\"\n", ListSpaces, TokenMap[**Index].Token);
#endif
}
return (TRUE);
}
bool SliceDirectString (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Keyword' the keyword to which this operand */
/* belongs, `Index' the current position in the line. */
/* A direct string has just been read and a '(' character is currently under the cursor. */
/* Post : Slicing is handled here. */
/* Possible are "string"(), "string"(num), "string"( TO ), "string"(num TO ), "string"( TO num) and "string"(num TO num). */
/* The return value is FALSE if an error was found (which has already been reported here). */
/* Import: ScanExpression. */
/**********************************************************************************************************************************/
{
bool SubType;
bool SetTokenBracket = FALSE;
Keyword = Keyword; /* (Keep compilers happy) */
(*Index) ++; /* Step past the opening bracket */
if (**Index == ')') /* Empty slice "abc"() is ok */
{
(*Index) ++;
return (TRUE);
}
if (**Index != 0xCC) /* Not "abc"( TO num) nor "abc"( TO ) */
{
if (!TokenBracket)
{
TokenBracket = TRUE;
SetTokenBracket = TRUE;
}
if (!ScanExpression (BasicLineNo, StatementNo, '(', Index, &SubType, 0)) /* First parameter */
return (FALSE);
if (SetTokenBracket)
TokenBracket = FALSE;
if (!SubType) /* Must be numeric */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Slice values must be numeric\n", BasicLineNo, StatementNo);
return (FALSE);
}
}
if (**Index == ')') /* "abc"(num) is ok */
{
(*Index) ++;
return (TRUE);
}
if (**Index != 0xCC) /* ('TO') */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected index character\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
if (**Index == ')') /* "abc"(num TO ) is ok */
{
(*Index) ++;
return (TRUE);
}
if (!TokenBracket)
{
TokenBracket = TRUE;
SetTokenBracket = TRUE;
}
if (!ScanExpression (BasicLineNo, StatementNo, '(', Index, &SubType, 0)) /* Second parameter */
return (FALSE);
if (SetTokenBracket)
TokenBracket = FALSE;
if (!SubType) /* Must be numeric */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Slice values must be numeric\n", BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index != ')')
{
BADTOKEN ("\")\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++; /* (Step past closing bracket) */
return (TRUE);
}
bool ScanStream (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Keyword' the keyword to which this operand */
/* belongs, `Index' the current position in the line. */
/* A stream hash mark (`#') has just been read. */
/* Post : The following stream number is checked to be a numeric expression. */
/* The return value is FALSE if an error was found (which has already been reported here). */
/* Import: HandleClass06. */
/**********************************************************************************************************************************/
{
if (!SignalInterface1 (BasicLineNo, StatementNo, 0))
return (FALSE);
return (HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)); /* Find numeric expression */
}
bool SignalInterface1 (int BasicLineNo, int StatementNo, int NewMode)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `NewMode' holds the required hardware mode. */
/* Post : The required hardware is tested for conflicts. */
/* The return value is FALSE if there was a conflict (which has already been reported here). */
/* Import: none. */
/**********************************************************************************************************************************/
{
if ((NewMode == 1 && UsesInterface1 == 2) || /* Interface1 required, but already flagged Opus ? */
(NewMode == 2 && UsesInterface1 == 1)) /* Opus required, but already flagged Interface1 ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - The program uses commands that are specific\n"
"for Interface 1 and Opus Discovery, but don't exist on both devices\n",
BasicLineNo, StatementNo);
return (FALSE);
}
UsesInterface1 = NewMode;
return (TRUE);
}
bool ScanChannel (int BasicLineNo, int StatementNo, int Keyword, byte **Index, byte *WhichChannel)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Keyword' the keyword to which this operand */
/* belongs, `Index' the current position in the line. */
/* Post : A channel identifier of the form "x";n; must follow. `x' is a single alphanumeric character, `n' is a numeric */
/* expression, the rest are required characters. */
/* The found channel identifier ('x') is returned (in lowercase) in `WhichChannel'. */
/* The return value is FALSE if an error was found (which has already been reported here). */
/* Import: HandleClass06, CheckEnd. */
/**********************************************************************************************************************************/
{
int NeededHardware = 0; /* (Default to Interface 1) */
*WhichChannel = '\0';
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != '\"')
{
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index))/* EXCEPTION: The Opus allows '<num>' to abbreviate '"m";<num>' */
{
fprintf (ErrStream, "Expected to find a channel identifier\n");
return (FALSE);
}
*WhichChannel = 'm';
if (!SignalInterface1 (BasicLineNo, StatementNo, 2)) /* Signal the Opus specificness */
return (FALSE);
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ';')
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
}
else
{
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (!isalpha (**Index) && /* (Ordinary channel) */
**Index != '#' && /* (Linked channel, OPEN # only) */
**Index != 0xAF && /* ('CODE' channel, OPEN # only) */
**Index != 0xCF) /* ('CAT' channel, OPEN # only) */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Channel name must be alphanumeric\n", BasicLineNo, StatementNo);
return (FALSE);
}
*WhichChannel = tolower (**Index);
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != '\"')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Channel name must be single character\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
if (*WhichChannel == 'k' || *WhichChannel == 's' || *WhichChannel == 'p' || /* (Normal Spectrum channels) */
*WhichChannel == 'm' || *WhichChannel == 't' || *WhichChannel == 'b' ||
*WhichChannel == '#' || *WhichChannel == 0xCF) /* ('CAT' channel) */
NeededHardware = 0;
else if (*WhichChannel == 'n') /* Network channel is available on Interface 1 but not on Opus */
NeededHardware = 1;
else if (*WhichChannel == 'j' || /* (Opus: Joystick channel) */
*WhichChannel == 'd' || /* (Opus: disk channel) */
*WhichChannel == 0xAF) /* (Opus: 'CODE' channel) */
NeededHardware = 2;
if (!SignalInterface1 (BasicLineNo, StatementNo, NeededHardware))
return (FALSE);
if (*WhichChannel == 'm' || *WhichChannel == 'd' || *WhichChannel == 'n' || /* Continue checking with these channels only */
*WhichChannel == '#' || *WhichChannel == 0xCF)
{
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ';')
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find numeric expression */
return (FALSE);
if (*WhichChannel == 'm') /* Omly the 'm' channel requires a ';' character following */
{
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ';')
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
}
}
}
return (TRUE);
}
bool ScanExpression (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type, int Level)
/**********************************************************************************************************************************/
/* Pre : `BasicLineNo' holds the line number, `StatementNo' the statement number, `Keyword' the keyword to which this operand */
/* belongs, `Index' the current position in the line. */
/* `Level' is used for recursion and must be 0 when called, unless when called from ScanVariable (then it must be 1). */
/* Post : An expression must be found, either numerical or string. Its type is returned in `Type' (TRUE for numerical). */
/* All subexpressions, between brackets, are dealt with using recursion. */
/* The return value is FALSE if an error was found (which has already been reported here). */
/* Import: ScanExpression (recursive), SliceDirectString, ScanVariable, HandleClassXX. */
/**********************************************************************************************************************************/
{
bool More = TRUE;
bool SubType = TRUE; /* (Assume numeric expression) */
bool SubSubType;
bool TypeKnown = FALSE;
bool TotalTypeKnown = FALSE;
bool Dummy;
int VarNameLen;
int ClassIndex = -1;
byte ThisToken;
#ifdef __DEBUG__
RecurseLevel ++;
memset (ListSpaces, ' ', RecurseLevel * 2);
ListSpaces[RecurseLevel * 2] = '\0';
printf ("DEBUG - %sEnter ScanExpression\n", ListSpaces);
#endif
if (**Index == '+' || **Index == '-') /* Unary plus and minus */
{
*Type = TRUE; /* Then we expect a numeric expression */
TypeKnown = TRUE;
(*Index) ++; /* Skip the sign */
}
while (More)
{
#ifdef __DEBUG__
printf ("DEBUG - %sScanExpression sub (keyword \"%s\"), first char is \"%s\"\n",
ListSpaces, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (**Index == '(') /* Opening bracket ? */
{
#ifdef __DEBUG__
printf ("DEBUG - %sRecurse ScanExpression for \"(\"\n", ListSpaces);
#endif
(*Index) ++; /* The 'parent' steps past the opening bracket */
if (!ScanExpression (BasicLineNo, StatementNo, '(', Index, &SubSubType, Level + 1)) /* Recurse */
return (FALSE);
if (TypeKnown && SubSubType != SubType) /* Bad subexpression type ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
else if (!TypeKnown) /* We didn't have an expected type yet ? */
{
SubType = SubSubType;
TypeKnown = TRUE;
}
(*Index) ++; /* The 'parent' steps past the closing bracket too */
if (**Index == '(') /* Slicing ? */
{
if (!SubSubType) /* Result was a string ? */
{
if (!SliceDirectString (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
}
else /* No, it was numerical, which you can't slice */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - cannot slice a numerical value\n",
BasicLineNo, StatementNo);
return (FALSE);
}
}
}
else if (**Index == ')') /* Closing bracket ? */
{ /* Leave the bracket for the parent, to allow functions (eg. "ATTR (...)") */
if (!TotalTypeKnown) /* 'Simple' expression ? */
*Type = SubType; /* Set return type */
#ifdef __DEBUG__
printf ("DEBUG - %sLeave ScanExpression, Type is %s next char is \"%s\"\n",
ListSpaces, *Type ? "NUM" : "ALPHA", TokenMap[**Index].Token);
if (-- RecurseLevel > 0)
memset (ListSpaces, ' ', RecurseLevel * 2);
ListSpaces[RecurseLevel * 2] = '\0';
#endif
return (TRUE); /* Step out of the recursion */
}
else if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
{
if (!TotalTypeKnown) /* 'Simple' expression ? */
*Type = SubType; /* Set return type */
if (Level) /* Not on lowest level ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - too few closing brackets\n", BasicLineNo, StatementNo);
return (FALSE);
}
More = FALSE;
}
else if (isdigit (**Index) || **Index == '.' || **Index == 0xC4) /* Number ? */
{
if (!TypeKnown) /* Unknown expression type yet ? */
{
TypeKnown = TRUE; /* Signal: it is numeric */
SubType = TRUE;
}
else if (!SubType) /* Type was known to be string ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
while (*(++ (*Index)) != 0x0E) /* Skip until the number marker */
;
(*Index) ++;
}
else if (**Index == '\"') /* Direct string ? */
{
if (!TypeKnown) /* Unknown expression type yet ? */
{
TypeKnown = TRUE; /* Signal: it is a string */
SubType = FALSE;
}
else if (SubType) /* Type was known to be numeric ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"') /* Concatenated strings are ok, since they allow the use of the " character */
{
while (*(++ (*Index)) != '\"') /* Find closing quote */
;
(*Index) ++; /* Step past it */
}
if (**Index == '(') /* String is sliced ? */
if (!SliceDirectString (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
}
else if (ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &SubSubType, &VarNameLen, 1)) /* Is it a variable ? */
{
if (!TypeKnown) /* Unknown expression type yet ? */
{
TypeKnown = TRUE; /* Signal: it is string */
SubType = SubSubType;
}
else if (SubType != SubSubType) /* Different type variable ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
}
else if (VarNameLen != 0) /* (Not a variable) */
return (FALSE); /* (But an error that was already reported) */
/* It's none of the above. Go check tokens */
else switch (TokenMap[**Index].TokenType)
{
case 0 : fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected token \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
case 1 :
case 2 : fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected keyword \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
case 3 :
case 4 :
case 5 : ThisToken = *((*Index) ++);
if (TokenMap[ThisToken].TokenType == 5)
{
if (Keyword != 0xF5 && Keyword != 0xE0) /* Not handling a PRINT or LPRINT ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected token \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
}
}
else if (ThisToken == 0xC0 && **Index == '\"') /* Special: USR "x" */
{
(*Index) ++; /* (Step past the opening quote) */
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (toupper (**Index) < 'A' || toupper (**Index) > 'U') /* Bad UDG character ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Bad UDG \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != '\"') /* More than one letter ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - An UDG name may be only 1 letter\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) --;
if (toupper (**Index) == 'T' || toupper (**Index) == 'U') /* One of the UDGs 'T' or 'U' ? */
switch (Is48KProgram) /* Then the program must be 48K */
{
case -1 : Is48KProgram = 1; break; /* Set the flag */
case 0 : fprintf (ErrStream, "ERROR - Line %d contains UDGs \'T\' and/or \'U\'\n"
"but the program was already marked 128K\n", BasicLineNo);
return (FALSE);
case 1 : break;
}
(*Index) += 2; /* Step past the UDG name and closing quote */
break; /* Done, step out */
}
else
{
if (!TypeKnown) /* Unknown expression type yet ? */
{
TypeKnown = TRUE; /* Set expected type */
SubType = (TokenMap[ThisToken].TokenType == 3);
}
else if ((SubType && TokenMap[ThisToken].TokenType == 4) ||
(!SubType && TokenMap[ThisToken].TokenType == 3))
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
}
ClassIndex = -1;
while (TokenMap[ThisToken].KeywordClass[++ ClassIndex]) /* Handle all class parameters */
{
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
else if (TokenMap[ThisToken].KeywordClass[ClassIndex] >= 32) /* Required token or class ? */
{
if (**Index != TokenMap[ThisToken].KeywordClass[ClassIndex]) /* (Required token) */
{ /* (Token not there) */
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected \"%c\", but got \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[ThisToken].KeywordClass[ClassIndex], TokenMap[**Index].Token);
return (FALSE);
}
else
{
if (**Index == '(')
{
#ifdef __DEBUG__
printf ("DEBUG - %sTurning on token bracket\n", ListSpaces);
#endif
TokenBracket = TRUE;
}
else if (**Index == ')')
{
#ifdef __DEBUG__
printf ("DEBUG - %sTurning off token bracket\n", ListSpaces);
#endif
TokenBracket = FALSE;
}
(*Index) ++;
}
}
else /* (Command class) */
{
switch (TokenMap[ThisToken].KeywordClass[ClassIndex])
{
case 1 : if (!HandleClass01 (BasicLineNo, StatementNo, ThisToken, Index, &Dummy)) /* (Special: FN) */
return (FALSE);
break;
case 3 : if (!HandleClass03 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 5 : if (!HandleClass05 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 6 : if (!HandleClass06 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 8 : if (!HandleClass08 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 10 : if (!HandleClass10 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 12 : if (!HandleClass12 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 13 : if (!HandleClass13 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
case 14 : if (!HandleClass14 (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
break;
}
#ifdef __DEBUG__
printf ("DEBUG - %sScanExpression status, Type is %s, next char is \"%s\"\n",
ListSpaces, *Type ? "NUM" : "ALPHA", TokenMap[**Index].Token);
#endif
}
}
if (ThisToken == 0xA6) /* INKEY$ ? */
if (**Index == '#') /* Type 'INKEY$#<stream>' ? */
{
(*Index) ++;
if (!ScanStream (BasicLineNo, StatementNo, ThisToken, Index))
return (FALSE);
}
break;
}
/* Piece done, continue */
if (TokenMap[Keyword].TokenType == 3 || TokenMap[Keyword].TokenType == 4) /* Just did an operand to a function ? */
{ /* Then step back to evaluate the result */
if (!TotalTypeKnown)
*Type = SubType;
#ifdef __DEBUG__
printf ("DEBUG - %sLeave ScanExpression, Type is %s, next char is \"%s\"\n",
ListSpaces, *Type ? "NUM" : "ALPHA", TokenMap[**Index].Token);
if (-- RecurseLevel > 0)
memset (ListSpaces, ' ', RecurseLevel * 2);
ListSpaces[RecurseLevel * 2] = '\0';
#endif
return (TRUE);
}
if (More)
{
if (**Index == 0xC5 || **Index == 0xC6) /* ('OR' and 'AND') */
{
#ifdef __DEBUG__
printf ("DEBUG - %sRecurse ScanExpression for \"%s\"\n", ListSpaces, TokenMap[**Index].Token);
#endif
//if (!TotalTypeKnown) /* 'Simple' expression before the AND/OR ? */
//*Type = SubType;
if (**Index == 0xC5 && !*Type)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - \"OR\" requires a numeric left value\n", BasicLineNo, StatementNo);
return (FALSE);
}
ThisToken = *((*Index) ++); /* Step over the operator - but remember it */
if (!ScanExpression (BasicLineNo, StatementNo, ThisToken, Index, &SubSubType, 0)) /* Recurse - at level 0! */
return (FALSE);
if (!SubSubType) /* The expression at the right must be numeric for both AND and OR */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - \"%s\" requires a numeric right value\n",
BasicLineNo, StatementNo, TokenMap[ThisToken].Token);
return (FALSE);
}
if (!TypeKnown) /* We didn't have an expected type yet ? */
{
TypeKnown = TRUE;
TotalTypeKnown = TRUE;
SubType = *Type = (bool)(ThisToken == 0xC6 && !*Type ? FALSE : TRUE); /* Signal resulting type */
/* x$ AND y -> result is string */
/* x AND y -> result is numeric */
/* x OR y -> result is numeric */
}
More = FALSE; /* (Because the recursing causes the expression to be evaluated right to left, we're done now) */
}
else if ((**Index == '=' || **Index == '<' || **Index == '>' || /* EXCEPTION: equations between brackets (side effects) */
**Index == 0xC7 || **Index == 0xC8 || **Index == 0xC9) && /* ("<=", ">=" and "<>") */
Level) /* Not on level 0: that is handled below! */
{ /* Expressions like 'LET A=(INKEY$="A")'; we're now between these brackets */
SubType = *Type = TRUE; /* Signal: result is going to be numeric */
TotalTypeKnown = TRUE;
TypeKnown = FALSE; /* Start with a fresh subexpression type */
(*Index) ++;
}
else if ((TokenMap[Keyword].TokenType != 4 && TokenMap[Keyword].TokenType != 3) || /* Not evaluating an expression token ? */
TokenBracket) /* Or evaluating an operand of a token ? */
{
if (**Index == '+') /* (Can apply to both string and numeric expressions) */
(*Index) ++;
else if (**Index == '-' || **Index == '*' || **Index == '/' || **Index == '^') /* (Numeric only) */
{
if (!SubType) /* Type was known to be string ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Type conflict in expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
/* Equations and logical operators turn the total result numeric, but each subexpression may be of any type */
else if ((**Index == '=' || **Index == '<' || **Index == '>' ||
**Index == 0xC7 || **Index == 0xC8 || **Index == 0xC9) && /* ("<=", ">=" and "<>") */
!Level) /* Only evaluate these on level 0! */
{
TotalTypeKnown = TRUE;
*Type = TRUE; /* Signal: result is going to be numeric */
TypeKnown = FALSE; /* Start with a fresh subexpression type */
(*Index) ++;
}
else
More = FALSE;
}
else
More = FALSE;
}
}
if (!TotalTypeKnown) /* 'Simple' expression ? */
*Type = SubType; /* Set return type */
#ifdef __DEBUG__
printf ("DEBUG - %sLeave ScanExpression, Type is %s, next char is \"%s\"\n",
ListSpaces, *Type ? "NUM" : "ALPHA", TokenMap[**Index].Token);
if (-- RecurseLevel > 0)
memset (ListSpaces, ' ', RecurseLevel * 2);
ListSpaces[RecurseLevel * 2] = '\0';
#endif
return (TRUE);
}
bool HandleClass01 (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool *Type)
/**********************************************************************************************************************************/
/* Class 1 = Used in LET. A variable is required. */
/* `Type' is returned to handle the rest of this special statement (HandleClass02) */
/* This function is also used to parse the variable name for DIM and FN. */
/**********************************************************************************************************************************/
{
int VarNameLen;
int ParseArray;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 1, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (Keyword == 0xA8 || Keyword == 0xE9) /* Do not parse any bracketing if checking DIM or FN */
ParseArray = -1;
else if (Keyword == 0xF1) /* LET is allowed to write to a substring */
ParseArray = 1;
else
ParseArray = 2;
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, Type, &VarNameLen, ParseArray))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
return (TRUE);
}
bool HandleClass02 (int BasicLineNo, int StatementNo, int Keyword, byte **Index, bool Type)
/**********************************************************************************************************************************/
/* Class 2 = Used in LET. An expression, numeric or string, must follow. */
/* `Type' is the type as returned previously by the HandleClass01 call */
/**********************************************************************************************************************************/
{
bool SubType;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 2, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &SubType, 0))
return (FALSE);
if (SubType != Type) /* Must match */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Bad assignment expression type\n", BasicLineNo, StatementNo);
return (FALSE);
}
return (TRUE);
}
bool HandleClass03 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 3 = A numeric expression may follow. Zero to be used in case of default. */
/**********************************************************************************************************************************/
{
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 3, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (**Index == ':' || **Index == 0x0D) /* No expression following ? */
return (TRUE); /* Then we're done already */
if (Keyword == 0xFD && **Index == '#') /* EXCEPTION: CLEAR may take a stream rather than a numeric expression */
{
(*Index) ++;
if (!SignalInterface1 (BasicLineNo, StatementNo, 0)) /* (Which is Interface1/Opus specific) */
return (FALSE);
if (**Index == ':' || **Index == 0x0D) /* No expression following ? */
return (TRUE); /* (An empty stream is allowed as well - it clears all streams at once) */
}
return (HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)); /* Find numeric expression */
}
bool HandleClass04 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 4 = A single character variable must follow. */
/**********************************************************************************************************************************/
{
bool Type;
int VarNameLen;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 4, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, 0))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (VarNameLen != 1 || !Type) /* Not single letter or not a numeric variable ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Wrong variable type\n", BasicLineNo, StatementNo);
return (FALSE);
}
return (TRUE);
}
bool HandleClass05 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 5 = A set of items may be given. */
/**********************************************************************************************************************************/
{
bool Type;
bool More = TRUE;
int VarNameLen;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 5, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
while (More)
{
while (**Index == ';' || **Index == ',' || **Index == '\'') /* One of the separator characters ? */
(*Index) ++; /* (More than one may follow) */
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
More = FALSE;
else if (**Index == '#') /* A stream ? */
{
(*Index) ++; /* (Step past the '#' mark) */
if (!ScanStream (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
}
else if (TokenMap[**Index].TokenType == 2 || /* A colour parameter ? */
**Index == 0xAD) /* TAB ? */
{
(*Index) ++; /* (Skip the token) */
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find parameter (numeric expression) */
return (FALSE);
}
else if (**Index == 0xAC) /* AT ? */
{
(*Index) ++; /* (Skip the token) */
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find first parameter (numeric expression) */
return (FALSE);
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ',') /* (Required separator token) */
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++; /* (Skip the token) */
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find second parameter (numeric expression) */
return (FALSE);
}
else if (Keyword == 0xEE && **Index == 0xCA) /* INPUT may use LINE */
{
(*Index) ++; /* (Skip the token) */
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, 0))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (Type) /* Not a alphanumeric variable ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - INPUT LINE requires an alphanumeric variable\n",
BasicLineNo, StatementNo);
return (FALSE);
}
}
else if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)) /* Get expression */
return (FALSE);
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
More = FALSE;
if (More)
if (**Index != ';' && **Index != ',' && **Index != '\'') /* One of the separator characters ? */
{
BADTOKEN ("separator \";\", \",\" or \"\'\"", TokenMap[**Index].Token);
return (FALSE);
}
}
return (TRUE);
}
bool HandleClass06 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 6 = A numeric expression must follow. */
/**********************************************************************************************************************************/
{
bool Type=TRUE;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 6, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)) /* Get expression */
return (FALSE);
if (!Type && Keyword != 0xC0) /* Must be numeric */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected numeric expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
return (TRUE);
}
bool HandleClass07 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 7 = Handles colour items. */
/* Effectively the same as Class 6 */
/**********************************************************************************************************************************/
{
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 7, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
return (HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)); /* Find numeric expression */
}
bool HandleClass08 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 8 = Two numeric expressions, separated by a comma, must follow. */
/**********************************************************************************************************************************/
{
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 8, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find first numeric expression */
return (FALSE);
if (**Index != ',')
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
return (HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)); /* Find second numeric expression */
}
bool HandleClass09 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 9 = As for class 8 but colour items may precede the expression. */
/* Used only by PLOT and DRAW. Colour items are TokenType 2 */
/**********************************************************************************************************************************/
{
bool CheckColour = TRUE;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 9, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
while (CheckColour)
{
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (TokenMap[**Index].TokenType == 2) /* A colour parameter ? */
{
(*Index) ++; /* Skip the token */
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find parameter (numeric expression) */
return (FALSE);
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ';') /* All colour parameters must be separated with semicolons */
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++; /* Skip the ";' */
}
else
CheckColour = FALSE;
}
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
return (HandleClass08 (BasicLineNo, StatementNo, Keyword, Index));
}
bool HandleClass10 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 10 = A string expression must follow. */
/**********************************************************************************************************************************/
{
bool Type;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 10, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)) /* Get expression */
return (FALSE);
if (Type) /* Must be string */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected string expression\n", BasicLineNo, StatementNo);
return (FALSE);
}
return (TRUE);
}
bool HandleClass11 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 11 = Handles cassette routines. */
/**********************************************************************************************************************************/
{
bool Type;
int VarNameLen;
int MoveLoop;
byte WhichChannel = '\0'; /* (Default is no channel; for tape) */
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 11, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
switch (Keyword)
{
case 0xEF: /* (LOAD) */
case 0xD6: /* (VERIFY) */
case 0xD5: if (**Index == '*') /* (MERGE) */
{
(*Index) ++;
if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel))
return (FALSE);
if (WhichChannel != 'm' && WhichChannel != 'b' && WhichChannel != 'n')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot LOAD/VERIFY/MERGE from the \"%s\" channel\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
}
else if (**Index == '!') /* 128K RAM-bank ? */
{
(*Index) ++;
switch (Is48KProgram) /* Then the program must be 128K */
{
case -1 : Is48KProgram = 0; break; /* Set the flag */
case 1 : fprintf (ErrStream, "ERROR - Line %d contains 128K file I/O, but the program\n"
"also uses UDGs \'T\' and/or \'U\'\n", BasicLineNo);
return (FALSE);
case 0 : break;
}
}
if (WhichChannel != '\0' && WhichChannel != 'm') /* Not tape nor microdrive/disk channel ? */
{
if (**Index != ':' && **Index != 0x0D && /* (End of statement) */
**Index != 0xAF && /* (CODE) */
**Index != 0xE4 && /* (DATA) */
**Index != 0xCA && /* (LINE) */
**Index != 0xAA) /* (SCREEN$) */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - The \"%s\" channel does not use filenames\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
}
else
{
if (**Index == '\"') /* Look for a filename */
{
while (**Index == '\"') /* Concatenated strings are ok, since they allow the use of the " character */
{ /* (And an empty string is allowed here as well) */
while (*(++ (*Index)) != '\"') /* Find closing quote */
if (**Index == 0x0D) /* End of line ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++; /* Step past it */
}
}
else if (**Index == ':' || **Index == 0x0D || /* (End of statement) */
**Index == 0xAF || /* (CODE) */
**Index == 0xE4 || /* (DATA) */
**Index == 0xCA || /* (LINE) */
**Index == 0xAA) /* (SCREEN$) */
{
BADTOKEN ("filename", TokenMap[**Index].Token);
return (FALSE);
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index)) /* Look for a string expression */
return (FALSE);
}
if (**Index != ':' && **Index != 0x0D) /* (Continue unless end of statement) */
{
if (**Index == 0xAF) /* CODE */
{
if (Keyword == 0xD5) /* (We were doing MERGE ?) */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Cannot MERGE CODE\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
if (**Index != ':' && **Index != 0x0D) /* Optional address ? */
{
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find address (numeric expression) */
return (FALSE);
if (**Index == ',') /* Also optional length ? */
{
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find length (numeric expression) */
return (FALSE);
}
else if (**Index != ':' && **Index != 0x0D)
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
}
else if (**Index == 0xAA) /* SCREEN$ */
(*Index) ++;
else if (**Index == 0xE4) /* DATA */
{
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, -1))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (VarNameLen != 1) /* Not single letter ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Wrong variable type; must be single character\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index != '(') /* The variable must be followed by an empty index */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - DATA requires an array\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
if (**Index != ')')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - DATA requires an empty array index\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
else
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unknown file-type \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
}
}
break;
case 0xF8: if (**Index == '*') /* (SAVE) */
{
(*Index) ++;
if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel))
return (FALSE);
if (WhichChannel != 'm' && WhichChannel != 'b' && WhichChannel != 'n')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot SAVE to the \"%s\" channel\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
}
else if (**Index == '!') /* 128K RAM-bank ? */
{
(*Index) ++;
switch (Is48KProgram) /* Then the program must be 128K */
{
case -1 : Is48KProgram = 0; break; /* Set the flag */
case 1 : fprintf (ErrStream, "ERROR - Line %d contains 128K file I/O, but the program\n"
"also uses UDGs \'T\' and/or \'U\'\n", BasicLineNo);
return (FALSE);
case 0 : break;
}
}
if (WhichChannel != '\0' && WhichChannel != 'm') /* Not tape nor microdrive/disk channel ? */
{
if (**Index != ':' && **Index != 0x0D && /* (End of statement) */
**Index != 0xAF && /* (CODE) */
**Index != 0xE4 && /* (DATA) */
**Index != 0xCA && /* (LINE) */
**Index != 0xAA) /* (SCREEN$) */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - The \"%s\" channel does not use filenames\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
}
else
{
if (**Index == '\"') /* Look for a filename */
{
if (*(*Index + 1) == '\"' && /* Empty string (not allowed) ? */
*(*Index + 2) != '\"') /* Concatenation - first char is a " (allowed) ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty filename not allowed\n", BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"') /* Concatenated strings are ok, since they allow the use of the " character */
{
while (*(++ (*Index)) != '\"') /* Find closing quote */
if (**Index == 0x0D) /* End of line ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n", BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++; /* Step past it */
}
}
else if (**Index == ':' || **Index == 0x0D || /* (End of statement) */
**Index == 0xAF || /* (CODE) */
**Index == 0xE4 || /* (DATA) */
**Index == 0xCA || /* (LINE) */
**Index == 0xAA) /* (SCREEN$) */
{
BADTOKEN ("filename", TokenMap[**Index].Token);
return (FALSE);
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index)) /* Look for a string expression */
return (FALSE);
}
if (**Index != ':' && **Index != 0x0D) /* (Continue unless end of statement) */
{
if (**Index == 0xAF) /* CODE */
{
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find address (numeric expression) */
return (FALSE);
if (**Index != ',')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - %s CODE requires both address and length\n",
BasicLineNo, StatementNo, TokenMap[Keyword].Token);
return (FALSE);
}
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find length (numeric expression) */
return (FALSE);
}
else if (**Index == 0xE4) /* DATA */
{
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, -1))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (VarNameLen != 1) /* Not single letter ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Wrong variable type; must be single character\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index != '(') /* The variable must be followed by an empty index */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - DATA requires an array\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
if (**Index != ')')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - DATA requires an empty array index\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
else if (**Index == 0xAA) /* SCREEN$ */
(*Index) ++;
else if (**Index == 0xCA) /* LINE */
{
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find starting line (numeric expression) */
return (FALSE);
}
else
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unknown file-type \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[**Index].Token);
return (FALSE);
}
}
break;
case 0xCF: if (!SignalInterface1 (BasicLineNo, StatementNo, 0)) /* (CAT) */
return (FALSE);
if (**Index == '#') /* A stream may precede the drive number */
{
(*Index) ++;
if (!ScanStream (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
if (**Index != ',') /* (Required separator token) */
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find drive number (numeric expression) */
return (FALSE);
break;
case 0xD0: if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel)) /* (FORMAT) */
return (FALSE);
switch (WhichChannel)
{
case 'm' : if (CheckEnd (BasicLineNo, StatementNo, Index)) /* "m" requires an additional new volume name */
return (FALSE);
if (**Index == '\"') /* Look for a volume name */
{
if (*(*Index + 1) == '\"' && /* Empty string (not allowed) ? */
*(*Index + 2) != '\"') /* Concatenation - first char is a " (allowed) ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty volume name not allowed\n",
BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"') /* Concatenated strings are ok, since they allow the use of the " character */
{
while (*(++ (*Index)) != '\"') /* Find closing quote */
if (**Index == 0x0D) /* End of line ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++; /* Step past it */
}
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index)) /* Look for a string expression */
return (FALSE);
break;
case 't' : /* The port channels requires an additional baud rate */
case 'b' :
case 'j' : if (**Index != ';') /* The joystick channel requires a operand to turn it on or off */
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Look for a numeric expression */
return (FALSE);
break;
default : fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot FORMAT from the \"%s\" channel\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
break;
case 0xD1: for (MoveLoop = 0 ; MoveLoop < 2 ; MoveLoop ++) /* (MOVE) */
{
if (**Index == '#')
{
(*Index) ++; /* (Step past the '#' mark) */
if (!ScanStream (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
}
else
{
if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel))
return (FALSE);
switch (WhichChannel)
{
case 'm' : if (CheckEnd (BasicLineNo, StatementNo, Index)) /* "m" requires an additional filename */
return (FALSE);
if (**Index == '\"') /* Look for a filename */
{
if (*(*Index + 1) == '\"' && /* Empty string (not allowed) ? */
*(*Index + 2) != '\"') /* Concatenation - first char is a " (allowed) ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty filename not allowed\n",
BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"')
{
while (*(++ (*Index)) != '\"')
if (**Index == 0x0D)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
break;
case 't' :
case 'b' :
case 'n' :
case 'd' : break; /* All these are okay and don't use extra parameters */
case 's' : if (MoveLoop == 0) /* The "s" channel is write-only */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot MOVE from the \"s\" channel\n",
BasicLineNo, StatementNo);
return (FALSE);
}
break;
case 'k' : if (MoveLoop == 1) /* The "k" channel is read-only */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot MOVE to the \"k\" channel\n",
BasicLineNo, StatementNo);
return (FALSE);
}
break;
default : fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot MOVE from/to the \"%s\" channel\n",
BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
}
if (MoveLoop == 0)
{
if (**Index != 0xCC) /* Required token 'TO' */
{
BADTOKEN ("\"TO\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
}
}
break;
case 0xD2: if (**Index == '!') /* (ERASE) */
{ /* 128K RAM-bank ? */
(*Index) ++;
switch (Is48KProgram) /* Then the program must be 128K */
{
case -1 : Is48KProgram = 0; break; /* Set the flag */
case 1 : fprintf (ErrStream, "ERROR - Line %d contains 128K file I/O, but the program\n"
"also uses UDGs \'T\' and/or \'U\'\n", BasicLineNo);
return (FALSE);
case 0 : break;
}
}
else
{
if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel))
return (FALSE);
if (WhichChannel != 'm')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - You can only ERASE from the ! or \"m\" channel\n",
BasicLineNo, StatementNo);
return (FALSE);
}
}
if (CheckEnd (BasicLineNo, StatementNo, Index)) /* Additional filename required */
return (FALSE);
if (**Index == '\"') /* Look for a filename */
{
if (*(*Index + 1) == '\"' && /* Empty string (not allowed) ? */
*(*Index + 2) != '\"') /* Concatenation - first char is a " (allowed) ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty filename not allowed\n",
BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"')
{
while (*(++ (*Index)) != '\"')
if (**Index == 0x0D)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
break;
case 0xD3: if (!ScanStream (BasicLineNo, StatementNo, Keyword, Index)) /* (OPEN #) */
return (FALSE);
if (**Index != ';' && **Index != ',') /* (Required token) */
{
BADTOKEN ("\";\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (!ScanChannel (BasicLineNo, StatementNo, Keyword, Index, &WhichChannel))
return (FALSE);
switch (WhichChannel)
{
case 'm' : if (CheckEnd (BasicLineNo, StatementNo, Index)) /* "m" requires an additional filename */
return (FALSE);
if (**Index == '\"') /* Look for a filename */
{
if (*(*Index + 1) == '\"' && /* Empty string (not allowed) ? */
*(*Index + 2) != '\"') /* Concatenation - first char is a " (allowed) ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty filename not allowed\n",
BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index == '\"')
{
while (*(++ (*Index)) != '\"')
if (**Index == 0x0D)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n",
BasicLineNo, StatementNo);
return (FALSE);
}
(*Index) ++;
}
}
else if (!HandleClass10 (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
break;
case 's' :
case 'k' :
case 'p' :
case 't' :
case 'b' :
case 'n' :
case 0xAF:
case 0xCF:
case '#' : break; /* All these are okay and don't use extra parameters */
default : fprintf (ErrStream, "ERROR in line %d, statement %d - You cannot attach a stream to the \"%s\" "
"channel\n", BasicLineNo, StatementNo, TokenMap[WhichChannel].Token);
return (FALSE);
}
if (**Index != ':' && **Index != 0x0D) /* (Continue unless end of statement) */
{
if (**Index == 0xBF) /* IN */
{
(*Index) ++;
if (!SignalInterface1 (BasicLineNo, StatementNo, 2)) /* This is Opus specific */
return (FALSE);
}
else if (**Index == 0xDF || /* OUT */
**Index == 0xB9) /* EXP */
{
(*Index) ++;
if (!SignalInterface1 (BasicLineNo, StatementNo, 2)) /* This is Opus specific */
return (FALSE);
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find numeric expression */
return (FALSE);
}
else if (**Index == 0xA5) /* RND */
{
(*Index) ++;
if (!SignalInterface1 (BasicLineNo, StatementNo, 2)) /* This is Opus specific */
return (FALSE);
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index)) /* Find numeric expression */
return (FALSE);
if (**Index == ',') /* RND may take a second parameter */
{
(*Index) ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, Index))
return (FALSE);
}
}
}
break;
case 0xD4: if (!ScanStream (BasicLineNo, StatementNo, Keyword, Index)) /* (CLOSE #) */
return (FALSE);
break;
}
return (TRUE);
}
bool HandleClass12 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 12 = One or more string expressions, separated by commas, must follow. */
/**********************************************************************************************************************************/
{
bool Type;
bool More = TRUE;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 12, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
while (More)
{
if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)) /* Find an expression */
return (FALSE);
if (Type) /* Must be string */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - \"%s\" requires string parameters\n",
BasicLineNo, StatementNo, TokenMap[Keyword].Token);
return (FALSE);
}
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
More = FALSE;
else if (**Index == ',') /* Separator ? */
(*Index) ++;
else if (**Index != ')')
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
return (TRUE);
}
bool HandleClass13 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 13 = One or more expressions, separated by commas, must follow (DATA, DIM, FN) */
/**********************************************************************************************************************************/
{
bool Type;
bool More = TRUE;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 13, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (**Index == ')' && Keyword == 0xA8) /* FN requires zero or more expressions */
return (TRUE); /* (The closing bracket is a required character and stepped over in CheckSyntax) */
while (More)
{
if (!ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)) /* Find an expression */
return (FALSE); /* (Don't care about the type) */
if (Keyword == 0xE9 && !Type) /* DIM requires numeric dimensions */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - \"DIM\" requires numeric dimensions\n", BasicLineNo, StatementNo);
return (FALSE);
}
if (Keyword == 0xE9 || Keyword == 0xA8) /* FN and DIM end with a closing bracket */
{
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index == ')')
More = FALSE;
}
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
More = FALSE;
else if (**Index == ',') /* Separator ? */
(*Index) ++;
else if (**Index != ')')
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
return (TRUE);
}
bool HandleClass14 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 14 = One or more variables, separated by commas, must follow (READ) */
/**********************************************************************************************************************************/
{
bool Type;
bool More = TRUE;
int VarNameLen;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 14, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
while (More)
{
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, 2)) /* We need a variable */
{
if (VarNameLen == 0) /* (Not a variable) */
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (**Index == ':' || **Index == 0x0D) /* End of statement or end of line ? */
More = FALSE;
else if (**Index == ',') /* Separator ? */
(*Index) ++;
else
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
return (TRUE);
}
bool HandleClass15 (int BasicLineNo, int StatementNo, int Keyword, byte **Index)
/**********************************************************************************************************************************/
/* Class 15 = DEF FN */
/**********************************************************************************************************************************/
{
bool Type;
int VarNameLen;
#ifdef __DEBUG__
printf ("DEBUG - %sLine %d, statement %d, Enter Class 15, keyword \"%s\", next is \"%s\"\n",
ListSpaces, BasicLineNo, StatementNo, TokenMap[Keyword].Token, TokenMap[**Index].Token);
#endif
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, -1))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (VarNameLen != 1) /* Not single letter ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Wrong variable type; must be single character\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index == '(') /* Arguments to be passed to the expression while running ? */
{
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index == ')')
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Empty parameter array not allowed\n", BasicLineNo, StatementNo);
return (FALSE);
}
while (**Index != ')')
{
if (!ScanVariable (BasicLineNo, StatementNo, Keyword, Index, &Type, &VarNameLen, -1))
{
if (VarNameLen == 0)
BADTOKEN ("variable", TokenMap[**Index].Token);
return (FALSE);
}
if (VarNameLen != 1) /* Not single letter ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Wrong variable type; must be single character\n",
BasicLineNo, StatementNo);
return (FALSE);
}
if (**Index != 0x0E) /* A number (marker) must follow each parameter */
{
BADTOKEN ("number marker", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++; /* (Step past it) */
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != ')')
{
if (**Index == ',')
(*Index) ++;
else
{
BADTOKEN ("\",\"", TokenMap[**Index].Token);
return (FALSE);
}
}
}
(*Index) ++;
}
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
if (**Index != '=')
{
BADTOKEN ("\"=\"", TokenMap[**Index].Token);
return (FALSE);
}
(*Index) ++;
if (CheckEnd (BasicLineNo, StatementNo, Index))
return (FALSE);
return (ScanExpression (BasicLineNo, StatementNo, Keyword, Index, &Type, 0)); /* Find an expression */
}
bool CheckSyntax (int BasicLineNo, byte *Line)
/**********************************************************************************************************************************/
/* Pre : `Line' points to the converted BASIC line. An initial syntax check has been done already - */
/* - The line number makes sense; */
/* - Keywords are at the beginning of each statement and not within a statement; */
/* - There are less than 128 statements in the line; */
/* - Brackets match on a per-line basis (but not necessarily on a per-statement basis!) */
/* - Quotes match; */
/* Post : The line has been checked against 'normal' Spectrum BASIC syntax. Extended devices that change the normal syntax */
/* (such as Interface 1 or disk interfaces) are not understood and will generate error messages. */
/* Import: None. */
/**********************************************************************************************************************************/
{
byte StrippedLine[MAXLINELENGTH + 1];
byte *StrippedIndex;
byte Keyword;
bool AllOk = TRUE;
bool VarType;
int StatementNo = 0;
int ClassIndex = -1;
StrippedIndex = &(StrippedLine[0]);
while (*Line != 0x0D) /* First clean up the line, dropping number expansions and trash */
{
switch (*Line)
{
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 9 :
case 10 :
case 11 :
case 12 :
case 13 : break;
case 14 : *(StrippedIndex ++) = *Line; Line += 5; break; /* EXCEPTION: keep the marker, but drop the number */
case 15 : break;
case 16 :
case 17 :
case 18 :
case 19 :
case 20 :
case 21 : Line ++; break;
case 22 :
case 23 : Line += 2; break;
case 24 :
case 25 :
case 26 :
case 27 :
case 28 :
case 29 :
case 30 :
case 31 :
case 32 : break; /* (We don't care for spaces either!) */
default : *(StrippedIndex ++) = *Line; break; /* Pass on only 'good' bits */
}
Line ++;
}
*(StrippedIndex ++) = 0x0D;
*StrippedIndex = '\0';
StrippedIndex = &(StrippedLine[0]); /* Ok, here goes... */
while (AllOk && *StrippedIndex != 0x0D) /* Handle each statement */
{
StatementNo ++;
Keyword = *(StrippedIndex ++);
if (Keyword == 0xEA) /* 'REM' ? */
return (TRUE); /* Then we're done checking this line */
if (TokenMap[Keyword].TokenType != 0 && TokenMap[Keyword].TokenType != 1 && TokenMap[Keyword].TokenType != 2) /* (Sanity) */
{
if (Keyword == 0xA9) /* EXCEPTION: POINT may be used as command */
{
if (*StrippedIndex != '#') /* It must be followed by a stream in that case */
{
fprintf (ErrStream, "ERROR - Keyword (\"%s\") error in line %d, statement %d\n",
TokenMap[Keyword].Token, BasicLineNo, StatementNo);
return (FALSE);
}
StrippedIndex ++;
if (!ScanStream (BasicLineNo, StatementNo, Keyword, &StrippedIndex)) /* (Also signals Interface1/Opus specificness) */
return (FALSE);
if (*StrippedIndex != ';')
{
BADTOKEN ("\";\"", TokenMap[*StrippedIndex].Token);
return (FALSE);
}
StrippedIndex ++;
if (!HandleClass06 (BasicLineNo, StatementNo, Keyword, &StrippedIndex))
return (FALSE);
}
else
{
fprintf (ErrStream, "ERROR - Keyword (\"%s\") error in line %d, statement %d\n",
TokenMap[Keyword].Token, BasicLineNo, StatementNo);
return (FALSE);
}
}
else
{
ClassIndex = -1;
#ifdef __DEBUG__
RecurseLevel = 0;
ListSpaces[0] = '\0';
printf ("DEBUG - Start Line %d, Statement %d, Keyword \"%s\"\n", BasicLineNo, StatementNo, TokenMap[Keyword].Token);
#endif
if ((Keyword == 0xE1 || Keyword == 0xF0) && *StrippedIndex == '#') /* EXCEPTION: LIST and LLIST may take a stream */
{
StrippedIndex ++;
if (!ScanStream (BasicLineNo, StatementNo, Keyword, &StrippedIndex)) /* (Also signals Interface1/Opus specificness) */
return (FALSE);
if (*StrippedIndex != ':' && *StrippedIndex != 0x0D) /* Line number is not required */
{
if (*StrippedIndex != ',')
{
BADTOKEN ("\",\"", TokenMap[*StrippedIndex].Token);
return (FALSE);
}
StrippedIndex ++;
}
}
while (AllOk && TokenMap[Keyword].KeywordClass[++ ClassIndex]) /* Handle all class parameters */
{
if (*StrippedIndex == 0x0D)
{
if (TokenMap[Keyword].KeywordClass[ClassIndex] != 3 && /* Class 5 and 3 need 0 or more arguments */
TokenMap[Keyword].KeywordClass[ClassIndex] != 5)
{
if ((Keyword == 0xEB && TokenMap[Keyword].KeywordClass[ClassIndex] == 0xCD) || /* 'FOR' doesn't need 'STEP' parameter */
(Keyword == 0xFC && TokenMap[Keyword].KeywordClass[ClassIndex] == ',')) /* 'DRAW' doesn't need a third parameter */
ClassIndex ++;
else
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected end of line\n", BasicLineNo, StatementNo);
AllOk = FALSE;
}
}
}
else if (TokenMap[Keyword].KeywordClass[ClassIndex] >= 32) /* Required token or class ? */
{
if (*StrippedIndex != TokenMap[Keyword].KeywordClass[ClassIndex]) /* (Required token) */
{
if ((Keyword == 0xEB && TokenMap[Keyword].KeywordClass[ClassIndex] == 0xCD && *StrippedIndex == ':') ||
(Keyword == 0xFC && TokenMap[Keyword].KeywordClass[ClassIndex] == ',' && *StrippedIndex == ':'))
ClassIndex ++; /* EXCEPTION: 'FOR' does not require the 'STEP' parameter */
/* EXCEPTION: 'DRAW' does not require the third parameter */
else
{ /* (Token not there) */
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected \"%s\", but got \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[TokenMap[Keyword].KeywordClass[ClassIndex]].Token,
TokenMap[*StrippedIndex].Token);
AllOk = FALSE;
}
}
else
StrippedIndex ++;
}
else /* (Command class) */
switch (TokenMap[Keyword].KeywordClass[ClassIndex])
{
case 1 : AllOk = HandleClass01 (BasicLineNo, StatementNo, Keyword, &StrippedIndex, &VarType); break;
case 2 : AllOk = HandleClass02 (BasicLineNo, StatementNo, Keyword, &StrippedIndex, VarType); break;
case 3 : AllOk = HandleClass03 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 4 : AllOk = HandleClass04 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 5 : AllOk = HandleClass05 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 6 : AllOk = HandleClass06 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 7 : AllOk = HandleClass07 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 8 : AllOk = HandleClass08 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 9 : AllOk = HandleClass09 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 10 : AllOk = HandleClass10 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 11 : AllOk = HandleClass11 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 12 : AllOk = HandleClass12 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 13 : AllOk = HandleClass13 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 14 : AllOk = HandleClass14 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
case 15 : AllOk = HandleClass15 (BasicLineNo, StatementNo, Keyword, &StrippedIndex); break;
}
}
}
if (AllOk && Keyword != 0xFA) /* Handling 'IF' and AllOk (i.e. just read the "THEN" ?) */
{ /* (Nope, go check end of statement) */
if (*StrippedIndex != ':' && *StrippedIndex != 0x0D)
{
if (Keyword == 0xFB && *StrippedIndex == '#') /* EXCEPTION: 'CLS #' is allowed */
{
StrippedIndex ++;
if (!SignalInterface1 (BasicLineNo, StatementNo, 0))
return (FALSE);
if (*StrippedIndex != ':' && *StrippedIndex != 0x0D)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected end of statement, but got \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[*StrippedIndex].Token);
AllOk = FALSE;
}
}
else
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected end of statement, but got \"%s\"\n",
BasicLineNo, StatementNo, TokenMap[*StrippedIndex].Token);
AllOk = FALSE;
}
}
}
if (AllOk && *StrippedIndex == ':') /* (Placing this check here allows weird (but legal) construction "THEN :") */
{
StrippedIndex ++;
while (*StrippedIndex == ':') /* (More consecutive ':' separators are allowed) */
{
StrippedIndex ++;
StatementNo ++;
}
}
}
return (AllOk);
}
int main (int argc, char **argv)
/**********************************************************************************************************************************/
/* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> MAIN PROGRAM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
/* Import: MatchToken, HandleNumbers, ExpandSequences, PrepareLine, CheckSyntax. */
/**********************************************************************************************************************************/
{
FILE *FpIn;
FILE *FpOut;
char FileNameIn[256] = "\0";
char FileNameOut[256] = "\0";
char LineIn[MAXLINELENGTH + 1]; /* One line read from the ASCII file */
char *BasicIndex; /* Current scan position in the (converted) ASCII line */
byte *ResultIndex; /* Current write index in to the binary result line */
byte Token;
int LineCount = 0; /* Line count in the ASCII file */
int BasicLineNo; /* Current BASIC line number */
int SubLineCount; /* Current statement number */
bool ExpectKeyword; /* If TRUE, the next scanned token must be a keyword */
bool InString; /* TRUE while inside quotes */
int BracketCount = 0; /* Match opening and closing brackets */
int AutoStart; /* Auto-start line as provided on the command line */
int ObjectLength; /* Binary length of one converted line */
int BlockSize = 0; /* Total size of the TAP block */
byte Parity = 0; /* Overall block parity */
bool AllOk = TRUE;
bool EndOfFile = FALSE;
bool WriteError = FALSE; /* Fingers crossed that this stays FALSE... */
size_t Size;
int Cnt;
ErrStream = stderr;
Cnt = 1;
for (Cnt = 1 ; Cnt < argc && AllOk; Cnt ++) /* Do all command line arguments */
{
if (argv[Cnt][0] == '-')
switch (tolower (argv[Cnt][1]))
{
case 'c' : CaseIndependant = TRUE; break;
case 'w' : NoWarnings = TRUE; break;
case 'q' : Quiet = TRUE; break;
case 'n' : DoCheckSyntax = FALSE; break;
case 'e' : ErrStream = stdout; break;
case 'a' : AutoStart = atoi (argv[Cnt] + 2);
if (AutoStart < 0 || AutoStart >= 10000)
{
fprintf (ErrStream, "Invalid auto-start line number %d\n", AutoStart);
exit (1);
}
TapeHeader.HStartLo = (byte)(AutoStart & 0xFF);
TapeHeader.HStartHi = (byte)(AutoStart >> 8);
break;
case 's' : if (strlen (argv[Cnt] + 2) > 10)
{
fprintf (ErrStream, "Spectrum blockname too long \"%s\"\n", argv[Cnt] + 2);
exit (1);
}
strncpy (TapeHeader.HName, argv[Cnt] + 2, strlen (argv[Cnt] + 2));
break;
default : fprintf (ErrStream, "Unknown switch \'%c\'\n", argv[Cnt][1]);
}
else if (FileNameIn[0] == '\0')
strcpy (FileNameIn, argv[Cnt]);
else if (FileNameOut[0] == '\0')
strcpy (FileNameOut, argv[Cnt]);
else
AllOk = FALSE;
}
if (FileNameIn[0] == '\0') /* We do need an input file! */
AllOk = FALSE;
if (!Quiet || !AllOk)
printf ("\nBAS2TAP v2.6 by Martijn van der Heide of ThunderWare Research Center\n\n");
if (!AllOk)
{
printf ("Usage: BAS2TAP [-q] [-w] [-e] [-c] [-aX] [-sX] FileIn [FileOut]\n");
printf (" -q = quiet: no banner, no progress indication\n");
printf (" -w = suppress generation of warnings\n");
printf (" -e = write errors to stdout in stead of stderr channel\n");
printf (" -c = case independant tokens (be careful here!)\n");
printf (" -n = disable syntax checking\n");
printf (" -a = set auto-start line in BASIC header\n");
printf (" -s = set \"filename\" in BASIC header\n");
exit (1);
}
if (FileNameOut[0] == '\0')
strcpy (FileNameOut, FileNameIn);
Size = strlen (FileNameOut);
while (-- Size > 0 && FileNameOut[Size] != '.')
;
if (Size == 0) /* No extension ? */
strcat (FileNameOut, ".tap");
else if (strcmp (FileNameOut + Size, ".tap") && strcmp (FileNameOut + Size, ".TAP"))
strcpy (FileNameOut + Size, ".tap");
if (!Quiet)
printf ("Creating output file %s\n",FileNameOut);
if ((FpIn = fopen (FileNameIn, "rt")) == NULL)
{
perror ("ERROR - Cannot open source file");
exit (1);
}
if ((FpOut = fopen (FileNameOut, "wb")) == NULL)
{
perror ("ERROR - Cannot create output file");
fclose (FpIn);
exit (1);
}
Parity = TapeHeader.Flag2;
if (fwrite (&TapeHeader, 1, sizeof (struct TapeHeader_s), FpOut) < sizeof (struct TapeHeader_s))
{ AllOk = FALSE; WriteError = TRUE; } /* Write dummy header to get space */
while (AllOk && !EndOfFile)
{
if (fgets (LineIn, MAXLINELENGTH + 1, FpIn) != NULL)
{
LineCount ++;
if (strlen (LineIn) >= MAXLINELENGTH)
{ /* We don't require an end-of-line marker */
fprintf (ErrStream, "ERROR - Line %d too long\n", LineCount);
AllOk = FALSE;
}
else if ((BasicLineNo = PrepareLine (LineIn, LineCount, &BasicIndex)) < 0)
{
if (BasicLineNo == -1) /* (Error) */
AllOk = FALSE;
else /* (Line should simply be skipped) */
;
}
else if (BasicLineNo >= 10000)
{
fprintf (ErrStream, "ERROR - Line number %d is larger than the maximum allowed\n", BasicLineNo);
AllOk = FALSE;
}
else
{
if (!Quiet)
{
printf ("\rConverting line %4d -> %4d\r", LineCount, BasicLineNo);
fflush (stdout); /* (Force line without end-of-line to be printed) */
}
InString = FALSE;
ExpectKeyword = TRUE;
SubLineCount = 1;
ResultIndex = ResultingLine + 4; /* Reserve space for line number and length */
HandlingDEFFN = FALSE;
while (*BasicIndex && AllOk)
{
if (InString)
{
if (*BasicIndex == '\"')
{
InString = FALSE;
*(ResultIndex ++) = *(BasicIndex ++);
while (*BasicIndex == ' ') /* Skip trailing spaces */
BasicIndex ++;
}
else
switch (ExpandSequences (BasicLineNo, &BasicIndex, &ResultIndex, FALSE))
{
case -1 : AllOk = FALSE; break; /* (Error - already reported) */
case 0 : *(ResultIndex ++) = *(BasicIndex ++); break; /* (No expansion made) */
case 1 : break;
}
}
else if (*BasicIndex == '\"')
{
if (ExpectKeyword)
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Expected keyword but got quote\n", BasicLineNo, SubLineCount);
AllOk = FALSE;
}
else
{
InString = TRUE;
*(ResultIndex ++) = *(BasicIndex ++);
}
}
else if (ExpectKeyword)
{
switch (MatchToken (BasicLineNo, TRUE, &BasicIndex, &Token))
{
case -2 : AllOk = FALSE; break; /* (Error - already reported) */
case -1 : fprintf (ErrStream, "ERROR in line %d, statement %d - Expected keyword but got token \"%s\"\n",
BasicLineNo, SubLineCount, TokenMap[Token].Token); /* (Not keyword) */
AllOk = FALSE;
break;
case 0 : fprintf (ErrStream, "ERROR in line %d, statement %d - Expected keyword but got \"%s\"\n", /* (No match) */
BasicLineNo, SubLineCount, TokenMap[(byte)(*BasicIndex)].Token);
AllOk = FALSE;
break;
case 1 : *(ResultIndex ++) = Token; /* (Found keyword) */
if (Token != ':') /* Special exception; empty statement */
ExpectKeyword = FALSE;
if (Token == DEFFN)
{
HandlingDEFFN = TRUE;
InsideDEFFN = FALSE;
}
if (Token == 0xEA) /* Special exception; REM */
while (*BasicIndex) /* Simply copy over the remaining part of the line, */
/* disregarding token or number expansions */
/* As brackets aren't tested for, the match counting stops here */
/* (a closing bracket in a REM statement will not be seen by BASIC) */
switch (ExpandSequences (BasicLineNo, &BasicIndex, &ResultIndex, FALSE))
{
case -1 : AllOk = FALSE; break;
case 0 : *(ResultIndex ++) = *(BasicIndex ++); break;
case 1 : break;
}
break;
}
}
else if (*BasicIndex == '(') /* Opening bracket */
{
BracketCount ++;
*(ResultIndex ++) = *(BasicIndex ++);
if (HandlingDEFFN && !InsideDEFFN)
#ifdef __DEBUG__
{
printf ("DEBUG - %sDEFFN, Going inside parameter list\n", ListSpaces);
InsideDEFFN = TRUE; /* Signal: require special treatment! */
}
#else
InsideDEFFN = TRUE; /* Signal: require special treatment! */
#endif
}
else if (*BasicIndex == ')') /* Closing bracket */
{
if (HandlingDEFFN && InsideDEFFN)
{
#ifdef __DEBUG__
printf ("DEBUG - %sDEFFN, Done parameter list\n", ListSpaces);
InsideDEFFN = TRUE; /* Signal: require special treatment! */
#endif
*(ResultIndex ++) = 0x0E; /* Insert room for the evaluator (call by value) */
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
InsideDEFFN = FALSE; /* Mark end of special treatment */
HandlingDEFFN = FALSE; /* (The part after the '=' is just like eg. LET) */
}
if (-- BracketCount < 0) /* More closing than opening brackets */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Too many closing brackets\n", BasicLineNo, SubLineCount);
AllOk = FALSE;
}
else
*(ResultIndex ++) = *(BasicIndex ++);
}
else if (*BasicIndex == ',' && HandlingDEFFN && InsideDEFFN)
{
#ifdef __DEBUG__
printf ("DEBUG - %sDEFFN, Done parameter; another follows\n", ListSpaces);
#endif
*(ResultIndex ++) = 0x0E; /* Insert room for the evaluator (call by value) */
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = 0x00;
*(ResultIndex ++) = *(BasicIndex ++); /* (Copy over the ',') */
}
else
switch (MatchToken (BasicLineNo, FALSE, &BasicIndex, &Token))
{
case -2 : AllOk = FALSE; break; /* (Error - already reported) */
case -1 : fprintf (ErrStream, "ERROR in line %d, statement %d - Unexpected keyword \"%s\"\n",/* (Match but keyword) */
BasicLineNo, SubLineCount, TokenMap[Token].Token);
AllOk = FALSE;
break;
case 0 : switch (HandleNumbers (BasicLineNo, &BasicIndex, &ResultIndex)) /* (No token) */
{
case 0 : switch (ExpandSequences (BasicLineNo, &BasicIndex, &ResultIndex, TRUE)) /* (No number) */
{
case -1 : AllOk = FALSE; break; /* (Error - already reported) */
case 0 : if (isalpha (*BasicIndex)) /* (No expansion made) */
while (isalnum (*BasicIndex)) /* Skip full strings in one go */
*(ResultIndex ++) = *(BasicIndex ++);
else
*(ResultIndex ++) = *(BasicIndex ++);
break;
case 1 : break;
}
break;
case -1 : AllOk = FALSE; break;
}
break;
case 1 : *(ResultIndex ++) = Token; /* (Found token, no keyword) */
if (Token == ':' || Token == 0xCB)
{
ExpectKeyword = TRUE;
HandlingDEFFN = FALSE;
if (BracketCount != 0) /* All brackets match ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Too few closing brackets\n",
BasicLineNo, SubLineCount);
AllOk = FALSE;
}
if (++ SubLineCount > 127)
{
fprintf (ErrStream, "ERROR - Line %d has too many statements\n", BasicLineNo);
AllOk = FALSE;
}
}
else if (Token == 0xC4) /* BIN */
{
if (HandleBIN (BasicLineNo, &BasicIndex, &ResultIndex) == -1)
AllOk = FALSE;
}
break;
}
}
*(ResultIndex ++) = 0x0D;
if (AllOk && BracketCount != 0) /* All brackets match ? */
{
fprintf (ErrStream, "ERROR in line %d, statement %d - Too few closing brackets\n", BasicLineNo, SubLineCount);
AllOk = FALSE;
}
if (AllOk && DoCheckSyntax)
AllOk = CheckSyntax (BasicLineNo, ResultingLine + 4); /* Check the syntax of the decoded line */
if (AllOk)
{
ObjectLength = (int)(ResultIndex - ResultingLine);
ResultingLine[0] = (byte)(BasicLineNo >> 8); /* Line number is put reversed */
ResultingLine[1] = (byte)(BasicLineNo & 0xFF);
ResultingLine[2] = (byte)((ObjectLength - 4) & 0xFF); /* Make sure this runs on any CPU */
ResultingLine[3] = (byte)((ObjectLength - 4) >> 8);
BlockSize += ObjectLength;
for (Cnt = 0 ; Cnt < ObjectLength ; Cnt ++)
Parity ^= ResultingLine[Cnt];
if (BlockSize > 41500) /* (= 65368-23755-<some work/stack space>) */
{
fprintf (ErrStream, "ERROR - Object file too large at line %d!\n", BasicLineNo);
AllOk = FALSE;
}
else
if (fwrite (ResultingLine, 1, ObjectLength, FpOut) != ObjectLength)
{ AllOk = FALSE; WriteError = TRUE; }
}
}
}
else
EndOfFile = TRUE;
}
if (!Quiet)
{
printf ("\r \r");
fflush (stdout);
}
if (!WriteError) /* Finish the TAP file no matter what went wrong, unless it was the writing itself */
{
ResultingLine[0] = Parity; /* Now it's time to write the 'real' header in front */
if (fwrite (ResultingLine, 1, 1, FpOut) < 1)
{
perror ("ERROR - Write error");
fclose (FpIn);
fclose (FpOut);
exit (1);
}
TapeHeader.HLenLo = TapeHeader.HBasLenLo = (byte)(BlockSize & 0xFF);
TapeHeader.HLenHi = TapeHeader.HBasLenHi = (byte)(BlockSize >> 8);
TapeHeader.LenLo2 = (byte)((BlockSize + 2) & 0xFF);
TapeHeader.LenHi2 = (byte)((BlockSize + 2) >> 8);
Parity = 0;
for (Cnt = 2 ; Cnt < 20 ; Cnt ++)
Parity ^= *((byte *)&TapeHeader + Cnt);
TapeHeader.Parity1 = Parity;
fseek (FpOut, 0, SEEK_SET);
if (fwrite (&TapeHeader, 1, sizeof (struct TapeHeader_s), FpOut) < sizeof (struct TapeHeader_s))
{
perror ("ERROR - Write error");
exit (1);
}
if (!Quiet)
{
if (AllOk)
printf ("Done! Listing contains %d %s.\n", LineCount, LineCount == 1 ? "line" : "lines");
else
printf ("Listing as far as done contains %d %s.\n", LineCount - 1, LineCount == 2 ? "line" : "lines");
if (Is48KProgram >= 0)
printf ("Note: this program can only be used in %dK mode\n", Is48KProgram ? 48 : 128);
switch (UsesInterface1)
{
case -1 : break; /* Neither of them */
case 0 : printf ("Note: this program requires Interface 1 or Opus Discovery\n"); break;
case 1 : printf ("Note: this program requires Interface 1\n"); break;
case 2 : printf ("Note: this program requires an Opus Discovery"); break;
}
}
}
else
perror ("ERROR - Write error");
fclose (FpIn);
fclose (FpOut);
return (0); /* (Keep weird compilers happy) */
}
|
the_stack_data/212644228.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int is_hex_digit(const char c)
{
if ((c >= '0') && (c <= '9'))
return 1;
if ((c >= 'A') && (c <= 'F'))
return 1;
if ((c >= 'a') && (c <= 'f'))
return 1;
return 0;
}
static char *is_ull_postfix(const char *str)
{
/*
* Check the ULL postfix.
* Combinations are L, LL, U, LU, LLU, UL, ULL.
* Reordered as L, LL, LLU, LU, U, UL, ULL
*/
if ((*str == 'L') || (*str == 'l')) {
++str;
if ((*str == 'L') || (*str == 'l')) {
++str;
if ((*str == 'U') || (*str == 'u')) {
return "ULL";
}
return "LL";
} else if ((*str == 'U') || (*str == 'u')) {
return "UL";
}
return "L";
} else if ((*str == 'U') || (*str == 'u')) {
++str;
if ((*str == 'L') || (*str == 'l')) {
++str;
if ((*str == 'L') || (*str == 'l')) {
return "ULL";
}
return "UL";
}
return "U";
}
return "";
}
static int check_if_hex_number(const char *str, int *len)
{
const char *p;
int at_least_one;
if (*str == 0)
return 0;
p = str;
/* Check the "0x" prefix */
if (*str == '0') {
++str;
if (*str == 0)
return 0;
if ((*str == 'x') || (*str == 'X'))
++str;
else
return 0;
} else {
return 0;
}
/* Check the 0-9A-F digits */
at_least_one = 0;
while (is_hex_digit(*str)) {
at_least_one = 1;
++str;
}
if (at_least_one == 1) {
char *ull_postfix;
if ((*str == ')') || (*str == ' ') || (*str == '\n') || (*str == '\r')) {
*len = str - p - 2; /* 0x is excluded in counting */
return 1;
}
*len = str - p - 2; /* 0x is excluded in counting */
/* Check ULL postfix but not process here */
ull_postfix = is_ull_postfix(str);
str += strlen(ull_postfix);
if ((*str >= 'a') && (*str <= 'z'))
return 0;
if ((*str >= 'A') && (*str <= 'Z'))
return 0;
return 1;
}
return 0;
}
static int format_hex(char *str, unsigned long long value, int ori_len)
{
int len;
if (ori_len <= 2)
len = sprintf(str, "0x%02llX", value);
else if (ori_len <= 4)
len = sprintf(str, "0x%04llX", value);
else if (ori_len <= 8)
len = sprintf(str, "0x%08llX", value);
else if (ori_len <= 12)
len = sprintf(str, "0x%012llX", value);
else
len = sprintf(str, "0x%016llX", value);
return len;
}
static void hex_up_cased(char *str_in, char *str_out, int out_len_limit)
{
char *p = str_in;
while (*p != 0) {
int len;
if (check_if_hex_number(p, &len) == 1) {
unsigned long long value;
char *ull_postfix;
value = strtoull(p + 2, &p, 16);
len = format_hex(str_out, value, len);
str_out += len;
ull_postfix = is_ull_postfix(p);
len = strlen(ull_postfix);
if (len > 0) {
sprintf(str_out, "%s", ull_postfix);
str_out += len;
p += len;
}
continue;
}
*str_out++ = *p++;
}
*str_out = 0;
}
static void dumpstr(const unsigned char *str)
{
const unsigned char *p = str;
while (*p != 0) {
printf("%02X ", *p++);
}
printf("\n");
}
int main(int argc, char *argv[])
{
const int strlen_limit = 1024 * 1024;
char str_read[strlen_limit];
char str_out[strlen_limit];
FILE *fp;
int Flag_debug = 0;
if (argc == 2) {
fp = fopen(argv[1], "r");
} else if (argc == 3) {
if (strncmp(argv[1], "-d", 2) == 0)
Flag_debug = 1;
fp = fopen(argv[2], "r");
} else {
printf("%s file\n", argv[0]);
return 0;
}
if (fp == NULL) {
fprintf(stderr, "%s open failed", argv[1]);
return -1;
}
while (!feof(fp)) {
if (fgets(str_read, strlen_limit, fp) == NULL) {
break;
}
hex_up_cased(str_read, str_out, strlen_limit);
printf("%s", str_out);
}
if (Flag_debug != 0) {
dumpstr(str_read);
dumpstr(str_out);
}
return 0;
}
|
the_stack_data/215766838.c | /*
* ia32abicc.c
*
* Support for Call-outs and Call-backs from the Plugin.
* Written by Eliot Miranda 11/07.
*/
/* null if compiled on other than x86, to get around gnu make bugs or
* misunderstandings on our part.
*/
#if defined(_M_I386) || defined(_M_IX86) || defined(_X86_) || defined(i386) || defined(i486) || defined(i586) || defined(i686) || defined(__i386__) || defined(__386__) || defined(X86) || defined(I386)
#if defined(_MSC_VER) || defined(__MINGW32__)
# include <Windows.h> /* for GetSystemInfo & VirtualAlloc */
#elif __APPLE__ && __MACH__
# include <sys/mman.h> /* for mprotect */
# if OBJC_DEBUG /* define this to get debug info for struct objc_class et al */
# include <objc/objc.h>
# include <objc/objc-class.h>
struct objc_class *baz;
void setbaz(void *p) { baz = p; }
void *getbaz() { return baz; }
# endif
# include <unistd.h> /* for getpagesize/sysconf */
# include <stdlib.h> /* for valloc */
# include <sys/mman.h> /* for mprotect */
#else
# include <unistd.h> /* for getpagesize/sysconf */
# include <stdlib.h> /* for valloc */
# include <sys/mman.h> /* for mprotect */
#endif
#include <string.h> /* for memcpy et al */
#include <setjmp.h>
#include <stdio.h> /* for fprintf(stderr,...) */
#include "objAccess.h"
#include "vmCallback.h"
#include "sqAssert.h"
#include "ia32abi.h"
#if !defined(min)
# define min(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifdef SQUEAK_BUILTIN_PLUGIN
extern
#endif
struct VirtualMachine* interpreterProxy;
#ifdef _MSC_VER
# define alloca _alloca
#endif
#if __GNUC__
# define setsp(sp) __asm__ volatile ("movl %0,%%esp" : : "m"(sp))
# define getsp() ({ void *sp; __asm__ volatile ("movl %%esp,%0" : "=r"(sp) : ); sp;})
#endif
#if __APPLE__ && __MACH__ && __i386__
# define STACK_ALIGN_BYTES 16
#elif __linux__ && __i386__
# define STACK_ALIGN_BYTES 16
#elif defined(_WIN32) && __SSE2__
/* using sse2 instructions requires 16-byte stack alignment but on win32 there's
* no guarantee that libraries preserve alignment so compensate on callback.
*/
# define STACK_ALIGN_HACK 1
# define STACK_ALIGN_BYTES 16
#endif
#if !defined(setsp)
# define setsp(ignored) 0
#endif
#define moduloPOT(m,v) (((v)+(m)-1) & ~((m)-1))
#define alignModuloPOT(m,v) ((void *)moduloPOT(m,(unsigned long)(v)))
/*
* Call a foreign function that answers an integral result in %eax (and
* possibly %edx) according to IA32-ish ABI rules.
*/
sqInt
callIA32IntegralReturn(SIGNATURE) {
#ifdef _MSC_VER
__int64 (*f)(), r;
#else
long long (*f)(), r;
#endif
#include "dabusiness.h"
}
/*
* Call a foreign function that answers a single-precision floating-point
* result in %f0 according to IA32-ish ABI rules.
*/
sqInt
callIA32FloatReturn(SIGNATURE) { float (*f)(), r;
#include "dabusiness.h"
}
/*
* Call a foreign function that answers a double-precision floating-point
* result in %f0 according to IA32-ish ABI rules.
*/
sqInt
callIA32DoubleReturn(SIGNATURE) { double (*f)(), r;
#include "dabusiness.h"
}
/* Queueing order for callback returns. To ensure that callback returns occur
* in LIFO order we provide mostRecentCallbackContext which is tested by the
* return primitive primReturnFromContextThrough. Note that in the threaded VM
* this does not have to be thread-specific or locked since it is within the
* bounds of the ownVM/disownVM pair.
*/
static VMCallbackContext *mostRecentCallbackContext = 0;
VMCallbackContext *
getMostRecentCallbackContext() { return mostRecentCallbackContext; }
#define getMRCC() mostRecentCallbackContext
#define setMRCC(t) (mostRecentCallbackContext = (void *)(t))
/*
* Entry-point for call-back thunks. Args are thunk address and stack pointer,
* where the stack pointer is pointing one word below the return address of the
* thunk's callee, 4 bytes below the thunk's first argument. The stack is:
* callback
* arguments
* retpc (thunk) <--\
* address of retpc-/ <--\
* address of address of ret pc-/
* thunkp
* esp->retpc (thunkEntry)
*
* The stack pointer is pushed twice to keep the stack alignment to 16 bytes, a
* requirement on platforms using SSE2 such as Mac OS X, and harmless elsewhere.
*
* This function's roles are to use setjmp/longjmp to save the call point
* and return to it, to correct C stack pointer alignment if necessary (see
* STACK_ALIGN_HACK), and to return any of the various values from the callback.
*
* Looking forward to support for x86-64, which typically has 6 register
* arguments, the function would take 8 arguments, the 6 register args as
* longs, followed by the thunkp and stackp passed on the stack. The register
* args would get copied into a struct on the stack. A pointer to the struct
* is then passed as an element of the VMCallbackContext.
*
* N.B. On gcc, thunkEntry fails if optimized, for as yet not fully
* diagnosed reasons. See
* https://github.com/OpenSmalltalk/opensmalltalk-vm/pull/353
* Hence the pragma below. Works fine for clang.
*/
long
#if defined(__GNUC__) && !defined(__clang__)
__attribute__((optimize("O0")))
#endif
thunkEntry(void *thunkp, sqIntptr_t *stackp)
{
VMCallbackContext vmcc;
int flags, returnType;
#if STACK_ALIGN_HACK
{ void *sp = getsp();
int offset = (unsigned long)sp & (STACK_ALIGN_BYTES - 1);
if (offset) {
# if _MSC_VER
_asm sub esp, dword ptr offset;
# elif __GNUC__
__asm__ ("sub %0,%%esp" : : "m"(offset));
# else
# error need to subtract offset from esp
# endif
sp = getsp();
assert(!((unsigned long)sp & (STACK_ALIGN_BYTES - 1)));
}
}
#endif /* STACK_ALIGN_HACK */
if ((flags = interpreterProxy->ownVM(0)) < 0) {
fprintf(stderr,"Warning; callback failed to own the VM\n");
return -1;
}
if (!(returnType = setjmp(vmcc.trampoline))) {
vmcc.savedMostRecentCallbackContext = getMRCC();
setMRCC(&vmcc);
vmcc.thunkp = thunkp;
vmcc.stackp = stackp + 2; /* skip address of retpc & retpc (thunk) */
vmcc.intregargsp = 0;
vmcc.floatregargsp = 0;
interpreterProxy->sendInvokeCallbackContext(&vmcc);
fprintf(stderr,"Warning; callback failed to invoke\n");
setMRCC(vmcc.savedMostRecentCallbackContext);
interpreterProxy->disownVM(flags);
return -1;
}
setMRCC(vmcc.savedMostRecentCallbackContext);
interpreterProxy->disownVM(flags);
switch (returnType) {
case retword: return vmcc.rvs.valword;
case retword64: {
long vhigh = vmcc.rvs.valleint64.high;
#if _MSC_VER
_asm mov edx, dword ptr vhigh;
#elif __GNUC__ || __SUNPRO_C
__asm__ ("mov %0,%%edx" : : "m"(vhigh));
#else
# error need to load edx with vmcc.rvs.valleint64.high on this compiler
#endif
return vmcc.rvs.valleint64.low;
}
case retdouble: {
double valflt64 = vmcc.rvs.valflt64;
#if _MSC_VER
_asm fld qword ptr valflt64;
#elif __GNUC__ || __SUNPRO_C
__asm__ ("fldl %0" : : "m"(valflt64));
#else
# error need to load %f0 with vmcc.rvs.valflt64 on this compiler
#endif
return 0;
}
case retstruct: memcpy( (void *)(stackp[1]),
vmcc.rvs.valstruct.addr,
vmcc.rvs.valstruct.size);
return stackp[1];
}
fprintf(stderr,"Warning; invalid callback return type\n");
return 0;
}
/*
* Thunk allocation support. Since thunks must be executable and some OSs
* may not provide default execute permission on memory returned by malloc
* we must provide memory that is guaranteed to be executable. The abstraction
* is to answer an Alien that references an executable piece of memory that
* is some (possiby unitary) multiple of the pagesize.
*
* We assume the Smalltalk image code will manage subdividing the executable
* page amongst thunks so there is no need to free these pages, since the image
* will recycle parts of the page for reclaimed thunks.
*/
#if defined(_MSC_VER) || defined(__MINGW32__)
static unsigned long pagesize = 0;
#endif
void *
allocateExecutablePage(sqIntptr_t *size)
{
void *mem;
#if defined(_MSC_VER) || defined(__MINGW32__)
#if !defined(MEM_TOP_DOWN)
# define MEM_TOP_DOWN 0x100000
#endif
if (!pagesize) {
SYSTEM_INFO sysinf;
GetSystemInfo(&sysinf);
pagesize = sysinf.dwPageSize;
}
/* N.B. VirtualAlloc MEM_COMMIT initializes the memory returned to zero. */
mem = VirtualAlloc( 0,
pagesize,
MEM_COMMIT | MEM_TOP_DOWN,
PAGE_EXECUTE_READWRITE);
if (mem)
*size = pagesize;
#else
# if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200112L
long pagesize = getpagesize();
# else
long pagesize = sysconf(_SC_PAGESIZE);
# endif
/* This is equivalent to valloc(pagesize) but at least on some versions of
* SELinux valloc fails to yield an wexecutable page, whereas this mmap
* call works everywhere we've tested so far. See
* http://lists.squeakfoundation.org/pipermail/vm-dev/2018-October/029102.html
*/
if (!(mem = mmap(0, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0)))
return 0;
// MAP_ANON should zero out the allocated page, but explicitly doing it shouldn't hurt
memset(mem, 0, pagesize);
*size = pagesize;
#endif
return mem;
}
#endif /* i386|i486|i586|i686 */
|
the_stack_data/848432.c | #include <stdio.h>
#include <math.h>
double askValue(const char* string);
const double G = 9.81;
int main(void)
{
double h0 = askValue("de la hauteur initiale"),
eps = askValue("du coefficient de frottement"),
nbr = askValue("du nombre de rebond");
double v;
for(int i=0; i<nbr; ++i){
v = sqrt(2*h0*G)*eps;
h0 = v*v/(2*G);
}
printf("%f",h0);
return 0;
}
double askValue(const char* string)
{
printf("Entrez la valeur %s ?\n",string);
double val;
scanf("%lf", &val);
return val;
}
|
the_stack_data/176705521.c | #include<stdio.h>
void main()
{
int userid;
printf("Enter Your User Id:");
scanf("%d",&userid);
if(userid==101)
{
printf("Software dev");
}
else if(userid==102)
{
printf("Application Dev");
}
else if(userid==103)
{
printf("IOS Dev");
}
else
{
printf("Please Contact Our Hireing team");
}
}
|
the_stack_data/72619.c | //selection sorting in C Programming
//This is beginner friendly selection sorting as it has just a simple for loop used
#include<stdio.h>
#include<stdlib.h>
int i,n;
void input();//function prototype
void display(int b[20]);//function prototype
void sorting(int c[20]);//function prototype
int main(){
input();
return 0;
}
void input(){
int a[20];
printf("Enter the total numbers you want to enter\t");
scanf("%d",&n);
printf("Enter the numbers you want to enter\t");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("The entered numbers are:\n");
display(a);
sorting(a);
}
void display(int b[20]){
for(i=0;i<n;i++){
printf("%d\t",b[i]);
}
}
void sorting(int c[20]){
int j,temp;
//selection sorting algorithm for ascending order
for(i=0;i<(n-1);i++){
for(j=i+1;j<n;j++){
if(c[i]>c[j]){
temp=c[i];
c[i]=c[j];
c[j]=temp;
}//if-close
}//j loop
}//i loop
printf("\nThe result after sorting in ascending order is:\n");
display(c);
//selection sorting algorithm for descending order
for(i=0;i<(n-1);i++){
for(j=i+1;j<n;j++){
if(c[i]<c[j]){
temp=c[i];
c[i]=c[j];
c[j]=temp;
}//if-close
}//j loop
}//i loop
printf("\nThe result after sorting in descending order is:\n");
display(c);
}
|
the_stack_data/73591.c | #include <stdio.h>
#include <stdint.h>
int main(void) {
__asmb_line_1:;
int32_t __asmb_reg_diff = 32;
__asmb_line_2:;
int32_t __asmb_reg_seq0 = 72;
__asmb_line_3:;
int32_t __asmb_reg_seq1 = 69;
__asmb_line_4:;
int32_t __asmb_reg_seq23 = 76;
__asmb_line_5:;
int32_t __asmb_reg_seq4 = 79;
__asmb_line_6:;
int32_t __asmb_reg_seq5 = 87;
__asmb_line_7:;
int32_t __asmb_reg_seq6 = __asmb_reg_seq4;
__asmb_line_8:;
int32_t __asmb_reg_seq7 = 82;
__asmb_line_9:;
int32_t __asmb_reg_seq8 = 76;
__asmb_line_10:;
int32_t __asmb_reg_seq9 = 68;
__asmb_line_11:;
printf("%c", __asmb_reg_seq0);
__asmb_line_12:;
__asmb_reg_seq1 += __asmb_reg_diff;
__asmb_line_13:;
printf("%c", __asmb_reg_seq1);
__asmb_line_14:;
printf("%c", __asmb_reg_seq23);
__asmb_line_15:;
printf("%c", __asmb_reg_seq23);
__asmb_line_16:;
__asmb_reg_seq4 += __asmb_reg_diff;
__asmb_line_17:;
printf("%c", __asmb_reg_seq4);
__asmb_line_18:;
printf("%c", 32);
__asmb_line_19:;
printf("%c", __asmb_reg_seq5);
__asmb_line_20:;
__asmb_reg_seq6 += __asmb_reg_diff;
__asmb_line_21:;
printf("%c", __asmb_reg_seq6);
__asmb_line_22:;
printf("%c", __asmb_reg_seq7);
__asmb_line_23:;
__asmb_reg_seq8 += __asmb_reg_diff;
__asmb_line_24:;
printf("%c", __asmb_reg_seq8);
__asmb_line_25:;
printf("%c", __asmb_reg_seq9);
return 0;
}
|
the_stack_data/218892785.c | //
// author: Michael Brockus
// gmail : <[email protected]>
//
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//
// If you want to use more than one condition, you
// can use if else-if statement. The syntax of the
// if else if statement is as follows:
//
// if (condition-1)
// {
// /* code block if condition-1 is true */
// }
// else if (condition-2)
// {
// /* code block if condition-2 is true */
// }
// else if (condition-3)
// {
// /* code block if condition-3 is true */
// }
// else
// {
// /* code block all conditions above are false */
// }
//
// The else-if statement is used to make multiway decisions.
// The conditions in the corresponding if and else if branch
// evaluates in sequence from top to bottom. If a condition
// evaluates to true, the statements associated with it executes
// and terminates the whole chain.
//
// You can have as many branches as you want but it is not
// recommended because the code looks less readable and difficult
// to maintain.
//
// The following example compares the input number with zero (0)
// and displays the corresponding message:
//
int x;
printf("%s", "Please enter a number: ");
scanf("%d", &x);
if (x > 0)
{
printf("%d > 0", x);
}
else if (x < 0)
{
printf("%d < 0", x);
}
else
{
puts("zero");
}
return EXIT_SUCCESS;
} // end of function main
|
the_stack_data/15762771.c | /*numPass=0, numTotal=8
Verdict:WRONG_ANSWER, Visibility:1, Input:"3
abc
4
dbca", ExpOutput:"1", Output:""
Verdict:WRONG_ANSWER, Visibility:1, Input:"4
abce
4
dbca", ExpOutput:"2", Output:""
Verdict:WRONG_ANSWER, Visibility:1, Input:"7
labexam
4
dbca", ExpOutput:"7", Output:""
Verdict:WRONG_ANSWER, Visibility:1, Input:"7
labexam
7
balmmmm", ExpOutput:"6", Output:""
Verdict:WRONG_ANSWER, Visibility:0, Input:"7
labexam
7
balmaex", ExpOutput:"0", Output:""
Verdict:WRONG_ANSWER, Visibility:0, Input:"7
labexam
9
balmaexam", ExpOutput:"2", Output:""
Verdict:WRONG_ANSWER, Visibility:0, Input:"7
labexam
9
pqrstuvwp", ExpOutput:"16", Output:""
Verdict:WRONG_ANSWER, Visibility:0, Input:"7
hellohi
9
lhoeidear", ExpOutput:"6", Output:""
*/
#include <stdio.h>
#include <stdlib.h>
int makeEqual(char * s1, int n1, char * s2, int n2){
int i;
for(i=0;i<n1;i++)
{
}
}
int main(){
char*a;
char*b;
int n1,n2,i,j;
scanf("%d",&n1);
a=(char*)malloc(n1*sizeof(char));
scanf("%s",a);
scanf("%d",&n2);
b=(char*)malloc(n2*sizeof(char));
scanf("%s",b);
return 0;
} |
the_stack_data/225143294.c | /* This program is designed so that the user enters a
letter and the program tells them if its a vowel or not.
Author: Robert Eviston
Date: 14th October 2013
Lab 4 Quetion 1
*/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char vowel1;
do
{
printf("Please Enter a vowel: \n");
printf("Press 0 to exit\n");
scanf("%c", &vowel1);
flushall();
switch( vowel1 )
{
case 'a':
{
printf("You entered a vowel\n");
break;
}
case 'e':
{
printf("You entered a vowel\n");
break;
}
case 'i':
{
printf("You entered a vowel\n");
break;
}
case 'o':
{
printf("You entered a vowel\n");
break;
}
case 'u':
{
printf("You entered a vowel\n");
break;
}
case 0:
{
printf("Wrong");
}
default:
{
printf("You did not enter a vowel\n");
}
}// end switch
}while ( vowel1!= 0);
return 0;
}// end main |
the_stack_data/870238.c | /* -------------------------------------------------------------------
* @doc AR|BO|RE|US C Examples: Digits order counting
* @notice
*
* @copyright Arboreus (http://arboreus.systems)
* @author Alexandr Kirilov (http://alexandr.kirilov.me)
* @created 02/19/2019 at 19:37
* */// --------------------------------------------------------------
// System includes
#include <stdio.h>
// Application
int main(int Counter, char *Arguments[]) {
long long int Number = 123456789;
int DigitsOrder = 0;
do {
DigitsOrder++;
printf("Number: %lld, DigitsOrder: %d\n",Number,DigitsOrder);
} while ((Number /= 10) > 0);
printf("The digits order is %d\n",DigitsOrder);
return 0;
} |
the_stack_data/37636908.c | /*Programa que calcula si una frase ingresada es un palíndromo o no
ignorando los espacios en blanco*/
#include<stdio.h>
char cadena[' '],normal[' '],inversa[' '];
int longitud,i,k,opc;
void main()
{
printf("\n\n\tIngrese una Cadena:");
flushall();
gets(cadena);
//calculo la longitud de la cadena
for(i=0;cadena[i]!= '\0';i++)
{
longitud++;
if(cadena[i] != ' ')
{
//guardo cadena normal sin espacios
normal[k]= cadena[i];
k++;
}
}
k=0;
//Imprimo la frase ingresada de atras hacia adelante
printf("\n\n\tLa frase inversa es: ");
for(i = longitud-1 ;i >= 0;i--)
{
printf("%c",cadena[i]);
// guardo inversa pero cin espacios
if(cadena[i] != ' ')
{
inversa[k] = cadena[i];
k++;
}
}
//compara las cadenas
for(i =0;i < longitud;i++)
{
if(normal[i] == inversa[i])
opc = opc +1 ;
else
opc = opc -1;
}
if(opc == longitud)
{
printf("\n\n\tLa cadena es un palindromo !!!");
}
else
{
printf("\n\n\tLa cadena no es un palindromo !!!");
}
}
|
the_stack_data/104828492.c | /*
* Server Software (COMSM2001), 2017-18, Coursework 1.
*
* This is a skeleton program for COMSM2001 (Server Software) coursework 1
* "the project marking problem". Your task is to synchronise the threads
* correctly by adding code in the places indicated by comments in the
* student, marker and run functions.
* You may create your own global variables and further functions.
* The code in this skeleton program can be used without citation in the files
* that you submit for your coursework.
*/
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <errno.h>
/*
* Parameters of the program. The constraints are D < T and
* S*K <= M*N.
*/
struct demo_parameters {
int S; /* Number of students */
int M; /* Number of markers */
int K; /* Number of markers per demo */
int N; /* Number of demos per marker */
int T; /* Length of session (minutes) */
int D; /* Length of demo (minutes) */
};
/* Global object holding the demo parameters. */
struct demo_parameters parameters;
/* The demo start time, set in the main function. Do not modify this. */
struct timeval starttime;
/*
* You may wish to place some global variables here.
* Remember, globals are shared between threads.
* You can also create functions of your own.
*/
/* The status of markers */
struct marker_status {
int markerID; /* the ID of the recorded marker */
int is_grabbed; /* indicate whether the marker is grabbed by a student (0 means not grab, 1 means grab) */
int studentID; /* the ID of the student that grabed this marker and it is unmeaning when is_grabbed=0 */
int job; /* indicate the number of job that the marker have done */
};
struct marker_status* markers;
/* The idle marker maintaining by min-heap */
struct heap {
int size; /* the number of elements in min-heap */
int max_size; /* the maximum number of elements that min-heap can has */
struct marker_status* elements; /* a array of marker_status, which indicates the status of idle markers */
};
struct heap idle_marker;
/*
* Marking whether the remaining time is enough for a new demo start.
* timeout=0 means the reamining time is enough;
* timeout=1 means all markers and students not in demo should exit lab;
*/
int timeout;
/* Mutex lock for preventing race conditions in global variables */
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
/* Condition variable for marker and student */
pthread_cond_t c_marker = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_student = PTHREAD_COND_INITIALIZER;
/* heap_init(): initialise the heap which maintains the idle marker */
void heap_init(struct heap* root, int max_size) {
root->size = 0;
root->max_size = parameters.M;
/* Dynamic allocate memory for the elements of heap */
root->elements= (struct marker_status *)malloc(
(max_size + 1) * sizeof(struct marker_status));
if (root->elements == NULL) {
fprintf(stderr, "**ERROR**: heap_init() is failed to allocate"
" memory for the elements of heap.\n");
abort();
}
/* The weight of node(0) must be the minimal */
root->elements[0].job = -1;
}
/* heap_insert(): insert a element into heap */
void heap_insert(struct heap* root, struct marker_status x) {
int i;
if (root->size >= root->max_size) {
fprintf(stderr, "**ERROR**: heap_insert(), the heap is full.\n");
abort();
}
root->size = root->size + 1;
for (i = root->size; root->elements[i/2].job > x.job; i /= 2) {
root->elements[i] = root->elements[i/2];
}
root->elements[i] = x;
}
/* heap_pop(): return and delete the element which has the minimal weight except root(0) */
struct marker_status heap_pop(struct heap* root) {
int i, j;
struct marker_status min_element, last_element;
if (root->size == 0) {
fprintf(stderr, "**ERROR**: heap_pop(), the heap is empty.\n");
abort();
}
min_element = root->elements[1];
last_element = root->elements[root->size--];
for (i = 1; i * 2 <= root->size; i = j) {
j = i * 2;
if (j != root->size && root->elements[j+1].job < root->elements[j].job)
j++;
if (last_element.job > root->elements[j].job)
root->elements[i] = root->elements[j];
else
break;
}
root->elements[i] = last_element;
return min_element;
}
/* initialise(): initialise the global variables */
void initialise() {
/*
* All markers are idle at the begining
* The idle_marker is a min-heap which maintains the idle markers
* and sort them by the number of job
*/
heap_init(&idle_marker, parameters.M);
/*
* It must have time for a new demo at the begining
* since parameters.D >= parameters.T
*/
timeout = 0;
/* Dynamically allocate the memory for the pointer of markers */
markers = (struct marker_status *)malloc(parameters.M * sizeof(struct marker_status));
if (markers == NULL) {
fprintf(stderr, "**ERROR**: main thread is failed to allocate "
"memory for the pointer of markers.\n");
abort();
}
/* Initialise the status of markers */
for (int i = 0; i < parameters.M; i++) {
markers[i].markerID = i;
markers[i].is_grabbed = 0;
markers[i].studentID = -1;
markers[i].job = 0;
/* Insert the marker into heap since all markers are idle at the begining */
heap_insert(&idle_marker, markers[i]);
}
}
/*
* grab(): grab markers
* return 0 means success, else fail
*/
int grab(int studentID, int* markerIDs) {
int num_grabbed = 0;
int markerID = 0;
struct marker_status x;
while ((num_grabbed < parameters.K) && (idle_marker.size != 0)) {
/* Get the idle marker which has the minimal job */
x = heap_pop(&idle_marker);
markerID = x.markerID;
/* The status of markers in min-heap should be not grabbed */
if (markers[markerID].is_grabbed == 0) {
/* Modify the status of marker */
markerIDs[num_grabbed] = markerID;
markers[markerID].is_grabbed = 1;
markers[markerID].studentID = studentID;
num_grabbed = num_grabbed + 1;
} else {
fprintf(stderr, "grab(): The status of marker %d"
"is grabbed.\n", markerID);
return 1;
}
}
/* Error check */
if (num_grabbed != parameters.K) {
fprintf(stderr, "grab(): The number of idle marker "
"is less than %d.\n", parameters.K);
return 2;
}
return 0;
}
/*
* release(): release marker
* return 0 means success, else fail
*/
int release(int markerID) {
/* Verify markerID validity */
if (markerID < 0 || markerID >= parameters.M) {
fprintf(stderr, "release(): The markerID=%d is illegal.\n", markerID);
return 2;
}
heap_insert(&idle_marker, markers[markerID]);
/* Error check */
if (idle_marker.size > parameters.M) {
fprintf(stderr, "release(): The number of idle marker is "
"bigger than %d after release.\n", parameters.M);
return 1;
}
return 0;
}
/*
* timenow(): returns current simulated time in "minutes" (cs).
* Assumes that starttime has been set already.
* This function is safe to call in the student and marker threads as
* starttime is set in the run() function.
*/
int timenow() {
struct timeval now;
gettimeofday(&now, NULL);
return (now.tv_sec - starttime.tv_sec) * 100 + (now.tv_usec - starttime.tv_usec) / 10000;
}
/* delay(t): delays for t "minutes" (cs) */
void delay(int t) {
struct timespec rqtp, rmtp;
t *= 10;
rqtp.tv_sec = t / 1000;
rqtp.tv_nsec = 1000000 * (t % 1000);
nanosleep(&rqtp, &rmtp);
}
/* panic(): simulates a student's panicking activity */
void panic() {
delay(random() % (parameters.T - parameters.D));
}
/* demo(): simulates a demo activity */
void demo() {
delay(parameters.D);
}
/*
* A marker thread. You need to modify this function.
* The parameter arg is the number of the current marker and the function
* doesn't need to return any values.
* Do not modify the printed output as it will be used as part of the testing.
*/
void *marker(void *arg) {
int markerID = *(int *)arg;
/*
* The following variable is used in the printf statements when a marker is
* grabbed by a student. It shall be set by this function whenever the
* marker is grabbed - and before the printf statements referencing it are
* executed.
*/
int studentID;
/*
* The following variable shall indicate which job the marker is currently
* executing, the first being job 0. The variable ranges from 0 to
* (parameters.N - 1) .
*/
int job = 0;
/* The variable for storing error code */
int err;
/* 1. Enter the lab. */
printf("%d marker %d: enters lab\n", timenow(), markerID);
/* A marker marks up to N projects. */
/* 2. Repeat (N times).
* (a) Wait to be grabbed by a student.
* (b) Wait for the student's demo to begin
* (you may not need to do anything here).
* (c) Wait for the demo to finish.
* Do not just wait a given time -
* let the student signal when the demo is over.
* (d) Exit the lab.
*/
/* Repeat N times */
while (job < parameters.N) {
err = pthread_mutex_lock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to acquire "
"locker (mut), %s.\n", markerID, strerror(errno));
abort();
}
/* Wait to be grabbed by a student or timeout */
while ((markers[markerID].is_grabbed == 0) && (timeout == 0)) {
err = pthread_cond_wait(&c_marker, &mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to "
"wait conditional variable (c_marker, mut), "
"%s.\n", studentID, strerror(errno));
abort();
}
}
if (timeout == 1) {
/*
* 3. If the end of the session approaches (i.e. there is no time
* to start another demo) then the marker waits for the current
* demo to finish (if they are currently attending one) and then
* exits the lab.
*/
/*
* Marker exit lab since timeout
* Unlock the locker before exit lab
*/
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to release"
" locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
printf("%d marker %d: exits lab (timeout)\n", timenow(), markerID);
return NULL;
} else {
/* Get the studentID which grabed this marker */
studentID = markers[markerID].studentID;
/* Verify studentID validity */
if (studentID < 0 || studentID >= parameters.S) {
fprintf(stderr, "**ERROR**: Marker %d grabbed by student "
"%d is illegal.\n", markerID, studentID);
abort();
}
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to "
"release locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
}
/* The following line shall be printed when a marker is grabbed by a student. */
printf("%d marker %d: grabbed by student %d (job %d)\n", timenow(), markerID, studentID, job + 1);
demo();
/* The following line shall be printed when a marker has finished attending a demo. */
printf("%d marker %d: finished with student %d (job %d)\n", timenow(), markerID, studentID, job + 1);
/*
* Wait for the demo to finish
* (a) acquire the locker (mut)
* (b) predicate: the statue of marker is not grab
* (c) the number of job adds one
* (d) if the job smaller than N,
* inserts this marker into idle_marker,
* sends the signal to student and release the locker
*/
err = pthread_mutex_lock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to acquire "
"locker (mut), %s.\n", markerID, strerror(errno));
abort();
}
while (markers[markerID].is_grabbed == 1) {
err = pthread_cond_wait(&c_marker, &mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to "
"wait conditional variable (c_student, mut), "
"%s.\n", studentID, strerror(errno));
abort();
}
}
job = job + 1;
markers[markerID].job = job;
if (job < parameters.N) {
err = release(markerID);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is "
"failed to release.\n", markerID);
abort();
}
err = pthread_cond_broadcast(&c_student);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to "
"broadcast student (c_student), "
"%s.\n", markerID, strerror(errno));
abort();
}
}
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Marker %d is failed to release "
"locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
}
/*
* When the marker exits the lab, exactly one of the following two lines shall be
* printed, depending on whether the marker has finished all their jobs or there
* is no time to complete another demo.
*/
printf("%d marker %d: exits lab (finished %d jobs)\n", timenow(), markerID, parameters.N);
return NULL;
}
/*
* A student thread. You must modify this function.
*/
void *student(void *arg) {
/* The ID of the current student. */
int studentID = *(int *)arg;
/* The variable for storing error code */
int err;
/* Store the markerID which grabbed by this student */
int* markerIDs;
/* Dynamic allocate memory for the point of markerIDs */
markerIDs = (int *)malloc(parameters.K * sizeof(int));
if (markerIDs == NULL) {
fprintf(stderr, "**ERROR**: Student %d is failed to allocate "
"memory for the pointer of markerIDs.\n", studentID);
abort();
}
/* 1. Panic! */
printf("%d student %d: starts panicking\n", timenow(), studentID);
panic();
/* 2. Enter the lab. */
printf("%d student %d: enters lab\n", timenow(), studentID);
/*
* 3. Grab K markers.
* (a) acquire the locker (mut)
* (b) predicate: there are K idle marker or timeout
* (c) if there are K idle marker, grab them and send
* signal to markers, release the locker
* (d) if timeout, release the locker and exit the lab
*/
err = pthread_mutex_lock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to acquire "
"locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
/* Waiting for K idle markers or timeout */
while ((idle_marker.size < parameters.K) && (timeout == 0)) {
err = pthread_cond_wait(&c_student, &mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to "
"wait conditional variable (c_student, mut), "
"%s.\n", studentID, strerror(errno));
abort();
}
}
if (timeout == 0) {
/* Student grabs K markers */
err = grab(studentID, markerIDs);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to "
"grab %d markers.\n", studentID, parameters.K);
abort();
}
/* Student broadcast markers after grab */
err = pthread_cond_broadcast(&c_marker);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to "
"broadcast markers (c_marker), %s.\n",
studentID, strerror(errno));
abort();
}
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to release"
" locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
} else {
/*
* Student exit the lab since timeout
* Unlock the locker (mut) before exit the lab
*/
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to release"
" locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
free(markerIDs);
printf("%d student %d: exits lab (timeout)\n", timenow(), studentID);
return NULL;
}
/* 4. Demo! */
/*
* If the student succeeds in grabbing K markers and there is enough time left
* for a demo, the following three lines shall be executed in order.
* If the student has not started their demo and there is not sufficient time
* left to do a full demo, the following three lines shall not be executed
* and the student proceeds to step 5.
*/
printf("%d student %d: starts demo\n", timenow(), studentID);
demo();
printf("%d student %d: ends demo\n", timenow(), studentID);
/*
* Release the markers that grabbed by this student
* (a) acquire the locker (mut)
* (b) set the grab status of markers
* (c) send the signal to markers
* (d) release the locker (mut)
*/
err = pthread_mutex_lock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to acquire "
"locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
for (int i = 0; i < parameters.K; i++) {
int markerID = markerIDs[i];
if (markerID < 0 || markerID >= parameters.M) {
fprintf(stderr, "**ERROR**: Student %d grabbed marker %d is"
" illegal.\n", studentID, markerID);
abort();
}
markers[markerID].is_grabbed = 0;
}
/* Student broadcast markers after demo */
err = pthread_cond_broadcast(&c_marker);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to "
"broadcast markers (c_marker), %s.\n",
studentID, strerror(errno));
abort();
}
err = pthread_mutex_unlock(&mut);
if (err != 0) {
fprintf(stderr, "**ERROR**: Student %d is failed to release"
" locker (mut), %s.\n", studentID, strerror(errno));
abort();
}
/* 5. Exit the lab. */
/*
* Exactly one of the following two lines shall be printed, depending on
* whether the student got to give their demo or not.
*/
printf("%d student %d: exits lab (finished)\n", timenow(), studentID);
/* Deallocate the memory */
free(markerIDs);
return NULL;
}
/* The function that runs the session.
* You MAY want to modify this function.
*/
void run() {
int i;
int ok;
int markerID[100], studentID[100];
pthread_t markerT[100], studentT[100];
printf("S=%d M=%d K=%d N=%d T=%d D=%d\n",
parameters.S,
parameters.M,
parameters.K,
parameters.N,
parameters.T,
parameters.D);
gettimeofday(&starttime, NULL); /* Save start of simulated time */
/* Initalise the global variable */
initialise();
/* Create S student threads */
for (i = 0; i < parameters.S; i++) {
studentID[i] = i;
ok = pthread_create(&studentT[i], NULL, student, &studentID[i]);
if (ok != 0) { abort(); }
}
/* Create M marker threads */
for (i = 0; i < parameters.M; i++) {
markerID[i] = i;
ok = pthread_create(&markerT[i], NULL, marker, &markerID[i]);
if (ok != 0) { abort(); }
}
/* With the threads now started, the session is in full swing ... */
delay(parameters.T - parameters.D);
/*
* When we reach here, this is the latest time a new demo could start.
* You might want to do something here or soon after.
*/
/*
* Main thread sets timeout and sends signal to students and markers
* (a) acquire the locker (mut)
* (b) set timeout=1
* (c) broadcast students (c_student) and markers (c_marker)
* (d) release the locker (mut)
*/
ok = pthread_mutex_lock(&mut);
if (ok != 0) {
fprintf(stderr, "**ERROR**: Main thread is failed to "
"acquire the locker (mut), %s.\n", strerror(errno));
abort();
}
timeout = 1;
ok = pthread_cond_broadcast(&c_student);
if (ok != 0) {
fprintf(stderr, "**ERROR**: Main thread is failed to "
"broadcast students (c_student), %s.\n", strerror(errno));
abort();
}
ok = pthread_cond_broadcast(&c_marker);
if (ok != 0) {
fprintf(stderr, "**ERROR**: Main thread is failed to "
"broadcast markers (c_marker), %s.\n", strerror(errno));
abort();
}
ok = pthread_mutex_unlock(&mut);
if (ok != 0) {
fprintf(stderr, "**ERROR**: Main thread is failed to "
"release the locker (mut), %s.\n", strerror(errno));
abort();
}
/* Wait for student threads to finish */
for (i = 0; i<parameters.S; i++) {
ok = pthread_join(studentT[i], NULL);
if (ok != 0) { abort(); }
}
/* Wait for marker threads to finish */
for (i = 0; i<parameters.M; i++) {
ok = pthread_join(markerT[i], NULL);
if (ok != 0) { abort(); }
}
/* Deallocates the memory */
free(markers);
free(idle_marker.elements);
}
/*
* main() checks that the parameters are ok. If they are, the interesting bit
* is in run() so please don't modify main().
*/
int main(int argc, char *argv[]) {
if (argc < 6) {
puts("Usage: demo S M K N T D\n");
exit(1);
}
parameters.S = atoi(argv[1]);
parameters.M = atoi(argv[2]);
parameters.K = atoi(argv[3]);
parameters.N = atoi(argv[4]);
parameters.T = atoi(argv[5]);
parameters.D = atoi(argv[6]);
if (parameters.M > 100 || parameters.S > 100) {
puts("Maximum 100 markers and 100 students allowed.\n");
exit(1);
}
if (parameters.D >= parameters.T) {
puts("Constraint D < T violated.\n");
exit(1);
}
if (parameters.S*parameters.K > parameters.M*parameters.N) {
puts("Constraint S*K <= M*N violated.\n");
exit(1);
}
srand(time(NULL));
// We're good to go.
run();
return 0;
}
|
the_stack_data/179829610.c | /* Where's Waldorf? */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char grid[51][51];
int m, n;
void read_grid() {
int i, j;
scanf("%d %d", &m, &n);
getchar();
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++)
grid[i][j] = toupper(getchar());
getchar();
}
}
int check(char *word, int x, int y, int size) {
int i;
char directions[8] = {1,1,1,1,1,1,1,1};
for (i = 0; i < size; i++) {
if ((x-i) > 0) {
if (word[i] != grid[x-i][y])
directions[0] = 0;
}
else
directions[0] = 0;
if ((x+i) <= m) {
if (word[i] != grid[x+i][y])
directions[1] = 0;
}
else
directions[1] = 0;
if ((y-i) > 0) {
if (word[i] != grid[x][y-i])
directions[2] = 0;
}
else
directions[2] = 0;
if ((y+i) <= n) {
if (word[i] != grid[x][y+i])
directions[3] = 0;
}
else
directions[3] = 0;
if (((x-i) > 0) && ((y-i) > 0)) {
if (word[i] != grid[x-i][y-i])
directions[4] = 0;
}
else
directions[4] = 0;
if (((x-i) > 0) && ((y+i) <= n)) {
if (word[i] != grid[x-i][y+i])
directions[5] = 0;
}
else
directions[5] = 0;
if (((x+i) <= m) && ((y-i) > 0)) {
if (word[i] != grid[x+i][y-i])
directions[6] = 0;
}
else
directions[6] = 0;
if (((x+i) <= m) && ((y+i) <= n)) {
if (word[i] != grid[x+i][y+i])
directions[7] = 0;
}
else
directions[7] = 0;
}
for (i = 0; i < 8; i++)
if (directions[i] == 1)
return 1;
return 0;
}
int main() {
int cases, k, i, j, l, size;
char name[82], found;
scanf("%d", &cases);
getchar();
while (cases) {
getchar();
read_grid();
scanf("%d", &k);
getchar();
for (i = 0; i < k; i++) {
fgets(name, 82, stdin);
size = strlen(name) - 1;
name[size] = '\0';
for (j = 0; j < size; j++)
name[j] = toupper(name[j]);
for (j = 1, found = 0; ((j <= m) && (!found)); j++)
for (l = 1; l <= n; l++)
if (check(name, j, l, size)) {
printf("%d %d\n", j, l);
found = 1;
break;
}
}
if (cases > 1)
putchar('\n');
cases--;
}
return 0;
}
|
the_stack_data/1252312.c | /*
* Date: 2014-06-08
* Author: [email protected]
*
*
* This is Example 1.5 from the test suit used in
*
* Termination Proofs for Linear Simple Loops.
* Hong Yi Chen, Shaked Flur, and Supratik Mukhopadhyay.
* SAS 2012.
*
* The test suite is available at the following URL.
* https://tigerbytes2.lsu.edu/users/hchen11/lsl/LSL_benchmark.txt
*
* Comment: terminating, linear
*/
typedef enum {false, true} bool;
extern int __VERIFIER_nondet_int(void);
int main() {
int x, oldx;
x = __VERIFIER_nondet_int();
while (x > 0 && 2*x <= oldx) {
oldx = x;
x = __VERIFIER_nondet_int();
}
return 0;
}
|
the_stack_data/11074196.c | #include "stdlib.h"
int atoi(const char *s)
{
int result = 0, sign = 1;
if (*s == -1)
{
sign = -1;
s++;
}
while (*s >= '0' && *s <= '9')
result = result * 10 + (*(s++) - '0');
return result * sign;
}
|
the_stack_data/369369.c | #include<stdio.h>
#include<signal.h>
main()
{
printf("Give process id");
int a,c;
scanf("%d",&a);
do{
printf("Give choice");
scanf("%d",&c);
if(c==0){kill(a,SIGINT);}
if(c==1){kill(a,SIGQUIT);}
if(c==2){kill(a,SIGUSR1);}
if(c==3){kill(a,SIGKILL);}
if(c==4){kill(a,SIGSTOP);}
if(c==5){kill(a,SIGCONT);}
if(c==6){kill(a,SIGCHLD);}
if(c==7){kill(a,SIGPIPE);}
}while(c!=8);
}
|
the_stack_data/7950077.c | #include <stdio.h>
#define STLEN 81
int main(void) {
char words[STLEN];
puts("Enter a string, please.");
gets(words);
printf("Your string twice:\n");
printf("%s\n", words);
puts(words);
puts("Done.");
return 0;
}
|
the_stack_data/151705745.c | #include <stdio.h>
int main(){
int ps2;
char xbox[10];
printf("Address of ps2 variable %p\n", &ps2);
printf("Address of xbox variable %p\n", &xbox);
return 0;
}
|
the_stack_data/486124.c | #include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <fcntl.h>
#define MAX_LENGTH_OF_COMMAND 128
#define MAX_NUMBER_OF_WORDS 64
#define MAX_NUMBER_OF_COMMANDS 16
int myLastCharacterLocationFinder(char* a) {
int i = 0;
while (a[i] != '\0') {
i++;
}
return i - 1;
}
char* iRed(char myLine[]){
char* templine1 = myLine;
int index=0;
bool iRedirect = false;
while (templine1[index] != '\0'){
if (templine1[index] == '<'){
iRedirect=true;
break;
}
index++;
}
char* in = NULL;
if (iRedirect){
in = strtok(templine1, "<");
in = strtok(NULL, " ");
}
return in;
}
char* oRed(char myLine[]){
char* templine2 = myLine;
bool oRedirect = false;
int index=0;
while (templine2[index] != '\0'){
if (templine2[index] == '>'){
oRedirect=true;
break;
}
index++;
}
char* out=NULL;
if (oRedirect){
out = strtok(templine2, ">");
out = strtok(NULL, " ");
}
return out;
}
char*** mySplitLine(char* myline) {
char*** splitted = malloc(sizeof(char**) * MAX_NUMBER_OF_COMMANDS);
char** commands = malloc(sizeof(char*) * MAX_NUMBER_OF_COMMANDS);
char* line = strtok(myline,"<>");
int numberOfCommands=0;
char* temp = strtok(line,"|");
while (temp != NULL){
commands[numberOfCommands]=temp;
temp = strtok(NULL,"|");
numberOfCommands++;
}
for (int i=0; i < numberOfCommands; i++) {
int numberOfWords=0;
char** words = malloc(sizeof(char*) * MAX_NUMBER_OF_WORDS);
char* temp2 = strtok(commands[i]," ");
while (temp2 != NULL){
words[numberOfWords]=temp2;
temp2 = strtok(NULL," ");
numberOfWords++;
}
splitted[i] = words;
}
splitted[numberOfCommands]=NULL;
return splitted;
}
void myCommandExecutor(char ***cmd, bool amp,char* in,char* out){
int p[2];
pid_t pid;
int fd_in = 0;
int status;
int counter=0;
while (*cmd != NULL){
counter++;
pipe(p);
if ((pid = fork()) == -1){
exit(1);
} else if (pid == 0) {
if (counter == 1 && in != NULL){
int in2 = open(in,O_RDONLY);
dup2(in2,STDIN_FILENO);
close(in2);
} else
dup2(fd_in, 0); //Wczytujemy dane z pipe'a (został już użyty, jeśli nie czytamy ze standardowego wejścia)
if (*(cmd + 1) != NULL) {
dup2(p[1], 1); //Wyjście ustawiamy na pipe
} else {
if (out != NULL){
int out2 = open(out,O_WRONLY|O_CREAT,0666);
dup2(out2,STDOUT_FILENO);
close(out2);
}
}
close(p[0]); //Zamykamy wejście
execvp((*cmd)[0], *cmd);
exit(0);
} else {
if (!amp)
wait(&status); //Czekamy na skończenie pracy dziecka
close(p[1]); //Zamykamy wyjście
fd_in = p[0]; //Ustawiamy wejście na pipe
cmd++;
}
}
}
char* myGetLine(){
char* line = NULL;
ssize_t bufsize = 0;
if (getline(&line, &bufsize, stdin) == EOF) {
printf("\n");
exit(0);
}
return line;
}
int main() {
char* line;
char*** commands;
char location[512];
getcwd(location, 512);
do {
printf("%s: (> ",location);
line = myGetLine();
if (line[myLastCharacterLocationFinder(line)] == '\n')
line[myLastCharacterLocationFinder(line)] = '\0';
bool amp=false;
if (line[myLastCharacterLocationFinder(line)] == '&') {
line[myLastCharacterLocationFinder(line)] = '\0';
amp=true;
}
char line3[MAX_LENGTH_OF_COMMAND];
strcpy(line3,line);
char line4[MAX_LENGTH_OF_COMMAND];
strcpy(line4,line);
char* iRedirect = iRed(line3);
char* oRedirect = oRed(line4);
commands = mySplitLine(line);
if (strcmp(commands[0][0],"cd")==0){
chdir(commands[0][1]);
getcwd(location, 512);
continue;
} else
if (strcmp(commands[0][0],"exit")==0){
printf("\n");
exit(0);
} else
myCommandExecutor(commands,amp,iRedirect,oRedirect);
free(line);
} while (1);
return 0;
} |
the_stack_data/20702.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* > \brief \b CLAQR1 sets a scalar multiple of the first column of the product of 2-by-2 or 3-by-3 matrix H a
nd specified shifts. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CLAQR1 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/claqr1.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/claqr1.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/claqr1.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CLAQR1( N, H, LDH, S1, S2, V ) */
/* COMPLEX S1, S2 */
/* INTEGER LDH, N */
/* COMPLEX H( LDH, * ), V( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > Given a 2-by-2 or 3-by-3 matrix H, CLAQR1 sets v to a */
/* > scalar multiple of the first column of the product */
/* > */
/* > (*) K = (H - s1*I)*(H - s2*I) */
/* > */
/* > scaling to avoid overflows and most underflows. */
/* > */
/* > This is useful for starting double implicit shift bulges */
/* > in the QR algorithm. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > Order of the matrix H. N must be either 2 or 3. */
/* > \endverbatim */
/* > */
/* > \param[in] H */
/* > \verbatim */
/* > H is COMPLEX array, dimension (LDH,N) */
/* > The 2-by-2 or 3-by-3 matrix H in (*). */
/* > \endverbatim */
/* > */
/* > \param[in] LDH */
/* > \verbatim */
/* > LDH is INTEGER */
/* > The leading dimension of H as declared in */
/* > the calling procedure. LDH >= N */
/* > \endverbatim */
/* > */
/* > \param[in] S1 */
/* > \verbatim */
/* > S1 is COMPLEX */
/* > \endverbatim */
/* > */
/* > \param[in] S2 */
/* > \verbatim */
/* > S2 is COMPLEX */
/* > */
/* > S1 and S2 are the shifts defining K in (*) above. */
/* > \endverbatim */
/* > */
/* > \param[out] V */
/* > \verbatim */
/* > V is COMPLEX array, dimension (N) */
/* > A scalar multiple of the first column of the */
/* > matrix K in (*). */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date June 2017 */
/* > \ingroup complexOTHERauxiliary */
/* > \par Contributors: */
/* ================== */
/* > */
/* > Karen Braman and Ralph Byers, Department of Mathematics, */
/* > University of Kansas, USA */
/* > */
/* ===================================================================== */
/* Subroutine */ int claqr1_(integer *n, complex *h__, integer *ldh, complex *
s1, complex *s2, complex *v)
{
/* System generated locals */
integer h_dim1, h_offset, i__1, i__2, i__3, i__4;
real r__1, r__2, r__3, r__4, r__5, r__6;
complex q__1, q__2, q__3, q__4, q__5, q__6, q__7, q__8;
/* Local variables */
real s;
complex h21s, h31s;
/* -- LAPACK auxiliary routine (version 3.7.1) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* June 2017 */
/* ================================================================ */
/* Quick return if possible */
/* Parameter adjustments */
h_dim1 = *ldh;
h_offset = 1 + h_dim1 * 1;
h__ -= h_offset;
--v;
/* Function Body */
if (*n != 2 && *n != 3) {
return 0;
}
if (*n == 2) {
i__1 = h_dim1 + 1;
q__2.r = h__[i__1].r - s2->r, q__2.i = h__[i__1].i - s2->i;
q__1.r = q__2.r, q__1.i = q__2.i;
i__2 = h_dim1 + 2;
s = (r__1 = q__1.r, abs(r__1)) + (r__2 = r_imag(&q__1), abs(r__2)) + (
(r__3 = h__[i__2].r, abs(r__3)) + (r__4 = r_imag(&h__[h_dim1
+ 2]), abs(r__4)));
if (s == 0.f) {
v[1].r = 0.f, v[1].i = 0.f;
v[2].r = 0.f, v[2].i = 0.f;
} else {
i__1 = h_dim1 + 2;
q__1.r = h__[i__1].r / s, q__1.i = h__[i__1].i / s;
h21s.r = q__1.r, h21s.i = q__1.i;
i__1 = (h_dim1 << 1) + 1;
q__2.r = h21s.r * h__[i__1].r - h21s.i * h__[i__1].i, q__2.i =
h21s.r * h__[i__1].i + h21s.i * h__[i__1].r;
i__2 = h_dim1 + 1;
q__4.r = h__[i__2].r - s1->r, q__4.i = h__[i__2].i - s1->i;
i__3 = h_dim1 + 1;
q__6.r = h__[i__3].r - s2->r, q__6.i = h__[i__3].i - s2->i;
q__5.r = q__6.r / s, q__5.i = q__6.i / s;
q__3.r = q__4.r * q__5.r - q__4.i * q__5.i, q__3.i = q__4.r *
q__5.i + q__4.i * q__5.r;
q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i;
v[1].r = q__1.r, v[1].i = q__1.i;
i__1 = h_dim1 + 1;
i__2 = (h_dim1 << 1) + 2;
q__4.r = h__[i__1].r + h__[i__2].r, q__4.i = h__[i__1].i + h__[
i__2].i;
q__3.r = q__4.r - s1->r, q__3.i = q__4.i - s1->i;
q__2.r = q__3.r - s2->r, q__2.i = q__3.i - s2->i;
q__1.r = h21s.r * q__2.r - h21s.i * q__2.i, q__1.i = h21s.r *
q__2.i + h21s.i * q__2.r;
v[2].r = q__1.r, v[2].i = q__1.i;
}
} else {
i__1 = h_dim1 + 1;
q__2.r = h__[i__1].r - s2->r, q__2.i = h__[i__1].i - s2->i;
q__1.r = q__2.r, q__1.i = q__2.i;
i__2 = h_dim1 + 2;
i__3 = h_dim1 + 3;
s = (r__1 = q__1.r, abs(r__1)) + (r__2 = r_imag(&q__1), abs(r__2)) + (
(r__3 = h__[i__2].r, abs(r__3)) + (r__4 = r_imag(&h__[h_dim1
+ 2]), abs(r__4))) + ((r__5 = h__[i__3].r, abs(r__5)) + (r__6
= r_imag(&h__[h_dim1 + 3]), abs(r__6)));
if (s == 0.f) {
v[1].r = 0.f, v[1].i = 0.f;
v[2].r = 0.f, v[2].i = 0.f;
v[3].r = 0.f, v[3].i = 0.f;
} else {
i__1 = h_dim1 + 2;
q__1.r = h__[i__1].r / s, q__1.i = h__[i__1].i / s;
h21s.r = q__1.r, h21s.i = q__1.i;
i__1 = h_dim1 + 3;
q__1.r = h__[i__1].r / s, q__1.i = h__[i__1].i / s;
h31s.r = q__1.r, h31s.i = q__1.i;
i__1 = h_dim1 + 1;
q__4.r = h__[i__1].r - s1->r, q__4.i = h__[i__1].i - s1->i;
i__2 = h_dim1 + 1;
q__6.r = h__[i__2].r - s2->r, q__6.i = h__[i__2].i - s2->i;
q__5.r = q__6.r / s, q__5.i = q__6.i / s;
q__3.r = q__4.r * q__5.r - q__4.i * q__5.i, q__3.i = q__4.r *
q__5.i + q__4.i * q__5.r;
i__3 = (h_dim1 << 1) + 1;
q__7.r = h__[i__3].r * h21s.r - h__[i__3].i * h21s.i, q__7.i =
h__[i__3].r * h21s.i + h__[i__3].i * h21s.r;
q__2.r = q__3.r + q__7.r, q__2.i = q__3.i + q__7.i;
i__4 = h_dim1 * 3 + 1;
q__8.r = h__[i__4].r * h31s.r - h__[i__4].i * h31s.i, q__8.i =
h__[i__4].r * h31s.i + h__[i__4].i * h31s.r;
q__1.r = q__2.r + q__8.r, q__1.i = q__2.i + q__8.i;
v[1].r = q__1.r, v[1].i = q__1.i;
i__1 = h_dim1 + 1;
i__2 = (h_dim1 << 1) + 2;
q__5.r = h__[i__1].r + h__[i__2].r, q__5.i = h__[i__1].i + h__[
i__2].i;
q__4.r = q__5.r - s1->r, q__4.i = q__5.i - s1->i;
q__3.r = q__4.r - s2->r, q__3.i = q__4.i - s2->i;
q__2.r = h21s.r * q__3.r - h21s.i * q__3.i, q__2.i = h21s.r *
q__3.i + h21s.i * q__3.r;
i__3 = h_dim1 * 3 + 2;
q__6.r = h__[i__3].r * h31s.r - h__[i__3].i * h31s.i, q__6.i =
h__[i__3].r * h31s.i + h__[i__3].i * h31s.r;
q__1.r = q__2.r + q__6.r, q__1.i = q__2.i + q__6.i;
v[2].r = q__1.r, v[2].i = q__1.i;
i__1 = h_dim1 + 1;
i__2 = h_dim1 * 3 + 3;
q__5.r = h__[i__1].r + h__[i__2].r, q__5.i = h__[i__1].i + h__[
i__2].i;
q__4.r = q__5.r - s1->r, q__4.i = q__5.i - s1->i;
q__3.r = q__4.r - s2->r, q__3.i = q__4.i - s2->i;
q__2.r = h31s.r * q__3.r - h31s.i * q__3.i, q__2.i = h31s.r *
q__3.i + h31s.i * q__3.r;
i__3 = (h_dim1 << 1) + 3;
q__6.r = h21s.r * h__[i__3].r - h21s.i * h__[i__3].i, q__6.i =
h21s.r * h__[i__3].i + h21s.i * h__[i__3].r;
q__1.r = q__2.r + q__6.r, q__1.i = q__2.i + q__6.i;
v[3].r = q__1.r, v[3].i = q__1.i;
}
}
return 0;
} /* claqr1_ */
|
the_stack_data/125139552.c | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : [email protected]
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include<stdio.h>
int main()
{
int t,n,ans;
scanf("%d",&t);
while(t--){
ans=0;
scanf("%d",&n);
while(n/100){
ans+=(n/100);
n%=100;
}
while(n/50){
ans+=(n/50);
n%=50;
}
while(n/10){
ans+=(n/10);
n%=10;
}
while(n/5){
ans+=(n/5);
n%=5;
}
while(n/2){
ans+=(n/2);
n%=2;
}
if(n) ans+=n;
printf("%d\n",ans);
}
return 0;
}
|
the_stack_data/234518164.c | /* Initialization of local const array */
int f(int x)
{
const int dfl = 2;
const int tbl[3] = { 12, 34, 56 };
return tbl[x >= 0 && x < 3 ? x : dfl];
}
|
the_stack_data/103265755.c | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/************************************************************************
* libc/math/lib_frexpl.c
*
* This file is a part of NuttX:
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Ported by: Darcy Gong
*
* It derives from the Rhombs OS math library by Nick Johnson which has
* a compatibile, MIT-style license:
*
* Copyright (C) 2009-2011 Nick Johnson <nickbjohnson4224 at gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
************************************************************************/
/************************************************************************
* Included Files
************************************************************************/
#include <math.h>
/************************************************************************
* Public Functions
************************************************************************/
#ifdef CONFIG_HAVE_LONG_DOUBLE
long double frexpl(long double x, int *exponent)
{
*exponent = (int)ceill(log2(x));
return x / ldexpl(1.0, *exponent);
}
#endif
|
the_stack_data/111731.c | /**~UML Diagram Interchange~
* UMLDiagramElement [Abstract Class]
*
* Description
*
* The most general class for UML diagram interchange.
*
* Generalizations
*
* DiagramElement
*
* Specializations
*
* UMLCompartment, UMLDiagram, UMLEdge, UMLShape
*
* Attributes
*
* isIcon : Boolean [1..1] = false
*
* For modelElements that have an option to be shown with shapes other than rectangles, such as Actors, or with
* other identifying shapes inside them, such as arrows distinguishing InputPins and OutputPins, or edges that
* have an option to be shown with lines other than solid with open arrow heads, such as Realization. A value of
* true for isIcon indicates the alternative notation shall be shown.
*
* Association Ends
*
* modelElement : Element [0..*]{redefines DiagramElement::modelElement} (opposite
* A_UMLDiagramElement_modelElement_umlDiagramElement::umlDiagramElement)
*
* Restricts UMLDiagramElements to show UML Elements, rather than other language elements.
*
* sharedStyle : UMLStyle [0..1]{redefines DiagramElement::sharedStyle} (opposite
* A_UMLDiagramElement_sharedStyle_styledElement::styledElement)
*
* Restricts shared styles to UMLStyles.
*
* ♦ localStyle : UMLStyle [0..1]{redefines DiagramElement::localStyle} (opposite
* A_UMLDiagramElement_localStyle_styledElement::styledElement)
*
* Restricts owned styles to UMLStyles.
*
* owningElement : UMLDiagramElement [0..1]{redefines DiagramElement::owningElement} (opposite
* UMLDiagramElement::ownedElement)
*
* Restricts UMLDiagramElements to be owned by only UMLDiagramElements.
*
* ♦ ownedElement : UMLDiagramElement [0..*]{ordered, redefines DiagramElement::ownedElement}
* (opposite UMLDiagramElement::owningElement)
*
* Restricts UMLDiagramElements to own only UMLDiagramElements.
**/ |
the_stack_data/215766973.c | # include <stdio.h>
int main()
{
double a;
int b;
a = 5.0;
b = (int) a;
printf("%d\n", b);
return 0;
}
|
the_stack_data/199835.c | #include <unistd.h>
#ifndef INT16_MAX
enum { INT16_MAX = (1 << 0) + (1 << 1) + (1 << 2) + (1 << 3) + (1 << 4) + (1 << 5) + (1 << 6) + (1 << 7) +
(1 << 8) + (1 << 9) + (1 << 10) + (1 << 11) + (1 << 12) + (1 << 13) + (1 << 14) };
#endif
enum { BUF_SIZE = INT16_MAX };
static char buffer[BUF_SIZE] = {};
static int write_long_long_int(long long int n) {
char * p;
p = buffer + BUF_SIZE;
p--;
*p = '\0';
p--;
for (;;) {
*p = '0' + (n % 10);
n = n / 10;
if (0 == n) break;
if (p == buffer) { return ~0; };
p--;
};
const int len = BUF_SIZE - (p - buffer) - 1;
write(STDOUT_FILENO, p, len);
return len;
};
static int write_int(int n) {
char * p;
p = buffer + BUF_SIZE;
p--;
*p = '\0';
p--;
for (;;) {
*p = '0' + (n % 10);
n = n / 10;
if (0 == n) break;
if (p == buffer) { return ~0; };
p--;
};
const int len = BUF_SIZE - (p - buffer) - 1;
write(STDOUT_FILENO, p, len);
return len;
};
static int write_string(const char * cstr) {
if (NULL == cstr) {
static const char s[] = "NULL";
write(STDOUT_FILENO, s, sizeof(s) - 1);
return sizeof(s) - 1;
};
const char * p = cstr;
for (;;) { if (*p == '\0') break; p++; };
const int len = p - cstr;
write(STDOUT_FILENO, cstr, len);
return len;
};
static int write_string_ln(const char * cstr) {
if (NULL == cstr) {
static const char s[] = "NULL" "\n";
write(STDOUT_FILENO, s, sizeof(s) - 1);
return sizeof(s);
};
const char * p = cstr;
for (;;) { if (*p == '\0') break; p++; };
const int len = p - cstr;
write(STDOUT_FILENO, cstr, len);
write(STDOUT_FILENO, "\n", 1);
return len + 1;
};
static int write_eol(void) {
write(STDOUT_FILENO, "\n", 1);
return 1;
};
static char tab_2hex[2] = {};
static void tab_2hex__bzero(void) {
tab_2hex[0] = '0';
tab_2hex[1] = '0';
};
#define CHAR_TO_DIGIT(__c__) ( \
((__c__) >= '0' && (__c__) <= '9') ? (__c__) - '0' : \
((__c__) >= 'A' && (__c__) <= 'F') ? (__c__) - 'A' + 10 : \
((__c__) >= 'a' && (__c__) <= 'f') ? (__c__) - 'a' + 10 : \
'?')
static unsigned char tab_2hex__convert(const int len) {
unsigned char n = 0;
if (len >= 2) { const int m = CHAR_TO_DIGIT(tab_2hex[1]); n += m; };
if (len >= 1) { const int m = CHAR_TO_DIGIT(tab_2hex[0]); n += (m << ((len - 1) << 2)); };
return n;
};
int main(const int argc, const char * argv[]) {
static unsigned char c;
static ssize_t read_nb;
static int tab_2hex_i;
for (;;) {
tab_2hex__bzero();
tab_2hex_i = -1;
for (;;) {
tab_2hex_i++;
if (2 == tab_2hex_i) break;
read_nb = read(STDIN_FILENO, &c, 1);
if (1 != read_nb) { break; };
const int in_range_huh = (c >= '0') && (c <= '1');
if (!in_range_huh) break;
tab_2hex[tab_2hex_i] = c;
};
if (tab_2hex_i > 0) {
const unsigned char u = tab_2hex__convert(tab_2hex_i);
write(STDOUT_FILENO, &u, 1);
};
if ( 0 == read_nb) { return 0; };
if (-1 == read_nb) { return -1; };
if ( 1 != read_nb) { return -2; };
};
return 0;
};
|
the_stack_data/19280.c | /*
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)div.c 8.1 (Berkeley) 6/4/93
* $FreeBSD: src/lib/libc/stdlib/div.c,v 1.3 2007/01/09 00:28:09 imp Exp $
* $DragonFly: src/lib/libc/stdlib/div.c,v 1.3 2005/11/20 12:37:48 swildner Exp $
*/
#include <stdlib.h> /* div_t */
div_t
div(int num, int denom)
{
div_t r;
r.quot = num / denom;
r.rem = num % denom;
/*
* The ANSI standard says that |r.quot| <= |n/d|, where
* n/d is to be computed in infinite precision. In other
* words, we should always truncate the quotient towards
* 0, never -infinity.
*
* Machine division and remainer may work either way when
* one or both of n or d is negative. If only one is
* negative and r.quot has been truncated towards -inf,
* r.rem will have the same sign as denom and the opposite
* sign of num; if both are negative and r.quot has been
* truncated towards -inf, r.rem will be positive (will
* have the opposite sign of num). These are considered
* `wrong'.
*
* If both are num and denom are positive, r will always
* be positive.
*
* This all boils down to:
* if num >= 0, but r.rem < 0, we got the wrong answer.
* In that case, to get the right answer, add 1 to r.quot and
* subtract denom from r.rem.
*/
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}
|
the_stack_data/136077.c | #include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]){
clock_t start, end;
start = clock();
char *ptr = malloc(1000000);
for (int i = 0; i < 1000000; i++) {
ptr[i] = i;
}
for (int i = 0; i < 1000000; i++) {
if ((i+1) % 4096) {
printf("");
}
}
end = clock();
double time_taken = ((double)start)/CLOCKS_PER_SEC; // in seconds
printf("took %f seconds to execute \n", time_taken);
}
|
the_stack_data/150144364.c | #include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
long long *ptr = calloc(MAX, sizeof(long long));
for (int i = 0; i < MAX; i++)
*ptr++ = 0;
for (int i = 0; i < MAX; i++)
--ptr;
++ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
while (*ptr) {
--ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++*ptr;
++ptr;
--*ptr;
}
++*ptr;
++ptr;
++*ptr;
--ptr;
--ptr;
while (*ptr) {
++ptr;
printf("%lld\n", *ptr);
++ptr;
while (*ptr) {
++ptr;
++*ptr;
--ptr;
--*ptr;
}
--ptr;
while (*ptr) {
++ptr;
++*ptr;
--ptr;
--*ptr;
}
++ptr;
++ptr;
while (*ptr) {
--ptr;
++*ptr;
--ptr;
++*ptr;
++ptr;
++ptr;
--*ptr;
}
--ptr;
--ptr;
--ptr;
--*ptr;
}
} |
the_stack_data/212644363.c | /* complex expressions with redundant side effects */
void foo(int j)
{
j++;
}
void assign04()
{
int i;
// This assignment works fine with transformers
i = (i = 2) + 1;
// Go around the problem with user_call_to_transformer()
foo( i = (i = 2) + 1);
// As in:
i = (i = 2) + 1;
foo(i);
}
|
the_stack_data/499068.c | #ifdef STM32F4xx
#include "stm32f4xx_hal_fmpi2c.c"
#endif
|
the_stack_data/18108.c | #include <stdio.h>
#include <stdlib.h>
long get_gcd_euclidian(long d1, long d2)
{
/* swap the numbers if d2 is greater than d1 */
if(d2 > d1)
{
d1 = d1 - d2;
d2 = d1 + d2;
d1 = d2 - d1;
}
if(d2 == 0)
{
return d1;
}
long rem = d1 % d2;
return get_gcd_euclidian(d2, rem);
}
long get_lcm_euclidian(long val1, long val2)
{
if(val1 == 0 || val2 == 0)
{
return 0;
}
long prod = (long)(val1 * val2);
long gcd = get_gcd_euclidian(val1, val2);
return (prod / gcd);
}
int main(void)
{
long ip1 = 0;
long ip2 = 0;
printf("Enter two numbers: ");
scanf("%ld %ld", &ip1, &ip2);
printf("LCM is %ld\n", get_lcm_euclidian(ip1, ip2));
return 0;
}
|
the_stack_data/14200666.c | int MAIN()
{
int i, num1;
int result = 0;
write("enter a integer");
num1 = read();
for (i = 0; i < num1; i = i + 1)
{
result = result + i;
}
write(result);
write("\n");
return 0;
}
|
the_stack_data/98575585.c | /* test error message: __RCRS__ may not have arguments */
#undef __RCRS__
#define __RCRS__(a) 3
|
the_stack_data/822323.c | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char *devname = "/dev/time_judge";
int fd;
unsigned char key;
fd = open(devname, O_RDWR);
while(1)
{
read(fd, &key, sizeof(key));
if(key)
printf("the key = %d\n",key);
key = 0;
}
close(fd);
}
|
the_stack_data/30658.c | /* $NetBSD: Lint_bcmp.c,v 1.1.2.1 1997/11/08 22:00:58 veego Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <string.h>
/*ARGSUSED*/
int
bcmp(b1, b2, len)
const void *b1, *b2;
size_t len;
{
return (0);
}
|
the_stack_data/903406.c | // Copyright 2019 King's College London.
// Created by the Software Development Team <http://soft-dev.org/>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME Software tracing is currently broken.
//
// a) mir_loc below (which should really be called *sir*_loc anyway) uses the
// old notion of a location (crate hash, def index, bb index), whereas when
// we moved SIR to the codegen it changed (symbol name, bb idx). This causes
// undefined behaviour.
//
// b) The code which inserts calls to the trace recorder operates at the wrong
// level. Instead of being a MIR pass, it should operate at the LLVM-level.
// Put differently, we should record which *LLVM* blocks we pass through,
// not which *MIR* blocks.
#include <stdint.h>
#include <stdlib.h>
#include <err.h>
#include <stdbool.h>
struct mir_loc {
uint64_t crate_hash;
uint32_t def_idx;
uint32_t bb_idx;
};
#define TL_TRACE_INIT_CAP 1024
#define TL_TRACE_REALLOC_CAP 1024
void yk_swt_start_tracing_impl(void);
void yk_swt_rec_loc_impl(uint64_t crate_hash, uint32_t def_idx, uint32_t bb_idx);
struct mir_loc *yk_swt_stop_tracing_impl(size_t *ret_trace_len);
// The trace buffer.
static __thread struct mir_loc *trace_buf = NULL;
// The number of elements in the trace buffer.
static __thread size_t trace_buf_len = 0;
// The allocation capacity of the trace buffer (in elements).
static __thread size_t trace_buf_cap = 0;
// Is the current thread tracing?
// true = we are tracing, false = we are not tracing or an error occurred.
static __thread bool tracing = false;
// Start tracing on the current thread.
// A new trace buffer is allocated and MIR locations will be written into it on
// subsequent calls to `yk_swt_rec_loc_impl`. If the current thread is already
// tracing, calling this will lead to undefined behaviour.
void
yk_swt_start_tracing_impl(void) {
trace_buf = calloc(TL_TRACE_INIT_CAP, sizeof(struct mir_loc));
if (trace_buf == NULL) {
err(EXIT_FAILURE, "%s: calloc: ", __func__);
}
trace_buf_cap = TL_TRACE_INIT_CAP;
tracing = true;
}
// Record a location into the trace buffer if tracing is enabled on the current thread.
void
yk_swt_rec_loc_impl(uint64_t crate_hash, uint32_t def_idx, uint32_t bb_idx)
{
if (!tracing) {
return;
}
// Check if we need more space and reallocate if necessary.
if (trace_buf_len == trace_buf_cap) {
if (trace_buf_cap >= SIZE_MAX - TL_TRACE_REALLOC_CAP) {
// Trace capacity would overflow.
tracing = false;
return;
}
size_t new_cap = trace_buf_cap + TL_TRACE_REALLOC_CAP;
if (new_cap > SIZE_MAX / sizeof(struct mir_loc)) {
// New buffer size would overflow.
tracing = false;
return;
}
size_t new_size = new_cap * sizeof(struct mir_loc);
trace_buf = realloc(trace_buf, new_size);
if (trace_buf == NULL) {
tracing = false;
return;
}
trace_buf_cap = new_cap;
}
struct mir_loc loc = { crate_hash, def_idx, bb_idx };
trace_buf[trace_buf_len] = loc;
trace_buf_len ++;
}
// Stop tracing on the current thread.
// On success the trace buffer is returned and the number of locations it
// holds is written to `*ret_trace_len`. It is the responsibility of the caller
// to free the returned trace buffer. A NULL pointer is returned on error.
// Calling this function when tracing was not started with
// `yk_swt_start_tracing_impl()` results in undefined behaviour.
struct mir_loc *
yk_swt_stop_tracing_impl(size_t *ret_trace_len) {
if (!tracing) {
free(trace_buf);
trace_buf = NULL;
trace_buf_len = 0;
}
// We hand ownership of the trace to Rust now. Rust is responsible for
// freeing the trace.
struct mir_loc *ret_trace = trace_buf;
*ret_trace_len = trace_buf_len;
// Now reset all off the recorder's state.
trace_buf = NULL;
tracing = false;
trace_buf_len = 0;
trace_buf_cap = 0;
return ret_trace;
}
|
the_stack_data/399775.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <time.h>
#define DEFAULT_M 16
#define DEFAULT_N 16
#define DEBUG 0
#define SHOWRESULT 1
#define CHECKPRECI 1e-8
void initRand( int, int, double[][*] );
void initZero( int, int, double[][*] );
void initUnit( int, int, double[][*] );
void transpose( int, int, double[][*] );
double getnorm( int, double[] );
double getsign( double ) ;
void normalize( int, double, double[] );
void printMatrix( int, int, double[][*] );
void printMatrixOctave( int, int, double[][*] );
void matmul( int, int, int, double[][*], double[][*], double[][*] );
bool check( int, int, double[][*], double[][*], double[][*] );
double getTime( void );
void printPerf( int, int, double );
void householder( int, int, double[][*], double[][*], double [][*] );
int main( int argc, char** argv ){
int M, N;
double time_start, time_end;
/* Init */
if( argc < 3 ) {
M = DEFAULT_M;
N = DEFAULT_N;
} else {
M = atoi( argv[1] );
N = atoi( argv[2] );
}
double A[M][N], R[N][N], Q[M][N];
initRand( M, N, A );
/* Here comes the fun */
time_start = getTime();
householder( M, N, A, Q, R );
time_end = getTime();
printPerf( M, N, (time_end - time_start ) );
/* Checks */
#if SHOWRESULT
printf( "R \n" );
printMatrix( N, N, R );
printf( "Q \n" );
printMatrix( M, N, Q );
#endif
/* Checks: A ?= QR and orthogonality of Q */
if( true == check( M, N, A, Q, R ) ){
printf( "[PASS]\n" );
} else {
printf( "[FAIL]\n" );
}
#if DEBUG
printf( "Initial matrix:\n" );
printMatrix( M, N, A );
printf( "Result check: QR = A\n" );
// memset( A, (char)0, M*N*sizeof( double ));
for( int i = 0 ; i < M ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
A[i][j] = 0.0;
}
}
matmul( M, N, N, A, Q, R );
printMatrix( M, N, A );
printf( "Unitarity check: Q*Q' = Q'*Q = I\n" );
// memset( R, (char)0, M*N*sizeof( double ));
for( int i = 0 ; i < N ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
R[i][j] = 0.0;
}
}
// memcpy( A, Q, M*N*sizeof( double ));
for( int i = 0 ; i < M ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
A[i][j] = Q[i][j];
}
}
transpose( M, N, A );
matmul( M, N, N, R, Q, A );
printMatrix( M, N, R );
#endif
return EXIT_SUCCESS;
}
void initRand( int lines, int col, double mat[ lines ][ col ] ){
int i, j;
srand( 0 );
for( i = 0 ; i < lines ; i++ ) {
for( j = 0 ; j < col ; j++ ) {
mat[i][j] = (double) rand() / ( (double) RAND_MAX + 1.0 );
}
}
}
double getTime(){
struct timespec tv;
clock_gettime( CLOCK_MONOTONIC, &tv );
return ( tv.tv_nsec + tv.tv_sec*1e9 );
}
void printPerf( int M, int N, double time ) {
double flops = 2.0 * (double) M * (double) N * (double) N / 3.0;
time *= 1e-3;
printf( "%d \t %d \t %.0lf usec \t %.3lf Mflops\n", M, N, time, flops / time );
}
void printMatrix( int M, int N, double mat[M][N] ){
int i, j;
printf( "-------------------------------------\n" );
for( i = 0 ; i < M ; i++ ){
for( j = 0 ; j < N ; j++ ){
printf( "%.2lf \t ", mat[ i ][ j ] );
}
printf( "\n" );
}
printf( "-------------------------------------\n" );
}
void printMatrixOctave( int M, int N, double mat[M][N] ){
int i, j;
printf( "-------------------------------------\n" );
printf( "[ " );
for( i = 0 ; i < M ; i++ ){
printf( "[ " );
for( j = 0 ; j < N ; j++ ){
printf( "%.2lf, ", mat[ i ][ j ] );
}
printf( " ];" );
}
printf( "]\n" );
printf( "-------------------------------------\n" );
}
bool isEqual( int M, int N, double A[M][N], double B[M][N] ) {
int i, j;
bool eq = true;
for( i = 0 ; i < M ; i++ ) {
for( j = 0 ; j < N ; j++ ) {
if( fabs( B[i][j] - A[i][j] ) > CHECKPRECI ) {
eq = false;
}
}
}
return eq;
}
bool checkCorrect( int M, int N, double A[M][N], double Q[M][N], double R[N][N] ) {
bool eq = true;
/* We want QR == A */
double tmp[M][N];
// memset( tmp, (char)0, M*N*sizeof( double ) );
for( int i = 0 ; i < N ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
tmp[i][j] = 0.0;
}
}
matmul( M, N, N, tmp, Q, R );
eq = isEqual( M, N, tmp, A );
return eq;
}
bool checkUnitary( int M, int N, double Q[M][N] ) {
double tmp[M][N];
double res[M][M];
double I[M][M];
/* We want Q*Q' = Q'*Q = I */
initUnit( M, M, I );
// memset( res, (char)0, M*N*sizeof( double ) );
for( int i = 0 ; i < N ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
res[i][j] = 0.0;
}
}
// memcpy( tmp, Q, M*N*sizeof( double ));
for( int i = 0 ; i < M ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
tmp[i][j] = Q[i][j];
}
}
transpose( M, N, tmp );
matmul( M, N, N, res, Q, tmp );
if( false == isEqual( M, M, I, res ) )
return false;
// memset( res, (char)0, M*N*sizeof( double ) );
for( int i = 0 ; i < N ; i++ ) {
for( int j = 0 ; j < N ; j++ ) {
res[i][j] = 0.0;
}
}
matmul( M, N, N, res, tmp, Q );
if( false == isEqual( M, M, I, res ) )
return false;
return true;
}
bool check( int M, int N, double A[M][N], double Q[M][N], double R[N][N] ) {
if( false == checkCorrect( M, N, A, Q, R ) ) {
printf( "Incorrect result: A != QR (recision requested: %e)\n", CHECKPRECI );
return false;
}
if( false == checkUnitary( M, N, Q ) ) {
printf( "Incorrect result: Q is not unitary (recision requested: %e)\n", CHECKPRECI );
return false;
}
return true;
}
|
the_stack_data/76700926.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: /* assert not proved */
/* assert not proved */
__VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { /* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
/* reachable */
__VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include "assert.h"
#include "pthread.h"
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void * P3(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p1_EAX;
int __unbuffered_p1_EAX = 0;
int __unbuffered_p2_EAX;
int __unbuffered_p2_EAX = 0;
int __unbuffered_p3_EAX;
int __unbuffered_p3_EAX = 0;
int __unbuffered_p3_EBX;
int __unbuffered_p3_EBX = 0;
int a;
int a = 0;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
_Bool x$flush_delayed;
int x$mem_tmp;
_Bool x$r_buff0_thd0;
_Bool x$r_buff0_thd1;
_Bool x$r_buff0_thd2;
_Bool x$r_buff0_thd3;
_Bool x$r_buff0_thd4;
_Bool x$r_buff1_thd0;
_Bool x$r_buff1_thd1;
_Bool x$r_buff1_thd2;
_Bool x$r_buff1_thd3;
_Bool x$r_buff1_thd4;
_Bool x$read_delayed;
int *x$read_delayed_var;
int x$w_buff0;
_Bool x$w_buff0_used;
int x$w_buff1;
_Bool x$w_buff1_used;
int y;
int y = 0;
int z;
int z = 0;
_Bool weak$$choice0;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
a = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd1 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$w_buff1_used;
x$r_buff0_thd1 = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1;
x$r_buff1_thd1 = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
x$w_buff1 = x$w_buff0;
x$w_buff0 = 2;
x$w_buff1_used = x$w_buff0_used;
x$w_buff0_used = TRUE;
__VERIFIER_assert(!(x$w_buff1_used && x$w_buff0_used));
x$r_buff1_thd0 = x$r_buff0_thd0;
x$r_buff1_thd1 = x$r_buff0_thd1;
x$r_buff1_thd2 = x$r_buff0_thd2;
x$r_buff1_thd3 = x$r_buff0_thd3;
x$r_buff1_thd4 = x$r_buff0_thd4;
x$r_buff0_thd2 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p1_EAX = y;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used;
x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2;
x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p2_EAX = z;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd3 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$w_buff1_used;
x$r_buff0_thd3 = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$r_buff0_thd3;
x$r_buff1_thd3 = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P3(void *arg)
{
__VERIFIER_atomic_begin();
z = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p3_EAX = z;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p3_EBX = a;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd4 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd4 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd4 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd4 || x$w_buff1_used && x$r_buff1_thd4 ? FALSE : x$w_buff1_used;
x$r_buff0_thd4 = x$w_buff0_used && x$r_buff0_thd4 ? FALSE : x$r_buff0_thd4;
x$r_buff1_thd4 = x$w_buff0_used && x$r_buff0_thd4 || x$w_buff1_used && x$r_buff1_thd4 ? FALSE : x$r_buff1_thd4;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
pthread_create(NULL, NULL, P3, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 4;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used;
x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0;
x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice0 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
weak$$choice2 = nondet_1();
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = weak$$choice2;
/* Program proven to be relaxed for X86, model checker says YES. */
x$mem_tmp = x;
/* Program proven to be relaxed for X86, model checker says YES. */
x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1);
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used));
/* Program proven to be relaxed for X86, model checker says YES. */
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0));
/* Program proven to be relaxed for X86, model checker says YES. */
x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program proven to be relaxed for X86, model checker says YES. */
main$tmp_guard1 = !(x == 2 && __unbuffered_p1_EAX == 0 && __unbuffered_p2_EAX == 0 && __unbuffered_p3_EAX == 1 && __unbuffered_p3_EBX == 0);
/* Program proven to be relaxed for X86, model checker says YES. */
x = x$flush_delayed ? x$mem_tmp : x;
/* Program proven to be relaxed for X86, model checker says YES. */
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
/* Program proven to be relaxed for X86, model checker says YES. */
__VERIFIER_assert(main$tmp_guard1);
/* reachable */
return 0;
}
|
the_stack_data/139061.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <event.h>
#include <evhttp.h>
/**
* Creates a generic channel name
*/
char *
channel_make_name() {
char *out = calloc(21, 1);
snprintf(out, 20, "chan-%d", rand());
return out;
}
struct host_info {
char *host;
short port;
};
/* reader thread, with counter of remaining messages */
struct reader_thread {
struct host_info *hi;
int reader_per_chan;
struct event_base *base;
char **channels;
int channel_count;
int request_count;
int byte_count;
};
struct writer_thread {
struct host_info *hi;
int writer_per_chan;
struct event_base *base;
char **channels;
int channel_count;
int byte_count;
unsigned int current_channel;
char *url;
};
/* readers */
void
process_message(struct reader_thread *rt, size_t sz) {
if(rt->request_count == 0) {
return;
}
rt->byte_count += sz;
if(rt->request_count % 10000 == 0) {
printf("%8d messages left (got %9d bytes so far).\n",
rt->request_count, rt->byte_count);
}
/* decrement read count, and stop receiving when we reach zero. */
rt->request_count--;
if(rt->request_count == 0) {
event_base_loopexit(rt->base, NULL);
}
}
/**
* Called when a message is sent on the HTTP channel pipe.
*/
void
on_http_message_chunk(struct evhttp_request *req, void *ptr) {
struct reader_thread *rt = ptr;
if(req->response_code == HTTP_OK) {
size_t sz = EVBUFFER_LENGTH(req->input_buffer);
process_message(rt, sz);
} else {
fprintf(stderr, "CHUNK FAIL (ret=%d)\n", req->response_code);
}
}
/**
* Called when a channel pipe is closed.
*/
void
on_end_of_subscribe(struct evhttp_request *req, void *nil){
(void)nil;
if(!req || req->response_code != HTTP_OK) {
/* fprintf(stderr, "subscribe FAIL (response_code=%d)\n", req->response_code); */
}
printf("end of subscribe\n");
}
/**
* pthread entry point, running the reader event base.
*/
void *
comet_run_readers(void *ptr) {
struct reader_thread *rt = ptr;
int i, j;
rt->base = event_base_new();
for(i = 0; i < rt->channel_count; ++i) {
char *chan = rt->channels[i];
char *url = calloc(strlen(chan) + 17, 1);
sprintf(url, "/subscribe?name=%s", chan);
for(j = 0; j < rt->reader_per_chan; ++j) {
struct evhttp_connection *evcon = evhttp_connection_new(rt->hi->host, rt->hi->port);
struct evhttp_request *evreq = evhttp_request_new(on_end_of_subscribe, rt);
evhttp_connection_set_base(evcon, rt->base);
evhttp_request_set_chunked_cb(evreq, on_http_message_chunk);
evhttp_make_request(evcon, evreq, EVHTTP_REQ_GET, url);
/* printf("[SUBSCRIBE: http://127.0.0.1:1234%s]\n", url); */
}
}
event_base_dispatch(rt->base);
return NULL;
}
/* writers */
void
publish(struct writer_thread *wt, const char *url);
/**
* Called after a publish query has returned.
*/
void
on_end_of_publish(struct evhttp_request *req, void *ptr){
(void)req;
struct writer_thread *wt = ptr;
/* enqueue another publication */
wt->current_channel++;
char *channel = wt->channels[wt->current_channel % wt->channel_count];
char template[] = "/publish?name=%s&data=hello-world";
char *url = calloc(strlen(channel) + sizeof(template), 1);
sprintf(url, template, channel);
publish(wt, url);
}
/**
* Enqueue an HTTP request to /publish in the writer thread's event base.
*/
void
publish(struct writer_thread *wt, const char *url) {
struct evhttp_connection *evcon = evhttp_connection_new(wt->hi->host, wt->hi->port);
struct evhttp_request *evreq = evhttp_request_new(on_end_of_publish, wt);
evhttp_connection_set_base(evcon, wt->base);
evhttp_make_request(evcon, evreq, EVHTTP_REQ_GET, url);
// printf("[PUBLISH: http://127.0.0.1:1234%s] : ret=%d\n", url, ret);
}
/**
* pthread entry point, running the writer event base.
*/
void *
comet_run_writers(void *ptr) {
int i, j;
struct writer_thread *wt = ptr;
wt->base = event_base_new();
for(i = 0; i < wt->channel_count; ++i) {
char template[] = "/publish?name=%s&data=hello-world";
char *url = calloc(strlen(wt->channels[i]) + sizeof(template), 1);
sprintf(url, template, wt->channels[i]);
for(j = 0; j < wt->writer_per_chan; ++j) {
publish(wt, url);
}
}
event_base_dispatch(wt->base);
free(wt->url);
return NULL;
}
int
main(int argc, char *argv[]) {
(void)argc;
(void)argv;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
srand(time(NULL));
int reader_per_chan = 400;
int writer_per_chan = 40;
int request_count = 1000000;
int channel_count = 2;
int i;
char **channels = calloc(channel_count, sizeof(char*));
for(i = 0; i < channel_count; ++i) {
channels[i] = channel_make_name();
}
struct host_info hi;
hi.host = "127.0.0.1";
hi.port = 9271;
printf("Using %d channels.\n", channel_count);
/* run readers */
printf("Running %d readers (%d per chan).\n", reader_per_chan * channel_count, reader_per_chan);
pthread_t reader_thread;
struct reader_thread rt;
rt.channels = channels;
rt.channel_count = channel_count;
rt.hi = &hi;
rt.reader_per_chan = reader_per_chan;
rt.request_count = request_count;
rt.byte_count = 0;
pthread_create(&reader_thread, NULL, comet_run_readers, &rt);
/* run writers */
printf("Running %d writers (%d per chan).\n", writer_per_chan * channel_count, writer_per_chan);
pthread_t writer_thread;
struct writer_thread wt;
wt.channels = channels;
wt.channel_count = channel_count;
wt.hi = &hi;
wt.writer_per_chan = writer_per_chan;
pthread_create(&writer_thread, NULL, comet_run_writers, &wt);
/* wait for readers to finish */
pthread_join(reader_thread, NULL);
/* timing */
clock_gettime(CLOCK_MONOTONIC, &t1);
float mili0 = t0.tv_sec * 1000 + t0.tv_nsec / 1000000;
float mili1 = t1.tv_sec * 1000 + t1.tv_nsec / 1000000;
printf("Read %d messages in %0.2f sec: %0.2f/sec\n", request_count, (mili1-mili0)/1000.0, 1000*(float)request_count/(mili1-mili0));
for(i = 0; i < channel_count; ++i) {
free(channels[i]);
}
free(channels);
return EXIT_SUCCESS;
}
|
the_stack_data/16296.c | /*
* $Xorg: WA8.c,v 1.4 2001/02/09 02:03:48 xorgcvs Exp $
*
*
Copyright 1989, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
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
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
* *
* Author: Keith Packard, MIT X Consortium
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <X11/Xos.h>
#include <X11/X.h>
#include <X11/Xmd.h>
#include <X11/Xdmcp.h>
int
XdmcpWriteARRAY8 (buffer, array)
XdmcpBufferPtr buffer;
ARRAY8Ptr array;
{
int i;
if (!XdmcpWriteCARD16 (buffer, array->length))
return FALSE;
for (i = 0; i < (int)array->length; i++)
if (!XdmcpWriteCARD8 (buffer, array->data[i]))
return FALSE;
return TRUE;
}
|
the_stack_data/95450069.c | #include <stdio.h>
void command(int a){
printf("geez");
};
|
the_stack_data/32950592.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 32
int numberOfDigits(const char * line);
int main() {
char line[MAX];
scanf("%[^\n]s", line);
getchar();
puts(line);
printf("%d\n", numberOfDigits(line));
return 0;
}
int numberOfDigits(const char * line) {
const int length = strlen(line);
int digits = 0;
for (int i = 0; i < length; i++) {
if (i % 3 == 0) {
digits++;
}
}
return digits;
} |
the_stack_data/718059.c | #include <stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {
printf("%c ", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
} |
the_stack_data/73576385.c | #include <sys/types.h>
#include <stdint.h>
#include <stddef.h>
#undef KEY
#if defined(__i386)
# define KEY '_','_','i','3','8','6'
#elif defined(__x86_64)
# define KEY '_','_','x','8','6','_','6','4'
#elif defined(__ppc__)
# define KEY '_','_','p','p','c','_','_'
#elif defined(__ppc64__)
# define KEY '_','_','p','p','c','6','4','_','_'
#elif defined(__aarch64__)
# define KEY '_','_','a','a','r','c','h','6','4','_','_'
#elif defined(__ARM_ARCH_7A__)
# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','A','_','_'
#elif defined(__ARM_ARCH_7S__)
# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','S','_','_'
#endif
#define SIZE (sizeof(off_t))
char info_size[] = {'I', 'N', 'F', 'O', ':', 's','i','z','e','[',
('0' + ((SIZE / 10000)%10)),
('0' + ((SIZE / 1000)%10)),
('0' + ((SIZE / 100)%10)),
('0' + ((SIZE / 10)%10)),
('0' + (SIZE % 10)),
']',
#ifdef KEY
' ','k','e','y','[', KEY, ']',
#endif
'\0'};
#ifdef __CLASSIC_C__
int main(argc, argv) int argc; char *argv[];
#else
int main(int argc, char *argv[])
#endif
{
int require = 0;
require += info_size[argc];
(void)argv;
return require;
}
|
the_stack_data/61998.c | /*
* CS:APP Data Lab
*
* <Please put your name and userid here>
*
* bits.c - Source file with your solutions to the Lab.
* This is the file you will hand in to your instructor.
*
* WARNING: Do not include the <stdio.h> header; it confuses the dlc
* compiler. You can still use printf for debugging without including
* <stdio.h>, although you might get a compiler warning. In general,
* it's not good practice to ignore compiler warnings, but in this
* case it's OK.
*/
#if 0
/*
* Instructions to Students:
*
* STEP 1: Read the following instructions carefully.
*/
You will provide your solution to the Data Lab by
editing the collection of functions in this source file.
INTEGER CODING RULES:
Replace the "return" statement in each function with one
or more lines of C code that implements the function. Your code
must conform to the following style:
int Funct(arg1, arg2, ...) {
/* brief description of how your implementation works */
int var1 = Expr1;
...
int varM = ExprM;
varJ = ExprJ;
...
varN = ExprN;
return ExprR;
}
Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xffffffff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>
Some of the problems restrict the set of allowed operators even further.
Each "Expr" may consist of multiple operators. You are not restricted to
one operator per line.
You are expressly forbidden to:
1. Use any control constructs such as if, do, while, for, switch, etc.
2. Define or use any macros.
3. Define any additional functions in this file.
4. Call any functions.
5. Use any other operations, such as &&, ||, -, or ?:
6. Use any form of casting.
7. Use any data type other than int. This implies that you
cannot use arrays, structs, or unions.
You may assume that your machine:
1. Uses 2s complement, 32-bit representations of integers.
2. Performs right shifts arithmetically.
3. Has unpredictable behavior when shifting an integer by more
than the word size.
EXAMPLES OF ACCEPTABLE CODING STYLE:
/*
* pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
*/
int pow2plus1(int x) {
/* exploit ability of shifts to compute powers of 2 */
return (1 << x) + 1;
}
/*
* pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
*/
int pow2plus4(int x) {
/* exploit ability of shifts to compute powers of 2 */
int result = (1 << x);
result += 4;
return result;
}
FLOATING POINT CODING RULES
For the problems that require you to implent floating-point operations,
the coding rules are less strict. You are allowed to use looping and
conditional control. You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants.
You are expressly forbidden to:
1. Define or use any macros.
2. Define any additional functions in this file.
3. Call any functions.
4. Use any form of casting.
5. Use any data type other than int or unsigned. This means that you
cannot use arrays, structs, or unions.
6. Use any floating point data types, operations, or constants.
NOTES:
1. Use the dlc (data lab checker) compiler (described in the handout) to
check the legality of your solutions.
2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
that you are allowed to use for your implementation of the function.
The max operator count is checked by dlc. Note that '=' is not
counted; you may use as many of these as you want without penalty.
3. Use the btest test harness to check your functions for correctness.
4. Use the BDD checker to formally verify your functions
5. The maximum number of ops for each function is given in the
header comment for each function. If there are any inconsistencies
between the maximum ops in the writeup and in this file, consider
this file the authoritative source.
/*
* STEP 2: Modify the following functions according the coding rules.
*
* IMPORTANT. TO AVOID GRADING SURPRISES:
* 1. Use the dlc compiler to check that your solutions conform
* to the coding rules.
* 2. Use the BDD checker to formally verify that your solutions produce
* the correct answers.
*/
#endif
/*
* copyLSB - set all bits of result to least significant bit of x
* Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int copyLSB(int x) {
return x << 31 >> 31;
}
/*
* conditional - same as x ? y : z
* Example: conditional(2,4,5) = 4
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 3
*/
int conditional(int x, int y, int z) {
int a = (!x) << 31 >> 31;
return (a & (y ^ z)) ^ y;
}
/*
* allEvenBits - return 1 if all even-numbered bits in word set to 1
* Examples allEvenBits(0xFFFFFFFE) = 0, allEvenBits(0x55555555) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
int allEvenBits(int x) {
int t = 0x55;
t |= t << 8;
t |= t << 16;
return !((x & t) ^ t);
}
/*
* implication - return x -> y in propositional logic - 0 for false, 1
* for true
* Example: implication(1,1) = 1
* implication(1,0) = 0
* Legal ops: ! ~ ^ |
* Max ops: 5
* Rating: 2
*/
int implication(int x, int y) {
return (!x) | y;
}
/*
* replaceByte(x,n,c) - Replace byte n in x with c
* Bytes numbered from 0 (LSB) to 3 (MSB)
* Examples: replaceByte(0x12345678,1,0xab) = 0x1234ab78
* You can assume 0 <= n <= 3 and 0 <= c <= 255
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 10
* Rating: 3
*/
int replaceByte(int x, int n, int c) {
n = n << 3;
return (x & ~(0xFF << n)) ^ (c << n);
}
/*
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 1 << 31;
}
/*
* minusOne - return a value of -1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 2
* Rating: 1
*/
int minusOne(void) {
return ~0;
}
/*
* isGreater - if x > y then return 1, else return 0
* Example: isGreater(4,5) = 0, isGreater(5,4) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
* Rating: 3
*/
int isGreater(int x, int y) {
return ((x + ~(((x ^ y) >> 31) | y)) >> 31) + 1;
}
/*
* isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
* Example: isAsciiDigit(0x35) = 1.
* isAsciiDigit(0x3a) = 0.
* isAsciiDigit(0x05) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 3
*/
int isAsciiDigit(int x) {
return (0x1F << 24 >> (x >> 1)) & !(x >> 6);
}
/* howManyBits - return the minimum number of bits required to represent x in
* two's complement
* Examples: howManyBits(12) = 5
* howManyBits(298) = 10
* howManyBits(-5) = 4
* howManyBits(0) = 1
* howManyBits(-1) = 1
* howManyBits(0x80000000) = 32
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 90
* Rating: 4
*/
int howManyBits(int x) {
int ans;
x = x ^ (x << 1);
ans = (!(x >> 16)) << 4;
ans ^= 24;
ans ^= (!(x >> ans)) << 3;
ans ^= 4;
ans ^= (!(x >> ans)) << 2;
ans += ((~0x5B) >> ((x >> ans) & 30)) & 3;
return ans + 1;
}
/*
* greatestBitPos - return a mask that marks the position of the
* most significant 1 bit. If x == 0, return 0
* Example: greatestBitPos(96) = 0x40
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 70
* Rating: 4
*/
int greatestBitPos(int x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ((~x >> 1) | (1 << 31)) & x;
}
/*
* satMul3 - multiplies by 3, saturating to Tmin or Tmax if overflow
* Examples: satMul3(0x10000000) = 0x30000000
* satMul3(0x30000000) = 0x7FFFFFFF (Saturate to TMax)
* satMul3(0x70000000) = 0x7FFFFFFF (Saturate to TMax)
* satMul3(0xD0000000) = 0x80000000 (Saturate to TMin)
* satMul3(0xA0000000) = 0x80000000 (Saturate to TMin)
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 25
* Rating: 3
*/
int satMul3(int x) {
int x2, x3;
int k;
x2 = x + x;
x3 = x2 + x;
k = (((x3 ^ x) | (x2 ^ x)) >> 31);
return (k | x3) ^ (((x >> 31) ^ (1 << 31)) & k);
}
/*
* subOK - Determine if can compute x-y without overflow
* Example: subOK(0x80000000,0x80000000) = 1,
* subOK(0x80000000,0x70000000) = 0,
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int subOK(int x, int y) {
int z = y + (~x);
return (((x ^ y) & (y ^ z)) >> 31) + 1;
}
/*
* float_neg - Return bit-level equivalent of expression -f for
* floating point argument f.
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representations of
* single-precision floating point values.
* When argument is NaN, return argument.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 10
* Rating: 2
*/
unsigned float_neg(unsigned uf) {
if ((uf & 0x7FFFFFFF) > 0x7F800000) {
return uf;
}
return uf ^ 0x80000000;
}
/*
* float_i2f - Return bit-level equivalent of expression (float) x
* Result is returned as unsigned int, but
* it is to be interpreted as the bit-level representation of a
* single-precision floating point values.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_i2f(int x) {
unsigned ux = x;
unsigned signexp = 0x4E800000;
int flag = 0;
int round = 0;
if (x) {
while (1) {
if (ux & 0x80000000) {
if (flag)
break;
else {
ux = -x;
signexp = 0xCE800000;
}
} else {
ux <<= 1;
signexp -= 0x800000;
}
flag = 1;
}
if (ux & 0x80)
if (ux & 0x17F)
round = 1;
return signexp + (ux >> 8) + round;
} else
return 0;
}
|
the_stack_data/145452000.c | /*
* Test the speed of GPIO's on a Raspberry Pi using direct hardware access
* (mem map).
*
* Note that RPi1 and RPi2 has different address and you need to add/remove
* the correct define.
*
* Original code is an example from http://elinux.org/RPi_GPIO_Code_Samples
*
* Uses GPIO 21
*/
// Use this for RPi1
//#define BCM2708_PERI_BASE 0x20000000
// Use this for RPi2
#define BCM2708_PERI_BASE 0x3F000000
#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#define PAGE_SIZE (4*1024)
#define BLOCK_SIZE (4*1024)
// GPIO setup macros.
#define INP_GPIO(pin) *(gpio+((pin)/10)) &= ~(7<<(((pin)%10)*3))
#define OUT_GPIO(pin) *(gpio+((pin)/10)) |= (1<<(((pin)%10)*3))
#define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
int mem_fd;
void *gpio_map;
// I/O access
volatile unsigned *gpio;
/*
* Set up a memory regions to access GPIO
*/
void setup_io()
{
/* open /dev/mem */
if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
printf("can't open /dev/mem \n");
exit(-1);
}
/* mmap GPIO */
gpio_map = mmap(
NULL, //Any adddress in our space will do
BLOCK_SIZE, //Map length
PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
MAP_SHARED, //Shared with other processes
mem_fd, //File to map
GPIO_BASE //Offset to GPIO peripheral
);
close(mem_fd); //No need to keep mem_fd open after mmap
if (gpio_map == MAP_FAILED) {
printf("mmap error %d\n", (int)gpio_map);//errno also set!
exit(-1);
}
// Always use volatile pointer!
gpio = (volatile unsigned *)gpio_map;
}
int main(int argc, char **argv)
{
// Set up gpi pointer for direct register access
setup_io();
// Switch to output mode, must use INP_GPIO before we can use OUT_GPIO
INP_GPIO(21);
OUT_GPIO(21);
// Set high, set low, repeat.
while (1)
{
GPIO_SET = 1<<21;
GPIO_CLR = 1<<21;
}
return 0;
}
|
the_stack_data/211081800.c | #include <assert.h>
int bar(int other)
{
assert(other == 4);
return other + 1;
}
int main()
{
int x = 3;
int y = bar(x + 1);
assert(y == 5);
}
|
the_stack_data/93886990.c | /*
* ipxcp.c - PPP IPX Control Protocol.
*
* Copyright (c) 1984-2000 Carnegie Mellon 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:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* [email protected]
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef IPX_CHANGE
#define RCSID "$Id: ipxcp.c,v 1.1.1.1 2005/05/19 10:53:06 r01122 Exp $"
/*
* TODO:
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "pppd.h"
#include "fsm.h"
#include "ipxcp.h"
#include "pathnames.h"
#include "magic.h"
static const char rcsid[] = RCSID;
/* global vars */
ipxcp_options ipxcp_wantoptions[NUM_PPP]; /* Options that we want to request */
ipxcp_options ipxcp_gotoptions[NUM_PPP]; /* Options that peer ack'd */
ipxcp_options ipxcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */
ipxcp_options ipxcp_hisoptions[NUM_PPP]; /* Options that we ack'd */
#define wo (&ipxcp_wantoptions[0])
#define ao (&ipxcp_allowoptions[0])
#define go (&ipxcp_gotoptions[0])
#define ho (&ipxcp_hisoptions[0])
/*
* Callbacks for fsm code. (CI = Configuration Information)
*/
static void ipxcp_resetci __P((fsm *)); /* Reset our CI */
static int ipxcp_cilen __P((fsm *)); /* Return length of our CI */
static void ipxcp_addci __P((fsm *, u_char *, int *)); /* Add our CI */
static int ipxcp_ackci __P((fsm *, u_char *, int)); /* Peer ack'd our CI */
static int ipxcp_nakci __P((fsm *, u_char *, int)); /* Peer nak'd our CI */
static int ipxcp_rejci __P((fsm *, u_char *, int)); /* Peer rej'd our CI */
static int ipxcp_reqci __P((fsm *, u_char *, int *, int)); /* Rcv CI */
static void ipxcp_up __P((fsm *)); /* We're UP */
static void ipxcp_down __P((fsm *)); /* We're DOWN */
static void ipxcp_finished __P((fsm *)); /* Don't need lower layer */
static void ipxcp_script __P((fsm *, char *)); /* Run an up/down script */
fsm ipxcp_fsm[NUM_PPP]; /* IPXCP fsm structure */
static fsm_callbacks ipxcp_callbacks = { /* IPXCP callback routines */
ipxcp_resetci, /* Reset our Configuration Information */
ipxcp_cilen, /* Length of our Configuration Information */
ipxcp_addci, /* Add our Configuration Information */
ipxcp_ackci, /* ACK our Configuration Information */
ipxcp_nakci, /* NAK our Configuration Information */
ipxcp_rejci, /* Reject our Configuration Information */
ipxcp_reqci, /* Request peer's Configuration Information */
ipxcp_up, /* Called when fsm reaches OPENED state */
ipxcp_down, /* Called when fsm leaves OPENED state */
NULL, /* Called when we want the lower layer up */
ipxcp_finished, /* Called when we want the lower layer down */
NULL, /* Called when Protocol-Reject received */
NULL, /* Retransmission is necessary */
NULL, /* Called to handle protocol-specific codes */
"IPXCP" /* String name of protocol */
};
/*
* Command-line options.
*/
static int setipxnode __P((char **));
static void printipxnode __P((option_t *,
void (*)(void *, char *, ...), void *));
static int setipxname __P((char **));
static option_t ipxcp_option_list[] = {
{ "ipx", o_bool, &ipxcp_protent.enabled_flag,
"Enable IPXCP (and IPX)", OPT_PRIO | 1 },
{ "+ipx", o_bool, &ipxcp_protent.enabled_flag,
"Enable IPXCP (and IPX)", OPT_PRIOSUB | OPT_ALIAS | 1 },
{ "noipx", o_bool, &ipxcp_protent.enabled_flag,
"Disable IPXCP (and IPX)", OPT_PRIOSUB },
{ "-ipx", o_bool, &ipxcp_protent.enabled_flag,
"Disable IPXCP (and IPX)", OPT_PRIOSUB | OPT_ALIAS },
{ "ipx-network", o_uint32, &ipxcp_wantoptions[0].our_network,
"Set our IPX network number", OPT_PRIO, &ipxcp_wantoptions[0].neg_nn },
{ "ipxcp-accept-network", o_bool, &ipxcp_wantoptions[0].accept_network,
"Accept peer IPX network number", 1,
&ipxcp_allowoptions[0].accept_network },
{ "ipx-node", o_special, (void *)setipxnode,
"Set IPX node number", OPT_A2PRINTER, (void *)printipxnode },
{ "ipxcp-accept-local", o_bool, &ipxcp_wantoptions[0].accept_local,
"Accept our IPX address", 1,
&ipxcp_allowoptions[0].accept_local },
{ "ipxcp-accept-remote", o_bool, &ipxcp_wantoptions[0].accept_remote,
"Accept peer's IPX address", 1,
&ipxcp_allowoptions[0].accept_remote },
{ "ipx-routing", o_int, &ipxcp_wantoptions[0].router,
"Set IPX routing proto number", OPT_PRIO,
&ipxcp_wantoptions[0].neg_router },
{ "ipx-router-name", o_special, setipxname,
"Set IPX router name", OPT_PRIO | OPT_A2STRVAL | OPT_STATIC,
&ipxcp_wantoptions[0].name },
{ "ipxcp-restart", o_int, &ipxcp_fsm[0].timeouttime,
"Set timeout for IPXCP", OPT_PRIO },
{ "ipxcp-max-terminate", o_int, &ipxcp_fsm[0].maxtermtransmits,
"Set max #xmits for IPXCP term-reqs", OPT_PRIO },
{ "ipxcp-max-configure", o_int, &ipxcp_fsm[0].maxconfreqtransmits,
"Set max #xmits for IPXCP conf-reqs", OPT_PRIO },
{ "ipxcp-max-failure", o_int, &ipxcp_fsm[0].maxnakloops,
"Set max #conf-naks for IPXCP", OPT_PRIO },
{ NULL }
};
/*
* Protocol entry points.
*/
static void ipxcp_init __P((int));
static void ipxcp_open __P((int));
static void ipxcp_close __P((int, char *));
static void ipxcp_lowerup __P((int));
static void ipxcp_lowerdown __P((int));
static void ipxcp_input __P((int, u_char *, int));
static void ipxcp_protrej __P((int));
static int ipxcp_printpkt __P((u_char *, int,
void (*) __P((void *, char *, ...)), void *));
struct protent ipxcp_protent = {
PPP_IPXCP,
ipxcp_init,
ipxcp_input,
ipxcp_protrej,
ipxcp_lowerup,
ipxcp_lowerdown,
ipxcp_open,
ipxcp_close,
ipxcp_printpkt,
NULL,
0,
"IPXCP",
"IPX",
ipxcp_option_list,
NULL,
NULL,
NULL
};
/*
* Lengths of configuration options.
*/
#define CILEN_VOID 2
#define CILEN_COMPLETE 2 /* length of complete option */
#define CILEN_NETN 6 /* network number length option */
#define CILEN_NODEN 8 /* node number length option */
#define CILEN_PROTOCOL 4 /* Minimum length of routing protocol */
#define CILEN_NAME 3 /* Minimum length of router name */
#define CILEN_COMPRESS 4 /* Minimum length of compression protocol */
#define CODENAME(x) ((x) == CONFACK ? "ACK" : \
(x) == CONFNAK ? "NAK" : "REJ")
static int ipxcp_is_up;
static char *ipx_ntoa __P((u_int32_t));
/* Used in printing the node number */
#define NODE(base) base[0], base[1], base[2], base[3], base[4], base[5]
/* Used to generate the proper bit mask */
#define BIT(num) (1 << (num))
/*
* Convert from internal to external notation
*/
static short int
to_external(internal)
short int internal;
{
short int external;
if (internal & BIT(IPX_NONE) )
external = IPX_NONE;
else
external = RIP_SAP;
return external;
}
/*
* Make a string representation of a network IP address.
*/
static char *
ipx_ntoa(ipxaddr)
u_int32_t ipxaddr;
{
static char b[64];
slprintf(b, sizeof(b), "%x", ipxaddr);
return b;
}
static u_char *
setipxnodevalue(src,dst)
u_char *src, *dst;
{
int indx;
int item;
for (;;) {
if (!isxdigit (*src))
break;
for (indx = 0; indx < 5; ++indx) {
dst[indx] <<= 4;
dst[indx] |= (dst[indx + 1] >> 4) & 0x0F;
}
item = toupper (*src) - '0';
if (item > 9)
item -= 7;
dst[5] = (dst[5] << 4) | item;
++src;
}
return src;
}
static int ipx_prio_our, ipx_prio_his;
static int
setipxnode(argv)
char **argv;
{
char *end;
int have_his = 0;
u_char our_node[6];
u_char his_node[6];
memset (our_node, 0, 6);
memset (his_node, 0, 6);
end = setipxnodevalue (*argv, our_node);
if (*end == ':') {
have_his = 1;
end = setipxnodevalue (++end, his_node);
}
if (*end == '\0') {
ipxcp_wantoptions[0].neg_node = 1;
if (option_priority >= ipx_prio_our) {
memcpy(&ipxcp_wantoptions[0].our_node[0], our_node, 6);
ipx_prio_our = option_priority;
}
if (have_his && option_priority >= ipx_prio_his) {
memcpy(&ipxcp_wantoptions[0].his_node[0], his_node, 6);
ipx_prio_his = option_priority;
}
return 1;
}
option_error("invalid parameter '%s' for ipx-node option", *argv);
return 0;
}
static void
printipxnode(opt, printer, arg)
option_t *opt;
void (*printer) __P((void *, char *, ...));
void *arg;
{
unsigned char *p;
p = ipxcp_wantoptions[0].our_node;
if (ipx_prio_our)
printer(arg, "%.2x%.2x%.2x%.2x%.2x%.2x",
p[0], p[1], p[2], p[3], p[4], p[5]);
printer(arg, ":");
p = ipxcp_wantoptions[0].his_node;
if (ipx_prio_his)
printer(arg, "%.2x%.2x%.2x%.2x%.2x%.2x",
p[0], p[1], p[2], p[3], p[4], p[5]);
}
static int
setipxname (argv)
char **argv;
{
char *dest = ipxcp_wantoptions[0].name;
char *src = *argv;
int count;
char ch;
ipxcp_wantoptions[0].neg_name = 1;
ipxcp_allowoptions[0].neg_name = 1;
memset (dest, '\0', sizeof (ipxcp_wantoptions[0].name));
count = 0;
while (*src) {
ch = *src++;
if (! isalnum (ch) && ch != '_') {
option_error("IPX router name must be alphanumeric or _");
return 0;
}
if (count >= sizeof (ipxcp_wantoptions[0].name) - 1) {
option_error("IPX router name is limited to %d characters",
sizeof (ipxcp_wantoptions[0].name) - 1);
return 0;
}
dest[count++] = toupper (ch);
}
dest[count] = 0;
return 1;
}
/*
* ipxcp_init - Initialize IPXCP.
*/
static void
ipxcp_init(unit)
int unit;
{
fsm *f = &ipxcp_fsm[unit];
f->unit = unit;
f->protocol = PPP_IPXCP;
f->callbacks = &ipxcp_callbacks;
fsm_init(&ipxcp_fsm[unit]);
memset (wo->name, 0, sizeof (wo->name));
memset (wo->our_node, 0, sizeof (wo->our_node));
memset (wo->his_node, 0, sizeof (wo->his_node));
wo->neg_nn = 1;
wo->neg_complete = 1;
wo->network = 0;
ao->neg_node = 1;
ao->neg_nn = 1;
ao->neg_name = 1;
ao->neg_complete = 1;
ao->neg_router = 1;
ao->accept_local = 0;
ao->accept_remote = 0;
ao->accept_network = 0;
wo->tried_rip = 0;
wo->tried_nlsp = 0;
}
/*
* Copy the node number
*/
static void
copy_node (src, dst)
u_char *src, *dst;
{
memcpy (dst, src, sizeof (ipxcp_wantoptions[0].our_node));
}
/*
* Compare node numbers
*/
static int
compare_node (src, dst)
u_char *src, *dst;
{
return memcmp (dst, src, sizeof (ipxcp_wantoptions[0].our_node)) == 0;
}
/*
* Is the node number zero?
*/
static int
zero_node (node)
u_char *node;
{
int indx;
for (indx = 0; indx < sizeof (ipxcp_wantoptions[0].our_node); ++indx)
if (node [indx] != 0)
return 0;
return 1;
}
/*
* Increment the node number
*/
static void
inc_node (node)
u_char *node;
{
u_char *outp;
u_int32_t magic_num;
outp = node;
magic_num = magic();
*outp++ = '\0';
*outp++ = '\0';
PUTLONG (magic_num, outp);
}
/*
* ipxcp_open - IPXCP is allowed to come up.
*/
static void
ipxcp_open(unit)
int unit;
{
fsm_open(&ipxcp_fsm[unit]);
}
/*
* ipxcp_close - Take IPXCP down.
*/
static void
ipxcp_close(unit, reason)
int unit;
char *reason;
{
fsm_close(&ipxcp_fsm[unit], reason);
}
/*
* ipxcp_lowerup - The lower layer is up.
*/
static void
ipxcp_lowerup(unit)
int unit;
{
fsm_lowerup(&ipxcp_fsm[unit]);
}
/*
* ipxcp_lowerdown - The lower layer is down.
*/
static void
ipxcp_lowerdown(unit)
int unit;
{
fsm_lowerdown(&ipxcp_fsm[unit]);
}
/*
* ipxcp_input - Input IPXCP packet.
*/
static void
ipxcp_input(unit, p, len)
int unit;
u_char *p;
int len;
{
fsm_input(&ipxcp_fsm[unit], p, len);
}
/*
* ipxcp_protrej - A Protocol-Reject was received for IPXCP.
*
* Pretend the lower layer went down, so we shut up.
*/
static void
ipxcp_protrej(unit)
int unit;
{
fsm_lowerdown(&ipxcp_fsm[unit]);
}
/*
* ipxcp_resetci - Reset our CI.
*/
static void
ipxcp_resetci(f)
fsm *f;
{
wo->req_node = wo->neg_node && ao->neg_node;
wo->req_nn = wo->neg_nn && ao->neg_nn;
if (wo->our_network == 0) {
wo->neg_node = 1;
ao->accept_network = 1;
}
/*
* If our node number is zero then change it.
*/
if (zero_node (wo->our_node)) {
inc_node (wo->our_node);
ao->accept_local = 1;
wo->neg_node = 1;
}
/*
* If his node number is zero then change it.
*/
if (zero_node (wo->his_node)) {
inc_node (wo->his_node);
ao->accept_remote = 1;
}
/*
* If no routing agent was specified then we do RIP/SAP according to the
* RFC documents. If you have specified something then OK. Otherwise, we
* do RIP/SAP.
*/
if (ao->router == 0) {
ao->router |= BIT(RIP_SAP);
wo->router |= BIT(RIP_SAP);
}
/* Always specify a routing protocol unless it was REJected. */
wo->neg_router = 1;
/*
* Start with these default values
*/
*go = *wo;
}
/*
* ipxcp_cilen - Return length of our CI.
*/
static int
ipxcp_cilen(f)
fsm *f;
{
int len;
len = go->neg_nn ? CILEN_NETN : 0;
len += go->neg_node ? CILEN_NODEN : 0;
len += go->neg_name ? CILEN_NAME + strlen (go->name) - 1 : 0;
/* RFC says that defaults should not be included. */
if (go->neg_router && to_external(go->router) != RIP_SAP)
len += CILEN_PROTOCOL;
return (len);
}
/*
* ipxcp_addci - Add our desired CIs to a packet.
*/
static void
ipxcp_addci(f, ucp, lenp)
fsm *f;
u_char *ucp;
int *lenp;
{
/*
* Add the options to the record.
*/
if (go->neg_nn) {
PUTCHAR (IPX_NETWORK_NUMBER, ucp);
PUTCHAR (CILEN_NETN, ucp);
PUTLONG (go->our_network, ucp);
}
if (go->neg_node) {
int indx;
PUTCHAR (IPX_NODE_NUMBER, ucp);
PUTCHAR (CILEN_NODEN, ucp);
for (indx = 0; indx < sizeof (go->our_node); ++indx)
PUTCHAR (go->our_node[indx], ucp);
}
if (go->neg_name) {
int cilen = strlen (go->name);
int indx;
PUTCHAR (IPX_ROUTER_NAME, ucp);
PUTCHAR (CILEN_NAME + cilen - 1, ucp);
for (indx = 0; indx < cilen; ++indx)
PUTCHAR (go->name [indx], ucp);
}
if (go->neg_router) {
short external = to_external (go->router);
if (external != RIP_SAP) {
PUTCHAR (IPX_ROUTER_PROTOCOL, ucp);
PUTCHAR (CILEN_PROTOCOL, ucp);
PUTSHORT (external, ucp);
}
}
}
/*
* ipxcp_ackci - Ack our CIs.
*
* Returns:
* 0 - Ack was bad.
* 1 - Ack was good.
*/
static int
ipxcp_ackci(f, p, len)
fsm *f;
u_char *p;
int len;
{
u_short cilen, citype, cishort;
u_char cichar;
u_int32_t cilong;
#define ACKCIVOID(opt, neg) \
if (neg) { \
if ((len -= CILEN_VOID) < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_VOID || \
citype != opt) \
break; \
}
#define ACKCICOMPLETE(opt,neg) ACKCIVOID(opt, neg)
#define ACKCICHARS(opt, neg, val, cnt) \
if (neg) { \
int indx, count = cnt; \
len -= (count + 2); \
if (len < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != (count + 2) || \
citype != opt) \
break; \
for (indx = 0; indx < count; ++indx) {\
GETCHAR(cichar, p); \
if (cichar != ((u_char *) &val)[indx]) \
break; \
}\
if (indx != count) \
break; \
}
#define ACKCINODE(opt,neg,val) ACKCICHARS(opt,neg,val,sizeof(val))
#define ACKCINAME(opt,neg,val) ACKCICHARS(opt,neg,val,strlen(val))
#define ACKCINETWORK(opt, neg, val) \
if (neg) { \
if ((len -= CILEN_NETN) < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_NETN || \
citype != opt) \
break; \
GETLONG(cilong, p); \
if (cilong != val) \
break; \
}
#define ACKCIPROTO(opt, neg, val) \
if (neg) { \
if (len < 2) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_PROTOCOL || citype != opt) \
break; \
len -= cilen; \
if (len < 0) \
break; \
GETSHORT(cishort, p); \
if (cishort != to_external (val) || cishort == RIP_SAP) \
break; \
}
/*
* Process the ACK frame in the order in which the frame was assembled
*/
do {
ACKCINETWORK (IPX_NETWORK_NUMBER, go->neg_nn, go->our_network);
ACKCINODE (IPX_NODE_NUMBER, go->neg_node, go->our_node);
ACKCINAME (IPX_ROUTER_NAME, go->neg_name, go->name);
if (len > 0)
ACKCIPROTO (IPX_ROUTER_PROTOCOL, go->neg_router, go->router);
/*
* This is the end of the record.
*/
if (len == 0)
return (1);
} while (0);
/*
* The frame is invalid
*/
IPXCPDEBUG(("ipxcp_ackci: received bad Ack!"));
return (0);
}
/*
* ipxcp_nakci - Peer has sent a NAK for some of our CIs.
* This should not modify any state if the Nak is bad
* or if IPXCP is in the OPENED state.
*
* Returns:
* 0 - Nak was bad.
* 1 - Nak was good.
*/
static int
ipxcp_nakci(f, p, len)
fsm *f;
u_char *p;
int len;
{
u_char citype, cilen, *next;
u_short s;
u_int32_t l;
ipxcp_options no; /* options we've seen Naks for */
ipxcp_options try; /* options to request next time */
BZERO(&no, sizeof(no));
try = *go;
while (len > CILEN_VOID) {
GETCHAR (citype, p);
GETCHAR (cilen, p);
len -= cilen;
if (len < 0)
goto bad;
next = &p [cilen - CILEN_VOID];
switch (citype) {
case IPX_NETWORK_NUMBER:
if (!go->neg_nn || no.neg_nn || (cilen != CILEN_NETN))
goto bad;
no.neg_nn = 1;
GETLONG(l, p);
if (l && ao->accept_network)
try.our_network = l;
break;
case IPX_NODE_NUMBER:
if (!go->neg_node || no.neg_node || (cilen != CILEN_NODEN))
goto bad;
no.neg_node = 1;
if (!zero_node (p) && ao->accept_local &&
! compare_node (p, ho->his_node))
copy_node (p, try.our_node);
break;
/* This has never been sent. Ignore the NAK frame */
case IPX_COMPRESSION_PROTOCOL:
goto bad;
case IPX_ROUTER_PROTOCOL:
if (!go->neg_router || (cilen < CILEN_PROTOCOL))
goto bad;
GETSHORT (s, p);
if (s > 15) /* This is just bad, but ignore for now. */
break;
s = BIT(s);
if (no.router & s) /* duplicate NAKs are always bad */
goto bad;
if (no.router == 0) /* Reset on first NAK only */
try.router = 0;
no.router |= s;
try.router |= s;
try.neg_router = 1;
break;
/* These, according to the RFC, must never be NAKed. */
case IPX_ROUTER_NAME:
case IPX_COMPLETE:
goto bad;
/* These are for options which we have not seen. */
default:
break;
}
p = next;
}
/*
* Do not permit the peer to force a router protocol which we do not
* support. However, default to the condition that will accept "NONE".
*/
try.router &= (ao->router | BIT(IPX_NONE));
if (try.router == 0 && ao->router != 0)
try.router = BIT(IPX_NONE);
if (try.router != 0)
try.neg_router = 1;
/*
* OK, the Nak is good. Now we can update state.
* If there are any options left, we ignore them.
*/
if (f->state != OPENED)
*go = try;
return 1;
bad:
IPXCPDEBUG(("ipxcp_nakci: received bad Nak!"));
return 0;
}
/*
* ipxcp_rejci - Reject some of our CIs.
*/
static int
ipxcp_rejci(f, p, len)
fsm *f;
u_char *p;
int len;
{
u_short cilen, citype, cishort;
u_char cichar;
u_int32_t cilong;
ipxcp_options try; /* options to request next time */
#define REJCINETWORK(opt, neg, val) \
if (neg && p[0] == opt) { \
if ((len -= CILEN_NETN) < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_NETN || \
citype != opt) \
break; \
GETLONG(cilong, p); \
if (cilong != val) \
break; \
neg = 0; \
}
#define REJCICHARS(opt, neg, val, cnt) \
if (neg && p[0] == opt) { \
int indx, count = cnt; \
len -= (count + 2); \
if (len < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != (count + 2) || \
citype != opt) \
break; \
for (indx = 0; indx < count; ++indx) {\
GETCHAR(cichar, p); \
if (cichar != ((u_char *) &val)[indx]) \
break; \
}\
if (indx != count) \
break; \
neg = 0; \
}
#define REJCINODE(opt,neg,val) REJCICHARS(opt,neg,val,sizeof(val))
#define REJCINAME(opt,neg,val) REJCICHARS(opt,neg,val,strlen(val))
#define REJCIVOID(opt, neg) \
if (neg && p[0] == opt) { \
if ((len -= CILEN_VOID) < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_VOID || citype != opt) \
break; \
neg = 0; \
}
/* a reject for RIP/SAP is invalid since we don't send it and you can't
reject something which is not sent. (You can NAK, but you can't REJ.) */
#define REJCIPROTO(opt, neg, val, bit) \
if (neg && p[0] == opt) { \
if ((len -= CILEN_PROTOCOL) < 0) \
break; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_PROTOCOL) \
break; \
GETSHORT(cishort, p); \
if (cishort != to_external (val) || cishort == RIP_SAP) \
break; \
neg = 0; \
}
/*
* Any Rejected CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
try = *go;
do {
REJCINETWORK (IPX_NETWORK_NUMBER, try.neg_nn, try.our_network);
REJCINODE (IPX_NODE_NUMBER, try.neg_node, try.our_node);
REJCINAME (IPX_ROUTER_NAME, try.neg_name, try.name);
REJCIPROTO (IPX_ROUTER_PROTOCOL, try.neg_router, try.router, 0);
/*
* This is the end of the record.
*/
if (len == 0) {
if (f->state != OPENED)
*go = try;
return (1);
}
} while (0);
/*
* The frame is invalid at this point.
*/
IPXCPDEBUG(("ipxcp_rejci: received bad Reject!"));
return 0;
}
/*
* ipxcp_reqci - Check the peer's requested CIs and send appropriate response.
*
* Returns: CONFACK, CONFNAK or CONFREJ and input packet modified
* appropriately. If reject_if_disagree is non-zero, doesn't return
* CONFNAK; returns CONFREJ if it can't return CONFACK.
*/
static int
ipxcp_reqci(f, inp, len, reject_if_disagree)
fsm *f;
u_char *inp; /* Requested CIs */
int *len; /* Length of requested CIs */
int reject_if_disagree;
{
u_char *cip, *next; /* Pointer to current and next CIs */
u_short cilen, citype; /* Parsed len, type */
u_short cishort; /* Parsed short value */
u_int32_t cinetwork; /* Parsed address values */
int rc = CONFACK; /* Final packet return code */
int orc; /* Individual option return code */
u_char *p; /* Pointer to next char to parse */
u_char *ucp = inp; /* Pointer to current output char */
int l = *len; /* Length left */
/*
* Reset all his options.
*/
BZERO(ho, sizeof(*ho));
/*
* Process all his options.
*/
next = inp;
while (l) {
orc = CONFACK; /* Assume success */
cip = p = next; /* Remember begining of CI */
if (l < 2 || /* Not enough data for CI header or */
p[1] < 2 || /* CI length too small or */
p[1] > l) { /* CI length too big? */
IPXCPDEBUG(("ipxcp_reqci: bad CI length!"));
orc = CONFREJ; /* Reject bad CI */
cilen = l; /* Reject till end of packet */
l = 0; /* Don't loop again */
goto endswitch;
}
GETCHAR(citype, p); /* Parse CI type */
GETCHAR(cilen, p); /* Parse CI length */
l -= cilen; /* Adjust remaining length */
next += cilen; /* Step to next CI */
switch (citype) { /* Check CI type */
/*
* The network number must match. Choose the larger of the two.
*/
case IPX_NETWORK_NUMBER:
/* if we wont negotiate the network number or the length is wrong
then reject the option */
if ( !ao->neg_nn || cilen != CILEN_NETN ) {
orc = CONFREJ;
break;
}
GETLONG(cinetwork, p);
/* If the network numbers match then acknowledge them. */
if (cinetwork != 0) {
ho->his_network = cinetwork;
ho->neg_nn = 1;
if (wo->our_network == cinetwork)
break;
/*
* If the network number is not given or we don't accept their change or
* the network number is too small then NAK it.
*/
if (! ao->accept_network || cinetwork < wo->our_network) {
DECPTR (sizeof (u_int32_t), p);
PUTLONG (wo->our_network, p);
orc = CONFNAK;
}
break;
}
/*
* The peer sent '0' for the network. Give it ours if we have one.
*/
if (go->our_network != 0) {
DECPTR (sizeof (u_int32_t), p);
PUTLONG (wo->our_network, p);
orc = CONFNAK;
/*
* We don't have one. Reject the value.
*/
} else
orc = CONFREJ;
break;
/*
* The node number is required
*/
case IPX_NODE_NUMBER:
/* if we wont negotiate the node number or the length is wrong
then reject the option */
if ( cilen != CILEN_NODEN ) {
orc = CONFREJ;
break;
}
copy_node (p, ho->his_node);
ho->neg_node = 1;
/*
* If the remote does not have a number and we do then NAK it with the value
* which we have for it. (We never have a default value of zero.)
*/
if (zero_node (ho->his_node)) {
orc = CONFNAK;
copy_node (wo->his_node, p);
INCPTR (sizeof (wo->his_node), p);
break;
}
/*
* If you have given me the expected network node number then I'll accept
* it now.
*/
if (compare_node (wo->his_node, ho->his_node)) {
orc = CONFACK;
ho->neg_node = 1;
INCPTR (sizeof (wo->his_node), p);
break;
}
/*
* If his node number is the same as ours then ask him to try the next
* value.
*/
if (compare_node (ho->his_node, go->our_node)) {
inc_node (ho->his_node);
orc = CONFNAK;
copy_node (ho->his_node, p);
INCPTR (sizeof (wo->his_node), p);
break;
}
/*
* If we don't accept a new value then NAK it.
*/
if (! ao->accept_remote) {
copy_node (wo->his_node, p);
INCPTR (sizeof (wo->his_node), p);
orc = CONFNAK;
break;
}
orc = CONFACK;
ho->neg_node = 1;
INCPTR (sizeof (wo->his_node), p);
break;
/*
* Compression is not desired at this time. It is always rejected.
*/
case IPX_COMPRESSION_PROTOCOL:
orc = CONFREJ;
break;
/*
* The routing protocol is a bitmask of various types. Any combination
* of the values RIP_SAP and NLSP are permissible. 'IPX_NONE' for no
* routing protocol must be specified only once.
*/
case IPX_ROUTER_PROTOCOL:
if ( !ao->neg_router || cilen < CILEN_PROTOCOL ) {
orc = CONFREJ;
break;
}
GETSHORT (cishort, p);
if (wo->neg_router == 0) {
wo->neg_router = 1;
wo->router = BIT(IPX_NONE);
}
if ((cishort == IPX_NONE && ho->router != 0) ||
(ho->router & BIT(IPX_NONE))) {
orc = CONFREJ;
break;
}
cishort = BIT(cishort);
if (ho->router & cishort) {
orc = CONFREJ;
break;
}
ho->router |= cishort;
ho->neg_router = 1;
/* Finally do not allow a router protocol which we do not
support. */
if ((cishort & (ao->router | BIT(IPX_NONE))) == 0) {
int protocol;
if (cishort == BIT(NLSP) &&
(ao->router & BIT(RIP_SAP)) &&
!wo->tried_rip) {
protocol = RIP_SAP;
wo->tried_rip = 1;
} else
protocol = IPX_NONE;
DECPTR (sizeof (u_int16_t), p);
PUTSHORT (protocol, p);
orc = CONFNAK;
}
break;
/*
* The router name is advisorary. Just accept it if it is not too large.
*/
case IPX_ROUTER_NAME:
if (cilen >= CILEN_NAME) {
int name_size = cilen - CILEN_NAME;
if (name_size > sizeof (ho->name))
name_size = sizeof (ho->name) - 1;
memset (ho->name, 0, sizeof (ho->name));
memcpy (ho->name, p, name_size);
ho->name [name_size] = '\0';
ho->neg_name = 1;
orc = CONFACK;
break;
}
orc = CONFREJ;
break;
/*
* This is advisorary.
*/
case IPX_COMPLETE:
if (cilen != CILEN_COMPLETE)
orc = CONFREJ;
else {
ho->neg_complete = 1;
orc = CONFACK;
}
break;
/*
* All other entries are not known at this time.
*/
default:
orc = CONFREJ;
break;
}
endswitch:
if (orc == CONFACK && /* Good CI */
rc != CONFACK) /* but prior CI wasnt? */
continue; /* Don't send this one */
if (orc == CONFNAK) { /* Nak this CI? */
if (reject_if_disagree) /* Getting fed up with sending NAKs? */
orc = CONFREJ; /* Get tough if so */
if (rc == CONFREJ) /* Rejecting prior CI? */
continue; /* Don't send this one */
if (rc == CONFACK) { /* Ack'd all prior CIs? */
rc = CONFNAK; /* Not anymore... */
ucp = inp; /* Backup */
}
}
if (orc == CONFREJ && /* Reject this CI */
rc != CONFREJ) { /* but no prior ones? */
rc = CONFREJ;
ucp = inp; /* Backup */
}
/* Need to move CI? */
if (ucp != cip)
BCOPY(cip, ucp, cilen); /* Move it */
/* Update output pointer */
INCPTR(cilen, ucp);
}
/*
* If we aren't rejecting this packet, and we want to negotiate
* their address, and they didn't send their address, then we
* send a NAK with a IPX_NODE_NUMBER option appended. We assume the
* input buffer is long enough that we can append the extra
* option safely.
*/
if (rc != CONFREJ && !ho->neg_node &&
wo->req_nn && !reject_if_disagree) {
if (rc == CONFACK) {
rc = CONFNAK;
wo->req_nn = 0; /* don't ask again */
ucp = inp; /* reset pointer */
}
if (zero_node (wo->his_node))
inc_node (wo->his_node);
PUTCHAR (IPX_NODE_NUMBER, ucp);
PUTCHAR (CILEN_NODEN, ucp);
copy_node (wo->his_node, ucp);
INCPTR (sizeof (wo->his_node), ucp);
}
*len = ucp - inp; /* Compute output length */
IPXCPDEBUG(("ipxcp: returning Configure-%s", CODENAME(rc)));
return (rc); /* Return final code */
}
/*
* ipxcp_up - IPXCP has come UP.
*
* Configure the IP network interface appropriately and bring it up.
*/
static void
ipxcp_up(f)
fsm *f;
{
int unit = f->unit;
IPXCPDEBUG(("ipxcp: up"));
/* The default router protocol is RIP/SAP. */
if (ho->router == 0)
ho->router = BIT(RIP_SAP);
if (go->router == 0)
go->router = BIT(RIP_SAP);
/* Fetch the network number */
if (!ho->neg_nn)
ho->his_network = wo->his_network;
if (!ho->neg_node)
copy_node (wo->his_node, ho->his_node);
if (!wo->neg_node && !go->neg_node)
copy_node (wo->our_node, go->our_node);
if (zero_node (go->our_node)) {
static char errmsg[] = "Could not determine local IPX node address";
if (debug)
error(errmsg);
ipxcp_close(f->unit, errmsg);
return;
}
go->network = go->our_network;
if (ho->his_network != 0 && ho->his_network > go->network)
go->network = ho->his_network;
if (go->network == 0) {
static char errmsg[] = "Can not determine network number";
if (debug)
error(errmsg);
ipxcp_close (unit, errmsg);
return;
}
/* bring the interface up */
if (!sifup(unit)) {
if (debug)
warn("sifup failed (IPX)");
ipxcp_close(unit, "Interface configuration failed");
return;
}
ipxcp_is_up = 1;
/* set the network number for IPX */
if (!sipxfaddr(unit, go->network, go->our_node)) {
if (debug)
warn("sipxfaddr failed");
ipxcp_close(unit, "Interface configuration failed");
return;
}
np_up(f->unit, PPP_IPX);
/*
* Execute the ipx-up script, like this:
* /etc/ppp/ipx-up interface tty speed local-IPX remote-IPX
*/
ipxcp_script (f, _PATH_IPXUP);
}
/*
* ipxcp_down - IPXCP has gone DOWN.
*
* Take the IP network interface down, clear its addresses
* and delete routes through it.
*/
static void
ipxcp_down(f)
fsm *f;
{
IPXCPDEBUG(("ipxcp: down"));
if (!ipxcp_is_up)
return;
ipxcp_is_up = 0;
np_down(f->unit, PPP_IPX);
cipxfaddr(f->unit);
sifnpmode(f->unit, PPP_IPX, NPMODE_DROP);
sifdown(f->unit);
ipxcp_script (f, _PATH_IPXDOWN);
}
/*
* ipxcp_finished - possibly shut down the lower layers.
*/
static void
ipxcp_finished(f)
fsm *f;
{
np_finished(f->unit, PPP_IPX);
}
/*
* ipxcp_script - Execute a script with arguments
* interface-name tty-name speed local-IPX remote-IPX networks.
*/
static void
ipxcp_script(f, script)
fsm *f;
char *script;
{
char strspeed[32], strlocal[32], strremote[32];
char strnetwork[32], strpid[32];
char *argv[14], strproto_lcl[32], strproto_rmt[32];
slprintf(strpid, sizeof(strpid), "%d", getpid());
slprintf(strspeed, sizeof(strspeed),"%d", baud_rate);
strproto_lcl[0] = '\0';
if (go->neg_router && ((go->router & BIT(IPX_NONE)) == 0)) {
if (go->router & BIT(RIP_SAP))
strlcpy (strproto_lcl, "RIP ", sizeof(strproto_lcl));
if (go->router & BIT(NLSP))
strlcat (strproto_lcl, "NLSP ", sizeof(strproto_lcl));
}
if (strproto_lcl[0] == '\0')
strlcpy (strproto_lcl, "NONE ", sizeof(strproto_lcl));
strproto_lcl[strlen (strproto_lcl)-1] = '\0';
strproto_rmt[0] = '\0';
if (ho->neg_router && ((ho->router & BIT(IPX_NONE)) == 0)) {
if (ho->router & BIT(RIP_SAP))
strlcpy (strproto_rmt, "RIP ", sizeof(strproto_rmt));
if (ho->router & BIT(NLSP))
strlcat (strproto_rmt, "NLSP ", sizeof(strproto_rmt));
}
if (strproto_rmt[0] == '\0')
strlcpy (strproto_rmt, "NONE ", sizeof(strproto_rmt));
strproto_rmt[strlen (strproto_rmt)-1] = '\0';
strlcpy (strnetwork, ipx_ntoa (go->network), sizeof(strnetwork));
slprintf (strlocal, sizeof(strlocal), "%0.6B", go->our_node);
slprintf (strremote, sizeof(strremote), "%0.6B", ho->his_node);
argv[0] = script;
argv[1] = ifname;
argv[2] = devnam;
argv[3] = strspeed;
argv[4] = strnetwork;
argv[5] = strlocal;
argv[6] = strremote;
argv[7] = strproto_lcl;
argv[8] = strproto_rmt;
argv[9] = go->name;
argv[10] = ho->name;
argv[11] = ipparam;
argv[12] = strpid;
argv[13] = NULL;
run_program(script, argv, 0, NULL, NULL);
}
/*
* ipxcp_printpkt - print the contents of an IPXCP packet.
*/
static char *ipxcp_codenames[] = {
"ConfReq", "ConfAck", "ConfNak", "ConfRej",
"TermReq", "TermAck", "CodeRej"
};
static int
ipxcp_printpkt(p, plen, printer, arg)
u_char *p;
int plen;
void (*printer) __P((void *, char *, ...));
void *arg;
{
int code, id, len, olen;
u_char *pstart, *optend;
u_short cishort;
u_int32_t cilong;
if (plen < HEADERLEN)
return 0;
pstart = p;
GETCHAR(code, p);
GETCHAR(id, p);
GETSHORT(len, p);
if (len < HEADERLEN || len > plen)
return 0;
if (code >= 1 && code <= sizeof(ipxcp_codenames) / sizeof(char *))
printer(arg, " %s", ipxcp_codenames[code-1]);
else
printer(arg, " code=0x%x", code);
printer(arg, " id=0x%x", id);
len -= HEADERLEN;
switch (code) {
case CONFREQ:
case CONFACK:
case CONFNAK:
case CONFREJ:
/* print option list */
while (len >= 2) {
GETCHAR(code, p);
GETCHAR(olen, p);
p -= 2;
if (olen < CILEN_VOID || olen > len) {
break;
}
printer(arg, " <");
len -= olen;
optend = p + olen;
switch (code) {
case IPX_NETWORK_NUMBER:
if (olen == CILEN_NETN) {
p += 2;
GETLONG(cilong, p);
printer (arg, "network %s", ipx_ntoa (cilong));
}
break;
case IPX_NODE_NUMBER:
if (olen == CILEN_NODEN) {
p += 2;
printer (arg, "node ");
while (p < optend) {
GETCHAR(code, p);
printer(arg, "%.2x", (int) (unsigned int) (unsigned char) code);
}
}
break;
case IPX_COMPRESSION_PROTOCOL:
if (olen == CILEN_COMPRESS) {
p += 2;
GETSHORT (cishort, p);
printer (arg, "compression %d", (int) cishort);
}
break;
case IPX_ROUTER_PROTOCOL:
if (olen == CILEN_PROTOCOL) {
p += 2;
GETSHORT (cishort, p);
printer (arg, "router proto %d", (int) cishort);
}
break;
case IPX_ROUTER_NAME:
if (olen >= CILEN_NAME) {
p += 2;
printer (arg, "router name \"");
while (p < optend) {
GETCHAR(code, p);
if (code >= 0x20 && code <= 0x7E)
printer (arg, "%c", (int) (unsigned int) (unsigned char) code);
else
printer (arg, " \\%.2x", (int) (unsigned int) (unsigned char) code);
}
printer (arg, "\"");
}
break;
case IPX_COMPLETE:
if (olen == CILEN_COMPLETE) {
p += 2;
printer (arg, "complete");
}
break;
default:
break;
}
while (p < optend) {
GETCHAR(code, p);
printer(arg, " %.2x", (int) (unsigned int) (unsigned char) code);
}
printer(arg, ">");
}
break;
case TERMACK:
case TERMREQ:
if (len > 0 && *p >= ' ' && *p < 0x7f) {
printer(arg, " ");
print_string(p, len, printer, arg);
p += len;
len = 0;
}
break;
}
/* print the rest of the bytes in the packet */
for (; len > 0; --len) {
GETCHAR(code, p);
printer(arg, " %.2x", (int) (unsigned int) (unsigned char) code);
}
return p - pstart;
}
#endif /* ifdef IPX_CHANGE */
|
the_stack_data/234517172.c |
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
char* aa = malloc(8);
aa[-1] = 17;
if (aa[-1] == 17)
printf("17\n"); else printf("not 17\n");
return 0;
}
|
the_stack_data/90761433.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2008-2014 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <pthread.h>
#include <assert.h>
#include <unistd.h>
static void *
start (void *arg)
{
assert (0);
return arg;
}
int main(void)
{
pthread_t thread;
int i;
switch (fork ())
{
case -1:
assert (0);
default:
break;
case 0:
i = pthread_create (&thread, NULL, start, NULL);
assert (i == 0);
i = pthread_join (thread, NULL);
assert (i == 0);
assert (0);
}
return 0;
}
|
the_stack_data/187642871.c | #include "string.h"
#include <stdio.h>
void print_str(const char *str)
{
printf("From C: %s\n", str);
}
const char *hello()
{
return "Hello FFI";
}
|
the_stack_data/1050101.c | /* PR c/66415 */
/* { dg-do compile } */
/* { dg-options "-Wformat" } */
#24
void
fn1 (void)
{
__builtin_printf ("xxxxxxxxxxxxxxxxx%dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
/* { dg-warning "format" "" { target *-*-* } 27 } */
}
|
the_stack_data/145453388.c | #include <stdio.h>
int find_nth_term(int n, int a, int b, int c)
{
// Variable declaration
int nth;
// If n is already calculated
if (n == 1) { return a; }
if (n == 2) { return b; }
if (n == 3) { return c; }
// Loop calculating S(i) = S(3) + S(2) + S(1) from i = 4 (S(4)) to n
for (int i = 4; i <= n; i++)
{
// S(i) = S(3) + S(2) + S(1)
nth = c + b + a;
// S(1) = S(2)
a = b;
// S(2) = S(3)
b = c;
// S(3) = S(i)
c = nth;
}
// Returns S(n)
return (nth);
}
int main(void)
{
// Variables declaration
int n, a, b, c;
// Assigns the input to the corresponding variables
scanf("%d %d %d %d", &n, &a, &b, &c);
// Assigns the return of the called function
int ans = find_nth_term(n, a, b, c);
// Prints ans content
printf("%d\n", ans);
// Returns successful exit status
return (0);
}
|
the_stack_data/707115.c | /*
Copyright (C) 2007 MySQL AB
All rights reserved. Use is subject to license terms.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#define N (1024*1024)
#define S 65537
/* The number S must be relative prime to N. */
uint32_t bm[N*4];
uint32_t bms[N][4];
uint32_t len[N];
uint32_t pos[N];
typedef uint32_t Uint32;
#define MEMCOPY_NO_WORDS(to, from, no_of_words) \
memcpy((to), (void*)(from), (size_t)(no_of_words << 2));
/****************************************************************************/
static void
getbits(const Uint32 *src, Uint32 bit_pos, Uint32 *dst, Uint32 count)
{
Uint32 val;
/* Move to start word in src. */
src+= bit_pos>>5;
bit_pos&= 31;
/*
If word-aligned, copy word-for-word is faster and avoids edge
cases with undefined bitshift operations.
*/
if (bit_pos==0)
{
MEMCOPY_NO_WORDS(dst, src, count>>5);
src+= count>>5;
dst+= count>>5;
count&= 31;
}
else
{
while(count >= 32)
{
/*
Get bits 0-X from first source word.
Get bits (X+1)-31 from second source word.
Handle endian so that we store bit 0 in the first byte, and bit 31 in
the last byte, so that we don't waste space on 32-bit aligning the
bitmap.
*/
#ifdef WORDS_BIGENDIAN
Uint32 firstpart_len= 32-bit_pos;
val= *src++ & (((Uint32)1<<firstpart_len)-1);
val|= *src & ((Uint32)0xffffffff << firstpart_len);
#else
val= *src++ >> bit_pos;
val|= *src << (32-bit_pos);
#endif
*dst++= val;
count-= 32;
}
}
/* Handle any partial word at the end. */
if (count>0)
{
if (bit_pos+count <= 32)
{
/* Last part is wholly contained in one source word. */
#ifdef WORDS_BIGENDIAN
val= *src >> (32-(bit_pos+count));
#else
val= *src >> bit_pos;
#endif
}
else
{
/* Need to assemble last part from two source words. */
#ifdef WORDS_BIGENDIAN
Uint32 firstpart_len= 32-bit_pos;
val= *src++ & (((Uint32)1<<firstpart_len)-1);
val|= (*src >> (32-count)) & ((Uint32)0xffffffff << firstpart_len);
#else
val= *src++ >> bit_pos;
val|= *src << (32-bit_pos);
#endif
}
/* Mask off any unused bits. */
*dst= val & (((Uint32)1<<count)-1);
}
}
static void
setbits(const Uint32 *src, Uint32 *dst, Uint32 bit_pos, Uint32 count)
{
Uint32 val;
/* Move to start word in dst. */
dst+= bit_pos>>5;
bit_pos&= 31;
#ifdef WORDS_BIGENDIAN
Uint32 low_mask= ((Uint32)0xffffffff)<<(32-bit_pos);
Uint32 high_mask= ~low_mask;
#else
Uint32 low_mask= (((Uint32)1)<<bit_pos) - 1;
Uint32 high_mask= ~low_mask;
#endif
if (bit_pos==0)
{
MEMCOPY_NO_WORDS(dst, src, count>>5);
src+= count>>5;
dst+= count>>5;
count&= 31;
}
else
{
while (count >= 32)
{
val= *src++;
#ifdef WORDS_BIGENDIAN
*dst= (*dst&low_mask) | (val&high_mask);
dst++;
*dst= (*dst&high_mask) | (val&low_mask);
#else
*dst= (*dst&low_mask) | (val<<bit_pos);
dst++;
*dst= (*dst&high_mask) | (val>>(32-bit_pos));
#endif
count-= 32;
}
}
/* Handle any partial word at the end. */
if (count > 0)
{
val= *src;
if (bit_pos+count <= 32)
{
/* Remaining part fits in one word of destination. */
Uint32 end_mask= (((Uint32)1)<<count) - 1;
#ifdef WORDS_BIGENDIAN
Uint32 shift= (32-(bit_pos+count));
*dst= (*dst&~(end_mask<<shift)) | ((val&end_mask)<<shift);
#else
*dst= (*dst&~(end_mask<<bit_pos)) | ((val&end_mask)<<bit_pos);
#endif
}
else
{
/* Need to split the remaining part across two destination words. */
#ifdef WORDS_BIGENDIAN
*dst= (*dst&low_mask) | (val&high_mask);
dst++;
Uint32 shift= 32-count;
Uint32 end_mask= ((((Uint32)1)<<(bit_pos+count-32)) - 1) << (32-bit_pos);
*dst= (*dst&~(end_mask<<shift)) | ((val&end_mask)<<shift);
#else
*dst= (*dst&low_mask) | (val<<bit_pos);
dst++;
Uint32 end_mask= (((Uint32)1)<<(count+bit_pos-32)) - 1;
*dst= (*dst&~end_mask) | ((val>>(32-bit_pos))&end_mask);
#endif
}
}
}
/****************************************************************************/
/* Set up a bunch of test bit fields. */
void fill(void)
{
uint32_t i,j;
uint32_t p= 0;
for(i= 0; i<N; i++)
{
memset(bms[i], 0, sizeof(bms[i]));
pos[i]= p;
do
len[i]= rand()%128;
while (!len[i]);
p+= len[i];
for(j= 0; j<len[i]; j++)
if(rand()%2)
bms[i][j>>5]|= (((uint32_t)1)<<(j&31));
}
}
void write(void)
{
uint32_t i, idx;
for(i=0, idx=0; i<N; i++, idx+= S)
{
if(idx>=N)
idx-= N;
setbits(&(bms[idx][0]), &(bm[0]), pos[idx], len[idx]);
}
}
void read(void)
{
uint32_t buf[4];
uint32_t i;
for(i=0; i<N; i++)
{
getbits(&(bm[0]), pos[i], &(buf[0]), len[i]);
assert(0==memcmp(buf, bms[i], ((len[i]+31)>>5)<<2));
}
}
int main(int argc, char *argv[])
{
uint32_t i;
srand(1);
fill();
write();
read();
exit(0);
return 0;
}
|
the_stack_data/115765625.c | // Compile this file to an object file, e.g.:
//
// gcc -O3 -c -o trace.o trace.c
//
// Then link it with your application.
//
// One easy way to use it with PLASMA is to put it in the link options.
// You can do it by adding the following line to your make.inc file:
//
// LDFLAGS = -fopenmp tools/trace.o
//
// Then wrap the calls you want to trace with calls to trace_event_start()
// and trace_event_stop(), e.g.:
//
// trace_cpu_start();
// cblas_zgemm(CblasColMajor, ...
// trace_cpu_stop("LightGoldenrodYellow");
//
// Provide the name of the color as a string.
// Use one of the X11 color names: https://en.wikipedia.org/wiki/X11_color_names
//
// Optionally, you can assign a label to a color using trace_label(), e.g.:
//
// trace_label("Teal", "gemm");
//
// Upon completion, the trace is written to an SVG file in the local folder.
// The name has the form trace_189648000.svg, where the number is the Unix time.
//
// Initially, tracing is on.
// You can turn it off by calling tracing_off();
// You can turn it back on by calling tracing_on();
//
// Unlike in the past renditions of this solution, here:
// - you do not include a header file,
// - you do not provide the color as an integer, but as a string,
// - you do not call the constructor trace_init(),
// - you do not call the destructor trace_finish().
#include <omp.h>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
// https://en.wikipedia.org/wiki/X11_color_names
static struct {
const char *color;
int value;
} Color[] = {
/* Pink colors */ /* Cyan colors */
{"Pink", 0xFFC0CB}, {"Aqua", 0x00FFFF},
{"LightPink", 0xFFB6C1}, {"Cyan", 0x00FFFF},
{"HotPink", 0xFF69B4}, {"LightCyan", 0xE0FFFF},
{"DeepPink", 0xFF1493}, {"PaleTurquoise", 0xAFEEEE},
{"PaleVioletRed", 0xDB7093}, {"Aquamarine", 0x7FFFD4},
{"MediumVioletRed", 0xC71585}, {"Turquoise", 0x40E0D0},
{"MediumTurquoise", 0x48D1CC},
/* Red colors */ {"DarkTurquoise", 0x00CED1},
{"LightSalmon", 0xFFA07A}, {"LightSeaGreen", 0x20B2AA},
{"Salmon", 0xFA8072}, {"CadetBlue", 0x5F9EA0},
{"DarkSalmon", 0xE9967A}, {"DarkCyan", 0x008B8B},
{"LightCoral", 0xF08080}, {"Teal", 0x008080},
{"IndianRed", 0xCD5C5C},
{"Crimson", 0xDC143C}, /* Blue colors */
{"FireBrick", 0xB22222}, {"LightSteelBlue", 0xB0C4DE},
{"DarkRed", 0x8B0000}, {"PowderBlue", 0xB0E0E6},
{"Red", 0xFF0000}, {"LightBlue", 0xADD8E6},
{"SkyBlue", 0x87CEEB},
/* Orange colors */ {"LightSkyBlue", 0x87CEFA},
{"OrangeRed", 0xFF4500}, {"DeepSkyBlue", 0x00BFFF},
{"Tomato", 0xFF6347}, {"DodgerBlue", 0x1E90FF},
{"Coral", 0xFF7F50}, {"CornflowerBlue", 0x6495ED},
{"DarkOrange", 0xFF8C00}, {"SteelBlue", 0x4682B4},
{"Orange", 0xFFA500}, {"RoyalBlue", 0x4169E1},
{"Blue", 0x0000FF},
/* Yellow colors */ {"MediumBlue", 0x0000CD},
{"Yellow", 0xFFFF00}, {"DarkBlue", 0x00008B},
{"LightYellow", 0xFFFFE0}, {"Navy", 0x000080},
{"LemonChiffon", 0xFFFACD}, {"MidnightBlue", 0x191970},
{"LightGoldenrodYellow", 0xFAFAD2},
{"PapayaWhip", 0xFFEFD5}, /* Purple, violet, and magenta */
{"Moccasin", 0xFFE4B5}, {"Lavender", 0xE6E6FA},
{"PeachPuff", 0xFFDAB9}, {"Thistle", 0xD8BFD8},
{"PaleGoldenrod", 0xEEE8AA}, {"Plum", 0xDDA0DD},
{"Khaki", 0xF0E68C}, {"Violet", 0xEE82EE},
{"DarkKhaki", 0xBDB76B}, {"Orchid", 0xDA70D6},
{"Gold", 0xFFD700}, {"Fuchsia", 0xFF00FF},
{"Magenta", 0xFF00FF},
/* Brown colors */ {"MediumOrchid", 0xBA55D3},
{"Cornsilk", 0xFFF8DC}, {"MediumPurple", 0x9370DB},
{"BlanchedAlmond", 0xFFEBCD}, {"BlueViolet", 0x8A2BE2},
{"Bisque", 0xFFE4C4}, {"DarkViolet", 0x9400D3},
{"NavajoWhite", 0xFFDEAD}, {"DarkOrchid", 0x9932CC},
{"Wheat", 0xF5DEB3}, {"DarkMagenta", 0x8B008B},
{"BurlyWood", 0xDEB887}, {"Purple", 0x800080},
{"Tan", 0xD2B48C}, {"Indigo", 0x4B0082},
{"RosyBrown", 0xBC8F8F}, {"DarkSlateBlue", 0x483D8B},
{"SandyBrown", 0xF4A460}, {"SlateBlue", 0x6A5ACD},
{"Goldenrod", 0xDAA520}, {"MediumSlateBlue", 0x7B68EE},
{"DarkGoldenrod", 0xB8860B},
{"Peru", 0xCD853F}, /* White colors */
{"Chocolate", 0xD2691E}, {"White", 0xFFFFFF},
{"SaddleBrown", 0x8B4513}, {"Snow", 0xFFFAFA},
{"Sienna", 0xA0522D}, {"Honeydew", 0xF0FFF0},
{"Brown", 0xA52A2A}, {"MintCream", 0xF5FFFA},
{"Maroon", 0x800000}, {"Azure", 0xF0FFFF},
{"AliceBlue", 0xF0F8FF},
/* Green colors */ {"GhostWhite", 0xF8F8FF},
{"DarkOliveGreen", 0x556B2F}, {"WhiteSmoke", 0xF5F5F5},
{"Olive", 0x808000}, {"Seashell", 0xFFF5EE},
{"OliveDrab", 0x6B8E23}, {"Beige", 0xF5F5DC},
{"YellowGreen", 0x9ACD32}, {"OldLace", 0xFDF5E6},
{"LimeGreen", 0x32CD32}, {"FloralWhite", 0xFFFAF0},
{"Lime", 0x00FF00}, {"Ivory", 0xFFFFF0},
{"LawnGreen", 0x7CFC00}, {"AntiqueWhite", 0xFAEBD7},
{"Chartreuse", 0x7FFF00}, {"Linen", 0xFAF0E6},
{"GreenYellow", 0xADFF2F}, {"LavenderBlush", 0xFFF0F5},
{"SpringGreen", 0x00FF7F}, {"MistyRose", 0xFFE4E1},
{"MediumSpringGreen", 0x00FA9A},
{"LightGreen", 0x90EE90}, /* Gray and black colors */
{"PaleGreen", 0x98FB98}, {"Gainsboro", 0xDCDCDC},
{"DarkSeaGreen", 0x8FBC8F}, {"LightGray", 0xD3D3D3},
{"MediumAquamarine", 0x66CDAA}, {"Silver", 0xC0C0C0},
{"MediumSeaGreen", 0x3CB371}, {"DarkGray", 0xA9A9A9},
{"SeaGreen", 0x2E8B57}, {"Gray", 0x808080},
{"ForestGreen", 0x228B22}, {"DimGray", 0x696969},
{"Green", 0x008000}, {"LightSlateGray", 0x778899},
{"DarkGreen", 0x006400}, {"SlateGray", 0x708090},
{"DarkSlateGray", 0x2F4F4F},
{"Black", 0x000000}
};
static int Trace = 1;
void trace_off() {Trace = 0;}
void trace_on() {Trace = 1;}
#define IMAGE_WIDTH 2390
#define IMAGE_HEIGHT 1000
#define MAP_SIZE 1024
static int ColorMap[MAP_SIZE];
static const char *Label[sizeof(Color)/sizeof(Color[0])] = { NULL };
static int NumColors = sizeof(Color)/sizeof(Color[0]);
static int NumThreads;
#define MAX_THREADS 256
#define MAX_THREAD_EVENTS 65536
static int EventNumThread [MAX_THREADS];
static double EventStartThread[MAX_THREADS][MAX_THREAD_EVENTS];
static double EventStopThread [MAX_THREADS][MAX_THREAD_EVENTS];
static int EventColorThread[MAX_THREADS][MAX_THREAD_EVENTS];
//------------------------------------------------------------------------------
// https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
static inline unsigned int color_index(const char *str)
{
unsigned int hash = 23;
unsigned int c;
unsigned char *ustr = (unsigned char*)str;
while ((c = *ustr++) != '\0')
hash = hash*307+c;
return hash%MAP_SIZE;
}
//------------------------------------------------------------------------------
void trace_cpu_start()
{
int thread_num = omp_get_thread_num() & (MAX_THREADS-1);
thread_num &= (MAX_THREADS-1);
int event_num = EventNumThread[thread_num];
EventStartThread[thread_num][event_num] = omp_get_wtime();
}
//------------------------------------------------------------------------------
void trace_cpu_stop(const char *color)
{
int thread_num = omp_get_thread_num();
thread_num &= (MAX_THREADS-1);
int event_num = EventNumThread[thread_num];
EventStopThread[thread_num][event_num] = omp_get_wtime();
EventColorThread[thread_num][event_num] = ColorMap[color_index(color)];
EventNumThread[thread_num] += Trace;
EventNumThread[thread_num] &= (MAX_THREAD_EVENTS-1);
}
//------------------------------------------------------------------------------
void trace_label(const char *color, const char *label)
{
Label[ColorMap[color_index(color)]] = label;
}
//------------------------------------------------------------------------------
static void trace_finish()
{
double min_time = INFINITY;
double max_time = 0.0;
for (int thread = 0; thread < NumThreads; thread++)
if (EventNumThread[thread] > 0)
if (EventStartThread[thread][0] < min_time)
min_time = EventStartThread[thread][0];
for (int thread = 0; thread < NumThreads; thread++)
if (EventNumThread[thread] > 0)
if (EventStopThread[thread][EventNumThread[thread]-1] > max_time)
max_time = EventStopThread[thread][EventNumThread[thread]-1];
double total_time = max_time - min_time;
double hscale = IMAGE_WIDTH / total_time;
double vscale = IMAGE_HEIGHT / (NumThreads + 1);
char file_name[32];
snprintf(file_name, 32, "trace_%ld.svg", (unsigned long int)time(NULL));
FILE *trace_file = fopen(file_name, "w");
assert(trace_file != NULL);
fprintf(trace_file,
"<svg viewBox=\"0 0 %d %d\">\n", IMAGE_WIDTH, IMAGE_HEIGHT);
// output events
int thread;
int event;
for (thread = 0; thread < NumThreads; thread++) {
for (event = 0; event < EventNumThread[thread]; event++) {
double start = EventStartThread[thread][event]-min_time;
double stop = EventStopThread[thread][event]-min_time;
fprintf(
trace_file,
"<rect x=\"%lf\" y=\"%lf\" width=\"%lf\" height=\"%lf\" "
"fill=\"#%06x\" stroke=\"#000000\" stroke-width=\"0.2\" "
"inkscape:label=\"%s\"/>\n",
start * hscale,
thread * vscale,
(stop-start) * hscale,
0.9 * vscale,
Color[EventColorThread[thread][event]].value,
Label[EventColorThread[thread][event]]);
}
}
// output legend
int x = 0;
int y = IMAGE_HEIGHT+50;
for (int color = 0; color < NumColors; color++) {
if (Label[color] != NULL) {
fprintf(
trace_file,
"<rect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" "
"fill=\"#%06x\" stroke=\"#000000\" stroke-width=\"1\"/>\n"
"<text x=\"%d\" y=\"%d\" "
"font-family=\"monospace\" font-size=\"35\" fill=\"black\">"
"%s</text>\n",
x, y,
50, 50,
Color[color].value,
x+75, y+36,
Label[color]);
x += 150;
x += strlen(Label[color])*22;
if (x > IMAGE_WIDTH) {
x = 0;
y += 100;
}
}
}
// output xticks time scale
// xtick spacing is power of 10, with at most 20 tick marks
double pwr = ceil( log10( total_time / 20 ));
double xtick = pow( 10., pwr );
int decimal_places = (pwr < 0 ? (int)-pwr : 0);
for (double t = 0; t < total_time; t += xtick) {
fprintf(
trace_file,
"<line x1=\"%f\" x2=\"%f\" y1=\"%f\" y2=\"%f\" "
"stroke=\"#000000\" stroke-width=\"1\" />\n"
"<text x=\"%f\" y=\"%f\" "
"font-family=\"monospace\" font-size=\"35\">%.*f</text>\n",
hscale * t,
hscale * t,
vscale * NumThreads,
vscale * (NumThreads + 0.9),
hscale * (t + 0.05*xtick),
vscale * (NumThreads + 0.9),
decimal_places, t);
}
fprintf(trace_file, "</svg>\n");
fclose(trace_file);
fprintf(stderr, "trace file: %s\n", file_name);
}
//------------------------------------------------------------------------------
__attribute__ ((constructor))
static void trace_init()
{
// Check if the maximums are powers of two.
assert (__builtin_popcount(MAX_THREADS) == 1);
assert (__builtin_popcount(MAX_THREAD_EVENTS) == 1);
// Initialize the color map.
for (int i = 0; i < NumColors; i++)
ColorMap[color_index(Color[i].color)] = i;
// Clip the number of threads.
NumThreads = omp_get_max_threads() < MAX_THREADS ?
omp_get_max_threads() : MAX_THREADS;
// Register the destructor.
atexit(trace_finish);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.