file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/1061853.c | /*
* $Id: ttysize.c,v 1.1 2018/06/09 02:03:03 tom Exp $
*
* ttysize.c -- obtain terminal-size for dialog
*
* Copyright 2018 Thomas E. Dickey
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License, version 2.1
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to
* Free Software Foundation, Inc.
* 51 Franklin St., Fifth Floor
* Boston, MA 02110, USA.
*
* An earlier version of this program lists as authors
* Savio Lam ([email protected])
*/
#include <dialog.h>
/*
* This is based on work I did for ncurses in 1997, and improved/extended for
* other terminal-based programs. The comments are from my original version -TD
*/
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef NEED_PTEM_H
/* On SCO, they neglected to define struct winsize in termios.h -- it's only
* in termio.h and ptem.h (the former conflicts with other definitions).
*/
# include <sys/stream.h>
# include <sys/ptem.h>
#endif
/*
* SCO defines TIOCGSIZE and the corresponding struct. Other systems (SunOS,
* Solaris, IRIX) define TIOCGWINSZ and struct winsize.
*/
#if defined(TIOCGSIZE)
# define IOCTL_WINSIZE TIOCGSIZE
# define STRUCT_WINSIZE struct ttysize
# define WINSIZE_ROWS(n) (int)n.ts_lines
# define WINSIZE_COLS(n) (int)n.ts_cols
#elif defined(TIOCGWINSZ)
# define IOCTL_WINSIZE TIOCGWINSZ
# define STRUCT_WINSIZE struct winsize
# define WINSIZE_ROWS(n) (int)n.ws_row
# define WINSIZE_COLS(n) (int)n.ws_col
#else
# undef HAVE_SIZECHANGE
#endif
int
dlg_ttysize(int fd, int *high, int *wide)
{
int rc = -1;
#ifdef HAVE_SIZECHANGE
if (isatty(fd)) {
STRUCT_WINSIZE size;
if (ioctl(fd, IOCTL_WINSIZE, &size) >= 0) {
*high = WINSIZE_ROWS(size);
*wide = WINSIZE_COLS(size);
rc = 0;
}
}
#else
high = 24;
wide = 80;
#endif /* HAVE_SIZECHANGE */
return rc;
}
|
the_stack_data/154826758.c | /**
* BOJ 1004번 C언어 소스 코드
* 작성자 : 동동매니저 (DDManager)
*
* ※ 실행 결과
* 사용 메모리 : 1,116 KB / 131,072 KB
* 소요 시간 : 0 ms / 2,000 ms
*
* Copyright 2019. DDManager all rights reserved.
*/
#include <stdio.h>
int check(int x,int xx,int y,int yy,int r){return (x-xx)*(x-xx)+(y-yy)*(y-yy)<r*r;}
int main(void){
int T,i;
scanf("%d",&T);
for(i=0;i<T;i++){
int sx,sy,ex,ey,n,x,y,r,j,c1,c2,cnt=0;
scanf("%d %d %d %d",&sx,&sy,&ex,&ey);
scanf("%d",&n);
for(j=0;j<n;j++){
scanf("%d %d %d",&x,&y,&r);
c1=check(x,sx,y,sy,r);
c2=check(x,ex,y,ey,r);
if(c1&&c2) continue;
else if(c1||c2) cnt++;
}
printf("%d\n",cnt);
}
return 0;
} |
the_stack_data/220456763.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
#include <stdlib.h>
extern int __VERIFIER_nondet_int(void);
static void fail(void) {
ERROR: __VERIFIER_error();
}
#define ___SL_ASSERT(cond) do { \
if (!(cond)) \
fail(); \
} while (0)
struct slave_item {
struct slave_item *next;
struct slave_item *prev;
};
struct slave_item* alloc_or_die_slave(void)
{
struct slave_item *ptr = malloc(sizeof(*ptr));
if (!ptr)
abort();
ptr->next = NULL;
ptr->prev = NULL;
return ptr;
}
struct master_item {
struct master_item *next;
struct master_item *prev;
struct slave_item *slave;
};
struct master_item* alloc_or_die_master(void)
{
struct master_item *ptr = malloc(sizeof(*ptr));
if (!ptr)
abort();
ptr->next = NULL;
ptr->prev = NULL;
ptr->slave = NULL;
return ptr;
}
// the argument should be of type 'struct slave_item**'
void dll_insert_slave(void **dll)
{
struct slave_item *item = alloc_or_die_slave();
struct slave_item *next = *dll;
item->next = next;
if (next)
next->prev = item;
*dll = item;
}
void* dll_create_generic(void (*insert_fnc)(void**))
{
void *dll = NULL;
insert_fnc(&dll);
insert_fnc(&dll);
while (__VERIFIER_nondet_int())
insert_fnc(&dll);
return dll;
}
struct slave_item* dll_create_slave(void)
{
return dll_create_generic(dll_insert_slave);
}
void dll_destroy_slave(struct slave_item *dll)
{
while (dll) {
struct slave_item *next = dll->next;
free(dll);
dll = next;
}
}
void dll_destroy_nested_lists(struct master_item *dll)
{
while (dll) {
dll_destroy_slave(dll->slave);
dll = dll->next;
}
}
void dll_reinit_nested_lists(struct master_item *dll)
{
while (dll) {
dll->slave = NULL;
dll = dll->next;
}
}
void dll_destroy_master(struct master_item *dll)
{
while (dll) {
struct master_item *next = dll->next;
free(dll);
dll = next;
}
}
// the argument should be of type 'struct master_item**'
void dll_insert_master(void **dll)
{
struct master_item *item = alloc_or_die_master();
struct master_item *next = *dll;
item->next = next;
if (next)
next->prev = item;
item->slave = dll_create_slave();
*dll = item;
}
struct master_item* dll_create_master(void)
{
return dll_create_generic(dll_insert_master);
}
void inspect_base(struct master_item *dll)
{
___SL_ASSERT(dll);
___SL_ASSERT(dll->next);
___SL_ASSERT(!dll->prev);
for (dll = dll->next; dll; dll = dll->next) {
___SL_ASSERT(dll->prev);
___SL_ASSERT(dll->prev->next);
___SL_ASSERT(dll->prev->next == dll);
}
}
void inspect_full(struct master_item *dll)
{
inspect_base(dll);
for (; dll; dll = dll->next) {
struct slave_item *pos = dll->slave;
___SL_ASSERT(pos);
___SL_ASSERT(pos->next);
___SL_ASSERT(!pos->prev);
for (pos = pos->next; pos; pos = pos->next) {
___SL_ASSERT(pos->prev);
___SL_ASSERT(pos->prev->next);
___SL_ASSERT(pos->prev->next == pos);
}
}
}
void inspect_dangling(struct master_item *dll)
{
inspect_base(dll);
for (; dll; dll = dll->next)
___SL_ASSERT(dll->slave);
}
void inspect_init(struct master_item *dll)
{
inspect_base(dll);
for (; dll; dll = dll->next)
___SL_ASSERT(!dll->slave);
}
int main()
{
struct master_item *dll = dll_create_master();
inspect_full(dll);
dll_destroy_nested_lists(dll);
inspect_dangling(dll);
dll_reinit_nested_lists(dll);
inspect_init(dll);
// just silence the garbage collector
dll_destroy_master(dll);
return 0;
}
|
the_stack_data/96142.c | #include<unistd.h>
#include<stdio.h>
int main()
{
printf("Before Execution: \n" );
execl("/bin/ls","ls",NULL);
printf("\n After Execution" );
} |
the_stack_data/417022.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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char rcsid[] = "$OpenBSD: fscanf.c,v 1.3 1997/07/25 20:30:09 mickey Exp $";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#ifdef __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif
#ifdef __STDC__
fscanf(FILE *fp, char const *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
#else
fscanf(fp, fmt, va_alist)
FILE *fp;
char *fmt;
va_dcl
{
int ret;
va_list ap;
va_start(ap);
#endif
ret = __svfscanf(fp, fmt, ap);
va_end(ap);
return (ret);
}
|
the_stack_data/39900.c | // vim: set ts=4:
/*
* The MIT License
*
* Copyright 2021 Jakub Jirutka <[email protected]>.
*
* 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 _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#define PROGNAME "zzz"
#ifndef VERSION
#define VERSION "0.1.0"
#endif
#ifndef ZZZ_HOOKS_DIR
#define ZZZ_HOOKS_DIR "/etc/zzz.d"
#endif
#ifndef ZZZ_LOCK_FILE
#define ZZZ_LOCK_FILE "/tmp/zzz.lock"
#endif
#define FLAG_VERBOSE 0x0001
#define ERR_GENERAL 1
#define ERR_WRONG_USAGE 10
#define ERR_UNSUPPORTED 11
#define ERR_LOCK 12
#define ERR_SUSPEND 20
#define ERR_HOOK 21
#define RC_OK 0
#define RC_ERR -1
#define isempty(arg) \
(arg == NULL || arg[0] == '\0')
#define log_err(format, ...) \
do { \
fprintf(stderr, PROGNAME ": ERROR: " format "\n", __VA_ARGS__); \
syslog(LOG_ERR, format, __VA_ARGS__); \
} while (0)
#define log_errno(format, ...) \
log_err(format ": %s", __VA_ARGS__, strerror(errno))
#define log_info(format, ...) \
do { \
syslog(LOG_INFO, format, __VA_ARGS__); \
printf(format "\n", __VA_ARGS__); \
} while (0)
#define log_debug(format, ...) \
if (flags & FLAG_VERBOSE) { \
syslog(LOG_DEBUG, format, __VA_ARGS__); \
printf(format "\n", __VA_ARGS__); \
}
extern char **environ;
static const char *HELP_MSG =
"Usage: " PROGNAME " [-v] [-n|s|S|z|Z|H|R|V|h]\n"
"\n"
"Suspend or hibernate the system.\n"
"\n"
"Options:\n"
" -n Dry run (sleep for 5s instead of suspend/hibernate).\n"
" -s Low-power idle (ACPI S1).\n"
" -S Deprecated alias for -s.\n"
" -z Suspend to RAM (ACPI S3). [default for zzz(8)]\n"
" -Z Hibernate to disk & power off (ACPI S4). [default for ZZZ(8)]\n"
" -H Hibernate to disk & suspend (aka suspend-hybrid).\n"
" -R Hibernate to disk & reboot.\n"
" -v Be verbose.\n"
" -V Print program name & version and exit.\n"
" -h Show this message and exit.\n"
"\n"
"Homepage: https://github.com/jirutka/zzz\n";
static unsigned int flags = 0;
static bool str_ends_with (const char *str, const char *suffix) {
int diff = strlen(str) - strlen(suffix);
return diff > 0 && strcmp(&str[diff], suffix) == 0;
}
static int run_hook (const char *path, const char **argv) {
posix_spawn_file_actions_t factions;
int rc = RC_ERR;
(void) posix_spawn_file_actions_init(&factions);
(void) posix_spawn_file_actions_addclose(&factions, STDIN_FILENO);
log_debug("Executing hook script: %s", path);
argv[0] = path; // XXX: mutates input argument!
pid_t pid;
if ((rc = posix_spawn(&pid, path, &factions, 0, (char *const *)argv, environ)) != 0) {
log_errno("Unable to execute hook script %s", path);
goto done;
}
int status;
(void) waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
rc = WEXITSTATUS(status);
log_err("Hook script %s exited with code %d", path, rc);
goto done;
}
rc = RC_OK;
done:
posix_spawn_file_actions_destroy(&factions);
argv[0] = NULL; // XXX: mutates input argument!
return rc;
}
static int filter_hook_script (const struct dirent *entry) {
struct stat sb;
return stat(entry->d_name, &sb) >= 0
&& S_ISREG(sb.st_mode) // is regular file
&& sb.st_mode & S_IXUSR // is executable by owner
&& !(sb.st_mode & S_IWOTH) // is not writable by others
&& sb.st_uid == 0; // is owned by root
}
static int run_hooks (const char *dirpath, const char **argv) {
struct dirent **entries = NULL;
int rc = RC_OK;
if (chdir(dirpath) < 0) {
errno = 0;
goto done;
}
int n = 0;
if ((n = scandir(".", &entries, filter_hook_script, alphasort)) < 0) {
log_errno("%s", dirpath);
rc = RC_ERR;
goto done;
}
char path[PATH_MAX] = "\0";
for (int i = 0; i < n; i++) {
(void) snprintf(path, sizeof(path), "%s/%s", dirpath, entries[i]->d_name);
if (run_hook(path, argv) != RC_OK) {
rc = RC_ERR;
}
}
done:
if (entries) free(entries);
(void) chdir("/");
return rc;
}
static int check_sleep_mode (const char *filepath, const char *mode) {
FILE *fp = NULL;
int rc = RC_ERR;
if (access(filepath, W_OK) < 0) {
log_errno("%s", filepath);
goto done;
}
char line[64] = "\0";
if ((fp = fopen(filepath, "r")) == NULL || fgets(line, sizeof(line), fp) == NULL) {
log_errno("Failed to read %s", filepath);
goto done;
}
// XXX: This is sloppy...
if (strstr(line, mode) != NULL) {
rc = RC_OK;
}
done:
if (fp) fclose(fp);
return rc;
}
static int file_write (const char *filepath, const char *data) {
FILE *fp = NULL;
int rc = RC_ERR;
if ((fp = fopen(filepath, "w")) == NULL) {
log_errno("%s", filepath);
goto done;
}
(void) setvbuf(fp, NULL, _IONBF, 0); // disable buffering
if (fputs(data, fp) < 0) {
log_errno("%s", filepath);
goto done;
}
rc = RC_OK;
done:
if (fp) fclose(fp);
return rc;
}
static int execute (const char* zzz_mode, const char* sleep_state, const char* hibernate_mode) {
int lock_fd = -1;
int rc = EXIT_SUCCESS;
// Check if we can fulfil the request.
if (!isempty(sleep_state) && check_sleep_mode("/sys/power/state", sleep_state) < 0) {
return ERR_UNSUPPORTED;
}
if (!isempty(hibernate_mode) && check_sleep_mode("/sys/power/disk", hibernate_mode) < 0) {
return ERR_UNSUPPORTED;
}
// Obtain exclusive lock.
if ((lock_fd = open(ZZZ_LOCK_FILE, O_CREAT | O_RDWR | O_CLOEXEC, 0600)) < 0) {
log_errno("Failed to write %s", ZZZ_LOCK_FILE);
return ERR_LOCK;
}
if (flock(lock_fd, LOCK_EX | LOCK_NB) < 0) {
log_err("%s", "Another instance of zzz is running");
return ERR_LOCK;
}
// The first element will be replaced in run_hook() with the script path.
const char *hook_args[] = { NULL, "pre", zzz_mode, NULL };
if (run_hooks(ZZZ_HOOKS_DIR, hook_args) < 0) {
rc = ERR_HOOK;
}
// For compatibility with zzz on Void Linux.
if (run_hooks(ZZZ_HOOKS_DIR "/suspend", hook_args) < 0) {
rc = ERR_HOOK;
}
if (!isempty(hibernate_mode) && file_write("/sys/power/disk", hibernate_mode) < 0) {
rc = ERR_SUSPEND;
goto done;
}
log_info("Going to %s (%s)", zzz_mode, sleep_state);
if (isempty(sleep_state)) {
sleep(5);
} else if (file_write("/sys/power/state", sleep_state) < 0) {
log_err("Failed to %s system", zzz_mode);
rc = ERR_SUSPEND;
goto done;
}
log_info("System resumed from %s (%s)", zzz_mode, sleep_state);
hook_args[1] = "post";
if (run_hooks(ZZZ_HOOKS_DIR, hook_args) < 0) {
rc = ERR_HOOK;
}
// For compatibility with zzz on Void Linux.
if (run_hooks(ZZZ_HOOKS_DIR "/resume", hook_args) < 0) {
rc = ERR_HOOK;
}
done:
// Release lock.
if (unlink(ZZZ_LOCK_FILE) < 0) {
log_errno("Failed to remove lock file %s", ZZZ_LOCK_FILE);
rc = ERR_GENERAL;
}
if (flock(lock_fd, LOCK_UN) < 0) {
log_errno("Failed to release lock on %s", ZZZ_LOCK_FILE);
rc = ERR_GENERAL;
}
(void) close(lock_fd);
return rc;
}
int main (int argc, char **argv) {
char *zzz_mode = "suspend";
char *sleep_state = "mem";
char *hibernate_mode = "";
if (str_ends_with(argv[0], "/ZZZ")) {
zzz_mode = "hibernate";
sleep_state = "disk";
hibernate_mode = "platform";
}
int optch;
opterr = 0; // don't print implicit error message on unrecognized option
while ((optch = getopt(argc, argv, "nsSzHRZvhV")) != -1) {
switch (optch) {
case -1:
break;
case 'n':
zzz_mode = "noop";
sleep_state = "";
hibernate_mode = "";
break;
case 's':
case 'S':
zzz_mode = "standby";
sleep_state = "freeze";
hibernate_mode = "";
break;
case 'z':
zzz_mode = "suspend";
sleep_state = "mem";
hibernate_mode = "";
break;
case 'H':
zzz_mode = "hibernate";
sleep_state = "disk";
hibernate_mode = "suspend";
break;
case 'R':
zzz_mode = "hibernate";
sleep_state = "disk";
hibernate_mode = "reboot";
break;
case 'Z':
zzz_mode = "hibernate";
sleep_state = "disk";
hibernate_mode = "platform";
break;
case 'v':
flags |= FLAG_VERBOSE;
break;
case 'h':
printf("%s", HELP_MSG);
return EXIT_SUCCESS;
case 'V':
puts(PROGNAME " " VERSION);
return EXIT_SUCCESS;
default:
fprintf(stderr, "%1$s: Invalid option: -%2$c (see %1$s -h)\n", PROGNAME, optopt);
return ERR_WRONG_USAGE;
}
}
(void) chdir("/");
// Clear environment variables.
environ = NULL;
// Set environment for hooks.
setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
setenv("ZZZ_MODE", zzz_mode, 1);
setenv("ZZZ_HIBERNATE_MODE", hibernate_mode, 1);
// Open connection to syslog.
openlog(PROGNAME, LOG_PID, LOG_USER);
return execute(zzz_mode, sleep_state, hibernate_mode);
}
|
the_stack_data/1009211.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
typedef struct _node{
char word[50], def[140];//palavra de ate 50 carateres e definicao de ate 140
struct _node *l, *u, *d, *r;//ponteiros para esquerda, cima, baixo e direita
}node;
/*
Em Skip lists eh comum definir o primeiro elemento como -inf e coloca-lo em todos os niveis, como estamos lidando com caracteres podemos definir -inf como 0 (zero) sem perda de generalidade
*/
void clearNode(node *n){//inicializacao de nodos
int i = 0;
for(; i < 50; i++){
n->word[i] = '\0';
n->def[i] = '\0';
}
for(; i < 140; i++)
n->def[i] = '\0';
n->l = NULL;
n->u = NULL;
n->d = NULL;
n->r = NULL;
}
void createaboveSL(node **ward, int *maxlvlcreated){//cria um nivel acima de todos
node *newzero;
newzero = (node *)malloc(sizeof(node));
clearNode(newzero);
newzero->d = *ward;//o novo sentinela->d aponta para o sentina atual
*ward = newzero;//o novo sentinela vira o sentinela atual
(*maxlvlcreated)++;
}
void deleteSL(node *ward){//deleta a SkipList inteira
node *a;
if(ward->d != NULL)//se tiver nodos abaixo chama a deleteSL de novo para a linha de baixo
deleteSL(ward->d);
while(ward != NULL){//enquanto o da direita nao for nulo
a = ward->r;//a guarda o endereco do proximo da direita
free(ward);//libera o atual
ward = a;//o sentinela recebe o proximo da direita
}
}
node *searchSL(node *ptr, char word[50], int lvl, int maxlvlcreated){//procura o elemento com a mesma palavra ou se nao achar retorna o anterior a ela alfabeticamente
if(strcmp(ptr->word, word) == 0)//se for a mesma palavra
if(lvl != maxlvlcreated)//se ainda nao for o nivel maximo ja criado
return searchSL(ptr->d, word, ++lvl, maxlvlcreated);//desce
else
return ptr;//retorna o ponteiro encontrado
else if(strcmp(ptr->word, word) < 0)//strcmp(a, b)//se a palavra no ponteiro for alfabeticamente menor que a que sera inserida
if(ptr->r != NULL)//se o proximo da direita nao for nulo
return searchSL(ptr->r, word, lvl, maxlvlcreated);//vai pra direira
else
if(lvl != maxlvlcreated)//se ainda nao for o nivel maximo ja criado
return searchSL(ptr->d, word, ++lvl, maxlvlcreated);//desce
else
return ptr;//retorna o ponteiro encontrado
else//strcmp(b, a)//se a palavra no ponteiro for alfabeticamente maior que a que sera inserida
if(lvl != maxlvlcreated)//se ainda nao for o nivel maximo ja criado
return searchSL(ptr->l->d, word, ++lvl, maxlvlcreated);//volta para a esquerda e desce
else
return ptr->l;//retorna o da esquerda
}
void insertSL(node **ward, char word[50], char def[140], int *maxlvlcreated){//insere elementos na SkipList
int i = 0, first = 1;
node *a = NULL, *underneath = NULL;
for(i = 0; rand()%2 || first; i++){//se o rand deixar cria niveis acima mas sempre entra uma vez pelo menos a primeira
if(i > *maxlvlcreated)//se o nivel que for criar ainda nao existir
createaboveSL(ward, maxlvlcreated);//crio um acima
a = searchSL(*ward, word, 0, (*maxlvlcreated - i));//procuro na SL do comeco ate o nivel i onde colocar o novo node
/*
a recebe o endereco da busca pela palavra a ser inserida
se ela ainda nao estiver na SkipList retornara um ponteiro para onde ela deve ser colocada em ordem alfabetica
se ela ja estiver mostra operacao invalida
*/
if(strcmp(a->word, word) == 0){
printf("OPERACAO INVALIDA\n");
break;
}
node *newnode;
newnode = (node *)malloc(sizeof(node));//aloca e limpa o novo nodo
clearNode(newnode);
strcpy(newnode->word, word);//coloco as informacoes
strcpy(newnode->def, def);
newnode->l = a;//manipulacoes de ponteiros
newnode->r = a->r;
a->r = newnode;
newnode->d = underneath;//o pontiero para baixo do novo nodo recebe o debaixo
if(underneath != NULL)
underneath->u = newnode;
if(newnode->r != NULL)
newnode->r->l = newnode;
underneath = newnode;//o ponteiro para o debaixo recebe o novo nodo caso seja criado algum acima desse novo
first = 0;
}
}
void removeSL(node *ward, char word[50], int maxlvlcreated){//remove elementos da SL
node *a = searchSL(ward, word, 0, maxlvlcreated);
if(strcmp(a->word, word) == 0)//se achar o nodo com a mesma palavra
while(a != NULL){//enquanto a nao for nulo
ward = a->u;//uso o ponteiro sentinela (sem altera-lo pq aqui ele eh apenas uma copia do original) para guardar o endereco de cima
a->l->r = a->r;//manipulacao de ponteiros
if(a->r != NULL)
a->r->l = a->l;
free(a);//libera a
a = ward;//a recebe o ponteiro guardado
}
else//se nao achar
printf("OPERACAO INVALIDA\n");
}
void changeSL(node *ward, char word[50], char def[140], int maxlvlcreated){//altera a definicao de uma palavra
node *a = searchSL(ward, word, 0, maxlvlcreated);
if(strcmp(a->word, word) != 0)//se nao achar a palavra na SL
printf("OPERACAO INVALIDA\n");
else
while(a != NULL){//enquanto a nao for nulo
strcpy(a->def, def);//altera a definicao
a = a->u;//a recebe o de cima
}
}
int main(){
char c, op, buffer[150], word[51] = {""}, def[141] = {""};//definicoes
int spc = 0, maxlvlcreated = -1, i = 0;//spc = contador de espacos lidos; maxlvlcreated = nives de skiplists criados
node *ward = NULL, *a;//ward = sentinela
createaboveSL(&ward, &maxlvlcreated);//cria a primeira lista
time_t t;
srand((unsigned)time(&t));//defino a seed do rand
while((c = getchar())){
if((c == EOF || c == '\n')){
if(op){//se tiver alguma operacao a ser realizada
if(spc == 1)//se na linha so tem um espaco
strcpy(word, buffer);//agora tenho que tratar uma palavra
else if(spc > 2){//se tiver mais que dois agora tenho que tratar uma definicao
strcat(def, " ");
strcat(def, buffer);
}
if(op == 'n') //iNsercao
insertSL(&ward, word, def, &maxlvlcreated);//chama a funcao insere
else if(op == 'l') //aLteracao
changeSL(ward, word, def, maxlvlcreated);//chama a funcao altera
else if(op == 'e') //rEmocao
removeSL(ward, word, maxlvlcreated);//chama a funcao remove
else if(op == 'u'){ //bUsca
a = searchSL(ward, word, 0, maxlvlcreated);//chama a funcao busca
if(strcmp(a->word, word) != 0)//se nao encontrar a palavra
printf("OPERACAO INVALIDA\n");
else//se encontrar
printf("%s %s\n", a->word, a->def);
}
else if(op == 'm'){//iMpressao
a = searchSL(ward, word, 0, maxlvlcreated);//chama a funcao busca
a = a->r;
/*
como nao existem palavras de um unico char a busca vai retornar um nodo antes
vou um nodo pra frente
*/
if(a->word[0] != word[0])//se o char inicial nao for o procurado
printf("NAO HA PALAVRAS INICIADAS POR %c\n", word[0]);
else
while(a->word[0] == word[0]){//enquanto o char inicial for igual ao pedido
printf("%s %s\n", a->word, a->def);//imprime
a = a->r;//vai para a proxima a direita
}
}
else{//se nao reconhecer a operacao
printf("OPERACAO INVALIDA\n");
}
spc = 0;//zera o contador de espacos que tem na linha
op = '\0';//zera a operacao
}
if(c == EOF)
break;
}
else if(c == 'i' || c == 'a' || c == 'r' || c == 'b')//o primeiro getchar pega um char da primeira operacao
ungetc(c, stdin);//entao devolvo ele
else if(c == ' '){
spc++;//aumenta o contador de espacos que tem a linha
if(spc == 1)//se for um tenho que tratar uma operacao
op = buffer[1];
else if(spc == 2)//se for dois tenho que tratar uma palavra
strcpy(word, buffer);
else if(spc == 3)//se for tres comeco a tratar uma definicao
strcpy(def, buffer);
else{//se forem acima de tres coloco um espaco no final e concateno as palavras que vao entrando na definicao
strcat(def, " ");
strcat(def, buffer);
}
}
for(i = 0; (c = getchar()) && (c != ' ') && (c != '\n') && (c != EOF); i++)//pego os chars da entrada
if(((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')))//se forem letras
buffer[i] = c;//entra para o buffer
else
i--;
buffer[i] = '\0';//concluo o buffer
ungetc(c, stdin);//devolvo o ' ', '\n' e o EOF para serem lidos na proxima iteracao do while
}
deleteSL(ward);//libera a SkipList
return 0;
}
|
the_stack_data/167331055.c | main(){
system("shutdown -a");
} |
the_stack_data/206394304.c | const unsigned char GPUImageVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:GPUImage PROJECT:GPUImage-1" "\n"; const double GPUImageVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/88386.c | #include <stdio.h> // printf()
#include <string.h> // strlen()
#include <fcntl.h> // O_WRONLY
#include <unistd.h> // write(), close()
int main()
{
char *temp = "wewakecorp";
int fd;
if (0 < (fd = open("./test.txt", O_WRONLY | O_CREAT | O_EXCL, 0644)))
{
write(fd, temp, strlen(temp));
close(fd);
}
else
{
printf("file open failed.\n");
}
return 0;
}
|
the_stack_data/108933.c | #include<stdio.h>
int main()
{
int t,i,j,n[1000000];
scanf("%d",&t);
for(i=0; i<t; i++)
{
scanf("%d",&n[i]);
}
return 0;
}
|
the_stack_data/69548.c | #include <wchar.h>
int wcsncmp(const wchar_t *l, const wchar_t *r, size_t n)
{
for (; n && *l==*r && *l && *r; n--, l++, r++);
return n ? *l - *r : 0;
}
|
the_stack_data/767787.c | #include <stdio.h>
#include <stdlib.h>
int** matrixReshape(int** nums, int numsSize, int* numsColSize, int r, int c, int* returnSize, int** returnColumnSizes)
{
*returnSize = numsSize;
// Return the matrix itself if the operation is not possible
if ((*numsColSize) * (numsSize) != (r * c))
{
*returnColumnSizes = numsColSize;
return nums;
}
// Else, perform the resizing
int** matrix = malloc(sizeof(int*) * r);
int i, j, counter, row, column;
*returnColumnSizes = malloc(sizeof(int) * r);
counter = 0;
for (i = 0; i < r; i++)
{
int* col = malloc(sizeof(int) * c);
for (j = 0; j < c; j++)
{
row = counter / (*numsColSize);
column = counter % (*numsColSize);
col[j] = nums[row][column];
counter++;
}
(*returnColumnSizes)[i] = c;
matrix[i] = col;
}
*returnSize = r;
return matrix;
}
int main(void)
{
int** resizedM;
int a1[] = {1, 2};
int b1[] = {3, 4};
int* m[] = {a1,b1};
int a = 2;
int r;
int* cs;
resizedM = matrixReshape(m, 2, &a, 4, 1, &r, &cs);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 1; j++)
{
printf("%i", resizedM[i][j]);
}
printf("\n");
}
return 0;
}
|
the_stack_data/86075944.c | #define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MINORBITS 8
#define MKDEV(ma,mi) (((ma) << MINORBITS) | (mi))
#define MAX_ID_LEN 40
#define MAX_NAME_LEN 40
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
#define VERSION "1.0.1"
/* These are all stolen from busybox's libbb to make
* error handling simpler (and since I maintain busybox,
* I'm rather partial to these for error handling).
* -Erik
*/
static const char *const app_name = "makedevs";
static const char *const memory_exhausted = "memory exhausted";
static char default_rootdir[]=".";
static char *rootdir = default_rootdir;
static int trace = 0;
struct name_id {
char name[MAX_NAME_LEN+1];
unsigned long id;
struct name_id *next;
};
static struct name_id *usr_list = NULL;
static struct name_id *grp_list = NULL;
static void verror_msg(const char *s, va_list p)
{
fflush(stdout);
fprintf(stderr, "%s: ", app_name);
vfprintf(stderr, s, p);
}
static void error_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
verror_msg(s, p);
va_end(p);
putc('\n', stderr);
exit(EXIT_FAILURE);
}
static void vperror_msg(const char *s, va_list p)
{
int err = errno;
if (s == 0)
s = "";
verror_msg(s, p);
if (*s)
s = ": ";
fprintf(stderr, "%s%s\n", s, strerror(err));
}
static void perror_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
vperror_msg(s, p);
va_end(p);
exit(EXIT_FAILURE);
}
static FILE *xfopen(const char *path, const char *mode)
{
FILE *fp;
if ((fp = fopen(path, mode)) == NULL)
perror_msg_and_die("%s", path);
return fp;
}
static char *xstrdup(const char *s)
{
char *t;
if (s == NULL)
return NULL;
t = strdup(s);
if (t == NULL)
error_msg_and_die(memory_exhausted);
return t;
}
static struct name_id* alloc_node(void)
{
struct name_id *node;
node = (struct name_id*)malloc(sizeof(struct name_id));
if (node == NULL) {
error_msg_and_die(memory_exhausted);
}
memset((void *)node->name, 0, MAX_NAME_LEN+1);
node->id = 0xffffffff;
node->next = NULL;
return node;
}
static struct name_id* parse_line(char *line)
{
char *p;
int i;
char id_buf[MAX_ID_LEN+1];
struct name_id *node;
node = alloc_node();
p = line;
i = 0;
// Get name field
while (*p != ':') {
if (i > MAX_NAME_LEN)
error_msg_and_die("Name field too long");
node->name[i++] = *p++;
}
node->name[i] = '\0';
p++;
// Skip the second field
while (*p != ':')
p++;
p++;
// Get id field
i = 0;
while (*p != ':') {
if (i > MAX_ID_LEN)
error_msg_and_die("ID filed too long");
id_buf[i++] = *p++;
}
id_buf[i] = '\0';
node->id = atol(id_buf);
return node;
}
static void get_list_from_file(FILE *file, struct name_id **plist)
{
char *line;
int len = 0;
size_t length = 256;
struct name_id *node, *cur;
if((line = (char *)malloc(length)) == NULL) {
error_msg_and_die(memory_exhausted);
}
while ((len = getline(&line, &length, file)) != -1) {
node = parse_line(line);
if (*plist == NULL) {
*plist = node;
cur = *plist;
} else {
cur->next = node;
cur = cur->next;
}
}
if (line)
free(line);
}
static unsigned long convert2guid(char *id_buf, struct name_id *search_list)
{
char *p;
int isnum;
struct name_id *node;
p = id_buf;
isnum = 1;
while (*p != '\0') {
if (!isdigit(*p)) {
isnum = 0;
break;
}
p++;
}
if (isnum) {
// Check for bad user/group name
node = search_list;
while (node != NULL) {
if (!strncmp(node->name, id_buf, strlen(id_buf))) {
fprintf(stderr, "WARNING: Bad user/group name %s detected\n", id_buf);
break;
}
node = node->next;
}
return (unsigned long)atol(id_buf);
} else {
node = search_list;
while (node != NULL) {
if (!strncmp(node->name, id_buf, strlen(id_buf)))
return node->id;
node = node->next;
}
error_msg_and_die("No entry for %s in search list", id_buf);
}
}
static void free_list(struct name_id *list)
{
struct name_id *cur;
cur = list;
while (cur != NULL) {
list = cur;
cur = cur->next;
free(list);
}
}
static void add_new_directory(char *name, char *path,
unsigned long uid, unsigned long gid, unsigned long mode)
{
if (trace)
fprintf(stderr, "Directory: %s %s UID: %ld GID %ld MODE: %04lo", path, name, uid, gid, mode);
if (mkdir(path, mode) < 0) {
if (EEXIST == errno) {
/* Unconditionally apply the mode setting to the existing directory.
* XXX should output something when trace */
chmod(path, mode & ~S_IFMT);
}
}
if (trace)
putc('\n', stderr);
chown(path, uid, gid);
}
static void add_new_device(char *name, char *path, unsigned long uid,
unsigned long gid, unsigned long mode, dev_t rdev)
{
int status;
struct stat sb;
if (trace) {
fprintf(stderr, "Device: %s %s UID: %ld GID: %ld MODE: %04lo MAJOR: %d MINOR: %d",
path, name, uid, gid, mode, (short)(rdev >> 8), (short)(rdev & 0xff));
}
memset(&sb, 0, sizeof(struct stat));
status = lstat(path, &sb);
if (status >= 0) {
/* It is ok for some types of files to not exit on disk (such as
* device nodes), but if they _do_ exist, the file type bits had
* better match those of the actual file or strange things will happen... */
if ((mode & S_IFMT) != (sb.st_mode & S_IFMT)) {
if (trace)
putc('\n', stderr);
error_msg_and_die("%s: existing file (04%o) type does not match specified file type (04%lo)!",
path, (sb.st_mode & S_IFMT), (mode & S_IFMT));
}
if (mode != sb.st_mode) {
if (trace)
fprintf(stderr, " -- applying new mode 04%lo (old was 04%o)\n", mode & ~S_IFMT, sb.st_mode & ~S_IFMT);
/* Apply the mode setting to the existing device node */
chmod(path, mode & ~S_IFMT);
}
else {
if (trace)
fprintf(stderr, " -- extraneous entry in table\n", path);
}
}
else {
mknod(path, mode, rdev);
if (trace)
putc('\n', stderr);
}
chown(path, uid, gid);
}
static void add_new_file(char *name, char *path, unsigned long uid,
unsigned long gid, unsigned long mode)
{
if (trace) {
fprintf(stderr, "File: %s %s UID: %ld GID: %ld MODE: %04lo\n",
path, name, gid, uid, mode);
}
int fd = open(path,O_CREAT | O_WRONLY, mode);
if (fd < 0) {
error_msg_and_die("%s: file can not be created!", path);
} else {
close(fd);
}
chmod(path, mode);
chown(path, uid, gid);
}
static void add_new_fifo(char *name, char *path, unsigned long uid,
unsigned long gid, unsigned long mode)
{
if (trace) {
printf("Fifo: %s %s UID: %ld GID: %ld MODE: %04lo\n",
path, name, gid, uid, mode);
}
int status;
struct stat sb;
memset(&sb, 0, sizeof(struct stat));
status = stat(path, &sb);
/* Update the mode if we exist and are a fifo already */
if (status >= 0 && S_ISFIFO(sb.st_mode)) {
chmod(path, mode);
} else {
if (mknod(path, mode, 0))
error_msg_and_die("%s: file can not be created with mknod!", path);
}
chown(path, uid, gid);
}
/* device table entries take the form of:
<path> <type> <mode> <usr> <grp> <major> <minor> <start> <inc> <count>
/dev/mem c 640 0 0 1 1 0 0 -
/dev/zero c 644 root root 1 5 - - -
type can be one of:
f A regular file
d Directory
c Character special device file
b Block special device file
p Fifo (named pipe)
I don't bother with symlinks (permissions are irrelevant), hard
links (special cases of regular files), or sockets (why bother).
Regular files must exist in the target root directory. If a char,
block, fifo, or directory does not exist, it will be created.
*/
static int interpret_table_entry(char *line)
{
char *name;
char usr_buf[MAX_ID_LEN];
char grp_buf[MAX_ID_LEN];
char path[4096], type;
unsigned long mode = 0755, uid = 0, gid = 0, major = 0, minor = 0;
unsigned long start = 0, increment = 1, count = 0;
if (0 > sscanf(line, "%40s %c %lo %40s %40s %lu %lu %lu %lu %lu", path,
&type, &mode, usr_buf, grp_buf, &major, &minor, &start,
&increment, &count))
{
fprintf(stderr, "%s: sscanf returned < 0 for line '%s'\n", app_name, line);
return 1;
}
uid = convert2guid(usr_buf, usr_list);
gid = convert2guid(grp_buf, grp_list);
if (strncmp(path, "/", 1)) {
error_msg_and_die("Device table entries require absolute paths");
}
name = xstrdup(path + 1);
/* prefix path with rootdir */
sprintf(path, "%s/%s", rootdir, name);
/* XXX Why is name passed into all of the add_new_*() routines? */
switch (type) {
case 'd':
mode |= S_IFDIR;
add_new_directory(name, path, uid, gid, mode);
break;
case 'f':
mode |= S_IFREG;
add_new_file(name, path, uid, gid, mode);
break;
case 'p':
mode |= S_IFIFO;
add_new_fifo(name, path, uid, gid, mode);
break;
case 'c':
case 'b':
mode |= (type == 'c') ? S_IFCHR : S_IFBLK;
if (count > 0) {
int i;
dev_t rdev;
char buf[80];
for (i = start; i < start + count; i++) {
sprintf(buf, "%s%d", name, i);
sprintf(path, "%s/%s%d", rootdir, name, i);
/* FIXME: MKDEV uses illicit insider knowledge of kernel
* major/minor representation... */
rdev = MKDEV(major, minor + (i - start) * increment);
sprintf(path, "%s/%s\0", rootdir, buf);
add_new_device(buf, path, uid, gid, mode, rdev);
}
} else {
/* FIXME: MKDEV uses illicit insider knowledge of kernel
* major/minor representation... */
dev_t rdev = MKDEV(major, minor);
add_new_device(name, path, uid, gid, mode, rdev);
}
break;
default:
error_msg_and_die("Unsupported file type");
}
if (name) free(name);
return 0;
}
static void parse_device_table(FILE * file)
{
char *line;
size_t length = 256;
int len = 0;
if((line = (char *)malloc(length)) == NULL) {
error_msg_and_die(memory_exhausted);
}
/* Looks ok so far. The general plan now is to read in one
* line at a time, trim off leading and trailing whitespace,
* check for leading comment delimiters ('#') or a blank line,
* then try and parse the line as a device table entry. If we fail
* to parse things, try and help the poor fool to fix their
* device table with a useful error msg... */
while ((len = getline(&line, &length, file)) != -1) {
/* First trim off any whitespace */
/* trim trailing whitespace */
while (len > 0 && isspace(line[len - 1]))
line[--len] = '\0';
/* trim leading whitespace */
memmove(line, &line[strspn(line, " \n\r\t\v")], len + 1);
/* If this is NOT a comment or an empty line, try to interpret it */
if (*line != '#' && *line != '\0') interpret_table_entry(line);
}
if (line)
free(line);
}
static int parse_devtable(FILE * devtable)
{
struct stat sb;
if (lstat(rootdir, &sb)) {
perror_msg_and_die("%s", rootdir);
}
if (chdir(rootdir))
perror_msg_and_die("%s", rootdir);
if (devtable)
parse_device_table(devtable);
return 0;
}
static struct option long_options[] = {
{"root", 1, NULL, 'r'},
{"help", 0, NULL, 'h'},
{"trace", 0, NULL, 't'},
{"version", 0, NULL, 'v'},
{"devtable", 1, NULL, 'D'},
{NULL, 0, NULL, 0}
};
static char *helptext =
"Usage: makedevs [OPTIONS]\n"
"Build entries based upon device_table.txt\n\n"
"Options:\n"
" -r, -d, --root=DIR Build filesystem from directory DIR (default: cwd)\n"
" -D, --devtable=FILE Use the named FILE as a device table file\n"
" -h, --help Display this help text\n"
" -t, --trace Be verbose\n"
" -v, --version Display version information\n\n";
int main(int argc, char **argv)
{
int c, opt;
extern char *optarg;
struct stat statbuf;
char passwd_path[PATH_MAX];
char group_path[PATH_MAX];
FILE *passwd_file = NULL;
FILE *group_file = NULL;
FILE *devtable = NULL;
DIR *dir = NULL;
umask (0);
if (argc==1) {
fprintf(stderr, helptext);
exit(1);
}
while ((opt = getopt_long(argc, argv, "D:d:r:htv",
long_options, &c)) >= 0) {
switch (opt) {
case 'D':
devtable = xfopen(optarg, "r");
if (fstat(fileno(devtable), &statbuf) < 0)
perror_msg_and_die(optarg);
if (statbuf.st_size < 10)
error_msg_and_die("%s: not a proper device table file", optarg);
break;
case 'h':
printf(helptext);
exit(0);
case 'r':
case 'd': /* for compatibility with mkfs.jffs, genext2fs, etc... */
if (rootdir != default_rootdir) {
error_msg_and_die("root directory specified more than once");
}
if ((dir = opendir(optarg)) == NULL) {
perror_msg_and_die(optarg);
} else {
closedir(dir);
}
/* If "/" is specified, use "" because rootdir is always prepended to a
* string that starts with "/" */
if (0 == strcmp(optarg, "/"))
rootdir = xstrdup("");
else
rootdir = xstrdup(optarg);
break;
case 't':
trace = 1;
break;
case 'v':
printf("%s: %s\n", app_name, VERSION);
exit(0);
default:
fprintf(stderr, helptext);
exit(1);
}
}
if (argv[optind] != NULL) {
fprintf(stderr, helptext);
exit(1);
}
// Get name-id mapping
sprintf(passwd_path, "%s/etc/passwd", rootdir);
sprintf(group_path, "%s/etc/group", rootdir);
if ((passwd_file = fopen(passwd_path, "r")) != NULL) {
get_list_from_file(passwd_file, &usr_list);
fclose(passwd_file);
}
if ((group_file = fopen(group_path, "r")) != NULL) {
get_list_from_file(group_file, &grp_list);
fclose(group_file);
}
// Parse devtable
if(devtable) {
parse_devtable(devtable);
fclose(devtable);
}
// Free list
free_list(usr_list);
free_list(grp_list);
return 0;
}
|
the_stack_data/147437.c | #include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len)
{
int i;
for (i = 0; i < len; i++)
printf(" %02x", start[i]);
printf("\n");
}
void show_int(int x)
{
show_bytes((byte_pointer) &x, sizeof(x));
}
void show_float(float x)
{
show_bytes((byte_pointer) &x, sizeof(x));
}
void show_pointer(void *x)
{
show_bytes((byte_pointer) &x, sizeof(x));
}
int main()
{
int ival = 1;
float fval = (float) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
} |
the_stack_data/111079141.c | // clang-format off
// RUN: %c-to-llvm %s | %apply-typeart -S | %filecheck %s
// RUN: %c-to-llvm %s | %apply-typeart -S 2>&1 | %filecheck %s --check-prefix=PASS-OUT
// clang-format on
#include <stdlib.h>
void test() {
void* p = malloc(42 * sizeof(int)); // LLVM-IR: lacks a bitcast
free(p);
}
// CHECK: [[POINTER:%[0-9a-z]+]] = call noalias{{( align [0-9]+)?}} i8* @malloc
// CHECK-NEXT: call void @__typeart_alloc(i8* [[POINTER]],
// CHECK-NOT: bitcast i8* [[POINTER]] to i32*
// CHECK: call void @free(i8* [[POINTER:%[0-9a-z]+]])
// CHECK-NEXT: call void @__typeart_free(i8* [[POINTER]])
// PASS-OUT: TypeArtPass [Heap]
// PASS-OUT-NEXT: Malloc{{[ ]*}}:{{[ ]*}}1
// PASS-OUT-NEXT: Free{{[ ]*}}:{{[ ]*}}1
// PASS-OUT-NEXT: Alloca{{[ ]*}}:{{[ ]*}}0
|
the_stack_data/61074048.c | #include <stdio.h>
#include <arpa/inet.h>
int big_to_little(int i){
int l = 0;
l = i>>24;
l |= ((i)&0xff0000)>>8;
l |= ((i)&0xff00)<<8;
l |= ((i)&0xff)<<24;
return l;
}
int swap_endian(int i){
char *p = (char *)&i;
char r[4] = {p[3],p[2],p[1],p[0]};
int * t = (int*)r;
return *t;
}
int main(){
int i,l,m,n,o;
scanf("%x", &i);
printf("0x%x\n", i);
l = big_to_little(i);
m = htonl(i);
n = ntohl(i);
o = swap_endian(i);
printf("0x%x\n",l);
printf("0x%x\n",m);
printf("0x%x\n",n);
printf("0x%x\n",o);
return 0;
}
|
the_stack_data/20450432.c | #include <stdio.h>
void rotate(int* nums, int numsSize, int k) {
while(k>=numsSize) {
k=k-numsSize;
}
if(k!=0) {
int a[k];
int i;
i=numsSize-k;
while(i<=numsSize-1) {
a[i+k-numsSize]=nums[i];
i=i+1;
}
i=numsSize-k-1;
while(i>=0) {
nums[i+k]=nums[i];
i=i-1;
}
i=0;
while(i<k) {
nums[i]=a[i];
i=i+1;
}
}
}
// for (int i = 0; i < k; i++) {
// m = nums[numsSize-1];
// for (size_t n = numsSize-1; n > 0; n--){
// nums[n] = nums[n-1];
// }
// nums[0] = m;
// }
int main(){
printf("test c main\n");
int a[6] = {1,2,3,4,5,6};
rotate(a,6,2);
for (size_t i = 0; i < 5; i++) {
/* code */
printf("%d\n", a[i]);
}
return 0;
}
|
the_stack_data/45451349.c | #include "stdio.h"
#ifndef EM_PORT_API
# if defined(__EMSCRIPTEN__)
# include <emscripten.h>
# if defined(__cplusplus)
# define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
# else
# define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
# endif
# else
# if defined(__cplusplus)
# define EM_PORT_API(rettype) extern "C" rettype
# else
# define EM_PORT_API(rettype) rettype
# endif
# endif
#endif
// emcc hello.c -o hello.js -s STANDALONE_WASM
//int main(){
// printf("hello world\n");
// return 0;
//}
// emcc -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['cwrap','ccall']\" hello.c -o hello.js
// emcc -o export.js export.c -s WASM=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']"
// emcc -o export.js export.c -s WASM=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']" -s STANDALONE_WASM
// emcc -o export.js export.c -O3 -s WASM=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']" -s STANDALONE_WASM
EM_PORT_API(int) show_me_the_answer() {
return 42;
} |
the_stack_data/182954323.c | int fun(int *a, int *b, int num)
{
int c[num];
for (int i = 0; i < num; i++)
{
c[i] = a[i] + b[i];
}
return c[0];
}
|
the_stack_data/26700972.c | #include <stdio.h>
void main() {
printf("Hello World!\n");
} |
the_stack_data/25697.c | // Write a C program to convert hexadecimal number to decimal number
#include<stdio.h>
int main()
{
long int hex;
printf("Enter a hexadecimal number\n");
scanf("%x",&hex);
printf("Entered hexadecimal number is %x\n",hex);
printf("Equivalent decimal number is %ld",hex);
}
/*Output:
Enter a hexadecimal number
2d
Entered hexadecimal number is 2d
Equivalent decimal number is 45*/ |
the_stack_data/482339.c | #include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 1024
// <цифра> ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
// <число> ::= <цифра> { <цифра> } [ '.' <цифра> { <цифра> } ]
//
// <выражение> ::= <слагаемое> [ ( '+' | '-' ) <слагаемое> ]
// <слагаемое> ::= <множитель> [ ( '*' | '/' ) <множитель> ]
// <множитель> ::= ( <число> | '(' <выражение> ')' ) [ '^' <множитель> ]
int say_hello_math(int val) {
printf("Hello From Math\n");
return val * val;
}
float eval(char *str);
float number(char *, unsigned *);
float expr(char *, unsigned *);
float term(char *, unsigned *);
float factor(char *, unsigned *);
/*int main() {
char str[BUF_SIZE];
printf("Enter expression: ");
fgets(str, BUF_SIZE, stdin);
printf("Result: %lf\n", eval(str));
return 0;
}*/
float eval(char *str) {
unsigned i = 0;
return expr(str, &i);
}
float number(char *str, unsigned *idx) {
float result = 0.0;
float div = 10.0;
int sign = 1;
if (str[*idx] == '-'){
sign = -1;
++*idx;
}
while (str[*idx] >= '0' && str[*idx] <= '9'){
result = result * 10.0 + (str[*idx] - '0');
++*idx;
}
if (str[*idx] == '.'){
++*idx;
while (str[*idx] >= '0' && str[*idx] <= '9'){
result = result + (str[*idx] - '0') / div;
div *= 10.0;
++*idx;
}
}
return sign * result;
}
float expr(char *str, unsigned *idx) {
float result = term(str, idx);
while (str[*idx] == '+' || str[*idx] == '-') {
switch (str[*idx]) {
case '+':
++*idx;
result += term(str, idx);
break;
case '-':
++*idx;
result -= term(str, idx);
break;
}
}
return result;
}
float term(char *str, unsigned *idx) {
float result = factor(str, idx);
float div;
while (str[*idx] == '*' || str[*idx] == '/') {
switch (str[*idx]) {
case '*':
++*idx;
result *= factor(str, idx);
break;
case '/':
++*idx;
div = factor(str, idx);
if (div != 0.0)
{
result /= div;
}
else
{
printf("Division by zero!\n");
exit(-1);
}
break;
}
}
return result;
}
float factor(char *str, unsigned *idx) {
float result;
int sign = 1;
if (str[*idx] == '-') {
sign = -1;
++*idx;
}
if (str[*idx] == '(') {
++*idx;
result = expr(str, idx);
if (str[*idx] != ')')
{
printf("Brackets unbalanced!\n");
exit(-2);
}
++*idx;
}
else
result = number(str, idx);
/*if (str[*idx] == '^')
{
++*idx;
result = pow(result, factor(str, idx));
}*/
return sign * result;
}
|
the_stack_data/145964.c | #define N 100
#define A 1
#define B 2
int func(int a,int b);
int func(int a,int b){
int c;
c = a + b * N;
return c;
}
int main(){
int c;
c = func(A,B);
return c;
}
|
the_stack_data/150140179.c | #include <stdio.h>
int a[30000];
int n;
int N(int l,int r)
{
int i,m=0;
for(i=l;i<=r;i++)
m=m+a[i];
return m%n;
}
int M(int l,int r)
{
int i,m=1,q=1;
for(i=l;i<=(r+l)/2;i++)
{m=m*a[i];
m=m%n;}
for(i;i<=r;i++)
{q=q*a[i];
q=q%n;}
m=(m*q)%n;
return m;
}
int H(int l,int r)
{
int i,m=0;
for(i=l;i<=r;i++)
m=m^a[i];
return m;
}
int main()
{
int i,k,d[1000],e[1000];
scanf("%d%d", &n, &k);
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
for(i=1;i<=k;i++)
scanf("%d%d",&d[i],&e[i]);
for(i=1;i<=k;i++)
{
if(N(d[i],e[i])>M(d[i],e[i]))
printf("%d",H(M(d[i],e[i]),N(d[i],e[i])));
else
printf("%d",H(N(d[i],e[i]),M(d[i],e[i])));
if(i!=k)printf("\n");
}
return 0;
} |
the_stack_data/64201430.c | #include <errno.h>
#include <malloc.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
#define handle_error(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)
static char *buffer;
static void handler(int sig, siginfo_t *si, void *unused) {
/* Note: calling printf() from a signal handler is not safe
(and should not be done in production programs), since
printf() is not async-signal-safe; see signal-safety(7).
Nevertheless, we use printf() here as a simple way of
showing that the handler was called. */
printf("Got SIGSEGV at address: %p\n", si->si_addr);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
int pagesize;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_SIGINFO;
//sigemptyset(&sa.sa_mask);
sa.sa_sigaction = handler;
if (sigaction(SIGSEGV, &sa, NULL) == -1)
handle_error("sigaction");
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1)
handle_error("sysconf");
/* Allocate a buffer aligned on a page boundary;
initial protection is PROT_READ | PROT_WRITE */
buffer = memalign(pagesize, 4 * pagesize);
if (buffer == NULL)
handle_error("memalign");
printf("Start of region: %p\n", buffer);
if (mprotect(buffer + pagesize * 2, pagesize, PROT_READ) == -1)
handle_error("mprotect");
for (char *p = buffer;;)
*(p++) = 'a';
printf("Loop completed\n"); /* Should never happen */
exit(EXIT_SUCCESS);
}
|
the_stack_data/132952553.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define handle_error(msg) \
do { \
perror (msg); \
exit (EXIT_FAILURE); \
} while (0)
/* Read text from the socket and print it out. Continue until the
socket closes. Return nonzero if the client sent a "quit"
message, zero otherwise. */
int server (int client_socket)
{
while (1) {
int length;
char *text;
/* First, read the length of the text message from the socket. If
read returns zero, the client closed the connection. */
if (read (client_socket, &length, sizeof (length)) == 0)
return 0;
/* Allocate a buffer to hold the text. */
text = (char *) malloc (length);
/* Read the text itself, and print it. */
read (client_socket, text, length);
printf ("%s\n", text);
/* Free the buffer. */
free (text);
/* If the client sent the message "quit", we're all done. */
if (!strcmp (text, "quit"))
return 1;
}
}
int main (int argc, char *const argv[])
{
const char *const socket_name = argv[1];
int socket_fd;
struct sockaddr_un name;
int client_sent_quit_message;
/* Create the socket. */
socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0);
/* Indicate that this is a server. */
name.sun_family = AF_LOCAL;
strcpy (name.sun_path, socket_name);
if (bind (socket_fd, (struct sockaddr *) &name, SUN_LEN (&name)) == -1)
handle_error ("bind");
/* Listen for connections. */
if (listen (socket_fd, 5) == -1)
handle_error ("listen");
/* Repeatedly accept connections, spinning off one server() to deal
with each client. Continue until a client sends a "quit" message. */
do {
struct sockaddr_un client_name;
socklen_t client_name_len;
int client_socket_fd;
/* Accept a connection. */
client_socket_fd = accept (socket_fd, (struct sockaddr *) &client_name, &client_name_len);
/* Handle the connection. */
client_sent_quit_message = server (client_socket_fd);
/* Close our end of the connection. */
close (client_socket_fd);
} while (!client_sent_quit_message);
/* Remove the socket file. */
close (socket_fd);
unlink (socket_name);
return 0;
}
|
the_stack_data/74957.c | #include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
char* fin = argv[1];
char* fout = argv[2];
int _fout = open(fout, O_WRONLY|O_TRUNC|O_CREAT, S_IRUSR|S_IWUSR);
int _fin = open(fin, O_RDONLY, S_IRUSR|S_IWUSR);
for(int i = 0; i < 3; i++)
{
argv++;
}
int wstatus;
pid_t pid = fork();
if (pid == -1)
{
perror("Something went wrong");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
close(STDIN_FILENO);
close(STDOUT_FILENO);
dup2(_fin, STDIN_FILENO);
dup2(_fout, STDOUT_FILENO);
int status = execvp(argv[0], argv);
if (status < 0)
{
perror("Unable to execute the bash command");
exit(EXIT_FAILURE);
}
}
else do
{
if ((pid = waitpid(pid, &wstatus, WNOHANG)) == -1)
{
perror("Error while waiting for child to terminate");
exit(EXIT_FAILURE);
}
else
{
if (WIFEXITED(wstatus))
{
close(_fout);
close(_fin);
printf("Requested process exited with status: %d.\n", (int)WEXITSTATUS(wstatus));
}
}
} while (pid == 0);
exit(EXIT_SUCCESS);
}
|
the_stack_data/179830812.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
typedef unsigned char BYTE;
typedef unsigned long LONG;
#define SHA_BLOCKSIZE 64
#define SHA_DIGESTSIZE 20
typedef struct {
LONG digest[5]; /* message digest */
LONG count_lo, count_hi; /* 64-bit bit count */
LONG data[16]; /* SHA data buffer */
} SHA_INFO;
void sha_init(SHA_INFO *);
void sha_update(SHA_INFO *, BYTE *, int);
void sha_final(SHA_INFO *);
void sha_stream(SHA_INFO *, FILE *);
void sha_print(SHA_INFO *);
/* SHA f()-functions */
#define f1(x,y,z) ((x & y) | (~x & z))
#define f2(x,y,z) (x ^ y ^ z)
#define f3(x,y,z) ((x & y) | (x & z) | (y & z))
#define f4(x,y,z) (x ^ y ^ z)
/* SHA constants */
#define CONST1 0x5a827999L
#define CONST2 0x6ed9eba1L
#define CONST3 0x8f1bbcdcL
#define CONST4 0xca62c1d6L
/* 32-bit rotate */
#define ROT32(x,n) ((x << n) | (x >> (32 - n)))
#define FUNC(n,i) \
temp = ROT32(A,5) + f##n(B,C,D) + E + W[i] + CONST##n; \
E = D; D = C; C = ROT32(B,30); B = A; A = temp
int main(int argc, char **argv) {
FILE *fin;
SHA_INFO sha_info;
//fin = fopen("input_verylarge.asc", "rb");
fin = fopen("input_large.asc", "rb");
if (fin == NULL) {
printf("error opening %s for reading\n", *argv);
} else {
sha_stream(&sha_info, fin);
sha_print(&sha_info);
fclose(fin);
}
return(0);
}
/* do SHA transformation */
static void sha_transform(SHA_INFO *sha_info)
{
int i;
LONG temp, A, B, C, D, E, W[80];
for (i = 0; i < 16; ++i) {
W[i] = sha_info->data[i];
}
for (i = 16; i < 80; ++i) {
W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
#ifdef USE_MODIFIED_SHA
W[i] = ROT32(W[i], 1);
#endif /* USE_MODIFIED_SHA */
}
A = sha_info->digest[0];
B = sha_info->digest[1];
C = sha_info->digest[2];
D = sha_info->digest[3];
E = sha_info->digest[4];
#ifdef UNROLL_LOOPS
FUNC(1, 0); FUNC(1, 1); FUNC(1, 2); FUNC(1, 3); FUNC(1, 4);
FUNC(1, 5); FUNC(1, 6); FUNC(1, 7); FUNC(1, 8); FUNC(1, 9);
FUNC(1,10); FUNC(1,11); FUNC(1,12); FUNC(1,13); FUNC(1,14);
FUNC(1,15); FUNC(1,16); FUNC(1,17); FUNC(1,18); FUNC(1,19);
FUNC(2,20); FUNC(2,21); FUNC(2,22); FUNC(2,23); FUNC(2,24);
FUNC(2,25); FUNC(2,26); FUNC(2,27); FUNC(2,28); FUNC(2,29);
FUNC(2,30); FUNC(2,31); FUNC(2,32); FUNC(2,33); FUNC(2,34);
FUNC(2,35); FUNC(2,36); FUNC(2,37); FUNC(2,38); FUNC(2,39);
FUNC(3,40); FUNC(3,41); FUNC(3,42); FUNC(3,43); FUNC(3,44);
FUNC(3,45); FUNC(3,46); FUNC(3,47); FUNC(3,48); FUNC(3,49);
FUNC(3,50); FUNC(3,51); FUNC(3,52); FUNC(3,53); FUNC(3,54);
FUNC(3,55); FUNC(3,56); FUNC(3,57); FUNC(3,58); FUNC(3,59);
FUNC(4,60); FUNC(4,61); FUNC(4,62); FUNC(4,63); FUNC(4,64);
FUNC(4,65); FUNC(4,66); FUNC(4,67); FUNC(4,68); FUNC(4,69);
FUNC(4,70); FUNC(4,71); FUNC(4,72); FUNC(4,73); FUNC(4,74);
FUNC(4,75); FUNC(4,76); FUNC(4,77); FUNC(4,78); FUNC(4,79);
#else /* !UNROLL_LOOPS */
for (i = 0; i < 20; ++i) {
FUNC(1,i);
}
for (i = 20; i < 40; ++i) {
FUNC(2,i);
}
for (i = 40; i < 60; ++i) {
FUNC(3,i);
}
for (i = 60; i < 80; ++i) {
FUNC(4,i);
}
#endif /* !UNROLL_LOOPS */
sha_info->digest[0] += A;
sha_info->digest[1] += B;
sha_info->digest[2] += C;
sha_info->digest[3] += D;
sha_info->digest[4] += E;
}
#ifdef LITTLE_ENDIAN
/* change endianness of data */
static void byte_reverse(LONG *buffer, int count)
{
int i;
BYTE ct[4], *cp;
count /= sizeof(LONG);
cp = (BYTE *) buffer;
for (i = 0; i < count; ++i) {
ct[0] = cp[0];
ct[1] = cp[1];
ct[2] = cp[2];
ct[3] = cp[3];
cp[0] = ct[3];
cp[1] = ct[2];
cp[2] = ct[1];
cp[3] = ct[0];
cp += sizeof(LONG);
}
}
#endif /* LITTLE_ENDIAN */
/* initialize the SHA digest */
void sha_init(SHA_INFO *sha_info)
{
sha_info->digest[0] = 0x67452301L;
sha_info->digest[1] = 0xefcdab89L;
sha_info->digest[2] = 0x98badcfeL;
sha_info->digest[3] = 0x10325476L;
sha_info->digest[4] = 0xc3d2e1f0L;
sha_info->count_lo = 0L;
sha_info->count_hi = 0L;
}
/* update the SHA digest */
void sha_update(SHA_INFO *sha_info, BYTE *buffer, int count)
{
if ((sha_info->count_lo + ((LONG) count << 3)) < sha_info->count_lo) {
++sha_info->count_hi;
}
sha_info->count_lo += (LONG) count << 3;
sha_info->count_hi += (LONG) count >> 29;
while (count >= SHA_BLOCKSIZE) {
memcpy(sha_info->data, buffer, SHA_BLOCKSIZE);
#ifdef LITTLE_ENDIAN
byte_reverse(sha_info->data, SHA_BLOCKSIZE);
#endif /* LITTLE_ENDIAN */
sha_transform(sha_info);
buffer += SHA_BLOCKSIZE;
count -= SHA_BLOCKSIZE;
}
memcpy(sha_info->data, buffer, count);
}
/* finish computing the SHA digest */
void sha_final(SHA_INFO *sha_info)
{
int count;
LONG lo_bit_count, hi_bit_count;
lo_bit_count = sha_info->count_lo;
hi_bit_count = sha_info->count_hi;
count = (int) ((lo_bit_count >> 3) & 0x3f);
((BYTE *) sha_info->data)[count++] = 0x80;
if (count > 56) {
memset((BYTE *) &sha_info->data + count, 0, 64 - count);
#ifdef LITTLE_ENDIAN
byte_reverse(sha_info->data, SHA_BLOCKSIZE);
#endif /* LITTLE_ENDIAN */
sha_transform(sha_info);
memset(&sha_info->data, 0, 56);
} else {
memset((BYTE *) &sha_info->data + count, 0, 56 - count);
}
#ifdef LITTLE_ENDIAN
byte_reverse(sha_info->data, SHA_BLOCKSIZE);
#endif /* LITTLE_ENDIAN */
sha_info->data[14] = hi_bit_count;
sha_info->data[15] = lo_bit_count;
sha_transform(sha_info);
}
/* compute the SHA digest of a FILE stream */
#define BLOCK_SIZE 8192
void sha_stream(SHA_INFO *sha_info, FILE *fin)
{
int i;
BYTE data[BLOCK_SIZE];
sha_init(sha_info);
while ((i = fread(data, 1, BLOCK_SIZE, fin)) > 0) {
sha_update(sha_info, data, i);
}
sha_final(sha_info);
}
/* print a SHA digest */
void sha_print(SHA_INFO *sha_info)
{
printf("%08lx %08lx %08lx %08lx %08lx\n",
sha_info->digest[0], sha_info->digest[1], sha_info->digest[2],
sha_info->digest[3], sha_info->digest[4]);
}
|
the_stack_data/43886938.c | // RUN: %clang_cc1 -analyze -analyzer-checker=unix.cstring.BadSizeArg -analyzer-store=region -Wno-strlcpy-strlcat-size -Wno-sizeof-array-argument -Wno-sizeof-pointer-memaccess -verify %s
typedef __SIZE_TYPE__ size_t;
char *strncat(char *, const char *, size_t);
size_t strlen (const char *s);
void testStrncat(const char *src) {
char dest[10];
strncat(dest, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA", sizeof(dest) - 1); // expected-warning {{Potential buffer overflow. Replace with 'sizeof(dest) - strlen(dest) - 1' or use a safer 'strlcat' API}}
strncat(dest, "AAAAAAAAAAAAAAAAAAAAAAAAAAA", sizeof(dest)); // expected-warning {{Potential buffer overflow. Replace with}}
strncat(dest, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", sizeof(dest) - strlen(dest)); // expected-warning {{Potential buffer overflow. Replace with}}
strncat(dest, src, sizeof(src)); // expected-warning {{Potential buffer overflow. Replace with}}
}
|
the_stack_data/59513632.c | /*
* pr_pset13_03.c
* A text file copy program that prompts the user to enter the name of src &
* dst files. It converts all text to uppercase to the output file.
* Created by gres.cher on 03/02/19.
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 81
void cptoup(FILE *dst, FILE *src);
char *mygets(char *restrict st, const int n);
int main(void)
{
int ch;
char filename[SIZE];
FILE *src, *dst;
fputs("Enter the name of the source text file:\n", stdout);
mygets(filename, SIZE);
if ((src = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Can't open %s\n", filename);
exit(EXIT_FAILURE);
}
fputs("Enter the name of the destination file:\n", stdout);
mygets(filename, SIZE);
if ((dst = fopen(filename, "wx")) == NULL)
{
fprintf(stderr, "Can't create output file.\n");
if ((dst = fopen(filename, "r")) != NULL)
{
fprintf(stderr, "Such file already exists.\n");
fclose(dst);
}
exit(EXIT_FAILURE);
}
// Copy text from src to dst file; convert all text as it's written to uppercase
while ((ch = getc(src)) != EOF)
putc(toupper(ch), dst);
if (fclose(src) != 0 || fclose(dst) != 0)
fprintf(stderr, "Error in closing files.\n");
return 0;
}
// Get a string from standard input
char *mygets(char *restrict st, const int n)
{
int ch, i;
for (i=0, ch=0; (i < n-1) && ((ch=getc(stdin)) != EOF) && (ch != '\n'); i++)
st[i] = ch;
st[i] = '\0';
if (ch != EOF && ch != '\n')
while (getchar() != '\n')
continue;
if (i > 0)
return st;
else
return NULL;
}
|
the_stack_data/1083046.c | // The code structure (especially file reading and saving functions) is adapted from the Word2Vec implementation
// https://github.com/tmikolov/word2vec
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#define MAX_STRING 100
#define ACOS_TABLE_SIZE 5000
#define MAX_SENTENCE_LENGTH 1000
#define MAX_CODE_LENGTH 40
const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary
const int corpus_max_size = 40000000; // Maximum 40M documents in the corpus
typedef float real;
struct vocab_word {
long long cn;
char *word;
};
char train_file[MAX_STRING], load_emb_file[MAX_STRING];
char word_emb[MAX_STRING], context_emb[MAX_STRING], doc_output[MAX_STRING];
char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
struct vocab_word *vocab;
int debug_mode = 2, window = 5, min_count = 5, num_threads = 20, min_reduce = 1;
int *vocab_hash;
long long *doc_sizes;
long long vocab_max_size = 1000, vocab_size = 0, corpus_size = 0, layer1_size = 100;
long long train_words = 0, word_count_actual = 0, iter = 10, file_size = 0;
int negative = 2;
const int table_size = 1e8;
int *word_table;
real alpha = 0.04, starting_alpha, sample = 1e-3, margin = 0.15;
real *syn0, *syn1neg, *syn1doc;
clock_t start;
void InitUnigramTable() {
int a, i;
double train_words_pow = 0;
double d1, power = 0.75;
word_table = (int *) malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / train_words_pow;
for (a = 0; a < table_size; a++) {
word_table[a] = i;
if (a / (double) table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
void ReadWord(char *word, FILE *fin) {
int a = 0, ch;
while (!feof(fin)) {
ch = fgetc(fin);
if (ch == 13) continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
if (a > 0) {
if (ch == '\n') ungetc(ch, fin);
break;
}
if (ch == '\n') {
strcpy(word, (char *) "</s>");
return;
} else continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;
}
// Returns hash value of a word
int GetWordHash(char *word) {
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
// Returns position of a word in the vocabulary; if the word is not found, returns -1
int SearchVocab(char *word) {
unsigned int hash = GetWordHash(word);
while (1) {
if (vocab_hash[hash] == -1) return -1;
if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];
hash = (hash + 1) % vocab_hash_size;
}
return -1;
}
// Locate line number of current file pointer
int FindLine(FILE *fin) {
long long pos = ftell(fin);
long long lo = 0, hi = corpus_size - 1;
while (lo < hi) {
long long mid = lo + (hi - lo) / 2;
if (doc_sizes[mid] > pos) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
// Reads a word and returns its index in the vocabulary
int ReadWordIndex(FILE *fin) {
char word[MAX_STRING];
ReadWord(word, fin);
if (feof(fin)) return -1;
return SearchVocab(word);
}
// Adds a word to the vocabulary
int AddWordToVocab(char *word) {
unsigned int hash, length = strlen(word) + 1;
if (length > MAX_STRING) length = MAX_STRING;
vocab[vocab_size].word = (char *) calloc(length, sizeof(char));
strcpy(vocab[vocab_size].word, word);
vocab[vocab_size].cn = 0;
vocab_size++;
// Reallocate memory if needed
if (vocab_size + 2 >= vocab_max_size) {
vocab_max_size += 1000;
vocab = (struct vocab_word *) realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
}
hash = GetWordHash(word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = vocab_size - 1;
return vocab_size - 1;
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) { // assert all sortings will be the same (since c++ qsort is not stable..)
if (((struct vocab_word *) b)->cn == ((struct vocab_word *) a)->cn) {
return strcmp(((struct vocab_word *) b)->word, ((struct vocab_word *) a)->word);
}
return ((struct vocab_word *) b)->cn - ((struct vocab_word *) a)->cn;
}
int IntCompare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
// Sorts the vocabulary by frequency using word counts
void SortVocab() {
int a, size;
unsigned int hash;
// Sort the vocabulary and keep </s> at the first position
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
size = vocab_size;
train_words = 0;
for (a = 0; a < size; a++) {
// Words occuring less than min_count times will be discarded from the vocab
if ((vocab[a].cn < min_count) && (a != 0)) {
vocab_size--;
free(vocab[a].word);
} else {
// Hash will be re-computed, as after the sorting it is not actual
hash = GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
train_words += vocab[a].cn;
}
}
vocab = (struct vocab_word *) realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));
}
// Reduces the vocabulary by removing infrequent tokens
void ReduceVocab() {
int a, b = 0;
unsigned int hash;
for (a = 0; a < vocab_size; a++)
if (vocab[a].cn > min_reduce) {
vocab[b].cn = vocab[a].cn;
vocab[b].word = vocab[a].word;
b++;
} else free(vocab[a].word);
vocab_size = b;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
for (a = 0; a < vocab_size; a++) {
// Hash will be re-computed, as it is not actual
hash = GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
}
fflush(stdout);
min_reduce++;
}
void LearnVocabFromTrainFile() {
char word[MAX_STRING];
FILE *fin;
long long a, i;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
vocab_size = 0;
AddWordToVocab((char *) "</s>");
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
train_words++;
if ((debug_mode > 1) && (train_words % 100000 == 0)) {
printf("%lldK%c", train_words / 1000, 13);
fflush(stdout);
}
i = SearchVocab(word);
if (i == -1) {
a = AddWordToVocab(word);
vocab[a].cn = 1;
}
else if (i == 0) {
vocab[i].cn++;
doc_sizes[corpus_size] = ftell(fin);
corpus_size++;
if (corpus_size >= corpus_max_size) {
printf("[ERROR] Number of documents in corpus larger than \"corpus_max_size\"! Set a larger \"corpus_max_size\" in Line 18 of jose.c!\n");
exit(1);
}
}
else vocab[i].cn++;
if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
file_size = ftell(fin);
fclose(fin);
}
void SaveVocab() {
long long i;
FILE *fo = fopen(save_vocab_file, "wb");
for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn);
fclose(fo);
}
void ReadVocab() {
long long a, i = 0;
char c;
char word[MAX_STRING];
FILE *fin = fopen(read_vocab_file, "rb");
if (fin == NULL) {
printf("Vocabulary file not found\n");
exit(1);
}
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
vocab_size = 0;
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
a = AddWordToVocab(word);
fscanf(fin, "%lld%c", &vocab[a].cn, &c);
i++;
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
fseek(fin, 0, SEEK_END);
file_size = ftell(fin);
fclose(fin);
}
void LoadEmb(char *emb_file, real *emb_ptr) {
long long a, b;
int *vocab_match_tmp = (int *) calloc(vocab_size, sizeof(int));
int vocab_size_tmp = 0, word_dim;
char *current_word = (char *) calloc(MAX_STRING, sizeof(char));
real *syn_tmp = NULL, norm;
unsigned long long next_random = 1;
a = posix_memalign((void **) &syn_tmp, 128, (long long) layer1_size * sizeof(real));
if (syn_tmp == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
printf("Loading embedding from file %s\n", emb_file);
if (access(emb_file, R_OK) == -1) {
printf("File %s does not exist\n", emb_file);
exit(1);
}
// read embedding file
FILE *fp = fopen(emb_file, "r");
fscanf(fp, "%d", &vocab_size_tmp);
fscanf(fp, "%d", &word_dim);
if (layer1_size != word_dim) {
printf("Embedding dimension incompatible with pretrained file!\n");
exit(1);
}
vocab_size_tmp = 0;
while (1) {
fscanf(fp, "%s", current_word);
a = SearchVocab(current_word);
if (a == -1) {
for (b = 0; b < layer1_size; b++) fscanf(fp, "%f", &syn_tmp[b]);
}
else {
for (b = 0; b < layer1_size; b++) fscanf(fp, "%f", &emb_ptr[a * layer1_size + b]);
vocab_match_tmp[vocab_size_tmp] = a;
vocab_size_tmp++;
}
if (feof(fp)) break;
}
printf("In vocab: %d\n", vocab_size_tmp);
qsort(&vocab_match_tmp[0], vocab_size_tmp, sizeof(int), IntCompare);
vocab_match_tmp[vocab_size_tmp] = vocab_size;
int i = 0;
for (a = 0; a < vocab_size; a++) {
if (a < vocab_match_tmp[i]) {
norm = 0.0;
for (b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long) 25214903917 + 11;
emb_ptr[a * layer1_size + b] = (((next_random & 0xFFFF) / (real) 65536) - 0.5) / layer1_size;
norm += emb_ptr[a * layer1_size + b] * emb_ptr[a * layer1_size + b];
}
for (b = 0; b < layer1_size; b++)
emb_ptr[a * layer1_size + b] /= sqrt(norm);
}
else if (i < vocab_size_tmp) {
i++;
}
}
fclose(fp);
free(current_word);
free(emb_file);
free(vocab_match_tmp);
free(syn_tmp);
}
void InitNet() {
long long a, b;
unsigned long long next_random = 1;
a = posix_memalign((void **) &syn0, 128, (long long) vocab_size * layer1_size * sizeof(real));
if (syn0 == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
a = posix_memalign((void **) &syn1neg, 128, (long long) vocab_size * layer1_size * sizeof(real));
a = posix_memalign((void **) &syn1doc, 128, (long long) corpus_size * layer1_size * sizeof(real));
if (syn1neg == NULL) {
printf("Memory allocation failed (syn1neg)\n");
exit(1);
}
if (syn1doc == NULL) {
printf("Memory allocation failed (syn1doc)\n");
exit(1);
}
real norm;
if (load_emb_file[0] != 0) {
char *center_emb_file = (char *) calloc(MAX_STRING, sizeof(char));
char *context_emb_file = (char *) calloc(MAX_STRING, sizeof(char));
strcpy(center_emb_file, load_emb_file);
strcat(center_emb_file, "_w.txt");
strcpy(context_emb_file, load_emb_file);
strcat(context_emb_file, "_v.txt");
LoadEmb(center_emb_file, syn0);
LoadEmb(context_emb_file, syn1neg);
}
else {
for (a = 0; a < vocab_size; a++) {
norm = 0.0;
for (b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long) 25214903917 + 11;
syn1neg[a * layer1_size + b] = (((next_random & 0xFFFF) / (real) 65536) - 0.5) / layer1_size;
norm += syn1neg[a * layer1_size + b] * syn1neg[a * layer1_size + b];
}
for (b = 0; b < layer1_size; b++)
syn1neg[a * layer1_size + b] /= sqrt(norm);
}
for (a = 0; a < vocab_size; a++) {
norm = 0.0;
for (b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long) 25214903917 + 11;
syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real) 65536) - 0.5) / layer1_size;
norm += syn0[a * layer1_size + b] * syn0[a * layer1_size + b];
}
for (b = 0; b < layer1_size; b++)
syn0[a * layer1_size + b] /= sqrt(norm);
}
}
for (a = 0; a < corpus_size; a++) {
norm = 0.0;
for (b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long) 25214903917 + 11;
syn1doc[a * layer1_size + b] = (((next_random & 0xFFFF) / (real) 65536) - 0.5) / layer1_size;
norm += syn1doc[a * layer1_size + b] * syn1doc[a * layer1_size + b];
}
for (b = 0; b < layer1_size; b++)
syn1doc[a * layer1_size + b] /= sqrt(norm);
}
}
void *TrainModelThread(void *id) {
long long a, b, d, doc = 0, word, last_word, sentence_length = 0, sentence_position = 0;
long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
long long l1, l2, l3 = 0, c, target, local_iter = iter;
unsigned long long next_random = (long long) id;
real f, g, h, step, obj_w = 0, obj_d = 0;
clock_t now;
real *neu1 = (real *) calloc(layer1_size, sizeof(real));
real *grad = (real *) calloc(layer1_size, sizeof(real));
real *neu1e = (real *) calloc(layer1_size, sizeof(real));
FILE *fi = fopen(train_file, "rb");
fseek(fi, file_size / (long long) num_threads * (long long) id, SEEK_SET);
while (1) {
if (word_count - last_word_count > 10000) {
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if ((debug_mode > 1)) {
now = clock();
printf("%cAlpha: %f Objective (w): %f Objective (d): %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
obj_w, obj_d, word_count_actual / (real) (iter * train_words + 1) * 100,
word_count_actual / ((real) (now - start + 1) / (real) CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - word_count_actual / (real) (iter * train_words + 1));
if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
}
if (sentence_length == 0) {
doc = FindLine(fi);
while (1) {
word = ReadWordIndex(fi);
if (feof(fi)) break;
if (word == -1) continue;
word_count++;
if (word == 0) break;
if (sample > 0) {
real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) /
vocab[word].cn;
next_random = next_random * (unsigned long long) 25214903917 + 11;
if (ran < (next_random & 0xFFFF) / (real) 65536) continue;
}
sen[sentence_length] = word;
sentence_length++;
if (sentence_length >= MAX_SENTENCE_LENGTH) break;
}
sentence_position = 0;
}
if (feof(fi) || (word_count > train_words / num_threads)) {
word_count_actual += word_count - last_word_count;
local_iter--;
if (local_iter == 0) break;
word_count = 0;
last_word_count = 0;
sentence_length = 0;
fseek(fi, file_size / (long long) num_threads * (long long) id, SEEK_SET);
continue;
}
word = sen[sentence_position];
if (word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] = 0;
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
next_random = next_random * (unsigned long long) 25214903917 + 11;
b = next_random % window;
for (a = b; a < window * 2 + 1 - b; a++)
if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
l1 = last_word * layer1_size; // positive center word u
obj_w = 0;
for (d = 0; d < negative + 1; d++) {
if (d == 0) {
l3 = word * layer1_size; // positive context word v
} else {
next_random = next_random * (unsigned long long) 25214903917 + 11;
target = word_table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
l2 = target * layer1_size; // negative center word u'
f = 0;
for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l3]; // f = cos(v, u) = v * u
h = 0;
for (c = 0; c < layer1_size; c++) h += syn0[c + l2] * syn1neg[c + l3]; // h = cos(v, u') = v * u'
if (f - h < margin) {
obj_w += margin - (f - h);
// compute context word gradient
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
for (c = 0; c < layer1_size; c++) neu1e[c] += syn0[c + l1] - f * syn1neg[c + l3] + h * syn1neg[c + l3] - syn0[c + l2];
// update positive center word
for (c = 0; c < layer1_size; c++) grad[c] = syn1neg[c + l3] - f * syn0[c + l1]; // negative Riemannian gradient
step = 1 - f; // cosine distance, d_cos
for (c = 0; c < layer1_size; c++) syn0[c + l1] += alpha * step * grad[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn0[c + l1] * syn0[c + l1];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn0[c + l1] /= g;
// update negative center word
for (c = 0; c < layer1_size; c++) grad[c] = h * syn0[c + l2] - syn1neg[c + l3];
step = 2 * h; // 2 * negative cosine similarity
for (c = 0; c < layer1_size; c++) syn0[c + l2] += alpha * step * grad[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn0[c + l2] * syn0[c + l2];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn0[c + l2] /= g;
// update context word
step = 1 - (f - h);
for (c = 0; c < layer1_size; c++) syn1neg[c + l3] += alpha * step * neu1e[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn1neg[c + l3] * syn1neg[c + l3];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn1neg[c + l3] /= g;
}
}
}
}
obj_d = 0;
l1 = doc * layer1_size; // positive document d
for (d = 0; d < negative + 1; d++) {
if (d == 0) {
l3 = word * layer1_size; // positive center word u
} else {
next_random = next_random * (unsigned long long) 25214903917 + 11;
target = word_table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
l2 = target * layer1_size; // negative center word u'
f = 0;
for (c = 0; c < layer1_size; c++) f += syn0[c + l3] * syn1doc[c + l1]; // f = cos(u, d) = u * d
h = 0;
for (c = 0; c < layer1_size; c++) h += syn0[c + l2] * syn1doc[c + l1]; // h = cos(u', d) = u' * d
if (f - h < margin) {
obj_d += margin - (f - h);
// compute document gradient
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
for (c = 0; c < layer1_size; c++) neu1e[c] += syn0[c + l3] - f * syn1doc[c + l1] + h * syn1doc[c + l1] - syn0[c + l2];
// update positive center word
for (c = 0; c < layer1_size; c++) grad[c] = syn1doc[c + l1] - f * syn0[c + l3];
step = 1 - f;
for (c = 0; c < layer1_size; c++) syn0[c + l3] += alpha * step * grad[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn0[c + l3] * syn0[c + l3];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn0[c + l3] /= g;
// update negative center word
for (c = 0; c < layer1_size; c++) grad[c] = h * syn0[c + l2] - syn1doc[c + l1];
step = 2 * h;
for (c = 0; c < layer1_size; c++) syn0[c + l2] += alpha * step * grad[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn0[c + l2] * syn0[c + l2];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn0[c + l2] /= g;
// update document
step = 1 - (f - h);
for (c = 0; c < layer1_size; c++) syn1doc[c + l1] += alpha * step * neu1e[c];
g = 0;
for (c = 0; c < layer1_size; c++) g += syn1doc[c + l1] * syn1doc[c + l1];
g = sqrt(g);
for (c = 0; c < layer1_size; c++) syn1doc[c + l1] /= g;
}
}
}
sentence_position++;
if (sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
fclose(fi);
free(neu1);
free(neu1e);
free(grad);
pthread_exit(NULL);
}
void TrainModel() {
long a, b;
FILE *fo;
pthread_t *pt = (pthread_t *) malloc(num_threads * sizeof(pthread_t));
printf("Starting training using file %s\n", train_file);
starting_alpha = alpha;
if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile();
if (save_vocab_file[0] != 0) SaveVocab();
InitNet();
InitUnigramTable();
start = clock();
for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *) a);
for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);
if (word_emb[0] != 0) {
fo = fopen(word_emb, "wb");
fprintf(fo, "%lld %lld\n", vocab_size, layer1_size);
for (a = 0; a < vocab_size; a++) {
fprintf(fo, "%s ", vocab[a].word);
for (b = 0; b < layer1_size; b++) {
fprintf(fo, "%lf ", syn0[a * layer1_size + b]);
}
fprintf(fo, "\n");
}
fclose(fo);
}
if (context_emb[0] != 0) {
FILE* fa = fopen(context_emb, "wb");
fprintf(fa, "%lld %lld\n", vocab_size, layer1_size);
for (a = 0; a < vocab_size; a++) {
fprintf(fa, "%s ", vocab[a].word);
for (b = 0; b < layer1_size; b++) {
fprintf(fa, "%lf ", syn1neg[a * layer1_size + b]);
}
fprintf(fa, "\n");
}
fclose(fa);
}
if (doc_output[0] != 0) {
FILE* fd = fopen(doc_output, "wb");
fprintf(fd, "%lld %lld\n", corpus_size, layer1_size);
for (a = 0; a < corpus_size; a++) {
fprintf(fd, "%ld ", a);
for (b = 0; b < layer1_size; b++) {
fprintf(fd, "%lf ", syn1doc[a * layer1_size + b]);
}
fprintf(fd, "\n");
}
fclose(fd);
}
}
int ArgPos(char *str, int argc, char **argv) {
int a;
for (a = 1; a < argc; a++)
if (!strcmp(str, argv[a])) {
if (a == argc - 1) {
printf("Argument missing for %s\n", str);
exit(1);
}
return a;
}
return -1;
}
int main(int argc, char **argv) {
int i;
if (argc == 1) {
printf("Parameters:\n");
printf("\t-train <file> (mandatory argument)\n");
printf("\t\tUse text data from <file> to train the model\n");
printf("\t-word-output <file>\n");
printf("\t\tUse <file> to save the resulting word vectors\n");
printf("\t-context-output <file>\n");
printf("\t\tUse <file> to save the resulting word context vectors\n");
printf("\t-doc-output <file>\n");
printf("\t\tUse <file> to save the resulting document vectors\n");
printf("\t-size <int>\n");
printf("\t\tSet size of word vectors; default is 100\n");
printf("\t-window <int>\n");
printf("\t\tSet max skip length between words; default is 5\n");
printf("\t-sample <float>\n");
printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the\n");
printf("\t\ttraining data will be randomly down-sampled; default is 1e-3, useful range is (0, 1e-3)\n");
printf("\t-negative <int>\n");
printf("\t\tNumber of negative examples; default is 2\n");
printf("\t-threads <int>\n");
printf("\t\tUse <int> threads; default is 20\n");
printf("\t-margin <float>\n");
printf("\t\tMargin used in loss function to separate positive samples from negative samples; default is 0.15\n");
printf("\t-iter <int>\n");
printf("\t\tRun more training iterations; default is 10\n");
printf("\t-min-count <int>\n");
printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");
printf("\t-alpha <float>\n");
printf("\t\tSet the starting learning rate; default is 0.04\n");
printf("\t-debug <int>\n");
printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
printf("\t-save-vocab <file>\n");
printf("\t\tThe vocabulary will be saved to <file>\n");
printf("\t-read-vocab <file>\n");
printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
printf("\t-load-emb <file>\n");
printf("\t\tThe pretrained embeddings will be read from <file>\n");
printf("\nExamples:\n");
printf(
"./jose -train text.txt -word-output jose.txt -size 100 -margin 0.15 -window 5 -sample 1e-3 -negative 2 -iter 10\n\n");
return 0;
}
word_emb[0] = 0;
save_vocab_file[0] = 0;
read_vocab_file[0] = 0;
if ((i = ArgPos((char *) "-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
if ((i = ArgPos((char *) "-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *) "-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *) "-load-emb", argc, argv)) > 0) strcpy(load_emb_file, argv[i + 1]);
if ((i = ArgPos((char *) "-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
if ((i = ArgPos((char *) "-word-output", argc, argv)) > 0) strcpy(word_emb, argv[i + 1]);
if ((i = ArgPos((char *) "-context-output", argc, argv)) > 0) strcpy(context_emb, argv[i + 1]);
if ((i = ArgPos((char *) "-doc-output", argc, argv)) > 0) strcpy(doc_output, argv[i + 1]);
if ((i = ArgPos((char *) "-window", argc, argv)) > 0) window = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
if ((i = ArgPos((char *) "-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-margin", argc, argv)) > 0) margin = atof(argv[i + 1]);
if ((i = ArgPos((char *) "-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]);
if ((i = ArgPos((char *) "-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
vocab = (struct vocab_word *) calloc(vocab_max_size, sizeof(struct vocab_word));
vocab_hash = (int *) calloc(vocab_hash_size, sizeof(int));
doc_sizes = (long long *) calloc(corpus_max_size, sizeof(long long));
if (negative <= 0) {
printf("ERROR: Nubmer of negative samples must be positive!\n");
exit(1);
}
TrainModel();
return 0;
}
|
the_stack_data/801678.c | /* Make sure that the struct s is fully expanded in the declaration of
the anonymous union because it has not been declared earlier */
union
{
struct s
{
int l;
} d;
int i;
} u;
|
the_stack_data/161081853.c | #include <stdio.h>
int main(int argc, char *argv[]) {
if(0) {
printf("TRUE\n");
} else {
printf("FALSE\n");
}
if(1) {
printf("TRUE\n");
} else {
printf("FALSE\n");
}
if(-1) {
printf("TRUE\n");
} else {
printf("FALSE\n");
}
}
|
the_stack_data/40763883.c | /*Exercise 3 - Repetition
Write a C program to calculate the sum of the numbers from 1 to n.
Where n is a keyboard input.
e.g.
n -> 100
sum = 1+2+3+....+ 99+100 = 5050
n -> 1-
sum = 1+2+3+...+10 = 55 */
#include<stdio.h>
int main()
{
int n = 0, count = 0;
float total = 0;
printf("Enter number:");
scanf("%d", &n);
while (count <= n)
{
total = total + count;
count++;
}
printf("Total %.2f", total);
return 0;
}
|
the_stack_data/129826719.c | /*
* Date: 2013-12-16
* Author: [email protected]
*
* Rotates x and y by 90 degrees
* Does not terminate.
*/
typedef enum {false, true} bool;
extern int __VERIFIER_nondet_int(void);
int main ()
{
int oldx;
int x;
int y;
x = __VERIFIER_nondet_int();
y = __VERIFIER_nondet_int();
// prevent underflow
if(!(x>=-2147483647)) return 0;
if(!(y>=-2147483647)) return 0;
while (true) {
oldx = x;
x = -y;
y = oldx;
}
return 0;
}
|
the_stack_data/779408.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// possible square states
#define VISIBLE_SAFE 0
#define HIDDEN_SAFE 1
#define HIDDEN_MINE 2
// the size of the starting grid
#define SIZE 8
// the possible command codes
#define DETECT_ROW 1
#define DETECT_COL 2
#define DETECT_SQUARE 3
#define REVEAL_SQUARE 4
#define GAMEPLAY_MODE 5
#define DEBUG_MODE 6
#define REVEAL_RADIAL 7
typedef struct node {
int row;
int col;
struct node *next;
} node;
void initialise_field(int minefield[SIZE][SIZE]);
int game_is_won(int(*minefield)[SIZE]);
void game_over(int(*minefield)[SIZE]);
void print_debug_minefield(int(*minefield)[SIZE]);
void print_gameplay_minefield(int(*minefield)[SIZE], int game_lost);
int char_to_int(char c);
int in_minefield(int row, int col);
void append(node **head, int row, int col);
int list_size(node *head);
int selected_mine(node *head, int row, int col);
node* iterate_square(int(*minefield)[SIZE], int row, int col);
void detect_row(int(*minefield)[SIZE], char *input);
void detect_col(int(*minefield)[SIZE], char *input);
void detect_square(int(*minefield)[SIZE], char *input);
void reveal_square(int(*minefield)[SIZE], char *input, int *first_turn);
void reveal_radial(int(*minefield)[SIZE], char *input, int *first_turn);
int main(void) {
int minefield[SIZE][SIZE];
int hints_remaining = 3;
char* out_of_hints_message = "Help already used";
initialise_field(minefield);
printf("Welcome to Minesweeper!\n");
printf("How many mines? ");
int mine_count;
while (1) {
scanf("%d", &mine_count);
if (mine_count <= 0 || mine_count >= 64) {
printf("Mine count must be greater than 0 and less than 64\n");
continue;
}
break;
}
setbuf(stdin, NULL);
if (mine_count != 0) {
printf("Enter pairs:\n");
}
int i = 0;
for (i; i < mine_count; ++i) {
char input[4];
fgets(input, 4, stdin);
int row = char_to_int(input[0]);
int col = char_to_int(input[2]);
setbuf(stdin, NULL);
if (!(in_minefield(row, col))) {
continue;
}
minefield[row][col] = HIDDEN_MINE;
}
printf("Game Started\n");
int first_turn = 1;
int in_gameplay_mode = 0;
// game loop
while (1) {
if (in_gameplay_mode) {
print_gameplay_minefield(&minefield, 0);
} else {
print_debug_minefield(&minefield);
}
if (game_is_won(&minefield)) {
exit(0);
}
char input[10];
fgets(input, 10, stdin);
int command = char_to_int(input[0]);
setbuf(stdin, NULL);
if (hints_remaining == 0 && (command == DETECT_ROW || command == DETECT_COL || command == DETECT_SQUARE)) {
printf("%s\n", out_of_hints_message);
continue;
}
if (command == DETECT_ROW) {
detect_row(&minefield, &input);
--hints_remaining;
}
if (command == DETECT_COL) {
detect_col(&minefield, &input);
--hints_remaining;
}
if (command == DETECT_SQUARE) {
detect_square(&minefield, &input);
--hints_remaining;
}
if (command == REVEAL_SQUARE) {
reveal_square(&minefield, &input, &first_turn);
}
if (command == GAMEPLAY_MODE && !(in_gameplay_mode)) {
in_gameplay_mode = 1;
printf("Gameplay mode activated\n");
printf("..\n");
printf("\\/\n");
}
if (command == DEBUG_MODE && in_gameplay_mode) {
in_gameplay_mode = 0;
printf("Debug mode activated\n");
}
if (command == REVEAL_RADIAL) {
reveal_radial(&minefield, &input, &first_turn);
}
}
return 0;
}
// set the entire minefield to HIDDEN_SAFE.
void initialise_field(int minefield[SIZE][SIZE]) {
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
minefield[i][j] = HIDDEN_SAFE;
j++;
}
i++;
}
}
int game_is_won(int (*minefield)[SIZE]) {
int value;
int row = 0;
for (row; row < SIZE; ++row) {
int col = 0;
for (col; col < SIZE; ++col) {
value = (*(*(minefield + row) + col));
if (value == HIDDEN_SAFE) {
return 0;
}
}
}
printf("Game won!\n");
return 1;
}
void game_over(int (*minefield)[SIZE]) {
printf("Game over\n");
printf("xx\n");
printf("/\\\n");
print_gameplay_minefield(minefield, 1);
exit(0);
}
// print out the actual values of the minefield.
void print_debug_minefield(int (*minefield)[SIZE]) {
int row = 0;
while (row < SIZE) {
int col = 0;
while (col < SIZE) {
printf("%d ", (*(*(minefield + row) + col)));
col++;
}
printf("\n");
row++;
}
}
// print hidden values of the minefield.
void print_gameplay_minefield(int (*minefield)[SIZE], int game_lost) {
char* header_row = " 00 01 02 03 04 05 06 07";
char* horizontal_border = " --------------------------";
char* empty_square = " ";
int value;
int mine_count;
printf("%s\n%s\n", header_row, horizontal_border);
int row = 0;
for (row; row < SIZE; ++row) {
int col = 0;
printf("0%d |", row);
for (col; col < SIZE; ++col) {
value = (*(*(minefield + row) + col));
if (value == VISIBLE_SAFE) {
node *head = iterate_square(minefield, row, col);
mine_count = list_size(head);
if (mine_count == 0) {
printf("%s", empty_square);
} else {
printf("0%d ", mine_count);
}
}
if (game_lost && value == HIDDEN_MINE) {
printf("() ");
continue;
}
if (value == HIDDEN_SAFE || value == HIDDEN_MINE) {
printf("## ");
}
}
printf("|\n");
}
printf("%s\n", horizontal_border);
}
int char_to_int(char c) {
return c - '0';
}
int in_minefield(int row, int col) {
if (row >= SIZE || col >= SIZE || row < 0 || col < 0) {
return 0;
}
return 1;
}
void append(node **head, int row, int col) {
node *new_node = (node*)malloc(sizeof(node));
if (new_node == NULL) {
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
new_node->row = row;
new_node->col = col;
new_node->next = NULL;
// check for first iteration
if (*head == NULL) {
*head = new_node;
} else {
node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
current->next->next = NULL;
}
}
int list_size(node *head) {
node *current = head;
if (current == NULL) {
return 0;
}
int count = 1;
while (current->next != NULL) {
current = current->next;
++count;
}
return count;
}
int selected_mine(node *head, int row, int col) {
node *current = head;
if (current == NULL) {
return 0;
}
while (current != NULL) {
if (current->row == row && current->col == col) {
return 1;
}
current = current->next;
}
return 0;
}
// return row and column of mines in linked list
node* iterate_square(int (*minefield)[SIZE], int row, int col) {
row -= 1; // start in first coord in top left square
col -= 1;
int size = 3;
// create linked list
node *head = NULL;
int i = row;
for (i; i < row+size; ++i) {
int j = col;
for (j; j < col+size; ++j) {
if (!(in_minefield(row, col))) {
continue;
}
if (*(*(minefield + i) + j) == HIDDEN_MINE) {
append(&head, i, j);
}
}
}
return head;
}
void detect_row(int (*minefield)[SIZE], char* input) {
int row = char_to_int(input[2]);
int mine_count = 0;
int col = 0;
for (col; col < SIZE; ++col) {
if (*(*(minefield + row) + col) == HIDDEN_MINE) {
++mine_count;
}
}
printf("There are %d mine(s) in row %d.\n", mine_count, row);
}
void detect_col(int (*minefield)[SIZE], char* input) {
int col = char_to_int(input[2]);
int mine_count = 0;
int row = 0;
for (row; row < SIZE; ++row) {
if (*(*(minefield + row) + col) == HIDDEN_MINE) {
++mine_count;
}
}
printf("There are %d mine(s) in column %d.\n", mine_count, col);
}
void detect_square(int (*minefield)[SIZE], char* input) {
int row = char_to_int(input[2]);
int col = char_to_int(input[4]);
node *head = iterate_square(minefield, row, col);
int mine_count = list_size(head);
printf("There are %d mine(s) in the square centered at row %d, column %d, of size 3\n", mine_count, row, col);
free(head);
}
void reveal_square(int (*minefield)[SIZE], char* input, int* first_turn) {
int row = char_to_int(input[2]);
int col = char_to_int(input[4]);
int size = 3;
node *head = iterate_square(minefield, row, col);
int mine_count = list_size(head);
if (selected_mine(head, row, col) && !(*first_turn)) {
game_over(minefield);
}
if (mine_count == 0 || *first_turn) {
row -= 1; // start in first coord in top left square
col -= 1;
int i = row;
for (i; i < row+size; ++i) {
int j = col;
for (j; j < col+size; ++j) {
if (!(in_minefield(i, j))) {
continue;
}
(*(*(minefield + i) + j)) = VISIBLE_SAFE;
}
}
} else {
(*(*(minefield + row) + col)) = VISIBLE_SAFE;
}
free(head);
*first_turn = 0;
}
void reveal_radial(int (*minefield)[SIZE], char *input, int *first_input) {
int row = char_to_int(input[2]);
int col = char_to_int(input[4]);
int size = 3;
reveal_square(minefield, input, first_input);
node *head = iterate_square(minefield, row, col);
int mine_count = list_size(head);
if (mine_count != 0) {
return;
}
typedef struct {
int row;
int col;
} RadialDirection;
RadialDirection degree_0 = {-1, 0};
RadialDirection degree_45 = {-1, 1};
RadialDirection degree_90 = {0, 1};
RadialDirection degree_135 = {1, 1};
RadialDirection degree_180 = {1, 0};
RadialDirection degree_225 = {1, -1};
RadialDirection degree_270 = {0, -1};
RadialDirection degree_315 = {-1, -1};
RadialDirection radial_directions[] = { degree_0, degree_45, degree_90, degree_135, degree_180, degree_225, degree_270, degree_315 };
size_t array_size = sizeof(radial_directions) / sizeof(RadialDirection);
int i = 0;
for (i; i < array_size; ++i) {
RadialDirection direction = radial_directions[i];
int radial_row = row;
int radial_col = col;
while (in_minefield(radial_row, radial_col)) {
node *head = iterate_square(minefield, radial_row, radial_col);
int mine_count = list_size(head);
(*(*(minefield + radial_row) + radial_col)) = VISIBLE_SAFE;
if (mine_count != 0) {
break;
}
radial_row += direction.row;
radial_col += direction.col;
}
}
}
|
the_stack_data/170453664.c | /*
http://stackoverflow.com/questions/15763965/how-can-i-calculate-the-median-of-values-in-sqlite
http://www.sqlite.org/contrib/download/extension-functions.c?get=25
http://www.sqlite.org/loadext.html
This library will provide common mathematical and string functions in
SQL queries using the operating system libraries or provided
definitions. It includes the following functions:
Math: acos, asin, atan, atn2, atan2, acosh, asinh, atanh, difference,
degrees, radians, cos, sin, tan, cot, cosh, sinh, tanh, coth, exp,
log, log10, power, sign, sqrt, square, ceil, floor, pi.
String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim,
replace, reverse, proper, padl, padr, padc, strfilter.
Aggregate: stdev, variance, mode, median, lower_quartile,
upper_quartile.
The string functions ltrim, rtrim, trim, replace are included in
recent versions of SQLite and so by default do not build.
Compilation instructions:
Compile this C source file into a dynamic library as follows:
* Linux:
gcc -fPIC -lm -shared extension-functions.c -o libsqlitefunctions.so
* Mac OS X:
gcc -fno-common -dynamiclib extension-functions.c -o libsqlitefunctions.dylib
(You may need to add flags
-I /opt/local/include/ -L/opt/local/lib -lsqlite3
if your sqlite3 is installed from Mac ports, or
-I /sw/include/ -L/sw/lib -lsqlite3
if installed with Fink.)
* Windows:
1. Install MinGW (http://www.mingw.org/) and you will get the gcc
(gnu compiler collection)
2. add the path to your path variable (isn't done during the
installation!)
3. compile:
gcc -shared -I "path" -o libsqlitefunctions.so extension-functions.c
(path = path of sqlite3ext.h; i.e. C:\programs\sqlite)
Usage instructions for applications calling the sqlite3 API functions:
In your application, call sqlite3_enable_load_extension(db,1) to
allow loading external libraries. Then load the library libsqlitefunctions
using sqlite3_load_extension; the third argument should be 0.
See http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
Select statements may now use these functions, as in
SELECT cos(radians(inclination)) FROM satsum WHERE satnum = 25544;
Usage instructions for the sqlite3 program:
If the program is built so that loading extensions is permitted,
the following will work:
sqlite> SELECT load_extension('./libsqlitefunctions.so');
sqlite> select cos(radians(45));
0.707106781186548
Note: Loading extensions is by default prohibited as a
security measure; see "Security Considerations" in
http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
If the sqlite3 program and library are built this
way, you cannot use these functions from the program, you
must write your own program using the sqlite3 API, and call
sqlite3_enable_load_extension as described above, or else
rebuilt the sqlite3 program to allow loadable extensions.
Alterations:
The instructions are for Linux, Mac OS X, and Windows; users of other
OSes may need to modify this procedure. In particular, if your math
library lacks one or more of the needed trig or log functions, comment
out the appropriate HAVE_ #define at the top of file. If you do not
wish to make a loadable module, comment out the define for
COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE. If you are using a
version of SQLite without the trim functions and replace, comment out
the HAVE_TRIM #define.
Liam Healy
History:
2010-01-06 Correct check for argc in squareFunc, and add Windows
compilation instructions.
2009-06-24 Correct check for argc in properFunc.
2008-09-14 Add check that memory was actually allocated after
sqlite3_malloc or sqlite3StrDup, call sqlite3_result_error_nomem if
not. Thanks to Robert Simpson.
2008-06-13 Change to instructions to indicate use of the math library
and that program might work.
2007-10-01 Minor clarification to instructions.
2007-09-29 Compilation as loadable module is optional with
COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE.
2007-09-28 Use sqlite3_extension_init and macros
SQLITE_EXTENSION_INIT1, SQLITE_EXTENSION_INIT2, so that it works with
sqlite3_load_extension. Thanks to Eric Higashino and Joe Wilson.
New instructions for Mac compilation.
2007-09-17 With help from Joe Wilson and Nuno Luca, made use of
external interfaces so that compilation is no longer dependent on
SQLite source code. Merged source, header, and README into a single
file. Added casts so that Mac will compile without warnings (unsigned
and signed char).
2007-09-05 Included some definitions from sqlite 3.3.13 so that this
will continue to work in newer versions of sqlite. Completed
description of functions available.
2007-03-27 Revised description.
2007-03-23 Small cleanup and a bug fix on the code. This was mainly
letting errno flag errors encountered in the math library and checking
the result, rather than pre-checking. This fixes a bug in power that
would cause an error if any non-positive number was raised to any
power.
2007-02-07 posted by Mikey C to sqlite mailing list.
Original code 2006 June 05 by relicoder.
*/
//#include "config.h"
//#define COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE 1
#define HAVE_ACOSH 1
#define HAVE_ASINH 1
#define HAVE_ATANH 1
#define HAVE_SINH 1
#define HAVE_COSH 1
#define HAVE_TANH 1
#define HAVE_LOG10 1
#define HAVE_ISBLANK 1
#define SQLITE_SOUNDEX 1
#define HAVE_TRIM 1 /* LMH 2007-03-25 if sqlite has trim functions */
#ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#else
#include "sqlite3.h"
#endif
#include <ctype.h>
/* relicoder */
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <errno.h> /* LMH 2007-03-25 */
#include <stdlib.h>
#include <assert.h>
#ifndef _MAP_H_
#define _MAP_H_
#include <stdint.h>
/*
** Simple binary tree implementation to use in median, mode and quartile calculations
** Tree is not necessarily balanced. That would require something like red&black trees of AVL
*/
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */
typedef int(*cmp_func)(const void *, const void *);
typedef void(*map_iterator)(void*, int64_t, void*);
typedef struct node{
struct node *l;
struct node *r;
void* data;
int64_t count;
} node;
typedef struct map{
node *base;
cmp_func cmp;
short free;
} map;
/*
** creates a map given a comparison function
*/
map map_make(cmp_func cmp);
/*
** inserts the element e into map m
*/
void map_insert(map *m, void *e);
/*
** executes function iter over all elements in the map, in key increasing order
*/
void map_iterate(map *m, map_iterator iter, void* p);
/*
** frees all memory used by a map
*/
void map_destroy(map *m);
/*
** compares 2 integers
** to use with map_make
*/
int int_cmp(const void *a, const void *b);
/*
** compares 2 doubles
** to use with map_make
*/
int double_cmp(const void *a, const void *b);
#endif /* _MAP_H_ */
typedef uint8_t u8;
typedef uint16_t u16;
typedef int64_t i64;
static char *sqlite3StrDup( const char *z ) {
char *res = sqlite3_malloc( strlen(z)+1 );
return strcpy( res, z );
}
/*
** These are copied verbatim from fun.c so as to not have the names exported
*/
/* LMH from sqlite3 3.3.13 */
/*
** This table maps from the first byte of a UTF-8 character to the number
** of trailing bytes expected. A value '4' indicates that the table key
** is not a legal first byte for a UTF-8 character.
*/
static const u8 xtra_utf8_bytes[256] = {
/* 0xxxxxxx */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 10wwwwww */
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
/* 110yyyyy */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 1110zzzz */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* 11110yyy */
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
};
/*
** This table maps from the number of trailing bytes in a UTF-8 character
** to an integer constant that is effectively calculated for each character
** read by a naive implementation of a UTF-8 character reader. The code
** in the READ_UTF8 macro explains things best.
*/
static const int xtra_utf8_bits[] = {
0,
12416, /* (0xC0 << 6) + (0x80) */
925824, /* (0xE0 << 12) + (0x80 << 6) + (0x80) */
63447168 /* (0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80 */
};
/*
** If a UTF-8 character contains N bytes extra bytes (N bytes follow
** the initial byte so that the total character length is N+1) then
** masking the character with utf8_mask[N] must produce a non-zero
** result. Otherwise, we have an (illegal) overlong encoding.
*/
static const int utf_mask[] = {
0x00000000,
0xffffff80,
0xfffff800,
0xffff0000,
};
/* LMH salvaged from sqlite3 3.3.13 source code src/utf.c */
#define READ_UTF8(zIn, c) { \
int xtra; \
c = *(zIn)++; \
xtra = xtra_utf8_bytes[c]; \
switch( xtra ){ \
case 4: c = (int)0xFFFD; break; \
case 3: c = (c<<6) + *(zIn)++; \
case 2: c = (c<<6) + *(zIn)++; \
case 1: c = (c<<6) + *(zIn)++; \
c -= xtra_utf8_bits[xtra]; \
if( (utf_mask[xtra]&c)==0 \
|| (c&0xFFFFF800)==0xD800 \
|| (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
} \
}
static int sqlite3ReadUtf8(const unsigned char *z){
int c;
READ_UTF8(z, c);
return c;
}
#define SKIP_UTF8(zIn) { \
zIn += (xtra_utf8_bytes[*(u8 *)zIn] + 1); \
}
/*
** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
** return the number of unicode characters in pZ up to (but not including)
** the first 0x00 byte. If nByte is not less than zero, return the
** number of unicode characters in the first nByte of pZ (or up to
** the first 0x00, whichever comes first).
*/
static int sqlite3Utf8CharLen(const char *z, int nByte){
int r = 0;
const char *zTerm;
if( nByte>=0 ){
zTerm = &z[nByte];
}else{
zTerm = (const char *)(-1);
}
assert( z<=zTerm );
while( *z!=0 && z<zTerm ){
SKIP_UTF8(z);
r++;
}
return r;
}
/*
** X is a pointer to the first byte of a UTF-8 character. Increment
** X so that it points to the next character. This only works right
** if X points to a well-formed UTF-8 string.
*/
#define sqliteNextChar(X) while( (0xc0&*++(X))==0x80 ){}
#define sqliteCharVal(X) sqlite3ReadUtf8(X)
/*
** This is a macro that facilitates writting wrappers for math.h functions
** it creates code for a function to use in SQlite that gets one numeric input
** and returns a floating point value.
**
** Could have been implemented using pointers to functions but this way it's inline
** and thus more efficient. Lower * ranking though...
**
** Parameters:
** name: function name to de defined (eg: sinFunc)
** function: function defined in math.h to wrap (eg: sin)
** domain: boolean condition that CAN'T happen in terms of the input parameter rVal
** (eg: rval<0 for sqrt)
*/
/* LMH 2007-03-25 Changed to use errno and remove domain; no pre-checking for errors. */
#define GEN_MATH_WRAP_DOUBLE_1(name, function) \
static void name(sqlite3_context *context, int argc, sqlite3_value **argv){\
double rVal = 0.0, val;\
assert( argc==1 );\
switch( sqlite3_value_type(argv[0]) ){\
case SQLITE_NULL: {\
sqlite3_result_null(context);\
break;\
}\
default: {\
rVal = sqlite3_value_double(argv[0]);\
errno = 0;\
val = function(rVal);\
if (errno == 0) {\
sqlite3_result_double(context, val);\
} else {\
sqlite3_result_error(context, strerror(errno), errno);\
}\
break;\
}\
}\
}\
/*
** Example of GEN_MATH_WRAP_DOUBLE_1 usage
** this creates function sqrtFunc to wrap the math.h standard function sqrt(x)=x^0.5
*/
GEN_MATH_WRAP_DOUBLE_1(sqrtFunc, sqrt)
/* trignometric functions */
GEN_MATH_WRAP_DOUBLE_1(acosFunc, acos)
GEN_MATH_WRAP_DOUBLE_1(asinFunc, asin)
GEN_MATH_WRAP_DOUBLE_1(atanFunc, atan)
/*
** Many of systems don't have inverse hyperbolic trig functions so this will emulate
** them on those systems in terms of log and sqrt (formulas are too trivial to demand
** written proof here)
*/
#ifndef HAVE_ACOSH
static double acosh(double x){
return log(x + sqrt(x*x - 1.0));
}
#endif
GEN_MATH_WRAP_DOUBLE_1(acoshFunc, acosh)
#ifndef HAVE_ASINH
static double asinh(double x){
return log(x + sqrt(x*x + 1.0));
}
#endif
GEN_MATH_WRAP_DOUBLE_1(asinhFunc, asinh)
#ifndef HAVE_ATANH
static double atanh(double x){
return (1.0/2.0)*log((1+x)/(1-x)) ;
}
#endif
GEN_MATH_WRAP_DOUBLE_1(atanhFunc, atanh)
/*
** math.h doesn't require cot (cotangent) so it's defined here
*/
static double cot(double x){
return 1.0/tan(x);
}
GEN_MATH_WRAP_DOUBLE_1(sinFunc, sin)
GEN_MATH_WRAP_DOUBLE_1(cosFunc, cos)
GEN_MATH_WRAP_DOUBLE_1(tanFunc, tan)
GEN_MATH_WRAP_DOUBLE_1(cotFunc, cot)
static double coth(double x){
return 1.0/tanh(x);
}
/*
** Many systems don't have hyperbolic trigonometric functions so this will emulate
** them on those systems directly from the definition in terms of exp
*/
#ifndef HAVE_SINH
static double sinh(double x){
return (exp(x)-exp(-x))/2.0;
}
#endif
GEN_MATH_WRAP_DOUBLE_1(sinhFunc, sinh)
#ifndef HAVE_COSH
static double cosh(double x){
return (exp(x)+exp(-x))/2.0;
}
#endif
GEN_MATH_WRAP_DOUBLE_1(coshFunc, cosh)
#ifndef HAVE_TANH
static double tanh(double x){
return sinh(x)/cosh(x);
}
#endif
GEN_MATH_WRAP_DOUBLE_1(tanhFunc, tanh)
GEN_MATH_WRAP_DOUBLE_1(cothFunc, coth)
/*
** Some systems lack log in base 10. This will emulate it
*/
#ifndef HAVE_LOG10
static double log10(double x){
static double l10 = -1.0;
if( l10<0.0 ){
l10 = log(10.0);
}
return log(x)/l10;
}
#endif
GEN_MATH_WRAP_DOUBLE_1(logFunc, log)
GEN_MATH_WRAP_DOUBLE_1(log10Func, log10)
GEN_MATH_WRAP_DOUBLE_1(expFunc, exp)
/*
** Fallback for systems where math.h doesn't define M_PI
*/
#undef M_PI
#ifndef M_PI
/*
** static double PI = acos(-1.0);
** #define M_PI (PI)
*/
#define M_PI 3.14159265358979323846
#endif
/* Convert Degrees into Radians */
static double deg2rad(double x){
return x*M_PI/180.0;
}
/* Convert Radians into Degrees */
static double rad2deg(double x){
return 180.0*x/M_PI;
}
GEN_MATH_WRAP_DOUBLE_1(rad2degFunc, rad2deg)
GEN_MATH_WRAP_DOUBLE_1(deg2radFunc, deg2rad)
/* constant function that returns the value of PI=3.1415... */
static void piFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
sqlite3_result_double(context, M_PI);
}
/*
** Implements the sqrt function, it has the peculiarity of returning an integer when the
** the argument is an integer.
** Since SQLite isn't strongly typed (almost untyped actually) this is a bit pedantic
*/
static void squareFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
i64 iVal = 0;
double rVal = 0.0;
assert( argc==1 );
switch( sqlite3_value_type(argv[0]) ){
case SQLITE_INTEGER: {
iVal = sqlite3_value_int64(argv[0]);
sqlite3_result_int64(context, iVal*iVal);
break;
}
case SQLITE_NULL: {
sqlite3_result_null(context);
break;
}
default: {
rVal = sqlite3_value_double(argv[0]);
sqlite3_result_double(context, rVal*rVal);
break;
}
}
}
/*
** Wraps the pow math.h function
** When both the base and the exponent are integers the result should be integer
** (see sqrt just before this). Here the result is always double
*/
/* LMH 2007-03-25 Changed to use errno; no pre-checking for errors. Also removes
but that was present in the pre-checking that called sqlite3_result_error on
a non-positive first argument, which is not always an error. */
static void powerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
double r1 = 0.0;
double r2 = 0.0;
double val;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
r1 = sqlite3_value_double(argv[0]);
r2 = sqlite3_value_double(argv[1]);
errno = 0;
val = pow(r1,r2);
if (errno == 0) {
sqlite3_result_double(context, val);
} else {
sqlite3_result_error(context, strerror(errno), errno);
}
}
}
/*
** atan2 wrapper
*/
static void atn2Func(sqlite3_context *context, int argc, sqlite3_value **argv){
double r1 = 0.0;
double r2 = 0.0;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
r1 = sqlite3_value_double(argv[0]);
r2 = sqlite3_value_double(argv[1]);
sqlite3_result_double(context, atan2(r1,r2));
}
}
/*
** Implementation of the sign() function
** return one of 3 possibilities +1,0 or -1 when the argument is respectively
** positive, 0 or negative.
** When the argument is NULL the result is also NULL (completly conventional)
*/
static void signFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
double rVal=0.0;
i64 iVal=0;
assert( argc==1 );
switch( sqlite3_value_type(argv[0]) ){
case SQLITE_INTEGER: {
iVal = sqlite3_value_int64(argv[0]);
iVal = ( iVal > 0) ? 1: ( iVal < 0 ) ? -1: 0;
sqlite3_result_int64(context, iVal);
break;
}
case SQLITE_NULL: {
sqlite3_result_null(context);
break;
}
default: {
/* 2nd change below. Line for abs was: if( rVal<0 ) rVal = rVal * -1.0; */
rVal = sqlite3_value_double(argv[0]);
rVal = ( rVal > 0) ? 1: ( rVal < 0 ) ? -1: 0;
sqlite3_result_double(context, rVal);
break;
}
}
}
/*
** smallest integer value not less than argument
*/
static void ceilFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
double rVal=0.0;
//i64 iVal=0;
assert( argc==1 );
switch( sqlite3_value_type(argv[0]) ){
case SQLITE_INTEGER: {
i64 iVal = sqlite3_value_int64(argv[0]);
sqlite3_result_int64(context, iVal);
break;
}
case SQLITE_NULL: {
sqlite3_result_null(context);
break;
}
default: {
rVal = sqlite3_value_double(argv[0]);
sqlite3_result_int64(context, (i64) ceil(rVal));
break;
}
}
}
/*
** largest integer value not greater than argument
*/
static void floorFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
double rVal=0.0;
//i64 iVal=0;
assert( argc==1 );
switch( sqlite3_value_type(argv[0]) ){
case SQLITE_INTEGER: {
i64 iVal = sqlite3_value_int64(argv[0]);
sqlite3_result_int64(context, iVal);
break;
}
case SQLITE_NULL: {
sqlite3_result_null(context);
break;
}
default: {
rVal = sqlite3_value_double(argv[0]);
sqlite3_result_int64(context, (i64) floor(rVal));
break;
}
}
}
/*
** Given a string (s) in the first argument and an integer (n) in the second returns the
** string that constains s contatenated n times
*/
static void replicateFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
unsigned char *z; /* input string */
unsigned char *zo; /* result string */
i64 iCount; /* times to repeat */
i64 nLen; /* length of the input string (no multibyte considerations) */
i64 nTLen; /* length of the result string (no multibyte considerations) */
i64 i=0;
if( argc!=2 || SQLITE_NULL==sqlite3_value_type(argv[0]) )
return;
iCount = sqlite3_value_int64(argv[1]);
if( iCount<0 ){
sqlite3_result_error(context, "domain error", -1);
}else{
nLen = sqlite3_value_bytes(argv[0]);
nTLen = nLen*iCount;
z=sqlite3_malloc(nTLen+1);
zo=sqlite3_malloc(nLen+1);
if (!z || !zo){
sqlite3_result_error_nomem(context);
if (z) sqlite3_free(z);
if (zo) sqlite3_free(zo);
return;
}
strcpy((char*)zo, (char*)sqlite3_value_text(argv[0]));
for(i=0; i<iCount; ++i){
strcpy((char*)(z+i*nLen), (char*)zo);
}
sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
sqlite3_free(z);
sqlite3_free(zo);
}
}
/*
** Some systems (win32 among others) don't have an isblank function, this will emulate it.
** This function is not UFT-8 safe since it only analyses a byte character.
*/
#ifndef HAVE_ISBLANK
int isblank(char c){
return( ' '==c || '\t'==c );
}
#endif
static void properFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const unsigned char *z; /* input string */
unsigned char *zo; /* output string */
unsigned char *zt; /* iterator */
char r;
int c=1;
assert( argc==1);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z = sqlite3_value_text(argv[0]);
zo = (unsigned char *)sqlite3StrDup((char *) z);
if (!zo) {
sqlite3_result_error_nomem(context);
return;
}
zt = zo;
while( (r = *(z++))!=0 ){
if( isblank(r) ){
c=1;
}else{
if( c==1 ){
r = toupper(r);
}else{
r = tolower(r);
}
c=0;
}
*(zt++) = r;
}
*zt = '\0';
sqlite3_result_text(context, (char*)zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
/*
** given an input string (s) and an integer (n) adds spaces at the begining of s
** until it has a length of n characters.
** When s has a length >=n it's a NOP
** padl(NULL) = NULL
*/
static void padlFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
i64 ilen; /* length to pad to */
i64 zl; /* length of the input string (UTF-8 chars) */
int i = 0;
const char *zi; /* input string */
char *zo; /* output string */
char *zt;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
zi = (char *)sqlite3_value_text(argv[0]);
ilen = sqlite3_value_int64(argv[1]);
/* check domain */
if(ilen<0){
sqlite3_result_error(context, "domain error", -1);
return;
}
zl = sqlite3Utf8CharLen(zi, -1);
if( zl>=ilen ){
/* string is longer than the requested pad length, return the same string (dup it) */
zo = sqlite3StrDup(zi);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
}else{
zo = sqlite3_malloc(strlen(zi)+ilen-zl+1);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
zt = zo;
for(i=1; i+zl<=ilen; ++i){
*(zt++)=' ';
}
/* no need to take UTF-8 into consideration here */
strcpy(zt,zi);
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
}
/*
** given an input string (s) and an integer (n) appends spaces at the end of s
** until it has a length of n characters.
** When s has a length >=n it's a NOP
** padl(NULL) = NULL
*/
static void padrFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
i64 ilen; /* length to pad to */
i64 zl; /* length of the input string (UTF-8 chars) */
i64 zll; /* length of the input string (bytes) */
int i = 0;
const char *zi; /* input string */
char *zo; /* output string */
char *zt;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
zi = (char *)sqlite3_value_text(argv[0]);
ilen = sqlite3_value_int64(argv[1]);
/* check domain */
if(ilen<0){
sqlite3_result_error(context, "domain error", -1);
return;
}
zl = sqlite3Utf8CharLen(zi, -1);
if( zl>=ilen ){
/* string is longer than the requested pad length, return the same string (dup it) */
zo = sqlite3StrDup(zi);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
}else{
zll = strlen(zi);
zo = sqlite3_malloc(zll+ilen-zl+1);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
zt = strcpy(zo,zi)+zll;
for(i=1; i+zl<=ilen; ++i){
*(zt++) = ' ';
}
*zt = '\0';
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
}
/*
** given an input string (s) and an integer (n) appends spaces at the end of s
** and adds spaces at the begining of s until it has a length of n characters.
** Tries to add has many characters at the left as at the right.
** When s has a length >=n it's a NOP
** padl(NULL) = NULL
*/
static void padcFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
i64 ilen; /* length to pad to */
i64 zl; /* length of the input string (UTF-8 chars) */
i64 zll; /* length of the input string (bytes) */
int i = 0;
const char *zi; /* input string */
char *zo; /* output string */
char *zt;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
zi = (char *)sqlite3_value_text(argv[0]);
ilen = sqlite3_value_int64(argv[1]);
/* check domain */
if(ilen<0){
sqlite3_result_error(context, "domain error", -1);
return;
}
zl = sqlite3Utf8CharLen(zi, -1);
if( zl>=ilen ){
/* string is longer than the requested pad length, return the same string (dup it) */
zo = sqlite3StrDup(zi);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
}else{
zll = strlen(zi);
zo = sqlite3_malloc(zll+ilen-zl+1);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
zt = zo;
for(i=1; 2*i+zl<=ilen; ++i){
*(zt++) = ' ';
}
strcpy(zt, zi);
zt+=zll;
for(; i+zl<=ilen; ++i){
*(zt++) = ' ';
}
*zt = '\0';
}
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
}
/*
** given 2 string (s1,s2) returns the string s1 with the characters NOT in s2 removed
** assumes strings are UTF-8 encoded
*/
static void strfilterFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *zi1; /* first parameter string (searched string) */
const char *zi2; /* second parameter string (vcontains valid characters) */
const char *z1;
const char *z21;
const char *z22;
char *zo; /* output string */
char *zot;
int c1 = 0;
int c2 = 0;
assert( argc==2 );
if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
sqlite3_result_null(context);
}else{
zi1 = (char *)sqlite3_value_text(argv[0]);
zi2 = (char *)sqlite3_value_text(argv[1]);
/*
** maybe I could allocate less, but that would imply 2 passes, rather waste
** (possibly) some memory
*/
zo = sqlite3_malloc(strlen(zi1)+1);
if (!zo){
sqlite3_result_error_nomem(context);
return;
}
zot = zo;
z1 = zi1;
while( (c1=sqliteCharVal((unsigned char *)z1))!=0 ){
z21=zi2;
while( (c2=sqliteCharVal((unsigned char *)z21))!=0 && c2!=c1 ){
sqliteNextChar(z21);
}
if( c2!=0){
z22=z21;
sqliteNextChar(z22);
strncpy(zot, z21, z22-z21);
zot+=z22-z21;
}
sqliteNextChar(z1);
}
*zot = '\0';
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
}
/*
** Given a string z1, retutns the (0 based) index of it's first occurence
** in z2 after the first s characters.
** Returns -1 when there isn't a match.
** updates p to point to the character where the match occured.
** This is an auxiliary function.
*/
static int _substr(const char* z1, const char* z2, int s, const char** p){
int c = 0;
int rVal=-1;
const char* zt1;
const char* zt2;
int c1,c2;
if( '\0'==*z1 ){
return -1;
}
while( (sqliteCharVal((unsigned char *)z2) != 0) && (c++)<s){
sqliteNextChar(z2);
}
c = 0;
while( (sqliteCharVal((unsigned char *)z2)) != 0 ){
zt1 = z1;
zt2 = z2;
do{
c1 = sqliteCharVal((unsigned char *)zt1);
c2 = sqliteCharVal((unsigned char *)zt2);
sqliteNextChar(zt1);
sqliteNextChar(zt2);
}while( c1 == c2 && c1 != 0 && c2 != 0 );
if( c1 == 0 ){
rVal = c;
break;
}
sqliteNextChar(z2);
++c;
}
if(p){
*p=z2;
}
return rVal >=0 ? rVal+s : rVal;
}
/*
** given 2 input strings (s1,s2) and an integer (n) searches from the nth character
** for the string s1. Returns the position where the match occured.
** Characters are counted from 1.
** 0 is returned when no match occurs.
*/
static void charindexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const u8 *z1; /* s1 string */
u8 *z2; /* s2 string */
int s=0;
int rVal=0;
assert( argc==3 ||argc==2);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){
sqlite3_result_null(context);
return;
}
z1 = sqlite3_value_text(argv[0]);
if( z1==0 ) return;
z2 = (u8*) sqlite3_value_text(argv[1]);
if(argc==3){
s = sqlite3_value_int(argv[2])-1;
if(s<0){
s=0;
}
}else{
s = 0;
}
rVal = _substr((char *)z1,(char *)z2,s,NULL);
sqlite3_result_int(context, rVal+1);
}
/*
** given a string (s) and an integer (n) returns the n leftmost (UTF-8) characters
** if the string has a length<=n or is NULL this function is NOP
*/
static void leftFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
int c=0;
int cc=0;
int l=0;
const unsigned char *z; /* input string */
const unsigned char *zt;
unsigned char *rz; /* output string */
assert( argc==2);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){
sqlite3_result_null(context);
return;
}
z = sqlite3_value_text(argv[0]);
l = sqlite3_value_int(argv[1]);
zt = z;
while( sqliteCharVal(zt) && c++<l)
sqliteNextChar(zt);
cc=zt-z;
rz = sqlite3_malloc(zt-z+1);
if (!rz){
sqlite3_result_error_nomem(context);
return;
}
strncpy((char*) rz, (char*) z, zt-z);
*(rz+cc) = '\0';
sqlite3_result_text(context, (char*)rz, -1, SQLITE_TRANSIENT);
sqlite3_free(rz);
}
/*
** given a string (s) and an integer (n) returns the n rightmost (UTF-8) characters
** if the string has a length<=n or is NULL this function is NOP
*/
static void rightFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
int l=0;
int c=0;
int cc=0;
const char *z;
const char *zt;
const char *ze;
char *rz;
assert( argc==2);
if( SQLITE_NULL == sqlite3_value_type(argv[0]) || SQLITE_NULL == sqlite3_value_type(argv[1])){
sqlite3_result_null(context);
return;
}
z = (char *)sqlite3_value_text(argv[0]);
l = sqlite3_value_int(argv[1]);
zt = z;
while( sqliteCharVal((unsigned char *)zt)!=0){
sqliteNextChar(zt);
++c;
}
ze = zt;
zt = z;
cc=c-l;
if(cc<0)
cc=0;
while( cc-- > 0 ){
sqliteNextChar(zt);
}
rz = sqlite3_malloc(ze-zt+1);
if (!rz){
sqlite3_result_error_nomem(context);
return;
}
strcpy((char*) rz, (char*) (zt));
sqlite3_result_text(context, (char*)rz, -1, SQLITE_TRANSIENT);
sqlite3_free(rz);
}
#ifndef HAVE_TRIM
/*
** removes the whitespaces at the begining of a string.
*/
const char* ltrim(const char* s){
while( *s==' ' )
++s;
return s;
}
/*
** removes the whitespaces at the end of a string.
** !mutates the input string!
*/
void rtrim(char* s){
char* ss = s+strlen(s)-1;
while( ss>=s && *ss==' ' )
--ss;
*(ss+1)='\0';
}
/*
** Removes the whitespace at the begining of a string
*/
static void ltrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *z;
assert( argc==1);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z = sqlite3_value_text(argv[0]);
sqlite3_result_text(context, ltrim(z), -1, SQLITE_TRANSIENT);
}
/*
** Removes the whitespace at the end of a string
*/
static void rtrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *z;
char *rz;
/* try not to change data in argv */
assert( argc==1);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z = sqlite3_value_text(argv[0]);
rz = sqlite3StrDup(z);
rtrim(rz);
sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT);
sqlite3_free(rz);
}
/*
** Removes the whitespace at the begining and end of a string
*/
static void trimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *z;
char *rz;
/* try not to change data in argv */
assert( argc==1);
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z = sqlite3_value_text(argv[0]);
rz = sqlite3StrDup(z);
rtrim(rz);
sqlite3_result_text(context, ltrim(rz), -1, SQLITE_TRANSIENT);
sqlite3_free(rz);
}
#endif
/*
** given a pointer to a string s1, the length of that string (l1), a new string (s2)
** and it's length (l2) appends s2 to s1.
** All lengths in bytes.
** This is just an auxiliary function
*/
// static void _append(char **s1, int l1, const char *s2, int l2){
// *s1 = realloc(*s1, (l1+l2+1)*sizeof(char));
// strncpy((*s1)+l1, s2, l2);
// *(*(s1)+l1+l2) = '\0';
// }
#ifndef HAVE_TRIM
/*
** given strings s, s1 and s2 replaces occurrences of s1 in s by s2
*/
static void replaceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *z1; /* string s (first parameter) */
const char *z2; /* string s1 (second parameter) string to look for */
const char *z3; /* string s2 (third parameter) string to replace occurrences of s1 with */
int lz1;
int lz2;
int lz3;
int lzo=0;
char *zo=0;
int ret=0;
const char *zt1;
const char *zt2;
assert( 3==argc );
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z1 = sqlite3_value_text(argv[0]);
z2 = sqlite3_value_text(argv[1]);
z3 = sqlite3_value_text(argv[2]);
/* handle possible null values */
if( 0==z2 ){
z2="";
}
if( 0==z3 ){
z3="";
}
lz1 = strlen(z1);
lz2 = strlen(z2);
lz3 = strlen(z3);
#if 0
/* special case when z2 is empty (or null) nothing will be changed */
if( 0==lz2 ){
sqlite3_result_text(context, z1, -1, SQLITE_TRANSIENT);
return;
}
#endif
zt1=z1;
zt2=z1;
while(1){
ret=_substr(z2,zt1 , 0, &zt2);
if( ret<0 )
break;
_append(&zo, lzo, zt1, zt2-zt1);
lzo+=zt2-zt1;
_append(&zo, lzo, z3, lz3);
lzo+=lz3;
zt1=zt2+lz2;
}
_append(&zo, lzo, zt1, lz1-(zt1-z1));
sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
sqlite3_free(zo);
}
#endif
/*
** given a string returns the same string but with the characters in reverse order
*/
static void reverseFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
const char *z;
const char *zt;
char *rz;
char *rzt;
int l = 0;
int i = 0;
assert( 1==argc );
if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
sqlite3_result_null(context);
return;
}
z = (char *)sqlite3_value_text(argv[0]);
l = strlen(z);
rz = sqlite3_malloc(l+1);
if (!rz){
sqlite3_result_error_nomem(context);
return;
}
rzt = rz+l;
*(rzt--) = '\0';
zt=z;
while( sqliteCharVal((unsigned char *)zt)!=0 ){
z=zt;
sqliteNextChar(zt);
for(i=1; zt-i>=z; ++i){
*(rzt--)=*(zt-i);
}
}
sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT);
sqlite3_free(rz);
}
/*
** An instance of the following structure holds the context of a
** stdev() or variance() aggregate computation.
** implementaion of http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Algorithm_II
** less prone to rounding errors
*/
typedef struct StdevCtx StdevCtx;
struct StdevCtx {
double rM;
double rS;
i64 cnt; /* number of elements */
};
/*
** An instance of the following structure holds the context of a
** mode() or median() aggregate computation.
** Depends on structures defined in map.c (see map & map)
** These aggregate functions only work for integers and floats although
** they could be made to work for strings. This is usually considered meaningless.
** Only usuall order (for median), no use of collation functions (would this even make sense?)
*/
typedef struct ModeCtx ModeCtx;
struct ModeCtx {
i64 riM; /* integer value found so far */
double rdM; /* double value found so far */
i64 cnt; /* number of elements so far */
double pcnt; /* number of elements smaller than a percentile */
i64 mcnt; /* maximum number of occurrences (for mode) */
i64 mn; /* number of occurrences (for mode and percentiles) */
i64 is_double; /* whether the computation is being done for doubles (>0) or integers (=0) */
map* m; /* map structure used for the computation */
int done; /* whether the answer has been found */
};
/*
** called for each value received during a calculation of stdev or variance
*/
static void varianceStep(sqlite3_context *context, int argc, sqlite3_value **argv){
StdevCtx *p;
double delta;
double x;
assert( argc==1 );
p = sqlite3_aggregate_context(context, sizeof(*p));
/* only consider non-null values */
if( SQLITE_NULL != sqlite3_value_numeric_type(argv[0]) ){
p->cnt++;
x = sqlite3_value_double(argv[0]);
delta = (x-p->rM);
p->rM += delta/p->cnt;
p->rS += delta*(x-p->rM);
}
}
/*
** called for each value received during a calculation of mode of median
*/
static void modeStep(sqlite3_context *context, int argc, sqlite3_value **argv){
ModeCtx *p;
i64 xi=0;
double xd=0.0;
i64 *iptr;
double *dptr;
int type;
assert( argc==1 );
type = sqlite3_value_numeric_type(argv[0]);
if( type == SQLITE_NULL)
return;
p = sqlite3_aggregate_context(context, sizeof(*p));
if( 0==(p->m) ){
p->m = calloc(1, sizeof(map));
if( type==SQLITE_INTEGER ){
/* map will be used for integers */
*(p->m) = map_make(int_cmp);
p->is_double = 0;
}else{
p->is_double = 1;
/* map will be used for doubles */
*(p->m) = map_make(double_cmp);
}
}
++(p->cnt);
if( 0==p->is_double ){
xi = sqlite3_value_int64(argv[0]);
iptr = (i64*)calloc(1,sizeof(i64));
*iptr = xi;
map_insert(p->m, iptr);
}else{
xd = sqlite3_value_double(argv[0]);
dptr = (double*)calloc(1,sizeof(double));
*dptr = xd;
map_insert(p->m, dptr);
}
}
/*
** Auxiliary function that iterates all elements in a map and finds the mode
** (most frequent value)
*/
static void modeIterate(void* e, i64 c, void* pp){
i64 ei;
double ed;
ModeCtx *p = (ModeCtx*)pp;
if( 0==p->is_double ){
ei = *(int*)(e);
if( p->mcnt==c ){
++p->mn;
}else if( p->mcnt<c ){
p->riM = ei;
p->mcnt = c;
p->mn=1;
}
}else{
ed = *(double*)(e);
if( p->mcnt==c ){
++p->mn;
}else if(p->mcnt<c){
p->rdM = ed;
p->mcnt = c;
p->mn=1;
}
}
}
/*
** Auxiliary function that iterates all elements in a map and finds the median
** (the value such that the number of elements smaller is equal the the number of
** elements larger)
*/
static void medianIterate(void* e, i64 c, void* pp){
i64 ei;
double ed;
double iL;
double iR;
int il;
int ir;
ModeCtx *p = (ModeCtx*)pp;
if(p->done>0)
return;
iL = p->pcnt;
iR = p->cnt - p->pcnt;
il = p->mcnt + c;
ir = p->cnt - p->mcnt;
if( il >= iL ){
if( ir >= iR ){
++p->mn;
if( 0==p->is_double ){
ei = *(int*)(e);
p->riM += ei;
}else{
ed = *(double*)(e);
p->rdM += ed;
}
}else{
p->done=1;
}
}
p->mcnt+=c;
}
/*
** Returns the mode value
*/
static void modeFinalize(sqlite3_context *context){
ModeCtx *p;
p = sqlite3_aggregate_context(context, 0);
if( p && p->m ){
map_iterate(p->m, modeIterate, p);
map_destroy(p->m);
free(p->m);
if( 1==p->mn ){
if( 0==p->is_double )
sqlite3_result_int64(context, p->riM);
else
sqlite3_result_double(context, p->rdM);
}
}
}
/*
** auxiliary function for percentiles
*/
static void _medianFinalize(sqlite3_context *context){
ModeCtx *p;
p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
if( p && p->m ){
p->done=0;
map_iterate(p->m, medianIterate, p);
map_destroy(p->m);
free(p->m);
if( 0==p->is_double )
if( 1==p->mn )
sqlite3_result_int64(context, p->riM);
else
sqlite3_result_double(context, p->riM*1.0/p->mn);
else
sqlite3_result_double(context, p->rdM/p->mn);
}
}
/*
** Returns the median value
*/
static void medianFinalize(sqlite3_context *context){
ModeCtx *p;
p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
if( p!=0 ){
p->pcnt = (p->cnt)/2.0;
_medianFinalize(context);
}
}
/*
** Returns the lower_quartile value
*/
static void lower_quartileFinalize(sqlite3_context *context){
ModeCtx *p;
p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
if( p!=0 ){
p->pcnt = (p->cnt)/4.0;
_medianFinalize(context);
}
}
/*
** Returns the upper_quartile value
*/
static void upper_quartileFinalize(sqlite3_context *context){
ModeCtx *p;
p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
if( p!=0 ){
p->pcnt = (p->cnt)*3/4.0;
_medianFinalize(context);
}
}
/*
** Returns the stdev value
*/
static void stdevFinalize(sqlite3_context *context){
StdevCtx *p;
p = sqlite3_aggregate_context(context, 0);
if( p && p->cnt>1 ){
sqlite3_result_double(context, sqrt(p->rS/(p->cnt-1)));
}else{
sqlite3_result_double(context, 0.0);
}
}
/*
** Returns the variance value
*/
static void varianceFinalize(sqlite3_context *context){
StdevCtx *p;
p = sqlite3_aggregate_context(context, 0);
if( p && p->cnt>1 ){
sqlite3_result_double(context, p->rS/(p->cnt-1));
}else{
sqlite3_result_double(context, 0.0);
}
}
#ifdef SQLITE_SOUNDEX
/* relicoder factored code */
/*
** Calculates the soundex value of a string
*/
static void soundex(const u8 *zIn, char *zResult){
int i, j;
static const unsigned char iCode[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
};
for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
if( zIn[i] ){
zResult[0] = toupper(zIn[i]);
for(j=1; j<4 && zIn[i]; i++){
int code = iCode[zIn[i]&0x7f];
if( code>0 ){
zResult[j++] = code + '0';
}
}
while( j<4 ){
zResult[j++] = '0';
}
zResult[j] = 0;
}else{
strcpy(zResult, "?000");
}
}
/*
** computes the number of different characters between the soundex value fo 2 strings
*/
static void differenceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
char zResult1[8];
char zResult2[8];
char *zR1 = zResult1;
char *zR2 = zResult2;
int rVal = 0;
int i = 0;
const u8 *zIn1;
const u8 *zIn2;
assert( argc==2 );
if( sqlite3_value_type(argv[0])==SQLITE_NULL || sqlite3_value_type(argv[1])==SQLITE_NULL ){
sqlite3_result_null(context);
return;
}
zIn1 = (u8*)sqlite3_value_text(argv[0]);
zIn2 = (u8*)sqlite3_value_text(argv[1]);
soundex(zIn1, zR1);
soundex(zIn2, zR2);
for(i=0; i<4; ++i){
if( sqliteCharVal((unsigned char *)zR1)==sqliteCharVal((unsigned char *)zR2) )
++rVal;
sqliteNextChar(zR1);
sqliteNextChar(zR2);
}
sqlite3_result_int(context, rVal);
}
#endif
/*
** This function registered all of the above C functions as SQL
** functions. This should be the only routine in this file with
** external linkage.
*/
int RegisterExtensionFunctions( sqlite3 *db )
{
static const struct FuncDef {
char *zName;
signed char nArg;
u8 argType; /* 0: none. 1: db 2: (-1) */
u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */
u8 needCollSeq;
void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
} aFuncs[] = {
/* math.h */
{ "acos", 1, 0, SQLITE_UTF8, 0, acosFunc },
{ "asin", 1, 0, SQLITE_UTF8, 0, asinFunc },
{ "atan", 1, 0, SQLITE_UTF8, 0, atanFunc },
{ "atn2", 2, 0, SQLITE_UTF8, 0, atn2Func },
/* XXX alias */
{ "atan2", 2, 0, SQLITE_UTF8, 0, atn2Func },
{ "acosh", 1, 0, SQLITE_UTF8, 0, acoshFunc },
{ "asinh", 1, 0, SQLITE_UTF8, 0, asinhFunc },
{ "atanh", 1, 0, SQLITE_UTF8, 0, atanhFunc },
{ "difference", 2, 0, SQLITE_UTF8, 0, differenceFunc},
{ "degrees", 1, 0, SQLITE_UTF8, 0, rad2degFunc },
{ "radians", 1, 0, SQLITE_UTF8, 0, deg2radFunc },
{ "cos", 1, 0, SQLITE_UTF8, 0, cosFunc },
{ "sin", 1, 0, SQLITE_UTF8, 0, sinFunc },
{ "tan", 1, 0, SQLITE_UTF8, 0, tanFunc },
{ "cot", 1, 0, SQLITE_UTF8, 0, cotFunc },
{ "cosh", 1, 0, SQLITE_UTF8, 0, coshFunc },
{ "sinh", 1, 0, SQLITE_UTF8, 0, sinhFunc },
{ "tanh", 1, 0, SQLITE_UTF8, 0, tanhFunc },
{ "coth", 1, 0, SQLITE_UTF8, 0, cothFunc },
{ "exp", 1, 0, SQLITE_UTF8, 0, expFunc },
{ "log", 1, 0, SQLITE_UTF8, 0, logFunc },
{ "log10", 1, 0, SQLITE_UTF8, 0, log10Func },
{ "power", 2, 0, SQLITE_UTF8, 0, powerFunc },
{ "sign", 1, 0, SQLITE_UTF8, 0, signFunc },
{ "sqrt", 1, 0, SQLITE_UTF8, 0, sqrtFunc },
{ "square", 1, 0, SQLITE_UTF8, 0, squareFunc },
{ "ceil", 1, 0, SQLITE_UTF8, 0, ceilFunc },
{ "floor", 1, 0, SQLITE_UTF8, 0, floorFunc },
{ "pi", 0, 0, SQLITE_UTF8, 1, piFunc },
/* string */
{ "replicate", 2, 0, SQLITE_UTF8, 0, replicateFunc },
{ "charindex", 2, 0, SQLITE_UTF8, 0, charindexFunc },
{ "charindex", 3, 0, SQLITE_UTF8, 0, charindexFunc },
{ "leftstr", 2, 0, SQLITE_UTF8, 0, leftFunc },
{ "rightstr", 2, 0, SQLITE_UTF8, 0, rightFunc },
#ifndef HAVE_TRIM
{ "ltrim", 1, 0, SQLITE_UTF8, 0, ltrimFunc },
{ "rtrim", 1, 0, SQLITE_UTF8, 0, rtrimFunc },
{ "trim", 1, 0, SQLITE_UTF8, 0, trimFunc },
{ "replace", 3, 0, SQLITE_UTF8, 0, replaceFunc },
#endif
{ "reverse", 1, 0, SQLITE_UTF8, 0, reverseFunc },
{ "proper", 1, 0, SQLITE_UTF8, 0, properFunc },
{ "padl", 2, 0, SQLITE_UTF8, 0, padlFunc },
{ "padr", 2, 0, SQLITE_UTF8, 0, padrFunc },
{ "padc", 2, 0, SQLITE_UTF8, 0, padcFunc },
{ "strfilter", 2, 0, SQLITE_UTF8, 0, strfilterFunc },
};
/* Aggregate functions */
static const struct FuncDefAgg {
char *zName;
signed char nArg;
u8 argType;
u8 needCollSeq;
void (*xStep)(sqlite3_context*,int,sqlite3_value**);
void (*xFinalize)(sqlite3_context*);
} aAggs[] = {
{ "stdev", 1, 0, 0, varianceStep, stdevFinalize },
{ "variance", 1, 0, 0, varianceStep, varianceFinalize },
{ "mode", 1, 0, 0, modeStep, modeFinalize },
{ "median", 1, 0, 0, modeStep, medianFinalize },
{ "lower_quartile", 1, 0, 0, modeStep, lower_quartileFinalize },
{ "upper_quartile", 1, 0, 0, modeStep, upper_quartileFinalize },
};
int i;
for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
void *pArg = 0;
switch( aFuncs[i].argType ){
case 1: pArg = db; break;
case 2: pArg = (void *)(-1); break;
}
//sqlite3CreateFunc
/* LMH no error checking */
sqlite3_create_function_v2(db, aFuncs[i].zName, aFuncs[i].nArg,
aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, NULL, NULL, NULL);
#if 0
if( aFuncs[i].needCollSeq ){
struct FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
if( pFunc && aFuncs[i].needCollSeq ){
pFunc->needCollSeq = 1;
}
}
#endif
}
for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
void *pArg = 0;
switch( aAggs[i].argType ){
case 1: pArg = db; break;
case 2: pArg = (void *)(-1); break;
}
//sqlite3CreateFunc
/* LMH no error checking */
sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
#if 0
if( aAggs[i].needCollSeq ){
struct FuncDefAgg *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
if( pFunc && aAggs[i].needCollSeq ){
pFunc->needCollSeq = 1;
}
}
#endif
}
return 0;
}
#ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE
int sqlite3_extension_init(
sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi){
SQLITE_EXTENSION_INIT2(pApi);
RegisterExtensionFunctions(db);
return 0;
}
#endif /* COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE */
map map_make(cmp_func cmp){
map r;
r.cmp=cmp;
r.base = 0;
return r;
}
void* xcalloc(size_t nmemb, size_t size, char* s){
void* ret = calloc(nmemb, size);
return ret;
}
void xfree(void* p){
free(p);
}
void node_insert(node** n, cmp_func cmp, void *e){
int c;
node* nn;
if(*n==0){
nn = (node*)xcalloc(1,sizeof(node), "for node");
nn->data = e;
nn->count = 1;
*n=nn;
}else{
c=cmp((*n)->data,e);
if(0==c){
++((*n)->count);
xfree(e);
}else if(c>0){
/* put it right here */
node_insert(&((*n)->l), cmp, e);
}else{
node_insert(&((*n)->r), cmp, e);
}
}
}
void map_insert(map *m, void *e){
node_insert(&(m->base), m->cmp, e);
}
void node_iterate(node *n, map_iterator iter, void* p){
if(n){
if(n->l)
node_iterate(n->l, iter, p);
iter(n->data, n->count, p);
if(n->r)
node_iterate(n->r, iter, p);
}
}
void map_iterate(map *m, map_iterator iter, void* p){
node_iterate(m->base, iter, p);
}
void node_destroy(node *n){
if(0!=n){
xfree(n->data);
if(n->l)
node_destroy(n->l);
if(n->r)
node_destroy(n->r);
xfree(n);
}
}
void map_destroy(map *m){
node_destroy(m->base);
}
int int_cmp(const void *a, const void *b){
int64_t aa = *(int64_t *)(a);
int64_t bb = *(int64_t *)(b);
/* printf("cmp %d <=> %d\n",aa,bb); */
if(aa==bb)
return 0;
else if(aa<bb)
return -1;
else
return 1;
}
int double_cmp(const void *a, const void *b){
double aa = *(double *)(a);
double bb = *(double *)(b);
/* printf("cmp %d <=> %d\n",aa,bb); */
if(aa==bb)
return 0;
else if(aa<bb)
return -1;
else
return 1;
}
void print_elem(void *e, int64_t c, void* p){
int ee = *(int*)(e);
printf("%d => %lld\n", ee, (long long int)c);
}
#if defined(__cplusplus)
}
#endif /* __cplusplus */
|
the_stack_data/158430.c | /* width.c -- field widths */
#include <stdio.h>
#define PAGES 959
int main(void)
{
printf("*%d*\n", PAGES);
printf("*%2d*\n", PAGES);
printf("*%10d*\n", PAGES);
printf("*%-10d*\n", PAGES);
return 0;
}
|
the_stack_data/50181.c | #include <stdlib.h>
#include <math.h>
/* Coefficients for the n=9 case from Cody (1965) "Chebyshev Approximations
for the Complete Elliptic Integrals K and E". According to this source
the error in the approximation itself should be below 1.45e-16 in the
worst case (E). This is close to machine epsilon.
The peculiar arrangement of this array is optimized for summing
both polynomials simultaneously using bunched, back-to-back
additions and multiplications with Horner's method. By doing it
in this order, we take advantage of pipelining by avoiding
dependencies between the consecutive multiply instructions.
This is more for the assembly language implementations than the
C implementation. On x87 this causes the compiler to emit a
sequence of fmul and fxch instructions, which is okay on the
Pentium (where the fxch gets combined with the fmul) but may
be slower than summing the polynomials one at a time on earlier
CPUs or other architectures. */
static const double dellke_coeff[40] = {
/* K E */
3.00725199036864838e-4, 3.25192015506390418e-4, /* a,c_9 */
6.66317524646073151e-5, 7.20316963457154599e-5, /* b,d_9 */
3.96847090209897819e-3, 4.30253777479311659e-3, /* a,c_8 */
1.72161470979865212e-3, 1.86453791840633632e-3, /* b,d_8 */
1.07959904905916349e-2, 1.17858410087339355e-2, /* a,c_7 */
9.28116038296860419e-3, 1.00879584943751004e-2, /* b,d_7 */
1.05899536209893585e-2, 1.18419259955012494e-2, /* a,c_6 */
2.06902400051008404e-2, 2.26603098916041221e-2, /* b,d_6 */
7.51938672180838102e-3, 9.03552773754088184e-3, /* a,c_5 */
2.95037293486887130e-2, 3.28110691727210618e-2, /* b,d_5 */
8.92664629455646620e-3, 1.17167669446577228e-2, /* a,c_4 */
3.73355466822860296e-2, 4.26725101265917523e-2, /* b,d_4 */
1.49420291422820783e-2, 2.18361314054868967e-2, /* a,c_3 */
4.88271550481180099e-2, 5.85927071842652739e-2, /* b,d_3 */
3.08851730018997099e-2, 5.68052233293082895e-2, /* a,c_2 */
7.03124954595466082e-2, 9.37499951163670673e-2, /* b,d_2 */
9.65735903017425285e-2, 4.43147180583368137e-1, /* a,c_1 */
1.24999999997640658e-1, 2.49999999997461423e-1, /* b,d_1 */
2*M_LN2, 1.0 , /* a,c_0 */
0.5, 0.0 /* b,d_0 */
};
/* Computes K(k) and E(e) given y=1-k^2. v[0] receives K and v[1] receives E.
The output vector format is to maintain compatibility with the assembly
language routine for SSE2. */
void dellke_gen (double y, double v[2]) {
double sa, sb, sc, sd, ly;
int i = 0;
ly = log(y);
/* Sum polynomials */
sa = dellke_coeff[i++] * y;
sc = dellke_coeff[i++] * y;
sb = dellke_coeff[i++] * y;
sd = dellke_coeff[i++] * y;
while(i < 36) {
sa = (sa + dellke_coeff[i++]) * y;
sc = (sc + dellke_coeff[i++]) * y;
sb = (sb + dellke_coeff[i++]) * y;
sd = (sd + dellke_coeff[i++]) * y;
}
sa += dellke_coeff[i++];
sc += dellke_coeff[i++];
sb += dellke_coeff[i++];
/* d0 = 0, so omitted */
/* Result */
v[0] = sa - sb*ly;
v[1] = sc - sd*ly;
}
|
the_stack_data/220456628.c | int main(void)
{
// check declaration splitting
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9;
int * p;
i0 = 0;
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
i5 = 5;
i6 = 6;
i7 = 7;
i8 = 8;
i9 = 9;
// break some register candidates
p = &i1;
p = &i3;
p = &i5;
p = &i7;
p = &i9;
return i0+i1+i2+i3+i4+i5+i6+i7+i8+i9;
}
|
the_stack_data/8086.c | // some global variables for each type
char c;
unsigned char uc;
short s;
unsigned short us;
int i;
unsigned int ui;
long l;
unsigned long ul;
long long ll;
unsigned long long ull;
void assert(int expr) {
if (expr == 0) { ERROR: goto ERROR; }
}
void overflow() {
// all values are -2^n - 2
c = -130;
uc = -258;
s = -32770;
us = -65538;
i = -2147483650LL;
ui = -4294967298LL;
ll = -9223372036854775810LL;
ull = -18446744073709551618LL;
assert(126 == c);
assert(32766 == s);
assert(2147483646 == i);
assert(9223372036854775806LL == ll);
assert(254 == uc);
assert(65534 == us);
assert(4294967294LL == ui);
assert(18446744073709551614LL == ull);
}
void minusOne() {
// all values are -1
c = -1;
uc = -1;
s = -1;
us = -1;
i = -1;
ui = -1;
ll = -1;
ull = -1;
assert(-1 == c);
assert(-1 == s);
assert(-1 == i);
assert(-1 == ll);
assert(255 == uc);
assert(65535 == us);
assert(4294967295LL == ui);
assert(18446744073709551615LL == ull);
assert(0 > c);
assert(0 > s);
assert(0 > i);
assert(0 > ll);
assert(0 < uc);
assert(0 < us);
assert(0 < ui);
assert(0 < ull);
}
void shiftOne() {
// all values are -1
c = -1;
uc = -1;
s = -1;
us = -1;
i = -1;
ui = -1;
ll = -1;
ull = -1;
// all values are -1
c = c>>1;
uc = uc>>1;
s = s>>1;
us = us>>1;
i = i>>1;
ui = ui>>1;
ll = ll>>1;
ull = ull>>1;
assert(-1 == c);
assert(-1 == s);
assert(-1 == i);
assert(-1 == ll);
assert(127 == uc);
assert(32767 == us);
assert(2147483647 == ui);
assert(9223372036854775807LL == ull);
}
void one() {
// all values are 1
c = 1;
uc = 1;
s = 1;
us = 1;
i = 1;
ui = 1;
ll = 1;
ull = 1;
assert(1 == c);
assert(1 == s);
assert(1 == i);
assert(1 == ll);
assert(1 == uc);
assert(1 == us);
assert(1 == ui);
assert(1 == ull);
}
void shiftSize() {
// all values are 0
c = 1<<8;
uc = 1<<8;
s = 1<<16;
us = 1<<16;
i = 1<<32;
ui = 1<<32;
ll = 1<<64;
ull = 1<<64;
assert(0 == c);
assert(0 == s);
assert(0 == i);
assert(0 == ll);
assert(0 == uc);
assert(0 == us);
assert(0 == ui);
assert(0 == ull);
}
int main() {
overflow();
minusOne();
shiftOne();
one();
shiftSize();
// 64bit only
if (sizeof(long) == 8) {
printf("64bit\n");
ul = -2;
ull = -1;
assert(0 < ul);
assert(ul < ull);
}
return (0);
}
|
the_stack_data/982511.c | #include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you\n");
// (\) is continuation operator, used to continue a macro that is too long for a single line
// (#) is stringize operator, used to converts a macro parameter into a string
int main() {
message_for(Imam, Sutono);
return 0;
} |
the_stack_data/96009.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* Strips spaces from both the front and back of a string,
* leaving any internal spaces alone.
*/
char* strip(char* str) {
int size;
int num_spaces;
int first_non_space, last_non_space, i;
char* result;
size = strlen(str);
// This counts the number of leading and trailing spaces
// so we can figure out how big the result array should be.
num_spaces = 0;
first_non_space = 0;
while (first_non_space<size && str[first_non_space] == ' ') {
++num_spaces;
++first_non_space;
}
last_non_space = size-1;
while (last_non_space>=0 && str[last_non_space] == ' ') {
++num_spaces;
--last_non_space;
}
// If num_spaces >= size then that means that the string
// consisted of nothing but spaces, so we'll return the
// empty string.
if (num_spaces >= size) {
return "";
}
// Allocate a slot for all the "saved" characters
// plus one extra for the null terminator.
result = calloc(size-num_spaces+1, sizeof(char));
// Copy in the "saved" characters.
for (i=first_non_space; i<=last_non_space; ++i) {
result[i-first_non_space] = str[i];
}
//free(result);
// Place the null terminator at the end of the result string.
result[i-first_non_space] = '\0';
return result;
}
/*
* Return true (1) if the given string is "clean", i.e., has
* no spaces at the front or the back of the string.
*/
int is_clean(char* str) {
char* cleaned;
int result;
// We check if it's clean by calling strip and seeing if the
// result is the same as the original string.
cleaned = strip(str);
// strcmp compares two strings, returning a negative value if
// the first is less than the second (in alphabetical order),
// 0 if they're equal, and a positive value if the first is
// greater than the second.
result = strcmp(str, cleaned);
if (cleaned[0] != '\0')
{
free(cleaned);
}
return result == 0;
}
int main() {
int i;
int NUM_STRINGS = 7;
// Makes an array of 7 string constants for testing.
char* strings[] = { "Morris",
" stuff",
"Minnesota",
"nonsense ",
"USA",
" ",
" silliness "
};
for (i=0; i<NUM_STRINGS; ++i) {
if (is_clean(strings[i])) {
printf("The string '%s' is clean.\n", strings[i]);
} else {
printf("The string '%s' is NOT clean.\n", strings[i]);
//free(strings[i]);
}
}
return 0;
}
|
the_stack_data/167330296.c | #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int main(int argc, char **args)
{
FILE *fin;
FILE *fout;
uint32_t fs;
uint32_t fptr;
uint8_t dbuf[2];
uint8_t rbcnt;
uint8_t tmp;
uint32_t mask;
if (argc != 3) {
printf("\nUsage: ./encode [input_f] [output_f]\n\n");
printf("[input_f] : File which contents are to be encrypted\n");
printf("[output_f] : File where encrypted contents are stored\n\n");
return 1;
}
fin = fopen(args[1], "rb");
if (!fin) {
printf("Error! Input file could not be opened!\n");
return 1;
}
fout = fopen(args[2], "wb");
if (!fout) {
printf("Error! Could not create output file!\n");
fclose(fin);
return 1;
}
fseek(fin, 0, SEEK_END);
fs = ftell(fin);
if (!fs) {
printf("Error! Input file is empty!\n");
fclose(fin);
fclose(fout);
return 1;
}
// Evil magic trix
mask = (0xa5a5a5a5) ^ (0x5a5a5a5a);
// 0xffffffff
mask &= (mask >> 24);
// 255? 0xff
fseek(fin, 0, SEEK_SET);
// 3 first bytes are handled differently
if (fs <= 2) {
printf("eka");
fread(dbuf, sizeof(uint8_t), fs, fin);
if ((fs % 2) == 0) {
printf("\n1:%c", dbuf[0]);
printf("\n2:%c", dbuf[1]);
tmp = (dbuf[0] ^ 0xa5) & mask;
dbuf[0] = ~(dbuf[1] & mask);
dbuf[1] = ~tmp;
printf("\n1:%c", dbuf[0]);
printf("\n2:%c", dbuf[1]);
fwrite(dbuf, sizeof(uint8_t), fs, fout);
}
else {
printf("else");
dbuf[0] = ~(dbuf[0] & mask);
}
}
else {
printf("toka");
rbcnt = 2;
for (fptr = 0; fptr < fs; fptr = fptr + 2) {
if (rbcnt > (fs - fptr)) {
rbcnt = fs - fptr;
}
printf("\nrbcnt:%d", rbcnt);
fread(dbuf, sizeof(uint8_t), rbcnt, fin);
if ((rbcnt % 2) == 0) {
tmp = (dbuf[0] ^ 0xa5) & mask;
dbuf[0] = ~(dbuf[1] & mask);
dbuf[1] = ~tmp;
fwrite(dbuf, sizeof(uint8_t), rbcnt, fout);
}
else {
printf("else");
printf("\n1:%d", dbuf[0]);
dbuf[0] = ~(dbuf[0] & mask);
printf("\n1:%d", dbuf[0]);
fwrite(dbuf, sizeof(uint8_t), rbcnt, fout);
}
}
}
fclose(fin);
fclose(fout);
return 0;
}
|
the_stack_data/1248280.c | #include <stdio.h>
#include <string.h>
int main()
{
int n, m;
long long sum, halfsum, i, j, k, num[1005], value[55], pre[260000], cur[260000];
while (scanf("%d", &n) != EOF && n > 0)
{
sum = 0;
for (m = 1; m <= n; m++)
{
scanf("%lld %lld", &value[m], &num[m]);
sum += num[m] * value[m];
}
halfsum = sum / 2;
memset(pre, 0, sizeof(long long)*260000);
memset(cur, 0, sizeof(long long)*260000);
for (i = 0; i <= num[1] * value[1]; i += value[1])
pre[i] = 1;
for (i = 2; i <= n; i++)
{
for (j = 0; j <= halfsum; j++)
{
for (k = 0; k <= num[i] * value[i] && k + j <= halfsum; k += value[i])
cur[k + j] += pre[j];
}
for (j = 0; j <= halfsum; j++)
{
pre[j] = cur[j];
cur[j] = 0;
}
}
for (i = halfsum; i >= 0; i--)
{
if (pre[i])
{
if (i <= sum - i)
printf("%lld %lld\n", sum-i, i);
else
printf("%lld %lld\n", i, sum - i);
break;
}
}
}
return 0;
}
|
the_stack_data/97381.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
pthread_t server_thread_id;
pthread_t interface_thread_id;
void *threadServer(void *args)
{
int returnValue = system("node ./src/server/app.js");
}
void *threadInterface(void *args)
{
int returnValue = system("python3 ./src/interface/rfid-interface.py");
}
void sigHandler(int _) {
pthread_cancel(server_thread_id);
pthread_cancel(interface_thread_id);
}
int main(void)
{
signal(SIGINT, sigHandler);
signal(SIGTERM, sigHandler);
pthread_create(&server_thread_id, NULL, threadServer, NULL);
pthread_create(&interface_thread_id, NULL, threadInterface, NULL);
pthread_join(server_thread_id, NULL);
pthread_join(interface_thread_id, NULL);
return 0;
} |
the_stack_data/983699.c | // Solved 2020-11-22 11:11
// Runtime: 0 ms (100.00%)
// Memory Usage: 5.6 MB (75.64%)
char* freqAlphabets(char* s) {
int l = strlen(s);
char *r = (char*)malloc(sizeof(char) * (l + 1)), *p = r;
for (int i = 0; i < l; i++) {
if (s[i] != '#') {
*(p++) = s[i] + 48; // (s[i] - '0' + 1) + 'a'
} else {
p -= 2;
*(p++) = 10 * s[i - 2] + s[i - 1] - 432; // 10 * (s[i - 2] - '0') + s[i - 1] + 48
}
}
*p = '\0';
return r;
}
|
the_stack_data/117934.c | ////////////////////////////////////////////////////////////////////////////////
//
// Filename: udiv.c
//
// Project: ZBasic, a generic toplevel impl using the full ZipCPU
//
// Purpose: This is a temporary file--a crutch if you will--until a similar
// capability is merged into GCC. Right now, GCC has no way of
// dividing two 64-bit numbers, and this routine provides that capability.
//
//
// Creator: Dan Gisselquist, Ph.D.
// Gisselquist Technology, LLC
//
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2015-2016, Gisselquist Technology, LLC
//
// This program is free software (firmware): 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 MERCHANTIBILITY 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. (It's in the $(ROOT)/doc directory, run make with no
// target there if the PDF file isn't present.) If not, see
// <http://www.gnu.org/licenses/> for a copy.
//
// License: GPL, v3, as defined and found on www.gnu.org,
// http://www.gnu.org/licenses/gpl.html
//
//
////////////////////////////////////////////////////////////////////////////////
//
//
#include <stdint.h>
#ifdef __ZIPCPU__
#include "zipcpu.h"
#else
uint32_t zip_bitrev(const uint32_t a) {
uint32_t r, b = a;
r = 0;
for(int i=0; i<32; i++) {
r = (r<<1) | (b&1);
b >>= 1;
} return r;
}
#endif
extern int cltz(unsigned long);
#ifdef __ZIPCPU__
#define ASMCLTZ
#endif
#ifdef ASMCLTZ
asm("\t.section\t.text\n\t.global\tcltz\n"
"\t.type\tcltz,@function\n"
"cltz:\n"
"\tMOV R1,R3\n"
"\tCLR R1\n"
"\tCMP 0,R3\n"
"\tMOV.Z R2,R3\n"
"\tADD.Z 32,R1\n"
"\tBREV R3\n"
"\tTEST 0x0ffff,R3\n"
"\tADD.Z 16,R1\n"
"\tLSR.Z 16,R3\n"
"\tTEST 0x0ff,R3\n"
"\tADD.Z 8,R1\n"
"\tLSR.Z 8,R3\n"
"\tTEST 0x0f,R3\n"
"\tADD.Z 4,R1\n"
"\tLSR.Z 4,R3\n"
"\tTEST 0x03,R3\n"
"\tADD.Z 2,R1\n"
"\tLSR.Z 2,R3\n"
"\tTEST 0x01,R3\n"
"\tADD.Z 1,R1\n"
"\tRETN\n");
#else
int
cltz(unsigned long v) {
uint32_t hv;
int cnt = 0;
hv = v >> 32;
if (hv == 0) {
cnt += 32;
hv = v & 0x0ffffffff;
}
hv = zip_bitrev(hv);
if ((hv & 0x0ffff)==0) {
cnt += 16;
hv = hv >> 16;
}
if ((hv & 0x0ff)==0) {
cnt += 8;
hv = hv >> 8;
}
if ((hv & 0x0f)==0) {
cnt += 4;
hv = hv >> 4;
}
if ((hv & 0x03)==0) {
cnt += 2;
hv = hv >> 2;
}
if ((hv & 0x01)==0)
cnt ++;
return cnt;
}
#endif
unsigned long
__udivdi3(unsigned long a, unsigned long b) {
unsigned long r;
if (a < b)
return 0;
if (((b>>32)==0)&&((a>>32)==0)) {
uint32_t ia, ib, ir;
ia = (uint32_t) a;
ib = (uint32_t) b;
ir = ia / ib;
r = (unsigned long)ir;
return r;
}
int la = cltz(a), lb = cltz(b);
a <<= la;
unsigned long m;
if ((lb - la < 32)&&(((b<<la)&0x0ffffffff)==0)) {
// Problem is now to divide
// [a * 2^(la-32)] / [b * 2^(la-32)] * 2^(la-la)
//
uint32_t ia, ib, ir;
b <<= la;
ia = (uint32_t)(a>>32);
ib = (uint32_t)(b>>32);
ir = ia / ib;
r = ir;
return r;
} else {
// Problem is now to divide
// [a * 2^(la)] / [b * 2^(lb)] * 2^(lb-la)
//
r = 0;
b <<= lb;
m = (1ul<<(lb-la));
while(m > 0) {
if (a >= b) {
r |= m;
a -= b;
}
m>>= 1;
b >>= 1;
} return r;
}
}
//
// A possible assembly version of __divdi3
//
// SUB 8,SP
// SW R0,(SP)
// SW R5,4(SP)
// LDI 0,R5
// CMP 0,R1
// BGE .La_is_nonneg
// XOR 1,R5
// XOR -1,R1
// XOR -1,R2
// ADD 1,R2
// ADD.C 1,R1
//.La_is_nonneg
// CMP 0,R3
// BGE .Lb_is_nonneg
// XOR 1,R5
// XOR -1,R3
// XOR -1,R3
// ADD 1,R4
// ADD.C 1,R3
//.Lb_is_nonneg
// TEST R5
// MOV .Lnegate_upon_return(PC),R0
// MOV.Z .Lsimple_return(PC),R0
// BRA __udivdi3
//.Lnegate_upon_return
// XOR -1,R2
// XOR -1,R1
// ADD 1,R2
// ADD.C 1,R1
//.Lsimple_return
//
// LW (SP),R0,(SP)
// LW 4(SP),R5)
// ADD 8,SP
// RETN
//
long __divdi3(long a, long b) {
int s = 0;
long r;
if (a < 0) {
s = 1; a = -a;
}
if (b < 0) {
s ^= 1; b = -b;
}
r = (long)__udivdi3((unsigned long)a, (unsigned long)b);
if (s)
r = -r;
return r;
}
|
the_stack_data/51209.c | /* Test for constant expressions: invalid null pointer constants in
various contexts (make sure NOPs are not inappropriately
stripped). */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-do compile } */
/* { dg-options "-std=iso9899:1999 -pedantic-errors" } */
void *p = (__SIZE_TYPE__)(void *)0; /* { dg-error "without a cast" } */
struct s { void *a; } q = { (__SIZE_TYPE__)(void *)0 }; /* { dg-error "without a cast|near initialization" } */
void *
f (void)
{
void *r;
r = (__SIZE_TYPE__)(void *)0; /* { dg-error "without a cast" } */
return (__SIZE_TYPE__)(void *)0; /* { dg-error "without a cast" } */
}
void g (void *); /* { dg-message "but argument is of type" } */
void
h (void)
{
g ((__SIZE_TYPE__)(void *)0); /* { dg-error "without a cast" } */
}
void g2 (int, void *); /* { dg-message "but argument is of type" } */
void
h2 (void)
{
g2 (0, (__SIZE_TYPE__)(void *)0); /* { dg-error "without a cast" } */
}
|
the_stack_data/62636572.c | #include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
|
the_stack_data/20450579.c | #include <pthread.h>
int x=1, m=0;
void thr() {
int l=1;
acquire(m); // m=0 /\ m'=1
if (l>=2) { x=0; }
else { x=1; }
assert(x>=1);
release(m);
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, thr, NULL);
return 0;
}
|
the_stack_data/526716.c | //file: _insn_test_v1mnz_X1.c
//op=263
#include <stdio.h>
#include <stdlib.h>
void func_exit(void) {
printf("%s\n", __func__);
exit(0);
}
void func_call(void) {
printf("%s\n", __func__);
exit(0);
}
unsigned long mem[2] = { 0x3713ce4eed37fdb1, 0xb8fb1c28cc3fba32 };
int main(void) {
unsigned long a[4] = { 0, 0 };
asm __volatile__ (
"moveli r37, -32459\n"
"shl16insli r37, r37, 16523\n"
"shl16insli r37, r37, 2092\n"
"shl16insli r37, r37, -8699\n"
"moveli r5, 8954\n"
"shl16insli r5, r5, 9384\n"
"shl16insli r5, r5, 3635\n"
"shl16insli r5, r5, -28024\n"
"moveli r22, 7513\n"
"shl16insli r22, r22, -1317\n"
"shl16insli r22, r22, 32450\n"
"shl16insli r22, r22, -11880\n"
"{ fnop ; v1mnz r37, r5, r22 }\n"
"move %0, r37\n"
"move %1, r5\n"
"move %2, r22\n"
:"=r"(a[0]),"=r"(a[1]),"=r"(a[2]));
printf("%016lx\n", a[0]);
printf("%016lx\n", a[1]);
printf("%016lx\n", a[2]);
return 0;
}
|
the_stack_data/237643201.c | /*
* Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#ifdef OPENSSL_NO_EGD
NON_EMPTY_TRANSLATION_UNIT
#else
# include <openssl/crypto.h>
# include <openssl/e_os2.h>
# include <openssl/rand.h>
/*
* Query an EGD
*/
# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_VOS) || defined(OPENSSL_SYS_UEFI)
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
{
return -1;
}
int RAND_egd(const char *path)
{
return -1;
}
int RAND_egd_bytes(const char *path, int bytes)
{
return -1;
}
# else
# include OPENSSL_UNISTD
# include <stddef.h>
# include <sys/types.h>
# include <sys/socket.h>
# ifndef NO_SYS_UN_H
# ifdef OPENSSL_SYS_VXWORKS
# include <streams/un.h>
# else
# include <sys/un.h>
# endif
# else
struct sockaddr_un {
short sun_family; /* AF_UNIX */
char sun_path[108]; /* path name (gag) */
};
# endif /* NO_SYS_UN_H */
# include <string.h>
# include <errno.h>
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
{
#if 0 /* No File by eunbin */
FILE *fp = NULL;
struct sockaddr_un addr;
int mybuffer, ret = -1, i, numbytes, fd;
unsigned char tempbuf[255];
if (bytes > (int)sizeof(tempbuf))
return -1;
/* Make socket. */
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
if (strlen(path) >= sizeof(addr.sun_path))
return -1;
strcpy(addr.sun_path, path);
i = offsetof(struct sockaddr_un, sun_path) + strlen(path);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1 || (fp = fdopen(fd, "r+")) == NULL)
return -1;
setbuf(fp, NULL);
/* Try to connect */
for ( ; ; ) {
if (connect(fd, (struct sockaddr *)&addr, i) == 0)
break;
# ifdef EISCONN
if (errno == EISCONN)
break;
# endif
switch (errno) {
# ifdef EINTR
case EINTR:
# endif
# ifdef EAGAIN
case EAGAIN:
# endif
# ifdef EINPROGRESS
case EINPROGRESS:
# endif
# ifdef EALREADY
case EALREADY:
# endif
/* No error, try again */
break;
default:
ret = -1;
goto err;
}
}
/* Make request, see how many bytes we can get back. */
tempbuf[0] = 1;
tempbuf[1] = bytes;
if (fwrite(tempbuf, sizeof(char), 2, fp) != 2 || fflush(fp) == EOF)
goto err;
if (fread(tempbuf, sizeof(char), 1, fp) != 1 || tempbuf[0] == 0)
goto err;
numbytes = tempbuf[0];
/* Which buffer are we using? */
mybuffer = buf == NULL;
if (mybuffer)
buf = tempbuf;
/* Read bytes. */
i = fread(buf, sizeof(char), numbytes, fp);
if (i < numbytes)
goto err;
ret = numbytes;
if (mybuffer)
RAND_add(tempbuf, i, i);
err:
if (fp != NULL)
fclose(fp);
return ret;
#endif
return 1;
}
int RAND_egd_bytes(const char *path, int bytes)
{
int num;
num = RAND_query_egd_bytes(path, NULL, bytes);
if (num < 0)
return -1;
if (RAND_status() != 1)
return -1;
return num;
}
int RAND_egd(const char *path)
{
return RAND_egd_bytes(path, 255);
}
# endif
#endif
|
the_stack_data/1256044.c |
#line 3 "lex.yy.c"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 0
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
#define YY_LINENO_REWIND_TO(ptr)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
yy_size_t yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#ifdef yytext_ptr
#undef yytext_ptr
#endif
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
#if defined(__GNUC__) && __GNUC__ >= 3
__attribute__((__noreturn__))
#endif
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 3
#define YY_END_OF_BUFFER 4
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[14] =
{ 0,
0, 0, 4, 3, 3, 3, 0, 2, 0, 0,
0, 1, 0
} ;
static yyconst YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 3, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 4, 1,
1, 1, 1, 1, 1, 1, 1, 1, 5, 1,
6, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst YY_CHAR yy_meta[7] =
{ 0,
1, 2, 1, 1, 1, 1
} ;
static yyconst flex_uint16_t yy_base[16] =
{ 0,
0, 3, 19, 5, 20, 9, 14, 0, 5, 1,
1, 20, 20, 15, 0
} ;
static yyconst flex_int16_t yy_def[16] =
{ 0,
14, 14, 13, 15, 13, 13, 15, 7, 7, 7,
7, 13, 0, 13, 13
} ;
static yyconst flex_uint16_t yy_nxt[27] =
{ 0,
7, 5, 12, 6, 5, 11, 6, 8, 9, 7,
10, 8, 9, 7, 10, 4, 4, 9, 13, 3,
13, 13, 13, 13, 13, 13
} ;
static yyconst flex_int16_t yy_chk[27] =
{ 0,
15, 1, 11, 1, 2, 10, 2, 4, 4, 6,
9, 6, 6, 6, 6, 14, 14, 7, 3, 13,
13, 13, 13, 13, 13, 13
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "com.l"
#line 2 "com.l"
int count = 0;
#line 474 "lex.yy.c"
#define INITIAL 0
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * _in_str );
FILE *yyget_out (void );
void yyset_out (FILE * _out_str );
yy_size_t yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int _line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
#ifndef YY_NO_UNPUT
static void yyunput (int c,char *buf_ptr );
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
{
#line 5 "com.l"
#line 694 "lex.yy.c"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_match:
do
{
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 14 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 20 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 6 "com.l"
{count++; ECHO;}
YY_BREAK
case 2:
YY_RULE_SETUP
#line 7 "com.l"
YY_BREAK
case 3:
YY_RULE_SETUP
#line 9 "com.l"
ECHO;
YY_BREAK
#line 767 "lex.yy.c"
case YY_STATE_EOF(INITIAL):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = (yytext_ptr);
yy_size_t number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (yy_size_t) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
yy_size_t new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((int) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
yy_state_type yy_current_state;
char *yy_cp;
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 14 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
int yy_is_jam;
char *yy_cp = (yy_c_buf_p);
YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 14 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 13);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
static void yyunput (int c, char * yy_bp )
{
char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up yytext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
yy_size_t number_to_move = (yy_n_chars) + 2;
char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
yy_size_t offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = (yy_size_t)size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
yy_size_t i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
yy_size_t yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param _line_number line number
*
*/
void yyset_lineno (int _line_number )
{
yylineno = _line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * _in_str )
{
yyin = _in_str ;
}
void yyset_out (FILE * _out_str )
{
yyout = _out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int _bdebug )
{
yy_flex_debug = _bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 9 "com.l"
main() {
yylex();
printf("\nCount=%d\n",count);
return 0;
}
|
the_stack_data/175143206.c | #include <stdio.h>
int main(int argc, char **argv) { printf("hello world\n"); } |
the_stack_data/61074103.c | /*
* Function to apply operator to integers 1 to n
*/
#include <stdio.h> /* scanf, printf */
#include <stdlib.h> /* abort */
#include <assert.h> /* assert */
/* declare function prototype to give as
* input to the 'apply' function
*/
typedef int (* Operator) (int arg1, int arg2);
int apply(int n, Operator op )
{
int i; /* counter variable */
int r; /* result */
/* pre-condition */
assert (n >= 1);
/* post-condition */
r = 1;
for(i = 2; i <= n; i = i + 1)
r = op(i, r);
return r;
}
/* some functions that conform the the Operator
* prototype declaration
*/
int plus(int a, int b)
{
return a + b;
}
int mult(int a, int b)
{
return a * b;
}
int main(void)
{
int sum; /* value of sum 1 to n */
int prod; /* value of product 1 to n */
int n; /* user given n */
scanf("%d", &n);
sum = apply(n, plus);
prod = apply(n, mult);
printf("%d\n", sum);
printf("%d\n", prod);
return 0;
} |
the_stack_data/26907.c | /* PR target/63947 */
/* { dg-do assemble } */
/* { dg-options "-Os" } */
/* { dg-additional-options "-march=i686" { target ia32 } } */
long double foo (unsigned a, unsigned b)
{
return a + b < a;
}
|
the_stack_data/89145.c | int main() {
for(int i = 0; i < 10; i = i + 1){
printf(i);
}
return 0;
}
|
the_stack_data/67326110.c | /* This test has architecture specific function passing details. */
/* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-stdarg" } */
/* LLVM LOCAL test not applicable */
/* { dg-require-fdump "" } */
#include <stdarg.h>
extern void foo (int, va_list);
extern void bar (int);
struct S1 { int i; double d; int j; double e; } s1;
struct S2 { double d; long i; } s2;
int y;
_Complex int ci;
_Complex double cd;
/* Here va_arg can be executed more than once for one va_start. */
void
f1 (int i, ...)
{
va_list ap;
va_start (ap, i);
while (i-- > 0)
s1 = va_arg (ap, struct S1);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save all GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save all GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
void
f2 (int i, ...)
{
va_list ap;
va_start (ap, i);
while (i-- > 0)
s2 = va_arg (ap, struct S2);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save all GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save all GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* Here va_arg can be executed at most as many times as va_start. */
void
f3 (int i, ...)
{
va_list ap;
int j = i;
while (j-- > 0)
{
va_start (ap, i);
s1 = va_arg (ap, struct S1);
va_end (ap);
bar (s1.i);
}
}
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 32 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 1 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
void
f4 (int i, ...)
{
va_list ap;
int j = i;
while (j-- > 0)
{
va_start (ap, i);
s2 = va_arg (ap, struct S2);
y = va_arg (ap, int);
va_end (ap);
bar (s2.i);
}
}
/* { dg-final { scan-tree-dump "f4: va_list escapes 0, needs to save 16 GPR units and 16 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 0, needs to save 24 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 0, needs to save 2 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
void
f5 (int i, ...)
{
va_list ap;
va_start (ap, i);
ci = va_arg (ap, _Complex int);
ci += va_arg (ap, _Complex int);
va_end (ap);
bar (__real__ ci + __imag__ ci);
}
/* { dg-final { scan-tree-dump "f5: va_list escapes 0, needs to save 16 GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 0, needs to save 32 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 0, needs to save (4|2) GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
void
f6 (int i, ...)
{
va_list ap;
va_start (ap, i);
ci = va_arg (ap, _Complex int);
cd = va_arg (ap, _Complex double);
va_end (ap);
bar (__real__ ci + __imag__ cd);
}
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save 8 GPR units and 32 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save 32 GPR units and 3" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|2) GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
void
f7 (int i, ...)
{
va_list ap;
va_start (ap, i);
cd = va_arg (ap, _Complex double);
cd += va_arg (ap, _Complex double);
va_end (ap);
bar (__real__ cd + __imag__ cd);
}
/* { dg-final { scan-tree-dump "f7: va_list escapes 0, needs to save 0 GPR units and 64 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 0, needs to save 32 GPR units and 2" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 0, needs to save 2 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { cleanup-tree-dump "stdarg" } } */
|
the_stack_data/237642189.c | #include <stdlib.h>
#include <stdio.h>
/* In C, a function is not a variable. But it is possible to address a function
* with a Pointer, which can be assigned, placed in arrays or passed as
* argument or returned as a result of other function.
*
* To define pointers to functions, you must declare what is the interface of
* the function, i.e., what are the arguments and what is the type of the
* returned value.
*
*/
int compare_ascend(int one, int other) {
return other - one;
}
int compare_descend(int one, int other) {
return one - other;
}
void sort(int *array, int size, int (*comparison)(int, int)) {
for (int i = 0; i < size; i++) {
int least = i;
for (int j = i + 1; j < size; j++) {
if ((*comparison)(array[least], array[j]) < 0) {
least = j;
}
}
if (least != i) {
int aux = array[i];
array[i] = array[least];
array[least] = aux;
}
}
}
void print_array(int *array, int size, char *format) {
printf("[ ");
for (int i = 0; i < (size - 1); i++) {
printf(format, array[i]);
printf(", ");
}
printf(format, array[size - 1]);
printf(" ]");
}
int main(int argc, char const *argv[]) {
printf("================================\n");
printf("FUNCTION POINTERS\n");
printf("================================\n\n");
const int max = 10;
int a[max], b[max];
int (*comparisons[])(int, int) = {compare_ascend, compare_descend};
for (int i = 0; i < max; i++) {
int j = max - i - 1;
a[j] = i;
b[i] = i;
}
printf("Original: A = ");
print_array(a, max, "%i");
printf("\n B = ");
print_array(b, max, "%i");
printf("\n");
sort(a, max, comparisons[0]);
sort(b, max, comparisons[1]);
printf("Sorted: A = ");
print_array(a, max, "%i");
printf("\n B = ");
print_array(b, max, "%i");
printf("\n\n");
return EXIT_SUCCESS;
}
|
the_stack_data/108878.c | /* ============================================================================
* Copyright (c) 2010, Michael A. Jackson (BlueQuartz Software)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of Michael A. Jackson nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#if 0
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "emmpm/common/allocate.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void *get_spc(int num, size_t size)
{
void *pt;
if( (pt=calloc((size_t)num,size)) == NULL ) {
fprintf(stderr, "==> calloc() error\n");
exit(-1);
}
return(pt);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void *mget_spc(int num,size_t size)
{
void *pt;
if( (pt=malloc((size_t)(num*size))) == NULL ) {
fprintf(stderr, "==> malloc() error\n");
exit(-1);
}
return(pt);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void **get_img(int wd,int ht, size_t size)
{
void *pt;
if( (pt=multialloc(size,2,ht,wd))==NULL) {
fprintf(stderr, "get_img: out of memory\n");
exit(-1);
}
return((void **)pt);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void EMMPM_free_img(void **pt)
{
multifree((void *)pt,2);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ***get_3d_img(int wd, int ht, int dp, size_t size)
{
void *pt;
if ((pt = multialloc(size, 3, wd, ht, dp)) == NULL)
{
fprintf(stderr, "get_3d_img: out of memory\n");
exit(-1);
}
return ((void ***)pt);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void EMMPM_free_3d_img(void ***pt)
{
multifree((void *)pt, 3);
}
/* modified from dynamem.c on 4/29/91 C. Bouman */
/* Converted to ANSI on 7/13/93 C. Bouman */
/* multialloc( s, d, d1, d2 ....) allocates a d dimensional array, whose */
/* dimensions are stored in a list starting at d1. Each array element is */
/* of size s. */
void *multialloc(size_t s, int d, ...)
{
va_list ap; /* varargs list traverser */
int max, /* size of array to be declared */
*q; /* pointer to dimension list */
char **r, /* pointer to beginning of the array of the
* pointers for a dimension */
**s1, *t, *tree; /* base pointer to beginning of first array */
int i, j; /* loop counters */
int *d1; /* dimension list */
va_start(ap,d);
d1 = (int *) mget_spc(d,sizeof(int));
for(i=0;i<d;i++)
d1[i] = va_arg(ap,int);
r = &tree;
q = d1; /* first dimension */
max = 1;
for (i = 0; i < d - 1; i++, q++) { /* for each of the dimensions
* but the last */
max *= (*q);
r[0]=(char *)mget_spc(max,sizeof(char **));
r = (char **) r[0]; /* step through to beginning of next
* dimension array */
}
max *= s * (*q); /* grab actual array memory */
r[0] = (char *)mget_spc(max,sizeof(char));
/*
* r is now set to point to the beginning of each array so that we can
* use it to scan down each array rather than having to go across and
* then down
*/
r = (char **) tree; /* back to the beginning of list of arrays */
q = d1; /* back to the first dimension */
max = 1;
for (i = 0; i < d - 2; i++, q++) { /* we deal with the last
* array of pointers later on */
max *= (*q); /* number of elements in this dimension */
for (j=1, s1=r+1, t=r[0]; j<max; j++) { /* scans down array for
* first and subsequent
* elements */
/* modify each of the pointers so that it points to
* the correct position (sub-array) of the next
* dimension array. s1 is the current position in the
* current array. t is the current position in the
* next array. t is incremented before s1 is, but it
* starts off one behind. *(q+1) is the dimension of
* the next array. */
*s1 = (t += sizeof (char **) * *(q + 1));
s1++;
}
r = (char **) r[0]; /* step through to begining of next
* dimension array */
}
max *= (*q); /* max is total number of elements in the
* last pointer array */
/* same as previous loop, but different size factor */
for (j = 1, s1 = r + 1, t = r[0]; j < max; j++)
*s1++ = (t += s * *(q + 1));
va_end(ap);
free((void *)d1);
return((void *)tree); /* return base pointer */
}
/*
* multifree releases all memory that we have already declared analogous to
* free() when using malloc()
*/
void multifree(void *r,int d)
{
void **p;
void *next;
int i;
for (p = (void **)r, i = 0; i < d; p = (void **) next,i++)
if (p != NULL) {
next = *p;
free((void *)p);
}
}
#endif
|
the_stack_data/31386875.c | #include<stdio.h>
#include<ctype.h>
#define MAX 100
float st[MAX];
int top=-1;
void push(float st[],float val);
float pop(float st[]);
float evaluate(char exp[]);
void main()
{
char exp[100];
float val;
printf("Enter Postfix Expression: ");
scanf("%s",exp);
val=evaluate(exp);
printf("Evaluation Of Postfix Expression: %.2f",val);
}
void push(float st[],float val)
{
if(top==MAX-1)
{
printf("\nStack Overflow");
}
else
{
top++;
st[top]=val;
}
}
float pop(float st[])
{
float val=-1;
if(top==-1)
{
printf("\nStack Underflow");
}
else
{
val=st[top];
top--;
}
return val;
}
float evaluate(char exp[])
{
int i=0;
float op1,op2,value;
while(exp[i]!='\0')
{
if(isdigit(exp[i]))
{
push(st,(float)(exp[i]-'0'));
}
else
{
op2=pop(st);
op1=pop(st);
switch(exp[i])
{
case '+':
value=op1+op2;
break;
case '-':
value=op1-op2;
break;
case '*':
value=op1*op2;
break;
case '/':
value=op1/op2;
break;
case '%':
value=(int)op1%(int)op2;
break;
}
push(st,value);
}
i++;
}
return (pop(st));
}
|
the_stack_data/111078382.c | /* DataToC output of file <object_empty_image_vert_glsl> */
extern int datatoc_object_empty_image_vert_glsl_size;
extern char datatoc_object_empty_image_vert_glsl[];
int datatoc_object_empty_image_vert_glsl_size = 769;
char datatoc_object_empty_image_vert_glsl[] = {
117,110,105,102,111,114,109, 32,109, 97,116, 52, 32, 77,111,100,101,108, 86,105,101,119, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 59, 13, 10,117,110,105,102,111,114,109, 32,109, 97,116, 52, 32, 77,111,100,101,108, 77, 97,116,114,105,120, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32, 97,115,112,101, 99,116, 88, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32, 97,115,112,101, 99,116, 89, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32,115,105,122,101, 59, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 50, 32,111,102,102,115,101,116, 59, 13, 10, 35,105,102,100,101,102, 32, 85, 83, 69, 95, 87, 73, 82, 69, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 51, 32, 99,111,108,111,114, 59, 13, 10, 35,101,108,115,101, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 52, 32,111, 98,106,101, 99,116, 67,111,108,111,114, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10,105,110, 32,118,101, 99, 50, 32,116,101,120, 67,111,111,114,100, 59, 13, 10,105,110, 32,118,101, 99, 50, 32,112,111,115, 59, 13, 10, 13, 10,102,108, 97,116, 32,111,117,116, 32,118,101, 99, 52, 32,102,105,110, 97,108, 67,111,108,111,114, 59, 13, 10, 13, 10, 35,105,102,110,100,101,102, 32, 85, 83, 69, 95, 87, 73, 82, 69, 13, 10,111,117,116, 32,118,101, 99, 50, 32,116,101,120, 67,111,111,114,100, 95,105,110,116,101,114,112, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10,118,111,105,100, 32,109, 97,105,110, 40, 41, 13, 10,123, 13, 10, 9,118,101, 99, 52, 32,112,111,115, 95, 52,100, 32, 61, 32,118,101, 99, 52, 40, 40,112,111,115, 32, 43, 32,111,102,102,115,101,116, 41, 32, 42, 32, 40,115,105,122,101, 32, 42, 32,118,101, 99, 50, 40, 97,115,112,101, 99,116, 88, 44, 32, 97,115,112,101, 99,116, 89, 41, 41, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 13, 10, 9,103,108, 95, 80,111,115,105,116,105,111,110, 32, 61, 32, 77,111,100,101,108, 86,105,101,119, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 32, 42, 32,112,111,115, 95, 52,100, 59, 13, 10, 35,105,102,100,101,102, 32, 85, 83, 69, 95, 87, 73, 82, 69, 13, 10, 9,103,108, 95, 80,111,115,105,116,105,111,110, 46,122, 32, 45, 61, 32, 49,101, 45, 53, 59, 13, 10, 9,102,105,110, 97,108, 67,111,108,111,114, 32, 61, 32,118,101, 99, 52, 40, 99,111,108,111,114, 44, 32, 49, 46, 48, 41, 59, 13, 10, 35,101,108,115,101, 13, 10, 9,116,101,120, 67,111,111,114,100, 95,105,110,116,101,114,112, 32, 61, 32,116,101,120, 67,111,111,114,100, 59, 13, 10, 9,102,105,110, 97,108, 67,111,108,111,114, 32, 61, 32,111, 98,106,101, 99,116, 67,111,108,111,114, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 85, 83, 69, 95, 87, 79, 82, 76, 68, 95, 67, 76, 73, 80, 95, 80, 76, 65, 78, 69, 83, 13, 10, 9,119,111,114,108,100, 95, 99,108,105,112, 95,112,108, 97,110,101,115, 95, 99, 97,108, 99, 95, 99,108,105,112, 95,100,105,115,116, 97,110, 99,101, 40, 40, 77,111,100,101,108, 77, 97,116,114,105,120, 32, 42, 32,112,111,115, 95, 52,100, 41, 46,120,121,122, 41, 59, 13, 10, 35,101,110,100,105,102, 13, 10,125, 13, 10,0
};
|
the_stack_data/69403.c | /*
Desenvolver um algoritmo que leia a altura de 15 pessoas. Este programa deverá calcular e
mostrar:
a. A menor altura do grupo;
b. A maior altura do grupo;
*/
//BIBLIOTECAS USADAS:
#include <stdio.h>
//FUNÇÃO PRINCIPAL
int main()
{
//DEFININDO VARIAVEIS
float maiorAltura = 0, menorAltura = 50, altura = 0;
int i, op;
//DISPLAY
printf("VEJA QUAL E A MAIOR ALTURA ENTRE 15 PESSOAS\n");
//LAÇO
for (i = 1; i <= 15; i++)
{
printf("Digite a altura do %i aluno\n",i);
scanf("%f", &altura);
if(altura > maiorAltura)
{
maiorAltura = altura;
}
if(menorAltura > altura)
{
menorAltura = altura;
}
printf("Deseja continuar?\n1 - SIM\n2 - NÃO\n");
scanf("%i", &op);
if (op == 2)
{
i = 16;
}
}
printf("A maior Altura do grupo eh: %.2f\n", maiorAltura);
printf("A menor altura do grupo eh: %.2f\n", menorAltura);
system("pause");
return 0;
}
|
the_stack_data/24454.c | /*
@@@@ PROGRAM NAME: knkcch06e03.c
@@@@ FLAGS: -std=c99
@@@@ PROGRAM STATEMENT: What output does the following for
statement produce?
for(i=5,j=i-1;i>0,j>0;--i,j=i-1)
printf("%d ",i);
*/
#include<stdio.h>
//------------------------START OF MAIN()--------------------------------------
int main(void)
{
printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
int i,j;
for(i=5,j=i-1;i>0,j>0;--i,j=i-1)
printf("%d ",i);
printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
return 0;
}
//-------------------------END OF MAIN()---------------------------------------
//---------------------------------------------------------------------------
/*
OUTPUT:
knkcch06e03.c:16:17: warning: relational comparison result unused [-Wunused-comparison]
for(i=5,j=i-1;i>0,j>0;--i,j=i-1)
~^~
1 warning generated.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 4 3 2
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
//--------------------------------------------------------------------------- |
the_stack_data/959886.c | // SPDX-License-Identifier: GPL-2.0
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 12345
#define RUNTIME 10
static struct {
unsigned int timeout;
unsigned int port;
} opts = {
.timeout = RUNTIME,
.port = PORT,
};
static void handler(int sig)
{
_exit(sig == SIGALRM ? 0 : 1);
}
static void set_timeout(void)
{
struct sigaction action = {
.sa_handler = handler,
};
sigaction(SIGALRM, &action, NULL);
alarm(opts.timeout);
}
static void do_connect(const struct sockaddr_in *dst)
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s >= 0)
fcntl(s, F_SETFL, O_NONBLOCK);
connect(s, (struct sockaddr *)dst, sizeof(*dst));
close(s);
}
static void do_accept(const struct sockaddr_in *src)
{
int c, one = 1, s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s < 0)
return;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
bind(s, (struct sockaddr *)src, sizeof(*src));
listen(s, 16);
c = accept(s, NULL, NULL);
if (c >= 0)
close(c);
close(s);
}
static int accept_loop(void)
{
struct sockaddr_in src = {
.sin_family = AF_INET,
.sin_port = htons(opts.port),
};
inet_pton(AF_INET, "127.0.0.1", &src.sin_addr);
set_timeout();
for (;;)
do_accept(&src);
return 1;
}
static int connect_loop(void)
{
struct sockaddr_in dst = {
.sin_family = AF_INET,
.sin_port = htons(opts.port),
};
inet_pton(AF_INET, "127.0.0.1", &dst.sin_addr);
set_timeout();
for (;;)
do_connect(&dst);
return 1;
}
static void parse_opts(int argc, char **argv)
{
int c;
while ((c = getopt(argc, argv, "t:p:")) != -1) {
switch (c) {
case 't':
opts.timeout = atoi(optarg);
break;
case 'p':
opts.port = atoi(optarg);
break;
}
}
}
int main(int argc, char *argv[])
{
pid_t p;
parse_opts(argc, argv);
p = fork();
if (p < 0)
return 111;
if (p > 0)
return accept_loop();
return connect_loop();
}
|
the_stack_data/462734.c |
void node_process(float in_m, float refl, float in_p, float *out_p, float *out_m)
{
const float tmp = refl * (in_p - in_m);
*out_p = in_p + tmp;
*out_m = in_m + tmp;
}
|
the_stack_data/178265671.c | /*
* FreeRTOS V202112.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/**
* @brief Mem fault handler.
*/
void MemManage_Handler( void ) __attribute__ (( naked ));
/*-----------------------------------------------------------*/
void MemManage_Handler( void )
{
__asm volatile
(
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, handler_address_const \n"
" bx r1 \n"
" \n"
" .align 4 \n"
" handler_address_const: .word vHandleMemoryFault \n"
);
}
/*-----------------------------------------------------------*/
|
the_stack_data/26700839.c | /*! ----------------------------------------------------------------------------
* @file main.c
* @brief TX with auto sleep example code
*
* @attention
*
* Copyright 2015 (c) Decawave Ltd, Dublin, Ireland.
* Copyright 2019 (c) Frederic Mes, RTLOC.
* All rights reserved.
*
* @author Decawave
*/
#ifdef EX_01C_DEF
#include "deca_device_api.h"
#include "deca_regs.h"
#include "deca_spi.h"
#include "port.h"
/* Example application name and version to display on console. */
#define APP_NAME "TX AUTO SLP v1.3"
/* Default communication configuration. */
static dwt_config_t config = {
5, /* Channel number. */
DWT_PRF_64M, /* Pulse repetition frequency. */
DWT_PLEN_128, /* Preamble length. Used in TX only. */
DWT_PAC8, /* Preamble acquisition chunk size. Used in RX only. */
9, /* TX preamble code. Used in TX only. */
9, /* RX preamble code. Used in RX only. */
1, /* 0 to use standard SFD, 1 to use non-standard SFD. */
DWT_BR_6M8, /* Data rate. */
DWT_PHRMODE_EXT, /* PHY header mode. */
(129) /* SFD timeout (preamble length + 1 + SFD length - PAC size). Used in RX only. */
};
/* The frame sent in this example is an 802.15.4e standard blink. It is a 12-byte frame composed of the following fields:
* - byte 0: frame type (0xC5 for a blink).
* - byte 1: sequence number, incremented for each new frame.
* - byte 2 -> 9: device ID, see NOTE 1 below.
* - byte 10/11: frame check-sum, automatically set by DW1000. */
static uint8 tx_msg[] = {0xC5, 0, 'D', 'E', 'C', 'A', 'W', 'A', 'V', 'E', 0, 0};
/* Index to access to sequence number of the blink frame in the tx_msg array. */
#define BLINK_FRAME_SN_IDX 1
/* Inter-frame delay period, in milliseconds. */
#define TX_DELAY_MS 1000
/* Dummy buffer for DW1000 wake-up SPI read. See NOTE 2 below. */
#define DUMMY_BUFFER_LEN 600
static uint8 dummy_buffer[DUMMY_BUFFER_LEN];
/**
* Application entry point.
*/
int dw_main(void)
{
/* Display application name on console. */
printk(APP_NAME);
/* Configure DW1000 SPI */
openspi();
/* Issue a wake-up in case DW1000 is asleep.
* Since DW1000 is not woken by the reset line, we could get here with it asleep. Note that this may be true in other examples but we pay special
* attention here because this example is precisely about sleeping. */
dwt_spicswakeup(dummy_buffer, DUMMY_BUFFER_LEN);
/* Reset and initialise DW1000. See NOTE 3 below.
* For initialisation, DW1000 clocks must be temporarily set to crystal speed. After initialisation SPI rate can be increased for optimum
* performance. */
reset_DW1000(); /* Target specific drive of RSTn line into DW1000 low for a period. */
port_set_dw1000_slowrate();
if (dwt_initialise(DWT_LOADNONE) == DWT_ERROR)
{
printk("INIT FAILED");
while (1)
{ };
}
port_set_dw1000_fastrate();
/* Configure DW1000. See NOTE 4 below. */
dwt_configure(&config);
/* Configure DW1000 LEDs */
dwt_setleds(1);
/* Configure sleep and wake-up parameters. */
dwt_configuresleep(DWT_PRESRV_SLEEP | DWT_CONFIG, DWT_WAKE_CS | DWT_SLP_EN);
/* Configure DW1000 to automatically enter sleep mode after transmission of a frame. */
dwt_entersleepaftertx(1);
/* Loop forever sending frames periodically. */
while (1)
{
/* Write frame data to DW1000 and prepare transmission. See NOTE 5 below. */
dwt_writetxdata(sizeof(tx_msg), tx_msg, 0); /* Zero offset in TX buffer. */
dwt_writetxfctrl(sizeof(tx_msg), 0, 0); /* Zero offset in TX buffer, no ranging. */
/* Start transmission. */
dwt_starttx(DWT_START_TX_IMMEDIATE);
/* It is not possible to access DW1000 registers once it has sent the frame and gone to sleep, and therefore we do not try to poll for TX
* frame sent, but instead simply wait sufficient time for the DW1000 to wake up again before we loop back to send another frame.
* If interrupts are enabled, (e.g. if MTXFRS bit is set in the SYS_MASK register) then the TXFRS event will cause an active interrupt and
* prevent the DW1000 from sleeping. */
/* Execute a delay between transmissions. */
Sleep(TX_DELAY_MS);
/* Wake DW1000 up. See NOTE 2 below. */
dwt_spicswakeup(dummy_buffer, DUMMY_BUFFER_LEN);
/* Increment the blink frame sequence number (modulo 256). */
tx_msg[BLINK_FRAME_SN_IDX]++;
}
}
#endif
/*****************************************************************************************************************************************************
* NOTES:
*
* 1. The device ID is a hard coded constant in the blink to keep the example simple but for a real product every device should have a unique ID.
* For development purposes it is possible to generate a DW1000 unique ID by combining the Lot ID & Part Number values programmed into the
* DW1000 during its manufacture. However there is no guarantee this will not conflict with someone else�s implementation. We recommended that
* customers buy a block of addresses from the IEEE Registration Authority for their production items. See "EUI" in the DW1000 User Manual.
* 2. The chosen method for waking the DW1000 up here is by maintaining SPI chip select line low for at least 500 us. This means that we need a buffer
* to collect the data that DW1000 outputs during this dummy SPI transaction. The length of the transaction, and then the time for which the SPI
* chip select is held low, is determined by the buffer length given to dwt_spicswakeup() so this length must be chosen high enough so that the
* DW1000 has enough time to wake up.
* 3. In this example, LDE microcode is not loaded upon calling dwt_initialise(). This will prevent the IC from generating an RX timestamp. If
* time-stamping is required, DWT_LOADUCODE parameter should be used. See two-way ranging examples (e.g. examples 5a/5b).
* 4. In a real application, for optimum performance within regulatory limits, it may be necessary to set TX pulse bandwidth and TX power, (using
* the dwt_configuretxrf API call) to per device calibrated values saved in the target system or the DW1000 OTP memory.
* 5. dwt_writetxdata() takes the full size of tx_msg as a parameter but only copies (size - 2) bytes as the check-sum at the end of the frame is
* automatically appended by the DW1000. This means that our tx_msg could be two bytes shorter without losing any data (but the sizeof would not
* work anymore then as we would still have to indicate the full length of the frame to dwt_writetxdata()).
* 6. The user is referred to DecaRanging ARM application (distributed with EVK1000 product) for additional practical example of usage, and to the
* DW1000 API Guide for more details on the DW1000 driver functions.
****************************************************************************************************************************************************/
|
the_stack_data/45451202.c | /*
* aolstub.c --
*
* This file provides the stubs needed for the AOLserver, to load NSF.
* Please note that at least AOLserver 4.* or NaviServer 4.99.4 or newer
* are required. Might have to have to apply a small patch to the
* AOLserver as well (available from www.xotcl.org) in order to get it
* working.
*
* Copyright (C) 2006-2013 Zoran Vasiljevic (a)
* Copyright (C) 2006-2014 Gustaf Neumann (b)
*
* (a) Archiware Inc.
*
* (b) Vienna University of Economics and Business
* Institute of Information Systems and New Media
* A-1020, Welthandelsplatz 1
* Vienna, Austria
*
* This work is licensed under the MIT License https://www.opensource.org/licenses/MIT
*
* 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.
*
*/
#ifdef AOL_SERVER
#include "nsf.h"
#include <ns.h>
NS_EXPORT int Ns_ModuleVersion = 1;
#if NS_MAJOR_VERSION>=4
# define AOL4
#endif
/*
*----------------------------------------------------------------------------
*
* NsNsf_Init --
*
* Loads the package for the first time, i.e. in the startup thread.
*
* Results:
* Standard Tcl result
*
* Side effects:
* Package initialized. Tcl commands created.
*
*----------------------------------------------------------------------------
*/
static int
NsNsf_Init (Tcl_Interp *interp, void *context)
{
static int firsttime = 1;
int ret;
ret = Nsf_Init(interp);
if (firsttime != 0) {
if (ret != TCL_OK) {
Ns_Log(Warning, "can't load module %s: %s", (char *)context,
Tcl_GetStringResult(interp));
} else {
Ns_Log(Notice, "%s module version %s", (char*)context, NSF_PATCHLEVELL);
/*
* Import the Nsf namespace only for the shell after
* predefined is through
*/
Tcl_Import(interp, Tcl_GetGlobalNamespace(interp), "nsf::*", 0);
}
firsttime = 0;
}
return ret;
}
/*
*----------------------------------------------------------------------------
*
* NsNsf_Init1 --
*
* Loads the package in each thread-interpreter.
* This is needed since Nsf Class/Object commands are not copied
* from the startup thread to the connection (or any other) thread.
* during AOLserver initialization and/or thread creation times.
*
* Why ?
*
* Simply because these two commands declare a delete callback which is
* unsafe to call in any other thread but in the one which created them.
*
* To understand this, you may need to get yourself acquainted with the
* mechanics of the AOLserver, more precisely, with the way Tcl interps
* are initialized (dive into nsd/tclinit.c in AOLserver distro).
*
* So, we made sure (by patching the AOLserver code) that no commands with
* delete callbacks declared, are ever copied from the startup thread.
* Additionally, we also made sure that AOLserver properly invokes any
* AtCreate callbacks. So, instead of activating those callbacks *after*
* running the Tcl-initialization script (which is the standard behavior)
* we activate them *before*. So we may get a chance to configure the
* interpreter correctly for any commands within the init script.
*
* Proper Nsf usage would be to declare all resources (classes, objects)
* at server initialization time and let AOLserver machinery to copy them
* (or re-create them, better yet) in each new thread.
* Resources created within a thread are automatically garbage-collected
* on thread-exit time, so don't create any Nsf resources there.
* Create them in the startup thread and they will automatically be copied
* for you.
* Look in <serverroot>/modules/tcl/nsf for a simple example.
*
* Results:
* Standard Tcl result.
*
* Side effects:
* Tcl commands created.
*
*----------------------------------------------------------------------------
*/
static int
NsNsf_Init1 (Tcl_Interp *interp, void *notUsed)
{
int result;
#ifndef AOL4
result = Nsf_Init(interp);
#else
result = TCL_OK;
#endif
/*
* Import the Nsf namespace only for the shell after
* predefined is through
*/
Tcl_Import(interp, Tcl_GetGlobalNamespace(interp), "nsf::*", 1);
return result;
}
/*
*----------------------------------------------------------------------------
*
* Ns_ModuleInit --
*
* Called by the AOLserver when loading shared object file.
*
* Results:
* Standard AOLserver result
*
* Side effects:
* Many. Depends on the package.
*
*----------------------------------------------------------------------------
*/
int Ns_ModuleInit(char *hServer, char *hModule) nonnull(1) nonnull(2);
int
Ns_ModuleInit(char *hServer, char *hModule) {
int ret;
assert(hServer != NULL);
assert(hModule != NULL);
/*Ns_Log(Notice, "+++ ModuleInit", "INIT");*/
ret = Ns_TclInitInterps(hServer, NsNsf_Init, (void*)hModule);
if (ret == TCL_OK) {
/*
* See discussion for NsNsf_Init1 procedure.
* Note that you need to patch AOLserver for this to work!
* The patch basically forbids copying of C-level commands with
* declared delete callbacks. It also runs all AtCreate callbacks
* BEFORE AOLserver runs the Tcl script for initializing new interps.
* These callbacks are then responsible for setting up the stage
* for correct (Nsf) extension startup (including copying any
* Nsf resources (classes, objects) created in the startup thread.
*/
Ns_TclRegisterAtCreate((Ns_TclInterpInitProc *)NsNsf_Init1, NULL);
}
return ret == TCL_OK ? NS_OK : NS_ERROR;
}
#else
/* avoid empty translation unit */
typedef void empty;
#endif
/*
* Local Variables:
* mode: c
* c-basic-offset: 2
* fill-column: 78
* indent-tabs-mode: nil
* End:
*/
|
the_stack_data/182954268.c | //
// Copyright 2011-2015 Jeff Bush
//
// 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.
//
int memcmp(const void *_str1, const void *_str2, unsigned int len)
{
const char *str1 = _str1;
const char *str2 = _str2;
while (len--)
{
int diff = *str1++ - *str2++;
if (diff)
return diff;
}
return 0;
}
|
the_stack_data/6388085.c | /* { dg-do compile { target {{ i?86-*-* x86_64-*-* } && lp64 } } } */
/* { dg-options "-O2 -m64 -fdump-tree-ivopts" } */
#define TYPE char*
/* Testing that only one induction variable is selected after IVOPT on
the given target instead of 3. */
void foo (int i_width, TYPE dst, TYPE src1, TYPE src2)
{
int x;
for( x = 0; x < i_width; x++ )
{
dst[x] = ( src1[x] + src2[x] + 1 ) >> 1;
}
}
/* { dg-final { scan-tree-dump-times "ivtmp.\[0-9_\]* = PHI <" 1 "ivopts"} } */
|
the_stack_data/161081918.c | #include<stdlib.h>
#include<stdio.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
|
the_stack_data/132953790.c | #include <stdio.h>
/*
* 二维数组
* */
int main(){
int a[2][3] = {{2, 2, 3}, {3, 4, 5}};
int tmp = a[0][1];
printf("a[0][1] = %d\n", tmp);
return 0;
}
|
the_stack_data/59513779.c | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct point {
double x, y;
};
double drand() {
return ((double) rand() / (RAND_MAX));
}
struct point random_element(struct point *array, size_t n) {
return array[rand() % (int)n];
}
void chaos_game(struct point *in, size_t in_n, struct point *out,
size_t out_n) {
struct point cur_point = {drand(), drand()};
for (size_t i = 0; i < out_n; ++i) {
out[i] = cur_point;
struct point tmp = random_element(in, in_n);
cur_point.x = 0.5 * (cur_point.x + tmp.x);
cur_point.y = 0.5 * (cur_point.y + tmp.y);
}
}
int main() {
const size_t point_count = 10000;
struct point shape_points [3] = {{0.0,0.0}, {0.5,sqrt(0.75)}, {1.0,0.0}};
struct point out_points[point_count];
srand((unsigned int)time(NULL));
chaos_game(shape_points, 3, out_points, point_count);
FILE *fp = fopen("sierpinksi.dat", "w+");
for (size_t i = 0; i < point_count; ++i) {
fprintf(fp, "%f\t%f\n", out_points[i].x, out_points[i].y);
}
fclose(fp);
return 0;
}
|
the_stack_data/43886873.c | #include <assert.h>
int main() {
volatile unsigned long value = -1;
assert(__builtin_ctzl(value) == 0);
if (sizeof(unsigned long) >= 8) {
value = 0x10000000000LL;
assert(__builtin_ctzl(value) == 40);
value = 0x43211000000LL;
assert(__builtin_ctzl(value) == 24);
}
value = 0x43211f0;
assert(__builtin_ctzl(value) == 4);
return 0;
}
|
the_stack_data/179830959.c | /* Check the behavior of the bitwsie xor on int */
typedef enum { false, true } bool;
int main(void)
{
int b, i;
b = i ^ i;
return 0;
}
|
the_stack_data/115467.c | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <assert.h>
#include <stdlib.h>
long int __fdelt_chk(long int d)
{
if (d < 0 || d >= FD_SETSIZE)
{
assert("__fdelt_chk() panic" == NULL);
abort();
}
return d / NFDBITS;
}
|
the_stack_data/132321.c | /* Name: hw3a-17.c
* Description: Chinese Railroad System with Depth First Search, Breadth First Search ,
* Depth First Search with Origin to Destination
*
* Author: Kyunghwa Lim (11/15/2009)
*
* Modified by: Kyunghwa Lim (11/21/2009)
*
* Version: BETA
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/* NUMBER OF MAX VERTEX */
#define VERTEXNUM 1024
/* NUMBER OF CITY */
#define CITYNUM 25
/* CITY INFORMATION STRUCTURE */
typedef struct city
{
char name[32]; /* city's name */
float north; /* city's longitude */
float east; /* city's latitude */
} CITY;
/* NODE */
typedef struct node
{
int vertex;
struct node* next; /* point next node */
} NODE;
/* HEAD NODE IN GRAPH LIST STRUCTURE */
typedef struct headtype
{
int data;
struct node* first; /* point first node */
} HT;
/* GRAPH STRUCTURE */
typedef struct graph
{
HT adlist[VERTEXNUM]; /* array of headlist */
} GRAPH;
/* QUEUE FOR CITY IN BFS*/
typedef struct queue
{
int data[VERTEXNUM]; /* queue array */
int front; /* index of front */
int rear; /* index of rear */
} SQ;
/*
* NAME: getint()
* RECEIVE INT FUNCTION
* ARGUMENTS: char* str
* RETURNS: one int variable
*/
int getint(char* str)
{
/* RETURN VALUE */
int temp;
gets(str);
temp = atol(str); /* string to int */
return temp;
}
/*
* NAME: initqueue()
* INITIALIZE QUEUE FUNCTION
* ARGUMENTS: SQ* q
* RETURNS: 1 always
*/
int initqueue(SQ* q)
{
q->front = q->rear = 0; /* initialize queue */
return 1;
}
/*
* NAME:enqueue()
* ENQUEUE FUNCTION
* ARGUMENTS: QS* q, int n
* RETURNS: 1 always
*/
int enqueue(SQ* q, int n)
{
/* if rear+1 equal to front, means queue is full */
if ((q->rear + 1) % VERTEXNUM == q->front)
{
printf("queue full");
return 0;
}
else
{
/* insert one data to queue */
q->data[q->rear] = n;
q->rear = (q->rear + 1) % VERTEXNUM;
}
return 1;
}
/*
* NAME: dequeue()
* DEQUEUE FUNCTION
* ARGUMENTS: SQ* q
* RETURNS: index of city number,0 for empty
*/
int dequeue(SQ* q)
{
/* RETURN VALUE */
int n; /* index of city number */
/* if front equal to rear, means queue is empty */
if (q->front == q->rear)
{
printf("queue empty");
return 0;
}
else
{
/* delete one data from queue */
n = q->data[q->front];
q->front = (q->front + 1) % VERTEXNUM;
}
return n;
}
/*
* NAME: isempty()
* DETERMINE QUEUE IS EMPTY FUNCTION
* ARGUMENTS: SQ* q
* RETURNS: 1 for empty, 0 for have node
*/
int isempty(SQ* q)
{
/* if queue is empty,return 1 else return 0 */
return (q->front == q->rear);
}
/*
* NAME: depthfirstsearch()
* Depth First Search FUNCTION
* ARGUMENTS: GRAPH* g, int n, int visited[CITYNUM], CITY* city
* RETURNS: 1 always
*/
int depthfirstsearch(GRAPH* ga, int n, int visited[CITYNUM], CITY* city)
{
NODE* temp;
printf("[%s]->", (city + (ga->adlist[n].data))->name);
visited[n] = 1;
/* visit all linked cities */
for (temp = ga->adlist[n].first; temp != NULL; temp = temp->next)
{
/* if this city not visited ,compare it,else pass this city */
if (!visited[temp->vertex])
{
/* visit next city */
depthfirstsearch(ga, temp->vertex, visited, city);
}
}
return 1;
}
/*
* NAME: breadthfirstsearch()
* Breadth First Search FUNCTION
* ARGUMENTS: GRAPH* g, int n, int visited[CITYNUM], CITY* city
* RETURNS: 1 always
*/
int breadthfirstsearch(GRAPH* ga, int n, int visited[CITYNUM], CITY* city)
{
SQ q; /* create a queue */
NODE* temp;
/* initialize queue */
initqueue(&q);
printf("[%s]->", (city + (ga->adlist[n].data))->name);
visited[n] = 1;
/* enqueue city number which started */
enqueue(&q, n);
/* DO THIS UNTIL QUEUE IS EMPTY */
while (!isempty(&q))
{
/* delete last visited cities */
n = dequeue(&q);
temp = ga->adlist[n].first;
/* DO THIS UNTIL TEMP IS NULL */
while (temp != NULL)
{
/* if this city not visited ,compare it,else pass this city */
if (!visited[temp->vertex])
{
printf("[%s]->", (city + (ga->adlist[temp->vertex].data))->name);
visited[temp->vertex] = 1;
enqueue(&q, temp->vertex);
}
temp = temp->next;
}
}
return 1;
}
/*
* NAME: vector()
* CALCULATE VECTOR FUNCTION
* ARGUMENTS: CITY* city1, CITY* city2, CITY* temp
* RETURNS: one vector
*/
CITY* vector(CITY* city1, CITY* city2, CITY* temp)
{
/* two point's coordinate */
float x1, x2, y1, y2;
x1 = city1->east;
x2 = city2->east;
y1 = city1->north;
y2 = city2->north;
temp->east = x2 - x1;
temp->north = y2 - y1;
/* return a vector */
return temp;
}
/*
* NAME: angle()
* CALCULATE ANGLE FUNCTION
* ARGUMENTS: CITY* vector1, CITY* vector2
* RETURNS: return the value of cos(angle)
*/
float angle(CITY* vector1, CITY* vector2)
{
/* RETURN VALUE */
float result;
result = ((vector1->east) * (vector2->east) + (vector1->north)
* (vector2->north)) / (sqrt((vector1->east) * (vector1->east)
+ (vector1->north) * (vector1->north)) * sqrt((vector2->east)
* (vector2->east) + (vector2->north) * (vector2->north)));
return (result);
}
/*
* NAME: origintodestination()
* PROGRAM MAIN FUNCTION
* ARGUMENTS: GRAPH* g, int n1, int n2, int visited[CITYNUM],
CITY* city)
* RETURNS: -1 for arrive city, 0 for return previous city, 1 for go to next city
*/
int origintodestination(GRAPH* ga, int n1, int n2, int visited[CITYNUM],
CITY* city)
{
/* temp node */
NODE* p;
NODE* temp;
/* vector1 is from current city to next city */
CITY* vector1 = (CITY*) malloc(sizeof(CITY));
/* vector2 is from current city to destination city */
CITY* vector2 = (CITY*) malloc(sizeof(CITY));
int sign = 1; /* quit variable */
int vertex;
float big; /* if angle is small, cos value is big */
int end; /* end sign variable */
vector2 = vector(city + n1, city + n2, vector2);
p = ga->adlist[n1].first;
/* print current city */
printf("[%s]->", (city + (ga->adlist[n1].data))->name);
/* this city is visited */
visited[n1] = 1;
/* if arrive to destination city , return -1 to finish all OTD function */
if (n1 == n2)
{
return -1;
}
/* DO THIS UNTIL QUIT */
while (sign >= 0)
{
/* if visited from current city to all next city, finish this OTD function */
if (p == NULL)
{
return 0;
}
/* PREPARATION */
end = 0;
temp = ga->adlist[n1].first;
/* DO THIS UNTIL TEMP POINT NULL */
while (temp)
{
/* if this city not visited ,compare it,else pass this city */
if (!visited[temp->vertex])
{
vector1 = vector(city + n1, city + temp->vertex, vector1);
end++;
/* if there is only one city can go */
if (end == 1)
{
vertex = temp->vertex;
big = angle(vector1, vector2);
}
else
{
/* find largest angle */
if (angle(vector1, vector2) > big)
{
big = angle(vector1, vector2);
vertex = temp->vertex;
}
}
}
temp = temp->next;
}
/* if there is no city can visit ,return 0 */
if (end == 0)
{
return 0;
}
/* visit next city */
sign = origintodestination(ga, vertex, n2, visited, city);
/* if next city can't visit any other city, print current city */
if (sign == 0)
{
printf("[%s]->", (city + (ga->adlist[n1].data))->name);
}
/* if arrive destination city, return -1 */
if (sign == -1)
{
return -1;
}
p = p->next;
}
return 1;
}
/*
* NAME: creategraph()
* CREATE GRAPH FUNCTION
* ARGUMENTS: GRAPH* ga, int connect[CITYNUM][CITYNUM]
* RETURNS: 1 always
*/
int creategraph(GRAPH* ga, int connect[CITYNUM][CITYNUM])
{
int i, j;
NODE* temp;
/* PREPARATION */
for (i = 0; i < CITYNUM; i++)
{
ga->adlist[i].data = i;
ga->adlist[i].first = NULL;
}
/* put the information from connect array to graph */
for (i = 0; i < CITYNUM; i++)
{
for (j = CITYNUM - 1; j >= 0; j--)
{
/* this two cities had no connection */
if (connect[i][j] <= 0)
{
continue;
}
/* insert NODE to graph */
temp = (NODE*) malloc(sizeof(NODE));
temp->vertex = j;
temp->next = ga->adlist[i].first;
ga->adlist[i].first = temp;
}
}
return 1;
}
/*
* NAME: read()
* READ FILE FUNCTION
* ARGUMENTS: CITY* city, GRAPH* ga, int connect[CITYNUM][CITYNUM], char* argv
* RETURNS: 1 always
*/
int readfile(CITY* city, GRAPH* ga, int connect[CITYNUM][CITYNUM], char* argv)
{
FILE *fp, *fopen();
char temp[32];
int i, j;
float num[4]; /* to save four number, temp variable */
int w; /* distance between two cities */
/* open file and read it */
if (fp = fopen(argv, "r"))
{
/* read one part of city's information */
for (i = 0; i < CITYNUM; i++)
{
fscanf(fp, "%s %f°%f'N %f°%f'E", temp, &num[0], &num[1], &num[2],
&num[3]);
strcpy(city[i].name, temp);
city[i].north = num[0] + num[1] / 60;
city[i].east = num[2] + num[3] / 60;
}
/* read connection of two cities */
for (i = 0; i < CITYNUM; i++)
{
for (j = 0; j < CITYNUM; j++)
{
fscanf(fp, "%d", &w);
connect[i][j] = w;
}
}
}
fclose(fp);
return 1;
}
/*
* NAME: citylist()
* PRINT CITYLIST FUNCTION
* ARGUMENTS: CITY* city
* RETURNS: 1 always
*/
int citylist(CITY* city)
{
int i;
/* show city's name */
printf("City number:\n");
for (i = 0; i < CITYNUM; i++)
{
printf("%d:%10s\t\t", i, city[i].name);
/* change line every tree cities */
if (i % 3 == 2)
{
printf("\n");
}
}
printf("\n");
return 1;
}
/*
* NAME: menu()
* PRINT MENU FUNCTION
* ARGUMENTS:
* RETURNS: 1 always
*/
int menu(void)
{
/* Show menu */
printf("+++++++ MENU ++++++\n");
printf("1. Depth First Search\n");
printf("2. Breadth First Search\n");
printf("3. Depth First Search with Origin to Destination\n");
printf("4. Quit\n");
return 1;
}
/*
* NAME: kernel()
* PROGRAM KERNEL FUNCTION
* ARGUMENTS: GRAPH* ga, char* argv
* RETURNS: 1 always
*/
int kernel(GRAPH* ga, char* argv)
{
int visited[CITYNUM]; /* array of visit record, 1 for visited 0 for not visited */
CITY city[CITYNUM]; /* array of city */
int connect[CITYNUM][CITYNUM]; /* TABLE OF linked between two citys */
int i;
int n; /* number of choosed menu */
int q = 0; /* use for quit */
char str[32]; /* use for get string */
int start, end; /* index of start number and end number */
/* read data from file named argv
* save city's name to CITY array
* save connection to connect array
*/
readfile(city, ga, connect, argv);
/* use data from file to make a new graph */
creategraph(ga, connect);
/* DO THIS UNTIL QUIT */
while (!q)
{
/* SHOWS MAIN MENU */
menu();
/* INPUT NUMBER FOR CHOOSE MENU */
printf("Input:");
n = getint(str);
switch (n)
{
/* Depth First Search */
case 1:
/* show city list */
citylist(city);
/* Input start number of city */
printf("input number for start:");
start = getint(str);
/* IF Input Error Selection */
if (start >= CITYNUM || start < 0)
{
printf("Error Input!\n");
break;
}
/* PREPARATION */
for (i = 0; i < CITYNUM; i++)
{
visited[i] = 0;
}
printf("Depth First Search :\n");
printf("Begin->");
/* start Depth First Search */
depthfirstsearch(ga, start, visited, city);
printf("End\n");
break;
/* Breadth First Search */
case 2:
/* show city list */
citylist(city);
/* Input start number of city */
printf("input number for start:");
start = getint(str);
/* IF Input Error Selection */
if (start >= CITYNUM || start < 0)
{
printf("Error Input!\n");
break;
}
/* PREPARATION */
for (i = 0; i < CITYNUM; i++)
{
visited[i] = 0;
}
printf("Breadth First Search :\n");
printf("Begin->");
/* start Breadth First Search */
breadthfirstsearch(ga, start, visited, city);
printf("End\n");
break;
/* Depth First Search with Origin to Destination */
case 3:
/* show city list */
citylist(city);
/* Input start number of city */
printf("input number for start:");
start = getint(str);
/* IF Input Error Selection */
if (start >= CITYNUM || start < 0)
{
printf("Error Input!\n");
break;
}
/* PREPARATION */
for (i = 0; i < CITYNUM; i++)
{
visited[i] = 0;
}
/* show city list */
citylist(city);
/* Input end number of city */
printf("input number for end:");
end = getint(str);
/* IF Input Error Selection */
if (end >= CITYNUM || end < 0)
{
printf("Error Input!\n");
break;
}
printf("Depth First Search with Origin to Destination:\n");
printf("Begin->");
/* start Depth First Search with Origin to Destination */
origintodestination(ga, start, end, visited, city);
printf("End\n");
break;
/* exit program */
case 4:
q = 1;
break;
/* IF Input Error select */
default:
printf("Error Input!!\n");
break;
}
}
return 1;
}
/*
* NAME: main()
* PROGRAM MAIN FUNCTION
* ARGUMENTS: int argc, char* argv[]
* RETURNS: 1 for found file, 0 for no file
*/
int main(int argc, char *argv[])
{
/* CREATE A GRAPH */
GRAPH ga;
/* IF NO FILE */
if (argv[1] == NULL)
{
printf("No file\n");
printf("EX: ./hw3-17 chcities-location.txt\n");
return 0;
}
/* START KERNEL FUNCTION */
kernel(&ga, argv[1]);
return 1;
}
|
the_stack_data/198579791.c | //
// Created by LCX on 2020/7/14.
//
#include <stdio.h>
#include <string.h>
int firstUniqChar(char * s){
int count = 0;
const char* pSrc = s;
if(pSrc == NULL)
{
count = -1;
return count;
}
while (*pSrc++)
{
count++;
}
//int count = strlen(s);
//printf("count:%d\n",count);
printf("count1:%d\n",count);
//int count = strlen(s);
int flag[26] = {0};
for (int i = 0; i < count; ++i) {
int index = s[i] - 'a';
flag[index]++;
}
for (int j = 0; j < count; ++j) {
int index = s[j] - 'a';
if(flag[index] == 1)
return j;
}
return -1;
}
int main(void)
{
char *s= "leetcode";
printf("%d\n", firstUniqChar(s));
}
|
the_stack_data/713319.c | /**************************************************************************/
/***************************************************************************
aahzd.c - a 'Demo Daemon' by Andrei Borovsky <[email protected]>
Based on the 'Hello World' public domain demon written by David Gillies <[email protected]> Sep 2003
and inspired by Robert L. Asprin greate funny books
This code is placed in the public domain. Unrestricted use or modification
of this code is permitted without attribution to the author.
***************************************************************************/
/* Note by A.B.: all the things referring to daemon name are renamed to aahz
in the name of the Asprin's daemon hero.
/**************************************************************************/
#ifdef __GNUC__
#define _GNU_SOURCE /* for strsignal() */
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <syslog.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
/*************************************************************************/
/* global variables and constants */
volatile sig_atomic_t gGracefulShutdown=0;
volatile sig_atomic_t gCaughtHupSignal=0;
int gLockFileDesc=-1;
int gMasterSocket=-1;
/* the 'well-known' port on which our server will be listening */
const int gaahzdPort=30333;
/* the path to our lock file */
/* Note by A.B: there was a slight bug here
in the original version, sunce ths variable was not actually used */
const char *const gLockFilePath = "/var/run/aahzd.pid";
/*************************************************************************/
/* prototypes */
int BecomeDaemonProcess(const char *const lockFileName,
const char *const logPrefix,
const int logLevel,
int *const lockFileDesc,
int *const thisPID);
int ConfigureSignalHandlers(void);
int BindPassiveSocket(const int portNum,
int *const boundSocket);
int AcceptConnections(const int master);
int HandleConnection(const int slave);
int WriteToSocket(const int sock,const char *const buffer,
const size_t buflen);
int ReadLine(const int sock,char *const buffer,const size_t buflen,
size_t *const bytesRead);
void FatalSigHandler(int sig);
void TermHandler(int sig);
void HupHandler(int sig);
void Usr1Handler(int sig);
void TidyUp(void);
/*************************************************************************/
int main(int argc,char *argv[])
{
int result;
pid_t daemonPID;
/**************************************************************/
/* Note by A.B.: Here is some code added to manage daemon */
/* via it's own executable. */
/**************************************************************/
if (argc > 1)
{
int fd, len;
pid_t pid;
char pid_buf[16];
if ((fd = open(gLockFilePath, O_RDONLY)) < 0)
{
perror("Lock file not found. May be the server is not running?");
exit(fd);
}
len = read(fd, pid_buf, 16);
pid_buf[len] = 0;
pid = atoi(pid_buf);
if(!strcmp(argv[1], "stop"))
{
kill(pid, SIGUSR1);
exit(EXIT_SUCCESS);
}
if(!strcmp(argv[1], "restart"))
{
kill(pid, SIGHUP);
exit(EXIT_SUCCESS);
}
printf ("usage %s [stop|restart]\n", argv[0]);
exit (EXIT_FAILURE);
}
/*************************************************************/
/* perhaps at this stage you would read a configuration file */
/*************************************************************/
/* the first task is to put ourself into the background (i.e
become a daemon. */
if((result=BecomeDaemonProcess(gLockFilePath,"aahzd",
LOG_DEBUG,&gLockFileDesc,&daemonPID))<0)
{
perror("Failed to become daemon process");
exit(result);
}
/* set up signal processing */
if((result=ConfigureSignalHandlers())<0)
{
syslog(LOG_LOCAL0|LOG_INFO,"ConfigureSignalHandlers failed, errno=%d",errno);
unlink(gLockFilePath);
exit(result);
}
/* now we must create a socket and bind it to a port */
if((result=BindPassiveSocket(gaahzdPort,&gMasterSocket))<0)
{
syslog(LOG_LOCAL0|LOG_INFO,"BindPassiveSocket failed, errno=%d",errno);
unlink(gLockFilePath);
exit(result);
}
/* now enter an infinite loop handling connections */
do
{
if(AcceptConnections(gMasterSocket)<0)
{
syslog(LOG_LOCAL0|LOG_INFO,"AcceptConnections failed, errno=%d",errno);
unlink(gLockFilePath);
exit(result);
}
/* the next conditional will be true if we caught signal SIGUSR1 */
if((gGracefulShutdown==1)&&(gCaughtHupSignal==0))
break;
/* if we caught SIGHUP, then start handling connections again */
gGracefulShutdown=gCaughtHupSignal=0;
}while(1);
TidyUp(); /* close the socket and kill the lock file */
return 0;
}
/**************************************************************************/
/***************************************************************************
BecomeDaemonProcess
Fork the process into the background, make a lock file, and open the
system log.
Inputs:
lockFileName I the path to the lock file
logPrefix I the string that will appear at the
start of all log messages
logLevel I the logging level for this process
lockFileDesc O the file descriptor of the lock file
thisPID O the PID of this process after fork()
has placed it in the background
Returns:
status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int BecomeDaemonProcess(const char *const lockFileName,
const char *const logPrefix,
const int logLevel,
int *const lockFileDesc,
pid_t *const thisPID)
{
int curPID,stdioFD,lockResult,killResult,lockFD,i,
numFiles;
char pidBuf[17],*lfs,pidStr[7];
FILE *lfp;
unsigned long lockPID;
struct flock exclusiveLock;
/* set our current working directory to root to avoid tying up
any directories. In a real server, we might later change to
another directory and call chroot() for security purposes
(especially if we are writing something that serves files */
chdir("/");
/* try to grab the lock file */
lockFD=open(lockFileName,O_RDWR|O_CREAT|O_EXCL,0644);
if(lockFD==-1)
{
/* Perhaps the lock file already exists. Try to open it */
lfp=fopen(lockFileName,"r");
if(lfp==0) /* Game over. Bail out */
{
perror("Can't get lockfile");
return -1;
}
/* We opened the lockfile. Our lockfiles store the daemon PID in them.
Find out what that PID is */
lfs=fgets(pidBuf,16,lfp);
if(lfs!=0)
{
if(pidBuf[strlen(pidBuf)-1]=='\n') /* strip linefeed */
pidBuf[strlen(pidBuf)-1]=0;
lockPID=strtoul(pidBuf,(char**)0,10);
/* see if that process is running. Signal 0 in kill(2) doesn't
send a signal, but still performs error checking */
killResult=kill(lockPID,0);
if(killResult==0)
{
printf("\n\nERROR\n\nA lock file %s has been detected. It appears it is owned\nby the (active) process with PID %ld.\n\n",lockFileName,lockPID);
}
else
{
if(errno==ESRCH) /* non-existent process */
{
printf("\n\nERROR\n\nA lock file %s has been detected. It appears it is owned\nby the process with PID %ld, which is now defunct. Delete the lock file\nand try again.\n\n",lockFileName,lockPID);
}
else
{
perror("Could not acquire exclusive lock on lock file");
}
}
}
else
perror("Could not read lock file");
fclose(lfp);
return -1;
}
/* we have got this far so we have acquired access to the lock file.
Set a lock on it */
exclusiveLock.l_type=F_WRLCK; /* exclusive write lock */
exclusiveLock.l_whence=SEEK_SET; /* use start and len */
exclusiveLock.l_len=exclusiveLock.l_start=0; /* whole file */
exclusiveLock.l_pid=0; /* don't care about this */
lockResult=fcntl(lockFD,F_SETLK,&exclusiveLock);
if(lockResult<0) /* can't get a lock */
{
close(lockFD);
perror("Can't get lockfile");
return -1;
}
/* now we move ourselves into the background and become a daemon.
Remember that fork() inherits open file descriptors among others so
our lock file is still valid */
curPID=fork();
switch(curPID)
{
case 0: /* we are the child process */
break;
case -1: /* error - bail out (fork failing is very bad) */
fprintf(stderr,"Error: initial fork failed: %s\n",
strerror(errno));
return -1;
break;
default: /* we are the parent, so exit */
exit(0);
break;
}
/* make the process a session and process group leader. This simplifies
job control if we are spawning child servers, and starts work on
detaching us from a controlling TTY */
if(setsid()<0)
return -1;
/* Note by A.B.: we skipped another fork here */
/* log PID to lock file */
/* truncate just in case file already existed */
if(ftruncate(lockFD,0)<0)
return -1;
/* store our PID. Then we can kill the daemon with
kill `cat <lockfile>` where <lockfile> is the path to our
lockfile */
sprintf(pidStr,"%d\n",(int)getpid());
write(lockFD,pidStr,strlen(pidStr));
*lockFileDesc=lockFD; /* return lock file descriptor to caller */
/* close open file descriptors */
/* Note by A.B.: sysconf(_SC_OPEN_MAX) does work under Linux.
No need in ad hoc guessing */
numFiles = sysconf(_SC_OPEN_MAX); /* how many file descriptors? */
for(i=numFiles-1;i>=0;--i) /* close all open files except lock */
{
if(i!=lockFD) /* don't close the lock file! */
close(i);
}
/* stdin/out/err to /dev/null */
umask(0); /* set this to whatever is appropriate for you */
stdioFD=open("/dev/null",O_RDWR); /* fd 0 = stdin */
dup(stdioFD); /* fd 1 = stdout */
dup(stdioFD); /* fd 2 = stderr */
/* open the system log - here we are using the LOCAL0 facility */
openlog(logPrefix,LOG_PID|LOG_CONS|LOG_NDELAY|LOG_NOWAIT,LOG_LOCAL0);
(void)setlogmask(LOG_UPTO(logLevel)); /* set logging level */
/* put server into its own process group. If this process now spawns
child processes, a signal sent to the parent will be propagated
to the children */
setpgrp();
return 0;
}
/**************************************************************************/
/***************************************************************************
ConfigureSignalHandlers
Set up the behaviour of the various signal handlers for this process.
Signals are divided into three groups: those we can ignore; those that
cause a fatal error but in which we are not particularly interested and
those that are used to control the server daemon. We don't bother with
the new real-time signals under Linux since these are blocked by default
anyway.
Returns: none
***************************************************************************/
/**************************************************************************/
int ConfigureSignalHandlers(void)
{
struct sigaction sighupSA,sigusr1SA,sigtermSA;
/* ignore several signals because they do not concern us. In a
production server, SIGPIPE would have to be handled as this
is raised when attempting to write to a socket that has
been closed or has gone away (for example if the client has
crashed). SIGURG is used to handle out-of-band data. SIGIO
is used to handle asynchronous I/O. SIGCHLD is very important
if the server has forked any child processes. */
signal(SIGUSR2, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGALRM, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGURG, SIG_IGN);
signal(SIGXCPU, SIG_IGN);
signal(SIGXFSZ, SIG_IGN);
signal(SIGVTALRM, SIG_IGN);
signal(SIGPROF, SIG_IGN);
signal(SIGIO, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
/* these signals mainly indicate fault conditions and should be logged.
Note we catch SIGCONT, which is used for a type of job control that
is usually inapplicable to a daemon process. We don't do anyting to
SIGSTOP since this signal can't be caught or ignored. SIGEMT is not
supported under Linux as of kernel v2.4 */
signal(SIGQUIT, FatalSigHandler);
signal(SIGILL, FatalSigHandler);
signal(SIGTRAP, FatalSigHandler);
signal(SIGABRT, FatalSigHandler);
signal(SIGIOT, FatalSigHandler);
signal(SIGBUS, FatalSigHandler);
#ifdef SIGEMT /* this is not defined under Linux */
signal(SIGEMT,FatalSigHandler);
#endif
signal(SIGFPE, FatalSigHandler);
signal(SIGSEGV, FatalSigHandler);
signal(SIGSTKFLT, FatalSigHandler);
signal(SIGCONT, FatalSigHandler);
signal(SIGPWR, FatalSigHandler);
signal(SIGSYS, FatalSigHandler);
/* these handlers are important for control of the daemon process */
/* TERM - shut down immediately */
sigtermSA.sa_handler=TermHandler;
sigemptyset(&sigtermSA.sa_mask);
sigtermSA.sa_flags=0;
sigaction(SIGTERM,&sigtermSA,NULL);
/* USR1 - finish serving the current connection and then close down
(graceful shutdown) */
sigusr1SA.sa_handler=Usr1Handler;
sigemptyset(&sigusr1SA.sa_mask);
sigusr1SA.sa_flags=0;
sigaction(SIGUSR1,&sigusr1SA,NULL);
/* HUP - finish serving the current connection and then restart
connection handling. This could be used to force a re-read of
a configuration file for example */
sighupSA.sa_handler=HupHandler;
sigemptyset(&sighupSA.sa_mask);
sighupSA.sa_flags=0;
sigaction(SIGHUP,&sighupSA,NULL);
return 0;
}
/**************************************************************************/
/***************************************************************************
BindPassiveSocket
Create a socket, bind it to a port and then place it in passive
(listen) mode to handle client connections.
Inputs:
interface I the IP address that should be bound
to the socket. This is important for
multihomed hosts, which may want to
restrict themselves to listening on a
given interface. If this is not the case,
use the special constant INADDR_ANY to
listen on all interfaces.
Returns:
status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int BindPassiveSocket(const int portNum,
int *const boundSocket)
{
/* Note by A.B.: simplified this function code a bit */
struct sockaddr_in sin;
int newsock,optval;
size_t optlen;
/* clear the socket address structure */
memset(&sin.sin_zero, 0, 8);
/* set up the fields. Note htonX macros are important for
portability */
sin.sin_port=htons(portNum);
sin.sin_family=AF_INET; /* Usage: AF_XXX here, PF_XXX in socket() */
sin.sin_addr.s_addr=htonl(INADDR_ANY);
if((newsock=socket(PF_INET, SOCK_STREAM, 0))<0)
return -1;
/* The SO_REUSEADDR socket option allows the kernel to re-bind
local addresses without delay (for our purposes, it allows re-binding
while the previous socket is in TIME_WAIT status, which lasts for
two times the Maximum Segment Lifetime - anything from
30 seconds to two minutes). It should be used with care as in
general you don't want two processes sharing the same port. There are
also dangers if a client tries to re-connect to the same port a
previous server used within the 2*MSL window that TIME_WAIT provides.
It's handy for us so the server can be restarted without having to
wait for termination of the TIME_WAIT period. */
optval=1;
optlen=sizeof(int);
setsockopt(newsock,SOL_SOCKET,SO_REUSEADDR,&optval,optlen);
/* bind to the requested port */
if(bind(newsock,(struct sockaddr*)&sin,sizeof(struct sockaddr_in))<0)
return -1;
/* put the socket into passive mode so it is lisetning for connections */
if(listen(newsock,SOMAXCONN)<0)
return -1;
*boundSocket=newsock;
return 0;
}
/* Note on restartable system calls:
several of the following functions check the return value from 'slow'
system calls (i.e. calls that can block indefinitely in the kernel)
and continue operation if the return value is EINTR. This error is
given if a system call is interrupted by a signal. However, many systems
can automatically restart system calls. Automatic restart is enabled by
setting the SA_RESTART flag in the sa_flags field of the struct sigaction.
We do not do this as we want the loop on accept() in AcceptConnections() to
look at the gGracefulShutdown flag which is set on recept of SIGHUP and
SIGUSR1 and is used to control the server.
You should still check for return code EINTR even if you have set SA_RESTART
to be on the safe side. Note that this simple behaviour WILL NOT WORK for
the connect() system call on many systems (although Linux appears to be an
exception). On such systems, you will need to call poll() or select() if
connect() is interrupted.
*/
/**************************************************************************/
/***************************************************************************
AcceptConnections
Repeatedly handle connections, blocking on accept() and then
handing off the request to the HandleConnection function.
Inputs:
master I the master socket that has been
bound to a port and is listening
for connection attempts
Returns:
status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int AcceptConnections(const int master)
{
int proceed=1,slave,retval=0;
struct sockaddr_in client;
socklen_t clilen;
while((proceed==1)&&(gGracefulShutdown==0))
{
/* block in accept() waiting for a request */
clilen=sizeof(client);
slave=accept(master,(struct sockaddr *)&client,&clilen);
if(slave<0) /* accept() failed */
{
if(errno==EINTR)
continue;
syslog(LOG_LOCAL0|LOG_INFO,"accept() failed: %m\n");
proceed=0;
retval=-1;
}
else
{
retval=HandleConnection(slave); /* process connection */
if(retval)
proceed=0;
}
close(slave);
}
return retval;
}
/**************************************************************************/
/***************************************************************************
HandleConnection
Service connections from the client. In practice, this function
would probably be used as a 'switchboard' to dispatch control to
helper functions based on the exact content of the client request.
Here, we simply read a CRLF-terminated line (the server is intended
to be exercised for demo purposes via a telnet client) and echo it
back to the client.
Inputs:
sock I the socket descriptor for this
particular connection event
Returns:
status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int HandleConnection(const int slave)
{
char readbuf[1025];
size_t bytesRead;
const size_t buflen=1024;
int retval;
retval=ReadLine(slave,readbuf,buflen,&bytesRead);
if(retval==0)
WriteToSocket(slave,readbuf,bytesRead);
return retval;
}
/**************************************************************************/
/***************************************************************************
WriteToSocket
Write a buffer full of data to a socket. Keep writing until
all the data has been put into the socket.
sock I the socket to read from
buffer I the buffer into which the data
is to be deposited
buflen I the length of the buffer in bytes
Returns: status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int WriteToSocket(const int sock,const char *const buffer,
const size_t buflen)
{
size_t bytesWritten=0;
ssize_t writeResult;
int retval=0,done=0;
do
{
writeResult=send(sock,buffer+bytesWritten,buflen-bytesWritten,0);
if(writeResult==-1)
{
if(errno==EINTR)
writeResult=0;
else
{
retval=1;
done=1;
}
}
else
{
bytesWritten+=writeResult;
if(writeResult==0)
done=1;
}
}while(done==0);
return retval;
}
/**************************************************************************/
/***************************************************************************
ReadLine
Read a CRLF terminated line from a TCP socket. This is not
the most efficient of functions, as it reads a byte at a
time, but enhancements are beyond the scope of this example.
sock I the socket to read from
buffer O the buffer into which the data
is to be deposited
buflen I the length of the buffer in bytes
bytesRead O the amount of data read
Returns: status code indicating success - 0 = success
***************************************************************************/
/**************************************************************************/
int ReadLine(const int sock,char *const buffer,const size_t buflen,
size_t *const bytesRead)
{
int done=0,retval=0;
char c,lastC=0;
size_t bytesSoFar=0;
ssize_t readResult;
do
{
readResult=recv(sock,&c,1,0);
switch(readResult)
{
case -1:
if(errno!=EINTR)
{
retval=-1;
done=1;
}
break;
case 0:
retval=0;
done=1;
break;
case 1:
buffer[bytesSoFar]=c;
bytesSoFar+=readResult;
if(bytesSoFar>=buflen)
{
done=1;
retval=-1;
}
if((c=='\n')&&(lastC=='\r'))
done=1;
lastC=c;
break;
}
}while(!done);
buffer[bytesSoFar]=0;
*bytesRead=bytesSoFar;
return retval;
}
/**************************************************************************/
/***************************************************************************
FatalSigHandler
General catch-all signal handler to mop up signals that we aren't
especially interested in. It shouldn't be called (if it is it
probably indicates an error). It simply dumps a report of the
signal to the log and dies. Note the strsignal() function may not be
available on all platform/compiler combinations.
sig I the signal number
Returns: none
***************************************************************************/
/**************************************************************************/
void FatalSigHandler(int sig)
{
#ifdef _GNU_SOURCE
syslog(LOG_LOCAL0|LOG_INFO,"caught signal: %s - exiting",strsignal(sig));
#else
syslog(LOG_LOCAL0|LOG_INFO,"caught signal: %d - exiting",sig);
#endif
closelog();
TidyUp();
_exit(0);
}
/**************************************************************************/
/***************************************************************************
TermHandler
Handler for the SIGTERM signal. It cleans up the lock file and
closes the server's master socket, then immediately exits.
sig I the signal number (SIGTERM)
Returns: none
***************************************************************************/
/**************************************************************************/
void TermHandler(int sig)
{
TidyUp();
_exit(0);
}
/**************************************************************************/
/***************************************************************************
HupHandler
Handler for the SIGHUP signal. It sets the gGracefulShutdown and
gCaughtHupSignal flags. The latter is used to distinguish this from
catching SIGUSR1. Typically in real-world servers, SIGHUP is used to
tell the server that it should re-read its configuration file. Many
important daemons do this, including syslog and xinetd (under Linux).
sig I the signal number (SIGTERM)
Returns: none
***************************************************************************/
/**************************************************************************/
void HupHandler(int sig)
{
syslog(LOG_LOCAL0|LOG_INFO,"caught SIGHUP");
gGracefulShutdown=1;
gCaughtHupSignal=1;
/****************************************************************/
/* perhaps at this point you would re-read a configuration file */
/****************************************************************/
return;
}
/**************************************************************************/
/***************************************************************************
Usr1Handler
Handler for the SIGUSR1 signal. This sets the gGracefulShutdown flag,
which permits active connections to run to completion before shutdown.
It is therefore a more friendly way to shut down the server than
sending SIGTERM.
sig I the signal number (SIGTERM)
Returns: none
***************************************************************************/
/**************************************************************************/
void Usr1Handler(int sig)
{
syslog(LOG_LOCAL0|LOG_INFO,"caught SIGUSR1 - soft shutdown");
gGracefulShutdown=1;
return;
}
/**************************************************************************/
/***************************************************************************
TidyUp
Dispose of system resources. This function is not strictly necessary,
as UNIX processes clean up after themselves (heap memory is freed,
file descriptors are closed, etc.) but it is good practice to
explicitly release that which you have allocated.
Returns: none
***************************************************************************/
/**************************************************************************/
void TidyUp(void)
{
if(gLockFileDesc!=-1)
{
close(gLockFileDesc);
unlink(gLockFilePath);
gLockFileDesc=-1;
}
if(gMasterSocket!=-1)
{
close(gMasterSocket);
gMasterSocket=-1;
}
}
|
the_stack_data/150140032.c | // WARNING in tracepoint_probe_register_prio
// https://syzkaller.appspot.com/bug?id=503e450222336861c418884793b219a9303e51e1
// status:fixed
// autogenerated by syzkaller (http://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
static uintptr_t syz_open_dev(uintptr_t a0, uintptr_t a1, uintptr_t a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block",
(uint8_t)a1, (uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf));
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
static void test();
void loop()
{
while (1) {
test();
}
}
long r[56];
void test()
{
memset(r, -1, sizeof(r));
r[0] = syscall(__NR_mmap, 0x20000000ul, 0xfff000ul, 0x3ul, 0x32ul,
0xfffffffffffffffful, 0x0ul);
memcpy((void*)0x20fa6000, "\x2f\x64\x65\x76\x2f\x73\x67\x23\x00", 9);
r[2] = syz_open_dev(0x20fa6000ul, 0x0ul, 0x0ul);
*(uint32_t*)0x2084cf90 = (uint32_t)0x0;
*(uint16_t*)0x2084cf94 = (uint16_t)0x0;
*(uint8_t*)0x2084cf96 = (uint8_t)0x0;
*(uint8_t*)0x2084cf97 = (uint8_t)0x0;
*(uint8_t*)0x2084cf98 = (uint8_t)0x0;
*(uint8_t*)0x2084cf99 = (uint8_t)0x0;
*(uint8_t*)0x2084cf9a = (uint8_t)0x0;
*(uint8_t*)0x2084cf9b = (uint8_t)0x0;
*(uint8_t*)0x2084cf9c = (uint8_t)0x0;
*(uint8_t*)0x2084cf9d = (uint8_t)0x0;
*(uint8_t*)0x2084cf9e = (uint8_t)0x0;
*(uint8_t*)0x2084cf9f = (uint8_t)0x0;
*(uint64_t*)0x2084cfa0 = (uint64_t)0x0;
*(uint32_t*)0x2084cfa8 = (uint32_t)0x0;
*(uint16_t*)0x2084cfac = (uint16_t)0x0;
*(uint8_t*)0x2084cfae = (uint8_t)0x800000000000;
*(uint8_t*)0x2084cfaf = (uint8_t)0x0;
*(uint8_t*)0x2084cfb0 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb1 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb2 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb3 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb4 = (uint8_t)0xfffffffffffffffc;
*(uint8_t*)0x2084cfb5 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb6 = (uint8_t)0x0;
*(uint8_t*)0x2084cfb7 = (uint8_t)0x0;
*(uint64_t*)0x2084cfb8 = (uint64_t)0x4;
*(uint32_t*)0x2084cfc0 = (uint32_t)0x0;
*(uint16_t*)0x2084cfc4 = (uint16_t)0x3;
*(uint8_t*)0x2084cfc6 = (uint8_t)0x2;
*(uint8_t*)0x2084cfc7 = (uint8_t)0x8000;
*(uint8_t*)0x2084cfc8 = (uint8_t)0x0;
*(uint8_t*)0x2084cfc9 = (uint8_t)0x1;
*(uint8_t*)0x2084cfca = (uint8_t)0x0;
*(uint8_t*)0x2084cfcb = (uint8_t)0x0;
*(uint8_t*)0x2084cfcc = (uint8_t)0x0;
*(uint8_t*)0x2084cfcd = (uint8_t)0x0;
*(uint8_t*)0x2084cfce = (uint8_t)0x0;
*(uint8_t*)0x2084cfcf = (uint8_t)0x0;
*(uint64_t*)0x2084cfd0 = (uint64_t)0x0;
*(uint32_t*)0x2084cfd8 = (uint32_t)0x0;
*(uint32_t*)0x2084cfdc = (uint32_t)0x0;
*(uint32_t*)0x2084cfe0 = (uint32_t)0x0;
*(uint32_t*)0x2084cfe4 = (uint32_t)0x0;
*(uint32_t*)0x2084cfe8 = (uint32_t)0x0;
*(uint32_t*)0x2084cfec = (uint32_t)0x0;
*(uint32_t*)0x2084cff0 = (uint32_t)0x0;
*(uint32_t*)0x2084cff4 = (uint32_t)0x0;
*(uint32_t*)0x2084cff8 = (uint32_t)0x0;
*(uint32_t*)0x2084cffc = (uint32_t)0x0;
r[52] = syscall(__NR_ioctl, r[2], 0xc0481273ul, 0x2084cf90ul);
memcpy((void*)0x20000ff7, "\x2f\x64\x65\x76\x2f\x73\x67\x23\x00", 9);
r[54] = syz_open_dev(0x20000ff7ul, 0x0ul, 0x0ul);
r[55] =
syscall(__NR_ioctl, r[54], 0x4000000000001276ul, 0x2002d000ul);
}
int main()
{
int i;
for (i = 0; i < 8; i++) {
if (fork() == 0) {
loop();
return 0;
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/132952418.c | /*
Author : Shubham Jante
Github : https://github.com/shubhamjante
LinkedIn : https://www.linkedin.com/in/shubhamjante/
Blog: : https://cpythonian.wordpress.com/
*/
#include <stdio.h>
int main()
{
double a, b, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
// Calculating product
product = a * b;
// %.2lf displays number up to 2 decimal point
printf("Product = %.2lf", product);
return 0;
} |
the_stack_data/35686.c | #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
typedef struct part
{
int number;
char name[21];
int on_hand;
struct part *next, *pre;
} Part;
void f(struct part part)
{
}
typedef struct complex
{
double real, imaginary;
} Complex;
int main()
{
struct
{
int x, y;
} x;
struct
{
int x, y;
} y;
typedef enum suits
{
CLUBS,
DIAMONDS,
HEARTS,
SPADES
} Suit;
Part a, b;
struct part c, d;
c = a;
struct ccc
{
double real, imaginary;
} c1 = {0.0, 1.0}, c2 = {1.0, 0.0}, c3;
c1 = c2;
c3.real = c1.real + c2.real;
c3.imaginary = c1.imaginary + c2.imaginary;
// struct complex c1, c2, c3;
struct
{
double a;
union
{
char b[4];
double c;
int d;
} e;
char f[4];
} s;
union
{
double a;
union
{
char b[4];
double c;
int d;
} u;
char f[4];
} u;
struct
{
// double a;
int b;
union
{
struct
{
int x, y;
} aa;
struct
{
int xx;
} bb;
};
} ua;
printf("%lu %lu %lu\n", sizeof s, sizeof u, sizeof ua);
printf("%p %p %p\n", &s.a, &s.e, &s.f);
ua.bb.xx = 12;
struct pinball_machine
{
char name[40];
int year;
enum
{
EM,
SS
} type;
int players;
};
struct pinball_machine mmc;
mmc.type = SS;
enum
{
ENQ = 37,
ACK,
BEL,
LF = 37,
ETB,
ESC
};
printf("%d %d %d\n", BEL, ETB, ESC);
return 0;
}
struct complex make_complex(double real, double imaginary)
{
return (struct complex){real, imaginary};
}
struct complex add_complex(struct complex a, struct complex b)
{
return (struct complex){a.real + b.real, a.imaginary + b.imaginary};
}
Complex make_complex2(double real, double imaginary)
{
return (Complex){real, imaginary};
}
Complex add_complex3(Complex a, Complex b)
{
return (Complex){a.real + b.real, a.imaginary + b.imaginary};
}
struct date
{
int month, day, year;
};
int day_of_year(struct date d)
{
int month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (d.year % 4 == 0 && d.year % 100 != 0 || d.year % 400 == 0)
{
month[1] = 29;
}
int day = d.day;
for (int i = 0; i < d.month - 1; i++)
{
day += month[i];
}
return day;
}
int compare_dates(struct date d1, struct date d2)
{
if (d1.year - d2.year != 0)
{
return d1.year < d2.year ? -1 : 1;
}
if (d1.month - d2.month != 0)
{
return d1.month < d2.month ? -1 : 1;
}
if (d1.day - d2.day != 0)
{
return d1.day < d2.day ? -1 : 1;
}
return 0;
}
struct time
{
int hours, minutes, seconds;
};
struct time split_time(int total_seconds)
{
return (struct time){total_seconds / 3600, total_seconds % 3600 / 60, total_seconds % 60};
}
struct fraction
{
int numerator, denominator; // 分子 分母
};
int gcd(struct fraction f)
{
int temp = 0;
for (; f.denominator != 0;)
{
temp = f.numerator % f.denominator;
f.numerator = f.denominator;
f.denominator = temp;
}
return f.numerator;
}
struct fraction func_16_7_1(struct fraction f)
{
int g = gcd(f);
f.numerator /= g;
f.denominator /= g;
return f;
}
// 相加
struct fraction func_16_7_2(struct fraction f1, struct fraction f2)
{
struct fraction f;
f.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
f.denominator = f1.denominator * f2.denominator;
return func_16_7_1(f);
}
// 相减
struct fraction func_16_7_3(struct fraction f1, struct fraction f2)
{
struct fraction f;
f.numerator = f1.numerator * f2.denominator - f2.numerator * f1.denominator;
f.denominator = f1.denominator * f2.denominator;
return func_16_7_1(f);
}
// mul
struct fraction func_16_7_4(struct fraction f1, struct fraction f2)
{
struct fraction f;
f.numerator = f1.numerator * f2.numerator;
f.denominator = f1.denominator * f2.denominator;
return func_16_7_1(f);
}
// div
struct fraction func_16_7_5(struct fraction f1, struct fraction f2)
{
struct fraction f;
f.numerator = f1.numerator * f2.denominator;
f.denominator = f1.denominator * f2.numerator;
return func_16_7_1(f);
}
struct color
{
int red;
int green;
int blue;
};
void func_16_8()
{
const struct color MAGENTA = {255, 0, 255};
const struct color MAGENTA99 = {.red = 255, .blue = 255};
}
struct color func_16_9_1_make_color(int red, int green, int blue)
{
red = red < 0 ? 0 : red;
green = green < 0 ? 0 : green;
blue = blue < 0 ? 0 : blue;
red = red > 255 ? 255 : red;
green = green > 255 ? 255 : green;
blue = blue > 255 ? 255 : blue;
return (struct color){red, green, blue};
}
int func_16_9_2_getRed(struct color c)
{
return c.red;
}
bool func_16_9_3_equal_color(struct color color1, struct color color2)
{
return (bool)(color1.red == color2.red && color1.green == color2.green && color1.blue == color2.blue);
}
struct color func_16_9_4_brighter(struct color c)
{
if (c.red == 0 && c.green == 0 && c.blue == 0)
{
return (struct color){3, 3, 3};
}
c.red = c.red < 3 && c.red > 0 ? 3 : c.red;
c.green = c.green < 3 && c.green > 0 ? 3 : c.green;
c.blue = c.blue < 3 && c.blue > 0 ? 3 : c.blue;
c.red = (int)(c.red / 0.7);
c.green = (int)(c.green / 0.7);
c.blue = (int)(c.blue / 0.7);
c.red = c.red > 255 ? 255 : c.red;
c.green = c.green > 255 ? 255 : c.green;
c.blue = c.blue > 255 ? 255 : c.blue;
return c;
}
struct color func_16_9_5_darker(struct color c)
{
c.red = (int)(c.red * 0.7);
c.green = (int)(c.green * 0.7);
c.blue = (int)(c.blue * 0.7);
return c;
}
struct point
{
int x, y;
};
struct rectangele
{
struct point upper_left, lower_right;
};
int func_16_10_1_area(struct rectangele r)
{
return abs(r.lower_right.x - r.upper_left.x) * (r.lower_right.y - r.upper_left.y);
}
struct point func_16_10_2_middle(struct rectangele r)
{
return (struct point){(r.lower_right.x + r.upper_left.x) / 2, (r.lower_right.y + r.upper_left.y) / 2};
}
struct rectangele func_16_10_3_move(struct rectangele r, int x, int y)
{
r.lower_right.x += x;
r.lower_right.y += y;
r.upper_left.x += x;
r.upper_left.y += y;
return r;
}
bool func_16_10_4_include(struct rectangele r, struct point p)
{
return p.x <= r.lower_right.x && p.x >= r.upper_left.x && p.y <= r.upper_left.y && p.y >= r.lower_right.y;
} |
the_stack_data/1262883.c | #include <stdio.h>
#include <math.h>
#include <stdbool.h>
double sn, cn, dn;
double gammln(double xx);
double factln( int n){
double a[101];
if (n < 0) printf("%s\n","Negative factorial in routine factln");
if (n <= 1) return 0.0;
if (n <= 100)
return (a[n] != 0.0 ? a[n] : (a[n]=gammln(n+1.0)));
else return gammln(n+1.0);
}
double gammln(double xx){
int j;
double x,y,tmp,ser;
const double cof[6]={76.18009172947146,-86.50532032941677,
24.01409824083091,-1.231739572450155,0.1208650973866179e-2,
-0.5395239384953e-5};
y=x=xx;
tmp=x+5.5;
tmp -= (x+0.5)*log(tmp);
ser=1.000000000190015;
for (j=0;j<6;j++) ser += cof[j]/++y;
return -tmp+log(2.5066282746310005*ser/x);
} |
the_stack_data/140766484.c | /*
* Copyright (c) 2012-2017 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef OPENVX_USE_IX
#include <vx_internal.h>
#include <stdio.h>
#include <VX/vx_khr_nn.h>
#ifndef VX_IX_USE_IMPORT_AS_KERNEL
#define VX_IX_USE_IMPORT_AS_KERNEL (VX_ENUM_BASE(VX_ID_KHRONOS, VX_ENUM_IX_USE) + 0x3) /*!< \brief Graph exported as user kernel. */
#endif
#define DEBUGPRINTF(x,...)
//#define DEBUGPRINTF printf
/*!
* \file
* \brief The Export Object as Binary API.
* See vx_ix_format.txt for details of the export format
*/
/*
Export objects to binary (import is in a separate file vx_ix_import.c)
Some notes on operation not fully characterised by the specification:
numrefs == 0 is tolerated
duplicate references are tolerated and all but the first ignored.
conflicts in the 'uses' array values are tolerated and resolved in what I think is a sensible way.
No real attempt has been made to reduce the size (or speed) of the export - this is a pragmatic implementation
that seeks merely to satisfy the specification.
*IMPORTANT NOTE*
================
This implementation requires that the exporting and importing implementations have the same endianness.
*/
#define VX_IX_ID (0x1234C0DE) /* To identify an export and make sure endian matches etc. */
#define VX_IX_VERSION ((VX_VERSION << 8) + 1)
struct VXBinHeaderS { /* What should be at the start of the binary blob */
vx_uint32 vx_ix_id; /* Unique ID */
vx_uint32 version; /* Version of the export/import */
vx_uint64 length; /* Total length of the blob */
vx_uint32 numrefs; /* Number of references originally supplied */
vx_uint32 actual_numrefs; /* Actual number of references exported */
};
typedef struct VXBinHeaderS VXBinHeader;
#define USES_OFFSET (sizeof(VXBinHeader))/* Where the variable part of the blob starts */
#define MAX_CONCURRENT_EXPORTS (10) /* Arbitrary limit on number of exports allowed at any one time */
#define IMAGE_SUB_TYPE_NORMAL (0) /* Code to indicate 'normal' image */
#define IMAGE_SUB_TYPE_UNIFORM (1) /* Code to indicate uniform image */
#define IMAGE_SUB_TYPE_ROI (2) /* Code to indocate ROI image */
#define IMAGE_SUB_TYPE_CHANNEL (3) /* Code to indicate image created from channel */
#define IMAGE_SUB_TYPE_TENSOR (4) /* Code to indicate an image created from a tensor */
#define IMAGE_SUB_TYPE_HANDLE (5) /* Code to indicate an image created from handle */
#define OBJECT_UNPROCESSED (0) /* Object has not yet been processed */
#define OBJECT_UNSIZED (1) /* Object has not yet been sized */
#define OBJECT_NOT_EXPORTED (2) /* Object is sized but not exported */
#define OBJECT_EXPORTED (3) /* Object has already been exported */
#define OBJECT_DUPLICATE (4) /* Object is a duplicate supplied by user */
struct VXBinExportRefTableS {
vx_reference ref; /* The reference */
vx_enum status; /* Progress of export */
vx_enum use; /* Use for the reference */
};
typedef struct VXBinExportRefTableS VXBinExportRefTable;
struct VXBinExportS {
vx_context context; /* Context supplied by the application */
const vx_reference *refs; /* Refs list supplied by the application */
const vx_enum *uses; /* Uses supplied by the application */
VXBinExportRefTable *ref_table; /* Table for all references compiled by export function */
vx_size numrefs; /* Number of references given by the application */
vx_size actual_numrefs; /* Actual number of references to be exported */
vx_uint8 *export_buffer; /* Buffer allocated for export */
vx_uint8 *curptr; /* Pointer into buffer for next free location */
vx_size export_length; /* Size in bytes of the buffer */
};
typedef struct VXBinExportS VXBinExport;
static vx_uint8 *exports[MAX_CONCURRENT_EXPORTS] = {NULL};
static vx_uint32 num_exports = 0;
static int exportToProcess(VXBinExport *xport, vx_size n, int calcSize)
{
return (calcSize ? OBJECT_UNSIZED : OBJECT_NOT_EXPORTED) == xport->ref_table[n].status;
}
static int isFromHandle(vx_reference ref)
{
/* Return TRUE if the reference has been created from a handle (i.e., by the application)*/
return (VX_TYPE_IMAGE == ref->type && VX_MEMORY_TYPE_NONE != ((vx_image)ref)->memory_type);
}
static int isImmutable(vx_kernel k, vx_uint32 p)
{
int retval = 0;
/* return true if parameter p of kernel k is immutable
This is based upon the parameter to a node function being not an OpenVX object
*/
if (k->enumeration < VX_KERNEL_MAX_1_2 && k->enumeration >= VX_KERNEL_COLOR_CONVERT)
{
switch (k->enumeration)
{
case VX_KERNEL_NON_LINEAR_FILTER:
case VX_KERNEL_SCALAR_OPERATION:
if (0 == p)
retval = 1;
break;
case VX_KERNEL_CHANNEL_EXTRACT:
case VX_KERNEL_HOUGH_LINES_P:
case VX_KERNEL_TENSOR_CONVERT_DEPTH:
if (1 == p)
retval = 1;
break;
case VX_KERNEL_LBP:
if (1 == p || 2 == p)
retval = 0;
break;
case VX_KERNEL_SCALE_IMAGE:
case VX_KERNEL_ADD:
case VX_KERNEL_SUBTRACT:
case VX_KERNEL_CONVERTDEPTH:
case VX_KERNEL_WARP_AFFINE:
case VX_KERNEL_WARP_PERSPECTIVE:
case VX_KERNEL_FAST_CORNERS:
case VX_KERNEL_REMAP:
case VX_KERNEL_HALFSCALE_GAUSSIAN:
case VX_KERNEL_NON_MAX_SUPPRESSION:
case VX_KERNEL_MATCH_TEMPLATE:
case VX_KERNEL_TENSOR_ADD:
case VX_KERNEL_TENSOR_SUBTRACT:
if (2 == p)
retval = 1;
break;
case VX_KERNEL_CANNY_EDGE_DETECTOR:
case VX_KERNEL_TENSOR_TRANSPOSE:
if (2 == p || 3 == p)
retval = 1;
break;
case VX_KERNEL_TENSOR_MATRIX_MULTIPLY:
if (3 == p)
retval = 1;
break;
case VX_KERNEL_MULTIPLY:
case VX_KERNEL_HOG_FEATURES:
case VX_KERNEL_TENSOR_MULTIPLY:
if (3 == p || 4 == p)
retval = 1;
break;
case VX_KERNEL_HARRIS_CORNERS:
if (4 == p || 5 == p)
retval = 1;
break;
case VX_KERNEL_OPTICAL_FLOW_PYR_LK:
if (5 == p || 9 == p)
retval = 1;
break;
case VX_KERNEL_HOG_CELLS:
if (1 == p || 2 == p || 3 == p)
retval = 1;
break;
case VX_KERNEL_BILATERAL_FILTER:
if (1 == p || 2 == p || 3 == p)
retval = 1;
break;
default: ;
}
}
return retval;
}
static void malloc_export(VXBinExport *xport)
{
xport->export_buffer = NULL;
/* allocate memory for an export */
if (xport->export_length && num_exports < MAX_CONCURRENT_EXPORTS)
{
for (int i = 0; i < MAX_CONCURRENT_EXPORTS && NULL == xport->export_buffer; ++i)
if (NULL == exports[i])
{
xport->export_buffer = (vx_uint8 *)malloc(xport->export_length);
exports[i] = xport->export_buffer;
}
}
/* increment number of exports if we have been successful */
if (xport->export_buffer)
++num_exports;
}
static vx_size indexIn(const VXBinExportRefTable *ref_table, const vx_reference ref, const vx_size num)
{
/* Return the index of the reference in the table, or num if it is not there */
vx_size i;
for (i = 0; i < num && ref != ref_table[i].ref; ++i)
{
;
}
return i;
}
static vx_uint32 indexOf(const VXBinExport *xport, const vx_reference ref)
{
/* Return the first index of the reference in the table or (xport->actual_numrefs + ref->type) if it is not there.
Note that it's not an error if the reference is not found; it may be that an object is being exported without
its parent, for example a pyramid level or element of an object array, or that we are looking for the context.
We test for context specifically to make the search faster, as this could be a frequent case. The type of an
unfound reference (usually scope) is encoded for error-checking upon import.
We also return 0xffffffff if the reference was NULL; this is for optional parameter checking.
*/
vx_uint32 i = xport->actual_numrefs + VX_TYPE_CONTEXT;
if (ref) /* Check for NULL: this could be an optional parameter */
{
if (VX_TYPE_CONTEXT != ref->type)
{
for (i = 0; i < xport->actual_numrefs && ref != xport->ref_table[i].ref; ++i)
{
;
}
if (i == xport->actual_numrefs) /* not found; encode the type of the reference for future use on import */
i += ref->type;
}
}
else
{
i = 0xFFFFFFFF;
}
return i;
}
static vx_uint8 *addressOf(VXBinExport *xport, const vx_size n)
{
/* Return the address of the offset into the blob of a given reference by it's index. */
return xport->export_buffer + USES_OFFSET + xport->numrefs * sizeof(vx_uint32) + n * sizeof(vx_uint64);
}
static void calculateUses(VXBinExport *xport)
{
/* Calculate what the uses for each object should be. This is essentially patching up uses assigned
by putInTable...
*/
vx_size i;
for (i = xport->numrefs; i < xport->actual_numrefs; ++i)
{
switch (xport->ref_table[i].use)
{
case VX_IX_USE_APPLICATION_CREATE:
case VX_IX_USE_EXPORT_VALUES:
case VX_IX_USE_NO_EXPORT_VALUES:
case VX_IX_USE_IMPORT_AS_KERNEL:
break; /* Already assigned, do nothing */
case VX_OUTPUT: /* Part processed by putInTable, is a net output */
xport->ref_table[i].use = VX_IX_USE_NO_EXPORT_VALUES;
default: /* All other cases, assume we need to export values unless virtual */
xport->ref_table[i].use = xport->ref_table[i].ref->is_virtual ?
VX_IX_USE_NO_EXPORT_VALUES :
VX_IX_USE_EXPORT_VALUES;
break;
}
}
}
static vx_size putInTable(VXBinExportRefTable *ref_table, const vx_reference newref, vx_size actual_numrefs, vx_enum use)
{
/* If the reference newref is NULL or is already in the table, just return actual_numrefs, else put
it in the table and return actual_numrefs + 1. Note that NULL can occur for absent optional parameters
and is treated specially during output and so does not appear in the table since it can't have been
supplied in original list of references passed to the export function as they must pass getStatus(). */
if (newref)
{
vx_size index = indexIn(ref_table, newref, actual_numrefs);
if (index == actual_numrefs)
{
/* Must be a new reference, initialise the table entry */
ref_table[index].ref = newref;
ref_table[index].status = OBJECT_UNPROCESSED;
ref_table[index].use = vx_true_e == newref->is_virtual ? VX_IX_USE_NO_EXPORT_VALUES : use;
++actual_numrefs;
}
else
{
/* Adjust use if required. This allows for inheriting of APPLICATION_CREATE and
EXPORT_VALUES, as well as adjusting uses according to readers and writers. */
if (VX_INPUT == ref_table[index].use ||
VX_BIDIRECTIONAL == ref_table[index].use ||
VX_IX_USE_APPLICATION_CREATE == use ||
VX_IX_USE_EXPORT_VALUES == use)
{
ref_table[index].use = use;
}
}
if (OBJECT_UNPROCESSED == ref_table[index].status)
{ /* We make sure we are not processing something we have already processed,
otherwise we could get in a loop because of processing parents that have
children poitning to their parents...*/
ref_table[index].status = OBJECT_UNSIZED;
/* Now we have to expand compound objects and ROI images */
if (VX_TYPE_GRAPH == newref->type)
{
/* Need to enumerate all graph parameters, nodes and node parameters in a graph */
vx_uint32 ix; /* for enumerating graph parameters, nodes and delays*/
vx_graph g = (vx_graph)newref;
for (ix = 0; ix < g->numParams; ++ix)
{
/* Graph parameters - bugzilla 16313 */
vx_reference r = g->parameters[ix].node->parameters[g->parameters[ix].index];
actual_numrefs = putInTable(ref_table, r, actual_numrefs, VX_IX_USE_NO_EXPORT_VALUES);
}
for (ix = 0; ix < g->numNodes; ++ix)
{
vx_node n = g->nodes[ix];
vx_uint32 p; /* for enumerating node parameters */
/* We don't have to put in nodes are these are output as part of each graph */
/* Bugzilla 16337 - we need to add in the kernel object, however. */
/* Bugzilla 16207 - may have to export kernel as VX_IX_USE_EXPORT_VALUES rather than VX_IX_USE_APPLICATION_CREATE */
vx_enum kernel_use = VX_IX_USE_NO_EXPORT_VALUES;
if (VX_IX_USE_NO_EXPORT_VALUES != ref_table[index].use &&
n->kernel->user_kernel &&
VX_TYPE_GRAPH == n->kernel->base.scope->type)
{
kernel_use = VX_IX_USE_EXPORT_VALUES;
}
actual_numrefs = putInTable(ref_table, (vx_reference)n->kernel, actual_numrefs, kernel_use);
for (p = 0; p < n->kernel->signature.num_parameters; ++p)
{
/* Add in each parameter. Note that absent optional parameters (NULL) will not end
up in the table and have special treatment on output (and input). */
actual_numrefs = putInTable(ref_table, n->parameters[p], actual_numrefs, n->kernel->signature.directions[p]);
/* If a node is replicated, need to check replicated flags and put parent in the list as well */
if (n->is_replicated && n->replicated_flags[p])
{
actual_numrefs = putInTable(ref_table, n->parameters[p]->scope, actual_numrefs, n->kernel->signature.directions[p]);
}
}
}
/* Need to enumerate all delays that are registered with this graph */
for (ix = 0; ix < VX_INT_MAX_REF; ++ix)
{
actual_numrefs = putInTable(ref_table, (vx_reference)g->delays[ix], actual_numrefs, VX_IX_USE_NO_EXPORT_VALUES);
}
/* Now need to patch up uses; any objects read but not written become VX_IX_EXPORT_VALUES */
for (ix = 1; ix < actual_numrefs; ++ix)
{
if (VX_INPUT == ref_table[ix].use ||
VX_BIDIRECTIONAL == ref_table[ix].use)
{
ref_table[ix].use = VX_IX_USE_EXPORT_VALUES;
}
}
}
else if (VX_TYPE_KERNEL == newref->type && VX_IX_USE_EXPORT_VALUES == ref_table[index].use)
{
/* Bugzilla 16207 */
actual_numrefs = putInTable(ref_table, newref->scope, actual_numrefs, VX_IX_USE_EXPORT_VALUES);
if (VX_TYPE_GRAPH != newref->scope->type)
{
DEBUGPRINTF("Error in graph kernel export; scope of kernel is not a graph! Difference is %d\n", newref->scope->type - VX_TYPE_GRAPH);
}
else
{
DEBUGPRINTF("Requesting export of graph with %u parameters\n", ((vx_graph)(newref->scope))->numParams);
}
}
else if (VX_TYPE_DELAY == newref->type)
{
vx_delay delay = (vx_delay)newref;
vx_uint32 c;
for (c = 0; c < delay->count; ++c)
{
/* if parent use is APPLICATION_CREATE or EXPORT_VALUES sub-object inherits use */
actual_numrefs = putInTable(ref_table, delay->refs[c], actual_numrefs, ref_table[index].use);
}
}
else if (VX_TYPE_PYRAMID == newref->type && vx_false_e == newref->is_virtual)
{
vx_pyramid pyramid = (vx_pyramid)newref;
vx_uint32 c;
for (c = 0; c < pyramid->numLevels; ++c)
{
/* if parent use is APPLICATION_CREATE or EXPORT_VALUES sub-object inherits use */
actual_numrefs = putInTable(ref_table, (vx_reference)pyramid->levels[c], actual_numrefs, ref_table[index].use);
}
}
else if (VX_TYPE_OBJECT_ARRAY == newref->type)
{
vx_object_array objArray = (vx_object_array)newref;
vx_uint32 c;
for (c = 0; c < objArray->num_items; ++c)
{
/* if parent use is APPLICATION_CREATE or EXPORT_VALUES sub-object inherits use */
actual_numrefs = putInTable(ref_table, objArray->items[c], actual_numrefs, ref_table[index].use);
}
}
else if (VX_TYPE_IMAGE == newref->scope->type
|| VX_TYPE_TENSOR == newref->scope->type
)
{
/* Must be an ROI or image from channel, or a tensor from view
so put parent object in the table as well; use becomes the same as child */
actual_numrefs = putInTable(ref_table, newref->scope, actual_numrefs, ref_table[index].use);
}
/* Special case of an object array of images created from tensor. Here we
need to put both the object array and the tensor in the table */
else if (VX_TYPE_OBJECT_ARRAY == newref->scope->type &&
VX_TYPE_IMAGE == newref->type &&
((vx_image)newref)->parent &&
VX_TYPE_TENSOR == ((vx_image)newref)->parent->base.type)
{
actual_numrefs = putInTable(ref_table, newref->scope, actual_numrefs, ref_table[index].use);
actual_numrefs = putInTable(ref_table, (vx_reference)(((vx_image)newref)->parent), actual_numrefs, ref_table[index].use);
}
}
}
return actual_numrefs;
}
static vx_status exportBytes(VXBinExport *xport, const void *data, const vx_size length, int calcSize)
{
vx_status status = VX_SUCCESS;
if (calcSize)
{
xport->export_length += length;
}
else if (xport->export_length - (xport->curptr - xport->export_buffer) >= length)
{
memcpy(xport->curptr, data, length);
xport->curptr += length;
}
else
{
DEBUGPRINTF("Failure in export bytes\n");
status = VX_FAILURE;
}
return status;
}
#define EXPORT_FUNCTION(funcname, datatype) \
static vx_status funcname(VXBinExport *xport, const datatype data, int calcSize) \
{ \
return exportBytes(xport, &data, sizeof(data), calcSize); \
}
#define EXPORT_FUNCTION_PTR(funcname, datatype) \
static vx_status funcname(VXBinExport *xport, const datatype *data, int calcSize) \
{ \
return exportBytes(xport, data, sizeof(*data), calcSize); \
}
EXPORT_FUNCTION(exportVxUint64, vx_uint64)
/* EXPORT_FUNCTION(exportVxInt64, vx_int64) */
/* EXPORT_FUNCTION(exportVxFloat64, vx_float64) */
EXPORT_FUNCTION(exportVxUint32, vx_uint32)
EXPORT_FUNCTION(exportVxInt32, vx_int32)
EXPORT_FUNCTION(exportVxFloat32, vx_float32)
EXPORT_FUNCTION(exportVxEnum, vx_enum)
EXPORT_FUNCTION(exportVxDfImage, vx_df_image)
EXPORT_FUNCTION(exportVxUint16, vx_uint16)
EXPORT_FUNCTION(exportVxInt16, vx_int16)
EXPORT_FUNCTION(exportVxUint8, vx_uint8)
EXPORT_FUNCTION_PTR(exportVxBorderT, vx_border_t)
EXPORT_FUNCTION_PTR(exportVxCoordinates2dT, vx_coordinates2d_t)
static vx_status exportHeader(VXBinExport *xport, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_size i;
if (!calcSize && ((NULL == xport->export_buffer) || xport->actual_numrefs & 0xffffffff00000000U))
{
DEBUGPRINTF("No memory\n");
status = VX_ERROR_NO_MEMORY;
}
else
{
status |= exportVxUint32(xport, (vx_uint32)VX_IX_ID, calcSize);
status |= exportVxUint32(xport, (vx_uint32)VX_IX_VERSION, calcSize);
status |= exportVxUint64(xport, (vx_uint64)xport->export_length, calcSize);
status |= exportVxUint32(xport, (vx_uint32)xport->numrefs, calcSize);
status |= exportVxUint32(xport, (vx_uint32)xport->actual_numrefs, calcSize);
for (i = 0; i < xport->numrefs && VX_SUCCESS == status; ++i)
{
status = exportVxUint32(xport, (vx_uint32)xport->uses[i], calcSize);
}
if (calcSize)
{
xport->export_length += xport->actual_numrefs * sizeof(vx_uint64);
}
else if (xport->export_length - (xport->curptr - xport->export_buffer) >= xport->actual_numrefs * sizeof(vx_uint64))
{
xport->curptr += xport->actual_numrefs * sizeof(vx_uint64);
}
else
{
DEBUGPRINTF("Failed in export header\n");
status = VX_FAILURE;
}
}
return status;
}
static vx_status exportObjectHeader(VXBinExport *xport, vx_size n, int calcSize)
{
/* Set the index into the memory blob for entry ix to be the current pointer, and
then exports the common information (header) for an object */
vx_status status = VX_SUCCESS;
if (calcSize)
{
xport->export_length += /* Check below that what is exported matches */
sizeof(vx_enum) + /* type of this object */
sizeof(vx_enum) + /* use for this object */
VX_MAX_REFERENCE_NAME + /* name */
sizeof(vx_uint8) + /* virtual flag */
sizeof(vx_uint32); /* scope */
xport->ref_table[n].status = OBJECT_NOT_EXPORTED;
}
else
{
VXBinExportRefTable *rt = xport->ref_table + n;
vx_uint8 *p = xport->curptr;
xport->curptr = addressOf(xport, n);
status = exportVxUint64(xport, (vx_uint64)(p - xport->export_buffer), 0);
xport->curptr = p;
status |= exportVxEnum(xport, rt->ref->type, 0); /* Export type of this object */
status |= exportVxEnum(xport, rt->use, 0); /* Export usage of this object */
status |= exportBytes(xport, rt->ref->name, VX_MAX_REFERENCE_NAME, 0); /* Export name of this object */
status |= exportVxUint8(xport, (vx_uint8)(rt->ref->is_virtual ? 1 : 0), 0); /* Export virtual flag */
status |= exportVxUint32(xport, indexOf(xport, rt->ref->scope), 0); /* Export scope, for virtuals etc */
xport->ref_table[n].status = OBJECT_EXPORTED;
}
return status;
}
static void computeROIStartXY(vx_image parent, vx_image roi, vx_uint32 *x, vx_uint32 *y)
{
vx_uint32 offset = roi->memory.ptrs[0] - parent->memory.ptrs[0];
*y = offset * roi->scale[0][VX_DIM_Y] / roi->memory.strides[0][VX_DIM_Y];
*x = (offset - ((*y * roi->memory.strides[0][VX_DIM_Y]) / roi->scale[0][VX_DIM_Y]) )
* roi->scale[0][VX_DIM_X] / roi->memory.strides[0][VX_DIM_X];
}
static vx_status exportPixel(VXBinExport *xport, void *base, vx_uint32 x, vx_uint32 y, vx_uint32 p,
vx_imagepatch_addressing_t *addr, vx_df_image format, int calcSize)
{
/* export a pixel. For some YUV formats the meaning of the values changes for odd pixels */
vx_status status = VX_FAILURE;
vx_pixel_value_t *pix = (vx_pixel_value_t *)vxFormatImagePatchAddress2d(base, x, y, addr);
switch (format)
{
case VX_DF_IMAGE_U8: /* single-plane 1 byte */
case VX_DF_IMAGE_YUV4: /* 3-plane 1 byte */
case VX_DF_IMAGE_IYUV:
status = exportVxUint8(xport, pix->U8, calcSize);
break;
case VX_DF_IMAGE_U16: /* single-plane U16 */
status = exportVxUint16(xport, pix->U16, calcSize);
break;
case VX_DF_IMAGE_S16: /* single-plane S16 */
status = exportVxInt16(xport, pix->S16, calcSize);
break;
case VX_DF_IMAGE_U32: /* single-plane U32 */
status = exportVxUint32(xport, pix->U32, calcSize);
break;
case VX_DF_IMAGE_S32: /* single-plane S32 */
status = exportVxInt32(xport, pix->S32, calcSize);
break;
case VX_DF_IMAGE_RGB: /* single-plane 3 bytes */
status = exportBytes(xport, pix->RGB, 3, calcSize);
break;
case VX_DF_IMAGE_RGBX: /* single-plane 4 bytes */
status = exportBytes(xport, pix->RGBX, 4, calcSize);
break;
case VX_DF_IMAGE_UYVY: /* single plane, export 2 bytes for UY or VY */
case VX_DF_IMAGE_YUYV: /* single plane, export 2 bytes for YU or YV */
status = exportBytes(xport, pix->YUV, 2, calcSize);
break;
case VX_DF_IMAGE_NV12: /* export 1 byte from 1st plane and 2 from second */
case VX_DF_IMAGE_NV21: /* second plane order is different for the two formats */
if (0 == p)
status = exportVxUint8(xport, pix->YUV[0], calcSize); /* Y */
else
status = exportBytes(xport, pix->YUV, 2, calcSize); /* U & V */
break;
default:
DEBUGPRINTF("Unsupported image format");
status = VX_ERROR_NOT_SUPPORTED;
}
return status;
}
static vx_status exportSinglePixel(VXBinExport *xport, void * base, vx_uint32 p,
vx_imagepatch_addressing_t *addr, vx_df_image format, int calcSize)
{
/* export 1st pixel, used for uniform images */
vx_status status = VX_FAILURE;
switch (format)
{
case VX_DF_IMAGE_U8: /* single-plane 1 byte */
case VX_DF_IMAGE_YUV4: /* 3-plane 1 byte */
case VX_DF_IMAGE_IYUV:
case VX_DF_IMAGE_U16: /* single-plane U16 */
case VX_DF_IMAGE_S16: /* single-plane S16 */
case VX_DF_IMAGE_U32: /* single-plane U32 */
case VX_DF_IMAGE_S32: /* single-plane S32 */
case VX_DF_IMAGE_RGB: /* single-plane 3 bytes */
case VX_DF_IMAGE_RGBX: /* single-plane 4 bytes */
status = exportPixel(xport, base, 0, 0, p, addr, format, calcSize);
break;
case VX_DF_IMAGE_UYVY: /* single plane, export 3 bytes for YUV mapping UY0VY1 -> YUV*/
{
vx_uint8 *pix = vxFormatImagePatchAddress2d(base, 0, 0, addr);
status = exportVxUint8(xport, pix[1], calcSize);
status |= exportVxUint8(xport, pix[0], calcSize);
status |= exportVxUint8(xport, pix[2], calcSize);
}
break;
case VX_DF_IMAGE_YUYV: /* single plane, export 3 bytes for YUV mapping Y0UY1V to YUV */
{
vx_uint8 *pix = vxFormatImagePatchAddress2d(base, 0, 0, addr);
status = exportVxUint8(xport, pix[0], calcSize);
status |= exportVxUint8(xport, pix[1], calcSize);
status |= exportVxUint8(xport, pix[3], calcSize);
}
break;
case VX_DF_IMAGE_NV12: /* export 1 byte from 1st plane (Y) and 2 from second */
case VX_DF_IMAGE_NV21: /* second plane UV order is different for the two formats */
{
vx_uint8 *pix = vxFormatImagePatchAddress2d(base, 0, 0, addr);
if (0 == p)
status = exportVxUint8(xport, pix[0], calcSize); /* Y */
else if (VX_DF_IMAGE_NV12 == format)
{
status = exportVxUint8(xport, pix[0], calcSize); /* U */
status |= exportVxUint8(xport, pix[1], calcSize); /* V */
}
else
{ /* U & V swapped for NV21 */
status = exportVxUint8(xport, pix[1], calcSize); /* U */
status |= exportVxUint8(xport, pix[0], calcSize); /* V */
}
}
break;
default:
DEBUGPRINTF("Unsupported pixel format");
status = VX_ERROR_NOT_SUPPORTED;
}
return status;
}
static vx_status exportImage(VXBinExport *xport, const vx_size n, int calcSize)
{
vx_image image = (vx_image)xport->ref_table[n].ref;
vx_status status = exportObjectHeader(xport, n, calcSize); /* Export common information */
if (VX_TYPE_IMAGE == image->base.scope->type)
{
/* Image is an ROI or image from channel. If parent has same
number of channels, we assume ROI, otherwise we assume
image from channel. We don't do any other checks... */
vx_image parent = image->parent; /* Note: parent has already been exported as scope in the object header */
if (parent->planes == image->planes)
{
/* This is image from ROI, export the parent and rectangle*/
vx_uint32 x = 0, y = 0;
computeROIStartXY(parent, image, &x, &y); /* Find where the ROI starts */
status = exportVxUint8(xport, (vx_uint8)IMAGE_SUB_TYPE_ROI, calcSize); /* Export as ROI */
status |= exportVxUint32(xport, x, calcSize); /* Export the dimensions */
status |= exportVxUint32(xport, y, calcSize); /* To use to make a vx_rectangle_t */
status |= exportVxUint32(xport, image->width + x, calcSize);
status |= exportVxUint32(xport, image->height + y, calcSize);
}
else
{
/* This is image from channel, export the parent and channel.
There are a lot of assumptions here, that the image from channel
is correctly formed... */
vx_enum channel = VX_CHANNEL_Y;
if (image->memory.ptrs[0] != parent->memory.ptrs[0])
{
if (image->memory.ptrs[1] == parent->memory.ptrs[1])
channel = VX_CHANNEL_U;
else
channel = VX_CHANNEL_Y;
}
status = exportVxUint8(xport, (vx_uint8)IMAGE_SUB_TYPE_CHANNEL, calcSize); /* Export as image from channel */
status |= exportVxUint32(xport, (vx_uint32)channel, calcSize); /* Export channel */
}
/* And that's all we do for image from ROI or channel */
}
else if (image->parent && VX_TYPE_TENSOR == image->parent->base.type)
{
/* object array of images from tensor
Notice that scope index (of the object array) has already been exported
in the object header, all other information will be exported with the
object array.
*/
status = exportVxUint8(xport, (vx_uint8)IMAGE_SUB_TYPE_TENSOR, calcSize);
}
else if (vx_true_e == image->constant)
{
/* This is a uniform image */
status = exportVxUint8(xport, (vx_uint8)IMAGE_SUB_TYPE_UNIFORM, calcSize);
/* output type */
status |= exportVxUint32(xport, (vx_uint32)image->width, calcSize); /* Image width */
status |= exportVxUint32(xport, (vx_uint32)image->height, calcSize); /* Image height */
status |= exportVxUint32(xport, (vx_uint32)image->format, calcSize); /* Image format */
/* Now we just output one pixel for each plane as the value to use;
On import the number of planes is determined by the format, so this relies on
a properly formed image...
TODO for version 1.2 we can optimise this since there is a uniform image value attribute.
*/
{
vx_rectangle_t rect;
vx_uint32 p;
vxGetValidRegionImage(image, &rect);
rect.end_x = rect.start_x + 1;
rect.end_y = rect.start_y + 1;
for (p = 0U; p < image->planes; ++p)
{
void *base = NULL;
vx_imagepatch_addressing_t addr;
vx_map_id id;
status |= vxMapImagePatch(image, &rect, p, &id, &addr, &base, VX_READ_ONLY, image->memory_type, 0);
status |= exportSinglePixel(xport, base, p, &addr, image->format, calcSize);
status |= vxUnmapImagePatch(image, id);
}
}
}
else if (VX_IX_USE_NO_EXPORT_VALUES == xport->ref_table[n].use && isFromHandle((vx_reference)image))
{
/* Image from handle - bugzilla 16312 */
vx_uint32 p = 0;
status = exportVxUint8(xport, IMAGE_SUB_TYPE_HANDLE, calcSize);
status |= exportVxUint32(xport, image->width, calcSize); /* Image width */
status |= exportVxUint32(xport, image->height, calcSize); /* Image height */
status |= exportVxDfImage(xport, image->format, calcSize); /* Image format */
status |= exportVxUint32(xport, image->planes, calcSize); /* Number of planes, for ease of import */
status |= exportVxEnum(xport, image->memory_type, calcSize); /* Memory type */
for (p = 0; p < image->planes; ++p)
{
status |= exportVxInt32(xport, image->memory.strides[p][VX_DIM_X], calcSize); /* x stride for plane p */
status |= exportVxInt32(xport, image->memory.strides[p][VX_DIM_Y], calcSize); /* y stride for plane p */
}
}
else
{
/* Regular image */
status = exportVxUint8(xport, IMAGE_SUB_TYPE_NORMAL, calcSize);
/* output type */
status |= exportVxUint32(xport, image->width, calcSize); /* Image width */
status |= exportVxUint32(xport, image->height, calcSize); /* Image height */
status |= exportVxDfImage(xport, image->format, calcSize); /* Image format */
/* Now we have to output the data, but only if use == VX_IX_USE_EXPORT_VALUES
and not virtual
*/
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[n].use && !image->base.is_virtual)
{
status |= exportVxUint32(xport, 1U, calcSize);
vx_rectangle_t rect;
vx_uint32 p;
vxGetValidRegionImage(image, &rect);
/* Output valid region */
status |= exportVxUint32(xport, rect.start_x, calcSize);
status |= exportVxUint32(xport, rect.start_y, calcSize);
status |= exportVxUint32(xport, rect.end_x, calcSize);
status |= exportVxUint32(xport, rect.end_y, calcSize);
/* The number of planes is derived from format upon input; here we output all
the available pixel data.
*/
for (p = 0U; p < image->planes; ++p)
{
void *base = NULL;
vx_uint32 x, y;
vx_imagepatch_addressing_t addr;
vx_map_id id;
status |= vxMapImagePatch(image, &rect, p, &id, &addr, &base,
VX_READ_ONLY, image->memory_type, 0);
/* The actual number of data is calculated in the same way upon input;
we don't need to export any of step_x, step_y, dim_x, dim_y, x or y.
*/
for (y = 0U; y < addr.dim_y; y += addr.step_y)
{
for( x = 0U; x < addr.dim_x; x += addr.step_x)
{
status |= exportPixel(xport, base, x, y, p, &addr, image->format, calcSize);
}
}
status |= vxUnmapImagePatch(image, id);
}
}
else
{
status |= exportVxUint32(xport, 0U, calcSize);
}
}
return status;
}
static vx_status exportLUT(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_lut_t *lut = (vx_lut_t *)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, (vx_uint32)lut->num_items, calcSize);
status |= exportVxEnum(xport, lut->item_type, calcSize);
status |= exportVxUint32(xport, lut->offset, calcSize);
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == lut->base.is_virtual && lut->memory.ptrs[0])
{
vx_uint32 size = lut->num_items * lut->item_size;
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, lut->memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportDistribution(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_distribution dist = (vx_distribution)xport->ref_table[i].ref;
vx_uint32 bins = (vx_uint32)dist->memory.dims[0][VX_DIM_X];
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, bins, calcSize);
status |= exportVxInt32(xport, dist->offset_x, calcSize);
status |= exportVxUint32(xport, dist->range_x, calcSize);
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == dist->base.is_virtual && dist->memory.ptrs[0])
{
vx_uint32 size = bins * sizeof(vx_uint32);
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, dist->memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportThreshold(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_threshold threshold = (vx_threshold)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxEnum(xport, threshold->thresh_type, calcSize);
status |= exportVxEnum(xport, threshold->data_type, calcSize);
status |= exportVxInt32(xport, threshold->value.S32, calcSize);
status |= exportVxInt32(xport, threshold->lower.S32, calcSize);
status |= exportVxInt32(xport, threshold->upper.S32, calcSize);
status |= exportVxInt32(xport, threshold->true_value.S32, calcSize);
status |= exportVxInt32(xport, threshold->false_value.S32, calcSize);
return status;
}
static vx_status exportMatrix(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_matrix mat = (vx_matrix)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, (vx_uint32)mat->columns, calcSize);
status |= exportVxUint32(xport, (vx_uint32)mat->rows, calcSize);
status |= exportVxEnum(xport, mat->data_type, calcSize);
status |= exportVxCoordinates2dT(xport, &mat->origin, calcSize);
status |= exportVxEnum(xport, mat->pattern, calcSize);
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == mat->base.is_virtual && mat->memory.ptrs[0])
{
vx_uint32 size = mat->columns * mat->rows;
if (VX_TYPE_FLOAT32 == mat->data_type) /* can only be int32, float32, or uint8 */
size *= sizeof(vx_float32);
else if (VX_TYPE_UINT32 == mat->data_type)
size *= sizeof(vx_int32);
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, mat->memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportConvolution(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_convolution conv = (vx_convolution)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, (vx_uint32)conv->base.columns, calcSize);
status |= exportVxUint32(xport, (vx_uint32)conv->base.rows, calcSize);
status |= exportVxUint32(xport, conv->scale, calcSize);
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == conv->base.base.is_virtual && conv->base.memory.ptrs[0])
{
vx_uint32 size = conv->base.columns * conv->base.rows + sizeof(vx_int16); /* only type supported is int16 */
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, conv->base.memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportScalar(VXBinExport *xport, const vx_size i, int calcSize)
{
/* NOTE - now supports new scalar types with user structs (Bugzilla 16338)
*/
vx_status status = VX_SUCCESS;
vx_scalar scalar = (vx_scalar)xport->ref_table[i].ref;
vx_uint32 item_size = ownSizeOfType(scalar->data_type);
if (item_size == 0ul)
{
for (vx_uint32 ix = 0; ix < VX_INT_MAX_USER_STRUCTS; ++ix)
{
if (scalar->base.context->user_structs[ix].type == scalar->data_type)
{
item_size = scalar->base.context->user_structs[ix].size;
break;
}
}
}
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxEnum(xport, scalar->data_type, calcSize);
status |= exportVxUint32(xport, item_size, calcSize);
if (VX_TYPE_USER_STRUCT_START <= scalar->data_type && /* Now output the name if it's a user struct (Bugzilla 16338 comment 2)*/
VX_TYPE_USER_STRUCT_END >= scalar->data_type)
{
int ix = scalar->data_type - VX_TYPE_USER_STRUCT_START;
if (scalar->base.context->user_structs[ix].name[0]) /* Zero length name not allowed */
status |= exportBytes(xport, &scalar->base.context->user_structs[ix].name, VX_MAX_STRUCT_NAME, calcSize);
else
status = VX_ERROR_INVALID_TYPE;
}
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == scalar->base.is_virtual)
{
void * data = malloc(item_size);
status |= exportVxUint32(xport, item_size, calcSize); /* Size of data following */
status |= vxCopyScalar(scalar, data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST); /* Read the data */
status |= exportBytes(xport, &scalar->data, item_size, calcSize); /* Export the data */
free(data);
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportArray(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_array arr = (vx_array)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, (vx_uint32)arr->num_items, calcSize);
status |= exportVxUint32(xport, arr->capacity, calcSize);
status |= exportVxEnum(xport, arr->item_type, calcSize);
status |= exportVxUint32(xport, arr->item_size, calcSize);
if (VX_TYPE_USER_STRUCT_START <= arr->item_type && /* Now output the name if it's a user struct (Bugzilla 16338 comment 2)*/
VX_TYPE_USER_STRUCT_END >= arr->item_type)
{
int ix = arr->item_type - VX_TYPE_USER_STRUCT_START;
if (arr->base.context->user_structs[ix].name[0]) /* Zero length name not allowed */
status |= exportBytes(xport, &arr->base.context->user_structs[ix].name, VX_MAX_STRUCT_NAME, calcSize);
else
status = VX_ERROR_INVALID_TYPE;
}
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == arr->base.is_virtual && arr->memory.ptrs[0])
{
vx_uint32 size = arr->num_items * arr->item_size;
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, arr->memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportRemap(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_remap remap = (vx_remap)xport->ref_table[i].ref;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, remap->src_width, calcSize);
status |= exportVxUint32(xport, remap->src_height, calcSize);
status |= exportVxUint32(xport, remap->dst_width, calcSize);
status |= exportVxUint32(xport, remap->dst_height, calcSize);
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == remap->base.is_virtual && remap->memory.ptrs[0])
{
vx_uint32 size = remap->dst_width * remap->dst_height * sizeof(vx_float32) * 2;
status |= exportVxUint32(xport, size, calcSize); /* Size of data following */
status |= exportBytes(xport, remap->memory.ptrs[0], size, calcSize); /* Export the data */
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* Output a zero to indicate no data */
}
return status;
}
static vx_status exportTensor(VXBinExport *xport, const vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_tensor tensor = (vx_tensor)xport->ref_table[i].ref;
vx_uint32 dim;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, tensor->number_of_dimensions, calcSize);
status |= exportVxEnum(xport, tensor->data_type, calcSize);
status |= exportVxUint8(xport, tensor->fixed_point_position, calcSize);
if (VX_TYPE_TENSOR == tensor->base.scope->type)
{
/* export offset of this tensor's memory address from that of its parent */
status |= exportVxUint32(xport, (vx_uint8 *)tensor->parent->addr - (vx_uint8 *)tensor->addr, calcSize);
}
else
{
status |= exportVxUint32(xport, 0U, calcSize); /* No memory pointer offset */
}
/* export the size of each dimension */
for (dim = 0; dim < tensor->number_of_dimensions && VX_SUCCESS == status; ++dim)
{
status = exportVxUint32(xport, (vx_uint32)tensor->dimensions[dim], calcSize);
}
/* export the stride for each dimension */
for (dim = 0; dim < tensor->number_of_dimensions && VX_SUCCESS == status; ++dim)
{
status = exportVxUint32(xport, (vx_uint32)tensor->stride[dim], calcSize);
}
if (VX_SUCCESS == status)
{
if (VX_IX_USE_EXPORT_VALUES == xport->ref_table[i].use &&
vx_false_e == tensor->base.is_virtual &&
NULL != tensor->addr &&
VX_TYPE_TENSOR != tensor->base.scope->type)
{
vx_uint32 size = tensor->dimensions[tensor->number_of_dimensions - 1] *
tensor->stride[tensor->number_of_dimensions - 1];
status = exportVxUint32(xport, size, calcSize); /* Size of data following */
if (calcSize)
{
xport->export_length += size;
}
else if (VX_SUCCESS == status)
{ /* Export the data */
vx_size starts[VX_MAX_TENSOR_DIMENSIONS] = {0};
status = vxCopyTensorPatch(tensor, tensor->number_of_dimensions, starts, tensor->dimensions,
tensor->stride, xport->curptr, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
xport->curptr += size;
}
}
else
{
status = exportVxUint32(xport, 0U, calcSize); /* Size of data following */
}
}
return status;
}
static vx_status exportKernel(VXBinExport *xport,vx_size i, int calcSize)
{
/* Bugzilla 16337 - need to export all kernel data*/
vx_status status = VX_SUCCESS;
vx_uint32 ix; /* for enumerating kernel parameters */
vx_kernel kernel = (vx_kernel)xport->ref_table[i].ref;
status |= exportObjectHeader(xport, i, calcSize);
status |= exportVxEnum(xport, kernel->enumeration, calcSize);
status |= exportBytes(xport, kernel->name, VX_MAX_KERNEL_NAME, calcSize);
status |= exportVxUint32(xport, kernel->signature.num_parameters, calcSize);
for (ix = 0; ix < kernel->signature.num_parameters; ++ix)
{
status |= exportVxEnum(xport, kernel->signature.directions[ix], calcSize);
status |= exportVxEnum(xport, kernel->signature.types[ix], calcSize);
status |= exportVxEnum(xport, kernel->signature.states[ix], calcSize);
}
return status;
}
static vx_status exportGraph(VXBinExport *xport,vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_uint32 ix; /* for enumerating graph nodes and delays */
vx_uint32 delay_count = 0; /* count of delays */
vx_graph g = (vx_graph)xport->ref_table[i].ref;
/* Bugzilla 16207. Allow export of graphs as user kernels; in this case the name
of the kernel will be the name of the reference to the graph and it must not have
a zero length */
if (VX_IX_USE_IMPORT_AS_KERNEL == xport->ref_table[i].use &&
0 == g->base.name[0])
status = VX_FAILURE;
status |= exportObjectHeader(xport, i, calcSize);
DEBUGPRINTF("Exporting graph with %u parameters\n", g->numParams);
/* Need to export all delays that are registered with this graph:
first, count them:
*/
for (ix = 0; ix < VX_INT_MAX_REF; ++ix)
{
if (g->delays[ix])
++delay_count;
}
status |= exportVxUint32(xport, delay_count, calcSize);
/* Now actually output each delay reference in turn */
for (ix = 0; ix < VX_INT_MAX_REF && VX_SUCCESS == status; ++ix)
{
if (g->delays[ix])
status |= exportVxUint32(xport, indexOf(xport, (vx_reference)g->delays[ix]), calcSize);
}
/* Now export the number of nodes */
status |= exportVxUint32(xport, g->numNodes, calcSize);
/* Now we will export all the nodes of the graph. All nodes are distinct so there
is no point them being indexed in the ref_table, they are just put here.
*/
for (ix = 0; ix < g->numNodes && VX_SUCCESS == status; ++ix)
{
vx_node node = g->nodes[ix];
vx_uint32 num_parameters = node->kernel->signature.num_parameters;
vx_uint32 p;
/* Bugzilla 16337 - user kernels, we have a kernel export function so we put a link to the kernel here */
status |= exportVxUint32(xport, indexOf(xport, (vx_reference)node->kernel), calcSize);
/* The parameter list */
for (p = 0; p < num_parameters; ++p)
{
status |= exportVxUint32(xport, indexOf(xport, node->parameters[p]), calcSize);
}
/* Replicated flags */
status |= exportVxUint8(xport, node->is_replicated ? 1 : 0, calcSize);
if (node->is_replicated)
{
for (p = 0; p < num_parameters; ++p)
{
status |= exportVxUint8(xport, node->replicated_flags[p] ? 1 : 0, calcSize);
}
}
/* Affinity */
status |= exportVxUint32(xport, node->affinity, calcSize);
/* Attributes */
status |= exportVxBorderT(xport, &node->attributes.borders, calcSize);
}
/* Now output the graph parameters list */
status |= exportVxUint32(xport, g->numParams, calcSize);
for (ix = 0; ix < g->numParams && VX_SUCCESS == status; ++ix)
{
/* find node in graph's list of nodes and export that index */
vx_uint32 nix;
for (nix = 0; nix < g->numNodes; ++nix)
if (g->nodes[nix] == g->parameters[ix].node)
break;
status |= exportVxUint32(xport, nix, calcSize);
status |= exportVxUint32(xport, g->parameters[ix].index, calcSize);
}
/* That is all for the graph */
return status;
}
static vx_status exportDelay(VXBinExport *xport, vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_delay delay = (vx_delay)xport->ref_table[i].ref;
vx_uint32 c;
/* export the delay info */
status = exportObjectHeader(xport, i, calcSize); /* Export common information */
status |= exportVxUint32(xport, delay->count, calcSize); /* Number of delay slots */
for (c = 0; c < delay->count && VX_SUCCESS == status; ++c)
{
/* export each slot reference */
status = exportVxUint32(xport, indexOf(xport, delay->refs[c]), calcSize);
}
return status;
}
static vx_status exportObjectArray(VXBinExport *xport, vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_object_array object_array = (vx_object_array)xport->ref_table[i].ref;
vx_uint32 c;
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, object_array->num_items, calcSize);
/* Look for the specical case of an object array of images whose parent is a tensor */
if (VX_TYPE_IMAGE == object_array->items[0]->type &&
((vx_image)object_array->items[0])->parent &&
VX_TYPE_TENSOR == ((vx_image)object_array->items[0])->parent->base.type)
{
status |= exportVxEnum(xport, VX_TYPE_TENSOR, calcSize); /* Indicate type of parent */
/* we need to output the information required to recreate the object array:
the number of items (already done), the tensor, the stride, the rectangle
describing the ROI, and the image format */
vx_rectangle_t rect;
vx_uint32 stride = 1;
vx_image image0 = (vx_image)object_array->items[0];
vx_tensor tensor = (vx_tensor)image0->parent;
/* Calculate the start_x and start_y from the memory pointer */
div_t divmod = div((int64_t)image0->memory.ptrs[0] - (int64_t)tensor->addr, image0->memory.strides[0][1]);
rect.start_y = divmod.quot;
rect.start_x = divmod.rem / (image0->memory.strides[0][1] / tensor->dimensions[0]);
rect.end_y = rect.start_y + image0->height;
rect.end_x = rect.start_x + image0->width;
if (object_array->num_items > 1)
{
/* Calculate the stride */
vx_image image1 = (vx_image)object_array->items[1];
stride = (image1->memory.ptrs[0] - image0->memory.ptrs[0])/image0->memory.strides[0][2];
}
status |= exportVxUint32(xport, indexOf(xport, &(tensor->base)), calcSize);
status |= exportVxUint32(xport, stride, calcSize);
status |= exportVxUint32(xport, rect.start_x, calcSize);
status |= exportVxUint32(xport, rect.start_y, calcSize);
status |= exportVxUint32(xport, rect.end_x, calcSize);
status |= exportVxUint32(xport, rect.end_y, calcSize);
status |= exportVxDfImage(xport, image0->format, calcSize);
}
else
status |= exportVxEnum(xport, VX_TYPE_INVALID, calcSize); /* Indicate type of parent */
for (c = 0; c < object_array->num_items; ++c)
{
status |= exportVxUint32(xport, indexOf(xport, object_array->items[c]), calcSize);
}
return status;
}
static vx_status exportPyramid(VXBinExport *xport, vx_size i, int calcSize)
{
vx_status status = VX_SUCCESS;
vx_pyramid pyramid = (vx_pyramid)xport->ref_table[i].ref;
vx_uint32 c;
/* Export the pyramid info */
status = exportObjectHeader(xport, i, calcSize);
status |= exportVxUint32(xport, pyramid->width, calcSize);
status |= exportVxUint32(xport, pyramid->height, calcSize);
status |= exportVxDfImage(xport, pyramid->format, calcSize);
status |= exportVxFloat32(xport, pyramid->scale, calcSize);
status |= exportVxUint32(xport, pyramid->numLevels, calcSize);
for (c = 0; c < pyramid->numLevels; ++c)
{
/* Export each level */
status |= exportVxUint32(xport, indexOf(xport, (vx_reference)pyramid->levels[c]), calcSize);
}
return status;
}
static vx_status exportObjects(VXBinExport *xport, int calcSize)
{
vx_size i; /* for enumerating the references */
vx_status status;
xport->curptr = xport->export_buffer;
status = exportHeader(xport, calcSize);
for (i = 0; i < xport->actual_numrefs && VX_SUCCESS == status; ++i)
{
if (exportToProcess(xport, i, calcSize))
{
switch (xport->ref_table[i].ref->type)
{
case VX_TYPE_IMAGE: status = exportImage(xport, i, calcSize); break;
case VX_TYPE_LUT: status = exportLUT(xport, i, calcSize); break;
case VX_TYPE_DISTRIBUTION: status = exportDistribution(xport, i, calcSize);break;
case VX_TYPE_THRESHOLD: status = exportThreshold(xport, i, calcSize); break;
case VX_TYPE_MATRIX: status = exportMatrix(xport, i, calcSize); break;
case VX_TYPE_CONVOLUTION: status = exportConvolution(xport, i, calcSize); break;
case VX_TYPE_SCALAR: status = exportScalar(xport, i, calcSize); break;
case VX_TYPE_ARRAY: status = exportArray(xport, i, calcSize); break;
case VX_TYPE_REMAP: status = exportRemap(xport, i, calcSize); break;
case VX_TYPE_OBJECT_ARRAY: status = exportObjectArray(xport, i, calcSize); break;
case VX_TYPE_PYRAMID: status = exportPyramid(xport, i, calcSize); break;
case VX_TYPE_DELAY: status = exportDelay(xport, i, calcSize); break;
case VX_TYPE_GRAPH: status = exportGraph(xport, i, calcSize); break;
case VX_TYPE_TENSOR: status = exportTensor(xport, i, calcSize); break;
case VX_TYPE_KERNEL: status = exportKernel(xport, i, calcSize); break;
default: /* something we don't export at all */
break;
}
}
}
return status;
}
VX_API_ENTRY vx_status VX_API_CALL vxExportObjectsToMemory (
vx_context context,
vx_size numrefs,
const vx_reference * refs,
const vx_enum * uses,
const vx_uint8 ** ptr,
vx_size * length )
{
vx_status retval = VX_SUCCESS; /* To keep track of any errors, and the return value */
VXBinExport xport =
{
.context = context,
.refs = refs,
.uses = uses,
.ref_table = NULL,
.numrefs = numrefs,
.actual_numrefs = numrefs,
.export_buffer = NULL, /* Where the data will go */
.curptr = NULL,
.export_length = 0 /* Size of the export */
};
vx_size i; /* For enumerating the refs and uses */
/* ----------- Do all the checks ----------- */
/* Check initial parameters */
if (VX_SUCCESS != vxGetStatus((vx_reference)context) ||
refs == NULL || /* no parameters may be NULL */
uses == NULL ||
ptr == NULL ||
length == NULL)
{
DEBUGPRINTF("Initial invalid parameters...\n");
retval = VX_ERROR_INVALID_PARAMETERS;
}
else
{
/* Check refs and uses array */
for (i = 0; i < numrefs && VX_SUCCESS == retval; ++i)
{
vx_size i2; /*for secondary enumeration of refs and uses array */
retval = vxGetStatus(refs[i]); /* All references must be valid */
if (VX_SUCCESS == retval)
{
/* For all objects the context must be the one given */
if (context != refs[i]->context)
{
DEBUGPRINTF("Wrong context\n");
retval = VX_ERROR_INVALID_PARAMETERS;
}
else
{
/* If references in 'refs' have names they must be unique,
but note we have to allow for duplicate references */
if (refs[i]->name[0] != '\0')
{
for (i2 = i + 1; i2 < numrefs; ++i2)
{
if (refs[i] != refs[i2] && 0 == strncmp(refs[i]->name, refs[i2]->name, VX_MAX_REFERENCE_NAME))
{
DEBUGPRINTF("Duplicate names\n");
retval = VX_ERROR_INVALID_PARAMETERS;
break;
}
}
}
}
}
if (VX_SUCCESS == retval)
{
switch (refs[i]->type)
{
/* Only graphs and data objects may be exported */
case VX_TYPE_GRAPH:
if (VX_IX_USE_EXPORT_VALUES != uses[i] )
{
retval = VX_ERROR_INVALID_PARAMETERS;
}
else
{
/* Verify graphs, re-instating their previous state */
vx_uint32 ix; /* for enumerating graph parameters and nodes */
vx_graph g = (vx_graph)refs[i];
retval = vxVerifyGraph(g); /* export will fail if verification fails */
if (retval)
{
DEBUGPRINTF("Graph verification failed!\n");
}
/* All graph parameters are automotically exported with VX_IX_USE_NO_EXPORT_VALUES unless
already listed - see 16313. If attached to another graph somewhere *must* be listed */
for (ix = 0; VX_SUCCESS == retval && ix < g->numParams; ++ix)
{
vx_reference r = g->parameters[ix].node->parameters[g->parameters[ix].index];
int found = 0;
for (i2 = 0; i2 < numrefs && !found; ++i2)
found = (refs[i2] == r);
if (!found)
{
/* now check to make sure thay are not on another graph somewhere */
for (i2 = i + 1; VX_SUCCESS == retval && i2 < numrefs; ++i2)
{
if (VX_TYPE_GRAPH == refs[i2]->type)
{
vx_graph g2 = (vx_graph)refs[i2];
vx_uint32 n = 0;
for (n = 0; VX_SUCCESS == retval && n < g2->numNodes; ++n)
{
vx_uint32 p = 0;
for (p = 0; VX_SUCCESS == retval && p < g2->nodes[n]->kernel->signature.num_parameters; ++p)
{
if (g2->nodes[n]->parameters[p] == r)
{
DEBUGPRINTF("Unlisted graph parameter found in another graph!\n");
retval = VX_ERROR_INVALID_PARAMETERS;
}
}
}
}
}
}
}
/* "Immutable" node parameters can't be in refs, need to check all nodes in the graph */
for (ix = 0; VX_SUCCESS == retval && ix < g->numNodes; ++ix)
{
vx_node n = g->nodes[ix];
vx_kernel k = n->kernel;
vx_uint32 p; /* for enumerating node parameters */
for (p = 0; VX_SUCCESS == retval && p < k->signature.num_parameters; ++p)
if (isImmutable(k, p))
{
vx_reference r = n->parameters[p];
for (i2 = 0; VX_SUCCESS == retval && i2 < numrefs; ++i2)
if (refs[i2] == r)
{
retval = VX_ERROR_INVALID_PARAMETERS;
DEBUGPRINTF("Immutable parameter found\n");
}
}
}
}
break;
case VX_TYPE_IMAGE:
case VX_TYPE_DELAY:
case VX_TYPE_LUT:
case VX_TYPE_DISTRIBUTION:
case VX_TYPE_PYRAMID:
case VX_TYPE_THRESHOLD:
case VX_TYPE_MATRIX:
case VX_TYPE_CONVOLUTION:
case VX_TYPE_SCALAR:
case VX_TYPE_ARRAY:
case VX_TYPE_REMAP:
case VX_TYPE_OBJECT_ARRAY:
case VX_TYPE_TENSOR:
{
vx_enum use = uses[i];
if (refs[i]->is_virtual || /* No exported references may be virtual */
/* Objects created from handles must use VX_IX_USE_APPLICATION_CREATE or VX_IS_USE_NO_EXPORT_VALUES (See bugzilla 16312)*/
(isFromHandle(refs[i]) && VX_IX_USE_APPLICATION_CREATE != use && VX_IX_USE_NO_EXPORT_VALUES != use) ||
/* uses must contain valid enumerants for objects that aren't graphs */
(use != VX_IX_USE_APPLICATION_CREATE &&
use != VX_IX_USE_EXPORT_VALUES &&
use != VX_IX_USE_NO_EXPORT_VALUES
)
)
{
retval = VX_ERROR_INVALID_PARAMETERS;
DEBUGPRINTF("Virtual or fromhandle found, i = %lu, use = %d, virtual = %s\n",
i, use, refs[i]->is_virtual ? "true" : "false");
}
break;
}
case VX_TYPE_KERNEL:
/* Bugzilla 16207 comment 3. 'graph kernels' may be exported as kernels. The
underlying graph is exported.
*/
if (VX_IX_USE_EXPORT_VALUES == uses[i])
{
if (vx_false_e == ((vx_kernel)refs[i])->user_kernel ||
VX_TYPE_GRAPH != refs[i]->scope->type)
{
/* Kernels being exported this way must be user kernels, and have their scope be a graph. */
retval = VX_ERROR_INVALID_PARAMETERS;
}
else
{
/* We don't have to process the graph at this stage as it must have already been verified
and checked.
It will be placed in ref_table for export processing later by putInTable().
*/
}
}
/* Bugzilla 16337 */
else if (VX_IX_USE_APPLICATION_CREATE != uses[i])
{
DEBUGPRINTF("Wrong use of vx_kernel\n");
retval = VX_ERROR_INVALID_PARAMETERS;
}
break;
default:
/* Disallowed export type */
DEBUGPRINTF("Illegal export type\n");
retval = VX_ERROR_NOT_SUPPORTED;
}
}
}
}
/* ----------- Checks done, if OK, try and export ----------- */
if (VX_SUCCESS == retval)
{
/* First, make a table of unique references to export; first allocate an array big enough for any eventuality */
xport.ref_table = (VXBinExportRefTable *)calloc(sizeof(VXBinExportRefTable), context->num_references);
xport.actual_numrefs = numrefs;
/* Now, populate the table and find the actual number of references to export */
if (xport.ref_table)
{
/* First, populate the table with references as is. Thus the first numrefs
entries in ref_table correspond to refs; there may be duplicates */
for (i = 0; i < numrefs; ++i)
{
xport.ref_table[i].ref = refs[i];
xport.ref_table[i].use = uses[i];
xport.ref_table[i].status = OBJECT_UNPROCESSED;
}
/* Now mark duplicates */
for (i = 0; i < numrefs; ++i)
{
vx_size i2; /* for finding duplicates */
for (i2 = i + 1; i2 < numrefs; ++i2 )
if (refs[i] == xport.ref_table[i2].ref)
xport.ref_table[i2].status = OBJECT_DUPLICATE;
}
/* Next, populate with references from any compound objects; putInTable will expand
them recursively, but will only process any object with status OBJECT_UNPROCESSED,
then setting its status to OBJECT_UNSIZED.
*/
for (i = 0; i < numrefs; ++i)
{
xport.actual_numrefs = putInTable(xport.ref_table, refs[i], xport.actual_numrefs, uses[i]);
}
/* Calculate the uses for each reference */
calculateUses(&xport);
/* Now, calculate the size of the export */
retval = exportObjects(&xport, 1);
/* Increment the length of the export to take into account a checksum at the end */
xport.export_length += sizeof(vx_uint32);
}
if (VX_SUCCESS == retval)
{
/* Now allocate buffer for the export */
malloc_export(&xport);
/* And actually do the export */
retval = exportObjects(&xport, 0);
/* Now fix up duplicates */
for (i = 0; i < numrefs; ++i)
{
vx_size i2; /* for finding duplicates */
for (i2 = i + 1; i2 < numrefs; ++i2 )
if (xport.ref_table[i].ref == xport.ref_table[i2].ref)
{
/* Make offset of duplicate equal to the offset of the original */
memcpy(addressOf(&xport, i2), addressOf(&xport, i), sizeof(vx_uint64));
}
}
/* Finally, calculate the checksum and place it at the end */
{
vx_uint32 checksum = 0;
xport.curptr = xport.export_buffer;
for (i = 0; i < xport.export_length - sizeof(checksum); ++i)
{
checksum += *xport.curptr++;
}
retval = exportVxUint32(&xport, checksum, 0);
}
}
free(xport.ref_table);
}
if (VX_SUCCESS == retval)
{
/* On success, set output values */
*ptr = xport.export_buffer;
*length = xport.export_length;
}
else
{
/* On failure, clear output values and release any allocated memory */
*ptr = NULL;
*length = 0;
vxReleaseExportedMemory(context, (const vx_uint8**)&xport.export_buffer);
}
return retval;
}
VX_API_ENTRY vx_status VX_API_CALL vxReleaseExportedMemory(vx_context context, const vx_uint8 ** ptr)
{
vx_status retval = VX_ERROR_INVALID_PARAMETERS;
/* First, check we have some exports to release, that the pointer provided is not NULL, and that
the context is valid. Note that the list of exports is across all contexts */
if (VX_SUCCESS == vxGetStatus((vx_reference)context) && *ptr && **ptr && num_exports)
{
/* next, find the pointer in our list of pointers.*/
for (int i = 0; i < MAX_CONCURRENT_EXPORTS && VX_SUCCESS != retval; ++i)
{
if (*ptr == exports[i])
{
/* found it, all good, we can free the memory, zero the pointers and set a successful return value */
free((void *)*ptr);
*ptr = NULL;
exports[i] = NULL;
--num_exports;
retval = VX_SUCCESS;
}
}
}
/* If we haven't found the pointer retval will be unchanged */
return retval;
}
#endif
|
the_stack_data/6387093.c | #include <stdio.h>
int main()
{
int n, i;
printf("plz input n=? ");
scanf("%d", &n);
for ( i = 2; i < n; i ++)
{
if (n%i==0)
break;
}
if (i<n)
printf("%d is not a prime number.\n",n);
else
printf("%d is a prime number.\n",n);
return 0;
} |
the_stack_data/97011643.c | #include <stdio.h>
int main(void)
{
char single_quote = '\'';
char double_quote = '\"';
char ascii_bell = '\a';
char backspace = '\b';
char formfeed = '\f';
char newline = '\n';
} |
the_stack_data/13248.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SHORT_INPUT "d11_short_input"
#define INPUT "d11_input"
int x, y;
int** m;
int n_step = 0;
int ni[8] = {-1, -1, -1, 0, 0, 1, 1, 1 };
int nj[8] = {-1, 0, 1, -1, 1, -1, 0, 1 };
void increase_neighbours(int i, int j) {
for (int d = 0; d < 8; d++) {
int di = i + ni[d];
int dj = j + nj[d];
int out_of_bounds = 0;
if (di < 0 || di >= y) out_of_bounds = 1;
if (dj < 0 || dj >= x) out_of_bounds = 1;
if (!out_of_bounds) {
m[di][dj]++;
if (m[di][dj] == 10) {
increase_neighbours(di, dj);
}
}
}
}
int step() {
n_step++;
int flashes = 0;
/* printf("\033[H\033[J"); // clear screen */
/* usleep(100000); */
// increase evey octopus
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
m[i][j]++;
if (m[i][j] == 10) {
increase_neighbours(i, j);
}
}
}
// check flashes
printf("\nAfter step %i\n", n_step);
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (m[i][j] > 9) {
m[i][j] = 0;
flashes++;
}
printf("%i", m[i][j]);
}
printf("\n");
}
return flashes;
}
int main(int ac, char** args) {
int input = ac > 1;
FILE *fp = fopen(input ? INPUT : SHORT_INPUT, "r");
if (fp == NULL) {
printf("cant read file\n");
return 1;
}
y = 0;
x = 0;
int x_done = 0;
// calc x and y of matrix
while (1) {
char c = fgetc(fp);
if (c == '\n') {
y++;
x_done = 1;
continue;
} else if (c == EOF) break;
if (!x_done) x++;
}
rewind(fp);
m = (int**)malloc(x * y * sizeof(int));
for (int i = 0; i < y; i++)
m[i] = (int*)malloc(x * sizeof(int));
// read file
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++)
m[i][j] = fgetc(fp) - '0';
fgetc(fp); // read '/n'
}
// until the number of flashes equals the number of octopuses
while (step() != x*y) {
/* if (n_step == 6969) { */
/* printf("\nerror?\n"); */
/* break; */
/* } */
}
printf("\nflashes synchronised after %i steps\n", n_step);
for (int i = 0; i < y; i++)
free(m[i]);
free(m);
return 0;
}
|
the_stack_data/68886848.c | #include <stdio.h>
int main()
{
int x ;
int cnt = 0;
scanf("%d", &x);
x += 1;
while(cnt < 100000){
int i;
int isPrime = 1;
for(i = 2; i < x; i++){
if(x % i == 0){
isPrime = 0;
break;
}
}
if(isPrime == 1){
cnt++;
printf("%d", x);
break;
}
x++;
}
return 0;
} |
the_stack_data/48575466.c | /*$$HEADER*/
/******************************************************************************/
/* */
/* H E A D E R I N F O R M A T I O N */
/* */
/******************************************************************************/
// Project Name : ORPSoC v2
// File Name : bin2srec.c
// Prepared By :
// Project Start :
/*$$COPYRIGHT NOTICE*/
/******************************************************************************/
/* */
/* C O P Y R I G H T N O T I C E */
/* */
/******************************************************************************/
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation;
version 2.1 of the License, a copy of which is available from
http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*$$DESCRIPTION*/
/******************************************************************************/
/* */
/* D E S C R I P T I O N */
/* */
/******************************************************************************/
//
// Generates SREC file output to stdout from binary file
//
#include <stdio.h>
#include <stdlib.h>
#define SMARK "S214"
#define SADDR 0x000000
#define INIT_ADDR 0x100100
#define SCHKSUM 0xff
int main(int argc, char **argv)
{
FILE *fd;
int c, j;
unsigned long addr = INIT_ADDR;
unsigned char chksum;
if(argc < 2) {
fprintf(stderr,"no input file specified\n");
exit(1);
}
if(argc > 2) {
fprintf(stderr,"too many input files (more than one) specified\n");
exit(1);
}
fd = fopen( argv[1], "r" );
if (fd == NULL) {
fprintf(stderr,"failed to open input file: %s\n",argv[1]);
exit(1);
}
while (!feof(fd)) {
j = 0;
chksum = SCHKSUM;
printf("%s%.6lx", SMARK, addr);
while (j < 16) {
c = fgetc(fd);
if (c == EOF) {
c = 0;
}
printf("%.2x", c);
chksum -= c;
j++;
}
chksum -= addr & 0xff;
chksum -= (addr >> 8) & 0xff;
chksum -= (addr >> 16) & 0xff;
chksum -= 0x14;
printf("%.2x\r\n", chksum);
addr += 16;
}
return 0;
}
|
the_stack_data/90765765.c | #include <stdio.h>
int main()
{
int NUM1, CONT, CONT2;
CONT = 1;
CONT2 = 0;
while (CONT <= 10)
{
printf("Digite o Numero %d:", CONT);
scanf("%d", & NUM1);
if ((NUM1 % 2) == 0)
{
CONT2 ++;
}
CONT ++;
}
printf("A quantidade dos numeros pares: %d \n", CONT2);
}
|
the_stack_data/64946.c | /****************************************************************************
* libc/math/lib_log10f.c
*
* This file is a part of NuttX:
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Ported by: Darcy Gong
*
* It derives from the Rhombus OS math library by Nick Johnson which has
* a compatibile, MIT-style license:
*
* Copyright (C) 2009, 2010 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
****************************************************************************/
float log10f(float x)
{
return (logf(x) / (float)M_LN10);
}
|
the_stack_data/1054257.c | /*numPass=6, numTotal=7
Verdict:ACCEPTED, Visibility:1, Input:"1 4 5", ExpOutput:"1111
1 1
1 1
1 1
1111
", Output:"1111
1 1
1 1
1 1
1111"
Verdict:ACCEPTED, Visibility:1, Input:"2 5 6", ExpOutput:"22222
2 2
2 2
2 2
2 2
22222
", Output:"22222
2 2
2 2
2 2
2 2
22222"
Verdict:ACCEPTED, Visibility:1, Input:"9 6 7", ExpOutput:"999999
9 9
9 9
9 9
9 9
9 9
999999
", Output:"999999
9 9
9 9
9 9
9 9
9 9
999999"
Verdict:ACCEPTED, Visibility:1, Input:"3 4 5", ExpOutput:"3333
3 3
3 3
3 3
3333
", Output:"3333
3 3
3 3
3 3
3333"
Verdict:ACCEPTED, Visibility:1, Input:"2 2 2", ExpOutput:"22
22
", Output:"22
22"
Verdict:ACCEPTED, Visibility:0, Input:"3 3 3", ExpOutput:"333
3 3
333
", Output:"333
3 3
333"
Verdict:WRONG_ANSWER, Visibility:0, Input:"1 1 1", ExpOutput:"1
", Output:"N"
*/
#include<stdio.h>
int main() {
int N,w,h,i,j,k,l,m,n;
scanf("%d",&N);
scanf("%d",&w);
scanf("%d",&h);
if(w==1){
if(h==1){
printf("N");
}
else{
for(m=0;m<h;m++)
{
printf("%d\n",N);
}
}
}
else{
if(h==1){
printf("%d",N);
for(n=0;n<w-2;n++)
{
printf(" ");
}
printf("%d",N);
}
else{
{
for(i=0;i<w;i++)
{
printf("%d",N);
}
printf("\n");
}
{
for(j=0;j<(h-2);j++)
{
printf("%d",N);
{
for(k=0;k<(w-2);k++)
{
printf(" ");
}
}
printf("%d\n",N);
}
}
{
for(l=0;l<w;l++)
{
printf("%d",N);
}
}
}
}
return 0;
} |
the_stack_data/168891846.c | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Simple SDL-based WebP file viewer.
// Does not support animation, just static images.
//
// Press 'q' to exit.
//
// Author: James Zern ([email protected])
#include <stdio.h>
#ifdef HAVE_CONFIG_H
#include "src/webp/config.h"
#endif
#ifdef BUILD_MONOLITHIC
#include "extras/tools.h"
#endif
#if defined(WEBP_HAVE_SDL)
#include "webp_to_sdl.h"
#include "webp/decode.h"
#include "imageio/imageio_util.h"
#include "../examples/unicode.h"
#if defined(WEBP_HAVE_JUST_SDL_H)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif
static void ProcessEvents(void) {
int done = 0;
SDL_Event event;
while (!done && SDL_WaitEvent(&event)) {
switch (event.type) {
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_q: done = 1; break;
default: break;
}
break;
default: break;
}
}
}
#ifdef BUILD_MONOLITHIC
int vwebp_sdl_main(int argc, const char** argv)
#else
int main(int argc, const char** argv)
#endif
{
int c;
int ok = 0;
INIT_WARGV(argc, argv);
for (c = 1; c < argc; ++c) {
const char* file = NULL;
const uint8_t* webp = NULL;
size_t webp_size = 0;
if (!strcmp(argv[c], "-h")) {
printf("Usage: %s [-h] image.webp [more_files.webp...]\n", argv[0]);
FREE_WARGV_AND_RETURN(0);
} else {
file = (const char*)GET_WARGV(argv, c);
}
if (file == NULL) continue;
if (!ImgIoUtilReadFile(file, &webp, &webp_size)) {
WFPRINTF(stderr, "Error opening file: %s\n", (const W_CHAR*)file);
goto Error;
}
if (webp_size != (size_t)(int)webp_size) {
free((void*)webp);
fprintf(stderr, "File too large.\n");
goto Error;
}
ok = WebpToSDL((const char*)webp, (int)webp_size);
free((void*)webp);
if (!ok) {
WFPRINTF(stderr, "Error decoding file %s\n", (const W_CHAR*)file);
goto Error;
}
ProcessEvents();
}
ok = 1;
Error:
SDL_Quit();
FREE_WARGV_AND_RETURN(ok ? 0 : 1);
}
#else // !WEBP_HAVE_SDL
#ifdef BUILD_MONOLITHIC
int vwebp_sdl_main(int argc, const char** argv)
#else
int main(int argc, const char** argv)
#endif
{
fprintf(stderr, "SDL support not enabled in %s.\n", argv[0]);
(void)argc;
return 0;
}
#endif
|
the_stack_data/662874.c | // KASAN: use-after-free Read in snd_pcm_timer_resolution
// https://syzkaller.appspot.com/bug?id=c041fdbeee530d37a31d3017e69c0e8a6e44604b
// status:fixed
// autogenerated by syzkaller (http://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/net.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
__attribute__((noreturn)) static void doexit(int status)
{
volatile unsigned i;
syscall(__NR_exit_group, status);
for (i = 0;; i++) {
}
}
#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
const int kFailStatus = 67;
const int kRetryStatus = 69;
static void fail(const char* msg, ...)
{
int e = errno;
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
fprintf(stderr, " (errno %d)\n", e);
doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus);
}
static uint64_t current_time_ms()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
fail("clock_gettime failed");
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static uintptr_t syz_open_dev(uintptr_t a0, uintptr_t a1, uintptr_t a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf));
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
#define XT_TABLE_SIZE 1536
#define XT_MAX_ENTRIES 10
struct xt_counters {
uint64_t pcnt, bcnt;
};
struct ipt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_entries;
unsigned int size;
};
struct ipt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct ipt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct ipt_table_desc {
const char* name;
struct ipt_getinfo info;
struct ipt_replace replace;
};
static struct ipt_table_desc ipv4_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
static struct ipt_table_desc ipv6_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
#define IPT_BASE_CTL 64
#define IPT_SO_SET_REPLACE (IPT_BASE_CTL)
#define IPT_SO_GET_INFO (IPT_BASE_CTL)
#define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1)
struct arpt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_entries;
unsigned int size;
};
struct arpt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct arpt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct arpt_table_desc {
const char* name;
struct arpt_getinfo info;
struct arpt_replace replace;
};
static struct arpt_table_desc arpt_tables[] = {
{.name = "filter"},
};
#define ARPT_BASE_CTL 96
#define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL)
#define ARPT_SO_GET_INFO (ARPT_BASE_CTL)
#define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1)
static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
struct ipt_get_entries entries;
socklen_t optlen;
int fd, i;
fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family);
for (i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
optlen = sizeof(table->info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
fail("getsockopt(IPT_SO_GET_INFO)");
}
if (table->info.size > sizeof(table->replace.entrytable))
fail("table size is too large: %u", table->info.size);
if (table->info.num_entries > XT_MAX_ENTRIES)
fail("too many counters: %u", table->info.num_entries);
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
fail("getsockopt(IPT_SO_GET_ENTRIES)");
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
struct xt_counters counters[XT_MAX_ENTRIES];
struct ipt_get_entries entries;
struct ipt_getinfo info;
socklen_t optlen;
int fd, i;
fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family);
for (i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
if (table->info.valid_hooks == 0)
continue;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
optlen = sizeof(info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen))
fail("getsockopt(IPT_SO_GET_INFO)");
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
fail("getsockopt(IPT_SO_GET_ENTRIES)");
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
}
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen))
fail("setsockopt(IPT_SO_SET_REPLACE)");
}
close(fd);
}
static void checkpoint_arptables(void)
{
struct arpt_get_entries entries;
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
optlen = sizeof(table->info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
fail("getsockopt(ARPT_SO_GET_INFO)");
}
if (table->info.size > sizeof(table->replace.entrytable))
fail("table size is too large: %u", table->info.size);
if (table->info.num_entries > XT_MAX_ENTRIES)
fail("too many counters: %u", table->info.num_entries);
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
fail("getsockopt(ARPT_SO_GET_ENTRIES)");
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_arptables()
{
struct xt_counters counters[XT_MAX_ENTRIES];
struct arpt_get_entries entries;
struct arpt_getinfo info;
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
if (table->info.valid_hooks == 0)
continue;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
optlen = sizeof(info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen))
fail("getsockopt(ARPT_SO_GET_INFO)");
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
fail("getsockopt(ARPT_SO_GET_ENTRIES)");
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
}
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen))
fail("setsockopt(ARPT_SO_SET_REPLACE)");
}
close(fd);
}
#include <linux/if.h>
#include <linux/netfilter_bridge/ebtables.h>
struct ebt_table_desc {
const char* name;
struct ebt_replace replace;
char entrytable[XT_TABLE_SIZE];
};
static struct ebt_table_desc ebt_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "broute"},
};
static void checkpoint_ebtables(void)
{
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
strcpy(table->replace.name, table->name);
optlen = sizeof(table->replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace,
&optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
fail("getsockopt(EBT_SO_GET_INIT_INFO)");
}
if (table->replace.entries_size > sizeof(table->entrytable))
fail("table size is too large: %u", table->replace.entries_size);
table->replace.num_counters = 0;
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace,
&optlen))
fail("getsockopt(EBT_SO_GET_INIT_ENTRIES)");
}
close(fd);
}
static void reset_ebtables()
{
struct ebt_replace replace;
char entrytable[XT_TABLE_SIZE];
socklen_t optlen;
unsigned i, j, h;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
if (table->replace.valid_hooks == 0)
continue;
memset(&replace, 0, sizeof(replace));
strcpy(replace.name, table->name);
optlen = sizeof(replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen))
fail("getsockopt(EBT_SO_GET_INFO)");
replace.num_counters = 0;
table->replace.entries = 0;
for (h = 0; h < NF_BR_NUMHOOKS; h++)
table->replace.hook_entry[h] = 0;
if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) {
memset(&entrytable, 0, sizeof(entrytable));
replace.entries = entrytable;
optlen = sizeof(replace) + replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen))
fail("getsockopt(EBT_SO_GET_ENTRIES)");
if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0)
continue;
}
for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) {
if (table->replace.valid_hooks & (1 << h)) {
table->replace.hook_entry[h] =
(struct ebt_entries*)table->entrytable + j;
j++;
}
}
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen))
fail("setsockopt(EBT_SO_SET_ENTRIES)");
}
close(fd);
}
static void checkpoint_net_namespace(void)
{
checkpoint_ebtables();
checkpoint_arptables();
checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void reset_net_namespace(void)
{
reset_ebtables();
reset_arptables();
reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void execute_one();
extern unsigned long long procid;
static void loop()
{
checkpoint_net_namespace();
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
fail("clone failed");
if (pid == 0) {
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
execute_one();
doexit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
int res = waitpid(-1, &status, __WALL | WNOHANG);
if (res == pid) {
break;
}
usleep(1000);
if (current_time_ms() - start < 3 * 1000)
continue;
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
while (waitpid(-1, &status, __WALL) != pid) {
}
break;
}
reset_net_namespace();
}
}
uint64_t r[1] = {0xffffffffffffffff};
unsigned long long procid;
void execute_one()
{
long res;
memcpy((void*)0x20000000, "/dev/snd/timer", 15);
res = syz_open_dev(0x20000000, 0, 0);
if (res != -1)
r[0] = res;
*(uint64_t*)0x20000380 = 0x20000240;
*(uint16_t*)0x20000240 = 0x10;
*(uint16_t*)0x20000242 = 0;
*(uint32_t*)0x20000244 = 0;
*(uint32_t*)0x20000248 = 0x3100008;
*(uint32_t*)0x20000388 = 0xc;
*(uint64_t*)0x20000390 = 0x20000340;
*(uint64_t*)0x20000340 = 0x200003c0;
*(uint16_t*)0x200003c0 = -1;
*(uint64_t*)0x20000348 = 3;
*(uint64_t*)0x20000398 = 1;
*(uint64_t*)0x200003a0 = 0;
*(uint64_t*)0x200003a8 = 0;
*(uint32_t*)0x200003b0 = 0x4000800;
syscall(__NR_sendmsg, -1, 0x20000380, 5);
*(uint32_t*)0x2000efcc = 3;
*(uint32_t*)0x2000efd0 = 0;
*(uint32_t*)0x2000efd4 = 0;
*(uint32_t*)0x2000efd8 = 0;
*(uint32_t*)0x2000efdc = 1;
*(uint8_t*)0x2000efe0 = 0;
*(uint8_t*)0x2000efe1 = 0;
*(uint8_t*)0x2000efe2 = 0;
*(uint8_t*)0x2000efe3 = 0;
*(uint8_t*)0x2000efe4 = 0;
*(uint8_t*)0x2000efe5 = 0;
*(uint8_t*)0x2000efe6 = 0;
*(uint8_t*)0x2000efe7 = 0;
*(uint8_t*)0x2000efe8 = 0;
*(uint8_t*)0x2000efe9 = 0;
*(uint8_t*)0x2000efea = 0;
*(uint8_t*)0x2000efeb = 0;
*(uint8_t*)0x2000efec = 0;
*(uint8_t*)0x2000efed = 0;
*(uint8_t*)0x2000efee = 0;
*(uint8_t*)0x2000efef = 0;
*(uint8_t*)0x2000eff0 = 0;
*(uint8_t*)0x2000eff1 = 0;
*(uint8_t*)0x2000eff2 = 0;
*(uint8_t*)0x2000eff3 = 0;
*(uint8_t*)0x2000eff4 = 0;
*(uint8_t*)0x2000eff5 = 0;
*(uint8_t*)0x2000eff6 = 0;
*(uint8_t*)0x2000eff7 = 0;
*(uint8_t*)0x2000eff8 = 0;
*(uint8_t*)0x2000eff9 = 0;
*(uint8_t*)0x2000effa = 0;
*(uint8_t*)0x2000effb = 0;
*(uint8_t*)0x2000effc = 0;
*(uint8_t*)0x2000effd = 0;
*(uint8_t*)0x2000effe = 0;
*(uint8_t*)0x2000efff = 0;
syscall(__NR_ioctl, r[0], 0x40345410, 0x2000efcc);
syscall(__NR_ioctl, r[0], 0x54a2);
memcpy((void*)0x20000180, "/dev/audio", 11);
syscall(__NR_openat, 0xffffffffffffff9c, 0x20000180, 0, 0);
}
int main()
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
for (procid = 0; procid < 8; procid++) {
if (fork() == 0) {
for (;;) {
loop();
}
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/990918.c | #include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#define MAXLINE 1024
#define MAX_EPOLL_SIZE 10000
int main(int argc,char **argv)
{
int listenfd,connfd;
struct sockaddr_in sockaddr;
char buff[MAXLINE];
int n;
memset(&sockaddr,0,sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
sockaddr.sin_port = htons(10004);
listenfd = socket(AF_INET,SOCK_STREAM,0);
/**
1. int epoll_create(int size); 创建一个epoll的句柄,size用来告诉内核这个监听的数目一共有多大。这个参数不同于select()中的第一个参数,给出最大监听的fd+1的值。
*/
int epfd = epoll_create(MAX_EPOLL_SIZE);
/**
2. int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
epoll的事件注册函数,它不同与select()是在监听事件时告诉内核要监听什么类型的事件,而是在这里先注册要监听的事件类型。第一个参数是epoll_create()的返回值,
第二个参数表示动作,用三个宏来表示:
EPOLL_CTL_ADD:注册新的fd到epfd中;
EPOLL_CTL_MOD:修改已经注册的fd的监听事件;
EPOLL_CTL_DEL:从epfd中删除一个fd;
第三个参数是需要监听的fd,第四个参数是告诉内核需要监听的事件
typedef union epoll_data {
void *ptr;
int fd;
__uint32_t u32;
__uint64_t u64;
} epoll_data_t;
struct epoll_event {
__uint32_t events;
epoll_data_t data;
};
*/
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = listenfd;
int ret = epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);
if(ret != 0){
printf("error\n");
exit(0);
}
bind(listenfd,(struct sockaddr *) &sockaddr,sizeof(sockaddr));
listen(listenfd,1024);
printf("Please wait for the client information\n");
struct epoll_event events[MAX_EPOLL_SIZE];
for(;;)
{
/**
3.int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);
等待事件的产生,类似于select()调用。参数events用来从内核得到事件的集合,maxevents告之内核这个events有多大,
这个 maxevents的值不能大于创建epoll_create()时的size,参数timeout是超时时间(毫秒,0会立即返回,-1将不确定,也有说法说是永久阻塞)。
该函数返回需要处理的事件数目,如返回0表示已超时。
*/
int fds = epoll_wait(epfd,events,30,1);
if(fds < 0){
printf("epoll_wait error, exit\n");
break;
}
for(int i = 0; i < fds; i++){
int fd = events[i].data.fd;
if((events[i].events & EPOLLIN) && fd == listenfd) // read event fd = listenfd 则accept
{
if((connfd = accept(listenfd,(struct sockaddr*)NULL,NULL))==-1)
{
printf("accpet socket error: %s errno :%d\n",strerror(errno),errno);
continue;
}
struct epoll_event ev;
ev.events = EPOLLIN | EPOLLOUT;
ev.data.fd = connfd;
int ret = epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev);
if(ret != 0){
printf("error\n");
exit(0);
}
}else if(events[i].events & EPOLLIN){
n = read(fd,buff,MAXLINE);
buff[n] = '\0';
printf("recv msg from client:%s",buff);
} else if(events[i].events & EPOLLOUT){
char *str = "HTTP/1.1 200 OK\r\nx-proxy-by: SmartGate-IDC\r\nDate: Tue, 17 Jul 2018 12:21:15 GMT\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Length: 8\r\n\r\n11111111";
write(fd,str,strlen(str));
close(connfd);
}
}
}
close(listenfd);
} |
the_stack_data/168893515.c | #define __noderef __attribute__((noderef))
#define __bitwise __attribute__((bitwise))
#define __nocast __attribute__((nocast))
#define __safe __attribute__((safe))
static void test_spec(void)
{
unsigned int obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_const(void)
{
const int obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
ptr = ptr;
ptr = &obj;
}
static void test_volatile(void)
{
volatile int obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_restrict(void)
{
int *restrict obj, *restrict *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_atomic(void)
{
int _Atomic obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_bitwise(void)
{
typedef int __bitwise type_t;
type_t obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_static(void)
{
static int obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_tls(void)
{
static __thread int obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
static void test_nocast(void)
{
int __nocast obj, *ptr;
typeof(obj) var = obj;
typeof(ptr) ptr2 = ptr;
typeof(*ptr) var2 = obj;
typeof(*ptr) *ptr3 = ptr;
typeof(obj) *ptr4 = ptr;
obj = obj;
ptr = ptr;
ptr = &obj;
obj = *ptr;
}
/*
* check-name: typeof-mods
*
* check-error-start
* check-error-end
*/
|
the_stack_data/1018188.c | /*
Week 8 Question 1
Description
Please finish the two function remove and inorder in template.
Please make sure that tree still be a binary search tree after remove .
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int data, height;
struct Node *left, *right, *parnt;
};
void getHigh(struct Node *root)
{
if (root)
{
int L, R;
if (root->left)
L = root->left->height + 1;
else
L = 1;
if (root->right)
R = root->right->height + 1;
else
R = 1;
if (L > R)
root->height = L;
else
root->height = R;
getHigh(root->parnt);
}
return;
}
void insert(struct Node **root, struct Node *node)
{
if (!(*root))
{
(*root) = node;
getHigh(node);
return;
}
struct Node *cur = (*root);
struct Node *head = (*root);
// printf("!123!\n");
while (1)
{
if (cur->data >= node->data) //go left
{
if (cur->left == NULL)
{
cur->left = node;
node->parnt = cur;
break;
}
cur = cur->left;
}
else if (cur->data < node->data)
{
if (cur->right == NULL)
{
cur->right = node;
node->parnt = cur;
break;
}
cur = cur->right;
}
}
// printf("return\n\n");
getHigh(node);
return;
}
/*
Function removal will remove all the node tree content data n.
The return value of function removal is a integer represent how many node are removed.
*/
struct Node *findMax(struct Node *root)
{
while (root->right)
{
root = root->right;
}
return root;
}
struct Node *find_min(struct Node *root)
{
while (root->left)
root = root->left;
return root;
}
struct Node *Find(struct Node *root, int targ)
{
while (1)
{
if (!root)
return NULL;
else
{
if (root->data == targ)
return root;
else if (root->data > targ) //root > elemt
root = root->left;
else //root < elemt
root = root->right;
if (!root)
return NULL;
}
}
}
void inorder(struct Node *root)
{
if (root)
{
//printf("%d(1) ", root->data);
inorder(root->left);
//printf("%d ", root->data);
printf("%d(%p) \n", root->data, root);
inorder(root->right);
//printf("%d(3) ", root->data);
}
//printf("NULL\n");
return;
}
void inorder_counts(struct Node *root, int *counts, int targ)
{
if (root)
{
inorder_counts(root->left, counts, targ);
if (root->data == targ)
(*counts)++;
inorder_counts(root->right, counts, targ);
}
return;
}
void delete_node(struct Node **tree, int targ)
{
if ((*tree) == NULL)
return;
struct Node *head = (*tree);
struct Node *root = (*tree);
struct Node *targPtr = Find(root, targ);
// printf("find:(%p)%d \t H:%d\n", targPtr, targPtr->data, targPtr->height);
if (targPtr == (*tree))
{
if ((!((*tree)->left)) && (!((*tree)->right)))
{
free(*tree);
return;
}
else if ((!((*tree)->left)) && ((*tree)->right))
{
struct Node *treeR = (*tree)->right;
(*tree)->right = NULL;
treeR->parnt = NULL;
free(*tree);
(*tree) = treeR;
}
else if (((*tree)->left) && (!((*tree)->right)))
{
struct Node *treeL = (*tree)->left;
(*tree)->left = NULL;
treeL->parnt = NULL;
free(*tree);
(*tree) = treeL;
}
else // ((*tree)->left) && ((*tree)->right)
{
int L = targPtr->left->height;
int R = targPtr->right->height;
if (R >= L)
{
// printf("R>=L\n");
struct Node *minNode = find_min((*tree)->right);
// printf("minNode:(%p)%d \t H:%d\n", minNode, minNode->data, minNode->height);
struct Node *targLeft = (*tree)->left;
(*tree)->left = NULL;
targLeft->parnt = NULL;
if (minNode->parnt == (*tree))
{
//printf("if (minNode->parnt == (*tree))\n");
(*tree)->right = NULL;
minNode->parnt = NULL;
}
else
{
struct Node *targRight = (*tree)->right;
(*tree)->right = NULL;
targRight->parnt = NULL;
struct Node *minNodeParnt = minNode->parnt;
minNode->parnt = NULL;
minNodeParnt->left = NULL;
struct Node *minNodeRight = minNode->right;
minNode->right = NULL;
if (minNodeRight)
{
minNodeRight->parnt = NULL;
minNodeRight->parnt = minNodeParnt;
}
minNodeParnt->left = minNodeRight;
targRight->parnt = minNode;
minNode->right = targRight;
}
targLeft->parnt = minNode;
minNode->left = targLeft;
free(*tree);
(*tree) = minNode;
}
else
{
//printf("else L<R\n");
struct Node *maxNode = findMax((*tree)->left);
struct Node *targRight = (*tree)->right;
(*tree)->right = NULL;
targRight->parnt = NULL;
if (maxNode->parnt == (*tree))
{
(*tree)->left = NULL;
maxNode->parnt = NULL;
}
else //max->parnt != (*tree)
{
struct Node *targLeft = (*tree)->left;
(*tree)->left = NULL;
targLeft->parnt = NULL;
struct Node *maxNodeParnt = maxNode->parnt;
maxNode->parnt = NULL;
maxNodeParnt->right = NULL;
struct Node *maxNodeLeft = maxNode->left;
maxNode->left = NULL;
if (maxNodeLeft)
{
maxNodeLeft->parnt = NULL;
maxNodeLeft->parnt = maxNodeParnt;
}
maxNodeParnt->right = maxNodeLeft;
targLeft->parnt = maxNode;
maxNode->left = targLeft;
}
maxNode->right = targRight;
targRight->parnt = maxNode;
free(*tree);
(*tree) = maxNode;
}
}
getHigh(*tree);
return;
}
else
{
if ((!(targPtr->left)) && (!(targPtr->right))) //targPtr has no child
{
struct Node *targParnt = targPtr->parnt;
targPtr->parnt = NULL;
if (targParnt->left == targPtr)
targParnt->left = NULL;
else //(targParnt->right == targ)
targParnt->right = NULL;
free(targPtr);
targPtr = targParnt;
}
else if ((!(targPtr->left)) && (targPtr->right)) //targ has right child
{
struct Node *minNode = find_min(targPtr->right);
struct Node *targParnt = targPtr->parnt;
targPtr->parnt = NULL;
if (minNode->parnt == targPtr)
{
targParnt->right = NULL;
minNode->parnt = NULL;
minNode->parnt = targParnt;
if (targParnt->right = targPtr)
{
targParnt->right = NULL;
targParnt->right = minNode;
}
else
{
targParnt->left = NULL;
targParnt->left = minNode;
}
}
else
{
struct Node *targRight = targPtr->right;
targPtr->right = NULL;
targRight->parnt = NULL;
struct Node *minNodeParnt = minNode->parnt;
minNode->parnt = NULL;
minNodeParnt->left = NULL;
struct Node *minNodeRight = minNode->right;
minNodeRight->parnt = NULL;
minNode->right = NULL;
minNodeRight->parnt = minNodeParnt;
minNodeParnt->left = minNodeRight;
minNode->parnt = targParnt;
if (targParnt->right == targPtr)
{
targParnt->right = NULL;
targParnt->right = minNode;
}
else
{
targParnt->left = NULL;
targParnt->left = minNode;
}
targRight->parnt = minNode;
minNode->right = targRight;
}
free(targPtr);
targPtr = minNode;
}
else if ((targPtr->left) && (!(targPtr->right))) //targ has left child
{
struct Node *maxNode = findMax(targPtr->left);
struct Node *targParnt = targPtr->parnt;
targPtr->parnt = NULL;
if (maxNode->parnt == targPtr)
{
targPtr->left = NULL;
maxNode->parnt = NULL;
}
else
{
struct Node *targLeft = targPtr->left;
targPtr->left = NULL;
targLeft->parnt = NULL;
struct Node *maxNodeParnt = maxNode->parnt;
maxNode->parnt = NULL;
maxNodeParnt->right = NULL;
struct Node *maxNodeLeft = maxNode->left;
maxNodeLeft->parnt = NULL;
maxNode->left = NULL;
maxNodeLeft->parnt = maxNodeParnt;
maxNodeParnt->right = maxNodeLeft;
targLeft->parnt = maxNode;
maxNode->left = targLeft;
}
maxNode->parnt = targParnt;
if (targParnt->right == targPtr)
{
targParnt->right = NULL;
targParnt->right = maxNode;
}
else
{
targParnt->left = NULL;
targParnt->left = maxNode;
}
free(targPtr);
targPtr = maxNode;
}
else if ((targPtr->left) && (targPtr->right)) //targ has both child
{
//printf("else if ((targ->left) && (targ->right))\n");
int L = targPtr->left->height;
int R = targPtr->right->height;
if (R >= L) //in right find minNode
{
printf("\t\tif( R >= L)\n");
struct Node *minNode = find_min(targPtr->right);
printf("miinNode:(%p)%d H:%d\n", minNode, minNode->data, minNode->height);
struct Node *targL = targPtr->left;
targPtr->left = NULL;
targL->parnt = NULL;
struct Node *targParnt = targPtr->parnt;
targPtr->parnt = NULL;
if (minNode->parnt == targPtr)
{
targPtr->right = NULL;
minNode->parnt = NULL;
}
else //minNode->parnt != targ
{
struct Node *minParnt = minNode->parnt;
minNode->parnt = NULL;
minParnt->left = NULL;
struct Node *minRight = minNode->right;
minNode->right = NULL;
if (minRight)
{
minRight->parnt = NULL;
minRight->parnt = minParnt;
}
minParnt->left = minRight;
minNode->right = minParnt;
minParnt->parnt = minNode;
}
///minNode connect to targ
minNode->parnt = targParnt;
if (targParnt->right == targPtr)
{
//printf("!!\n");
targParnt->right = NULL;
targParnt->right = minNode;
}
else
{
targParnt->left = NULL;
targParnt->left = minNode;
}
minNode->left = targL;
targL->parnt = minNode;
free(targPtr);
targPtr = minNode;
//printf("-----------targ--------------------------------%p----------------------------------------------\n", targ);
}
else //in left child find maximum node
{
struct Node *maxNode = findMax(targPtr->left);
printf("max:%d(%p) H:%d\n", maxNode->data, maxNode, maxNode->height);
struct Node *targR = targPtr->right;
targPtr->right = NULL;
targR->parnt = NULL;
struct Node *targL = targPtr->left;
printf("targL:%d(%p) H:%d\n", targL->data, targL, targL->height);
struct Node *targParnt = targPtr->parnt;
targPtr->parnt = NULL;
if (maxNode->parnt == targPtr)
{
targPtr->left = NULL;
maxNode->parnt = NULL;
}
else //maxNode->parnt != targ
{
struct Node *maxParnt = maxNode->parnt;
maxNode->parnt = NULL;
maxParnt->right = NULL;
struct Node *maxLeft = maxNode->left;
maxNode->left = NULL;
if (maxLeft)
{
maxLeft->parnt = NULL;
maxLeft->parnt = maxParnt;
}
maxParnt->right = maxLeft;
maxNode->left = targL;
targL->parnt = maxNode;
}
///maxNode connect to targ
maxNode->parnt = targParnt;
if (targParnt->right == targPtr)
{
targParnt->right = NULL;
targParnt->right = maxNode;
}
else
{
targParnt->left = NULL;
targParnt->left = maxNode;
}
maxNode->right = targR;
targR->parnt = maxNode;
free(targPtr);
targPtr = maxNode;
}
}
getHigh(targPtr);
return;
}
}
int removal(struct Node **root, int target)
{
int couts = 0;
struct Node *cur = *root;
//first, counts how many nodes needed to be removed
inorder_counts(cur, &couts, target);
if (couts == 0)
return couts;
int tmp = 0;
while (tmp != couts)
{
//printf("tmp:%d\n", tmp);
/*printf("\n--------------------------------------------------\n");
inorder(*root);*/
delete_node(root, target);
tmp++;
//printf("tmp:%d\n", tmp);
printf("\n--------------------------------------------------\n");
inorder(*root);
printf("\n==================================================\n");
}
return couts;
}
int main()
{
struct Node *tree = NULL, *node;
int j, k, l;
srand(5);
for (j = 0; j < 15; j++)
{
node = (struct Node *)malloc(sizeof(struct Node));
node->data = rand() % 10;
printf("%d ", node->data);
printf("%d\n", j);
node->left = NULL;
node->right = NULL;
node->parnt = NULL;
node->height = 0;
insert(&tree, node);
}
printf("\n");
inorder(tree);
printf("\n");
for (j = 0; j < 10; j++)
{
l = rand() % 10;
printf("l:%d\t", l);
k = removal(&tree, l);
printf("Remove %d(%d)\n", l, k);
}
inorder(tree);
printf("\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.