filename
stringlengths
3
9
code
stringlengths
4
1.87M
365238.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The University of Texas at Austin 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. */ // Guard the function definitions so that they are only compiled when // #included from files that define the object API macros. #ifdef BLIS_ENABLE_OAPI // // Define object-based interfaces. // #undef GENFRONT #define GENFRONT( opname ) \ \ void PASTEMAC(opname,EX_SUF) \ ( \ obj_t* alpha, \ obj_t* a, \ obj_t* b, \ obj_t* beta, \ obj_t* c \ BLIS_OAPI_CNTX_PARAM \ ) \ { \ BLIS_OAPI_CNTX_DECL \ \ /* Invoke the operation's "ind" function--its induced method front-end. This function will call native execution for real domain problems. For complex problems, it calls the highest priority induced method that is available (ie: implemented and enabled), and if none are enabled, it calls native execution. */ \ PASTEMAC(opname,ind) \ ( \ alpha, \ a, \ b, \ beta, \ c, \ cntx \ ); \ } GENFRONT( gemm ) GENFRONT( her2k ) GENFRONT( syr2k ) #undef GENFRONT #define GENFRONT( opname ) \ \ void PASTEMAC(opname,EX_SUF) \ ( \ side_t side, \ obj_t* alpha, \ obj_t* a, \ obj_t* b, \ obj_t* beta, \ obj_t* c \ BLIS_OAPI_CNTX_PARAM \ ) \ { \ BLIS_OAPI_CNTX_DECL \ \ PASTEMAC(opname,ind) \ ( \ side, \ alpha, \ a, \ b, \ beta, \ c, \ cntx \ ); \ } GENFRONT( hemm ) GENFRONT( symm ) GENFRONT( trmm3 ) #undef GENFRONT #define GENFRONT( opname ) \ \ void PASTEMAC(opname,EX_SUF) \ ( \ obj_t* alpha, \ obj_t* a, \ obj_t* beta, \ obj_t* c \ BLIS_OAPI_CNTX_PARAM \ ) \ { \ BLIS_OAPI_CNTX_DECL \ \ PASTEMAC(opname,ind) \ ( \ alpha, \ a, \ beta, \ c, \ cntx \ ); \ } GENFRONT( herk ) GENFRONT( syrk ) #undef GENFRONT #define GENFRONT( opname ) \ \ void PASTEMAC(opname,EX_SUF) \ ( \ side_t side, \ obj_t* alpha, \ obj_t* a, \ obj_t* b \ BLIS_OAPI_CNTX_PARAM \ ) \ { \ BLIS_OAPI_CNTX_DECL \ \ PASTEMAC(opname,ind) \ ( \ side, \ alpha, \ a, \ b, \ cntx \ ); \ } GENFRONT( trmm ) GENFRONT( trsm ) #endif
996881.c
#include <FlailSnail/FlailSnail.h> int main(int argc, char* argv[]){ print_provenance_log(argc,argv); }
545188.c
float *CVE_2012_1960_VULN_build_input_gamma_table(struct curveType *TRC) { float *gamma_table; if (!TRC) return NULL; gamma_table = malloc(sizeof(float)*256); if (gamma_table) { if (TRC->type == PARAMETRIC_CURVE_TYPE) { compute_curve_gamma_table_type_parametric(gamma_table, TRC->parameter, TRC->count); } else { if (TRC->count == 0) { compute_curve_gamma_table_type0(gamma_table); } else if (TRC->count == 1) { compute_curve_gamma_table_type1(gamma_table, u8Fixed8Number_to_float(TRC->data[0])); } else { compute_curve_gamma_table_type2(gamma_table, TRC->data, TRC->count); } } } return gamma_table; }
583000.c
#include "rt64.h" #define KSTACK_SZ (PG_SZ4K * KSTACK_PAGES) static u8 kstacks[MAX_PROC][KSTACK_SZ] __page_align; static u8 ustacks[MAX_PROC][USTACK_SZ] __page_align; struct proc procs[MAX_PROC]; // For now: alloc proc just uses nproc++ -> no deletion of processes int nproc; __thread struct proc *curproc; void sched(void) { if (curproc->state == RUNNING) panic("sched running"); if (readeflags() & FL_IF) panic("sched interruptible"); struct proc *old = curproc; #ifdef DEBUG_SCHED cprintf("proc: sched %s -> %s\n", curproc->name, curcpu->idleproc->name); #endif curproc = curcpu->idleproc; lcr3(V2P(curproc->pt_root)); swtch(&old->ctx, curcpu->idlectx); ASSERT(curproc != curcpu->idleproc); } void yield(void) { ASSERT(curproc->state == RUNNING); cli(); // will sti in idle curproc->state = RUNNABLE; // must be after cli sched(); } // Insert the current thread (kerninit i.e. idle) into the process queue void procinit(void) { // This is a form of dynamic allocation actually curproc = &procs[nproc++]; curproc->state = RUNNING; safestrcpy(curproc->name, "idle", 16); // XXX: better be sprintf curproc->name[5] = '0' + curcpu->index; curproc->name[6] = '\0'; // kstack field is used for returning from user. // the init idle task does not accept returning from user. // nor does it have dedicated kstacks[*] pages. curproc->kstack = NULL; curproc->pt_root = kpml4; curproc->pid = nproc; curcpu->idlectx = &curproc->ctx; curcpu->idleproc = curproc; cprintf("[%d] proc: init\n", curcpu->index); } /* * Meat of the scheduler. */ struct proc *find_runnable_proc(void) { static int i = 0; // round robin while (1) { if (procs[i].state == RUNNABLE) { int old = i; i = (i + 1) % nproc; return &procs[old]; } i = (i + 1) % nproc; } return NULL; } void idlemain(void) { for (;;) { #ifdef DEBUG_SCHED cprintf("idle: enter\n"); #endif sti(); // TODO: lock ptable struct proc *p = 0; if ((p = find_runnable_proc())) { curproc = p; curproc->state = RUNNING; #ifdef DEBUG_SCHED cprintf("proc: sched %s -> %s\n", curcpu->idleproc->name, curproc->name); #endif // task switch boilerplate lcr3(V2P(curproc->pt_root)); set_task_kstack(); swtch(curcpu->idlectx, &curproc->ctx); ASSERT(curproc == curcpu->idleproc); } else { #ifndef CONFIG_IDLE_POOL hlt(); // WFI. #endif } } } /* * Allocate a struct proc from procs. * * Initializes fields: * pid ctx kstack state */ static struct proc *allocproc(void) { struct proc *p = &procs[nproc]; p->state = RESERVE; p->pid = nproc++; memset(&p->ctx, 0, sizeof(struct context)); p->kstack = kstacks[p->pid]; return p; } struct proc *spawn(struct newprocdesc *desc) { ASSERT(MINPRIO <= desc->prio && desc->prio <= MAXPRIO); struct proc *p = allocproc(); safestrcpy(p->name, desc->name, 16); p->prio = desc->prio; p->pt_root = kpml4; p->ctx.rip = (u64)desc->func; p->ctx.rsp = (u64)p->kstack + KSTACK_SZ; p->ctx.rbp = (u64)p->kstack + KSTACK_SZ; p->ctx.rdi = (u64)desc->initarg; // Leave room: when desc->func returns, automatically calls exit p->ctx.rsp -= XLENB; *(usize *)p->ctx.rsp = (usize)spawnret; // Leave room: swtch will store return address here p->ctx.rsp -= XLENB; // Set RUNNABLE only when everything has been setup p->state = RUNNABLE; // OPT: kfree this pid's ustack return p; } struct proc *spawnuser(struct newprocdesc *desc) { ASSERT(MINPRIO <= desc->prio && desc->prio <= MAXPRIO); struct proc *p = allocproc(); safestrcpy(p->name, desc->name, 16); p->prio = desc->prio; p->pt_root = upml4; p->ctx.rip = (u64)trapret; p->ctx.rsp = (u64)p->kstack + KSTACK_SZ; p->ctx.rbp = (u64)p->kstack + KSTACK_SZ; // Leave room: trapret restores initial registers from this trapframe p->ctx.rsp -= sizeof(struct trapframe); p->tf = (void *)p->ctx.rsp; memset(p->tf, 0, sizeof(struct trapframe)); // Leave room: swtch will store return address here p->ctx.rsp -= XLENB; void *ustack = ustacks[p->pid]; paging_map(p->pt_root, (usize)ustack, V2P(ustack), USTACK_SZ, PF_U | PF_W); p->tf->ss = (SEG_UDATA << 3) | DPL_USER; p->tf->rsp = (usize)ustack + PG_SZ4K; // Leave room: when user function returns, automatically calls usysexit p->tf->rsp -= XLENB; *(usize *)p->tf->rsp = (usize)spawnuserret; p->tf->rflags = FL_IF; p->tf->cs = (SEG_UCODE << 3) | DPL_USER; p->tf->rip = (u64)desc->func; p->tf->rdi = (u64)desc->initarg; // Set RUNNABLE only when everything has been setup p->state = RUNNABLE; return p; } void exit(void *retval) { ASSERT(curproc->state == RUNNING); cli(); curproc->state = EXITED; curproc->retval = retval; cprintf("proc: exited %s, retval=%p\n", curproc->name, retval); sched(); panic("proc: exit unreachable"); } void sleep(int nticks) { if (nticks < 0) panic("cannot sleep %d ticks", nticks); if (nticks == 0) return; ASSERT(curproc->state == RUNNING); cli(); // will sti in idle curproc->state = SLEEPING; // must be after cli curproc->sleeprem = nticks; sched(); }
816478.c
/* * MSACM library * * Copyright 1998 Patrik Stridvall * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdarg.h> #include "windef.h" #include "winbase.h" #include "winerror.h" #include "mmsystem.h" #include "mmreg.h" #include "msacm.h" #include "msacmdrv.h" #include "wineacm.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(msacm); /************************************************************************** * DllEntryPoint (MSACM.255) * * MSACM DLL entry point * */ BOOL WINAPI MSACM_DllEntryPoint(DWORD fdwReason, HINSTANCE16 hinstDLL, WORD ds, WORD wHeapSize, DWORD dwReserved1, WORD wReserved2) { static HANDLE hndl; TRACE("0x%x 0x%lx\n", hinstDLL, fdwReason); switch (fdwReason) { case DLL_PROCESS_ATTACH: if (!hndl && !(hndl = LoadLibraryA("MSACM32.DLL"))) { ERR("Could not load sibling MsAcm32.dll\n"); return FALSE; } break; case DLL_PROCESS_DETACH: FreeLibrary(hndl); hndl = 0; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } return TRUE; } /*********************************************************************** * acmGetVersion (MSACM.7) */ DWORD WINAPI acmGetVersion16(void) { return acmGetVersion(); } /*********************************************************************** * acmMetrics (MSACM.8) */ MMRESULT16 WINAPI acmMetrics16( HACMOBJ16 hao, UINT16 uMetric, LPVOID pMetric) { FIXME("(0x%04x, %d, %p): semi-stub\n", hao, uMetric, pMetric); if(!hao) return acmMetrics(0, uMetric, pMetric); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverEnum (MSACM.10) */ MMRESULT16 WINAPI acmDriverEnum16( ACMDRIVERENUMCB16 fnCallback, DWORD dwInstance, DWORD fdwEnum) { FIXME("(%p, %ld, %ld): stub\n", fnCallback, dwInstance, fdwEnum ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverDetails (MSACM.11) */ MMRESULT16 WINAPI acmDriverDetails16( HACMDRIVERID16 hadid, LPACMDRIVERDETAILS16 padd, DWORD fdwDetails) { FIXME("(0x%04x, %p, %ld): stub\n", hadid, padd, fdwDetails); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverAdd (MSACM.12) */ MMRESULT16 WINAPI acmDriverAdd16( LPHACMDRIVERID16 phadid, HINSTANCE16 hinstModule, LPARAM lParam, DWORD dwPriority, DWORD fdwAdd) { FIXME("(%p, 0x%04x, %ld, %ld, %ld): stub\n", phadid, hinstModule, lParam, dwPriority, fdwAdd ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverRemove (MSACM.13) */ MMRESULT16 WINAPI acmDriverRemove16( HACMDRIVERID16 hadid, DWORD fdwRemove) { FIXME("(0x%04x, %ld): stub\n", hadid, fdwRemove); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverOpen (MSACM.14) */ MMRESULT16 WINAPI acmDriverOpen16( LPHACMDRIVER16 phad, HACMDRIVERID16 hadid, DWORD fdwOpen) { FIXME("(%p, 0x%04x, %ld): stub\n", phad, hadid, fdwOpen); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverClose (MSACM.15) */ MMRESULT16 WINAPI acmDriverClose16( HACMDRIVER16 had, DWORD fdwClose) { FIXME("(0x%04x, %ld): stub\n", had, fdwClose); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverMessage (MSACM.16) */ LRESULT WINAPI acmDriverMessage16( HACMDRIVER16 had, UINT16 uMsg, LPARAM lParam1, LPARAM lParam2) { FIXME("(0x%04x, %d, %ld, %ld): stub\n", had, uMsg, lParam1, lParam2 ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return 0; } /*********************************************************************** * acmDriverID (MSACM.17) */ MMRESULT16 WINAPI acmDriverID16( HACMOBJ16 hao, LPHACMDRIVERID16 phadid, DWORD fdwDriverID) { FIXME("(0x%04x, %p, %ld): stub\n", hao, phadid, fdwDriverID); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmDriverPriority (MSACM.18) */ MMRESULT16 WINAPI acmDriverPriority16( HACMDRIVERID16 hadid, DWORD dwPriority, DWORD fdwPriority) { FIXME("(0x%04x, %ld, %ld): stub\n", hadid, dwPriority, fdwPriority ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatTagDetails (MSACM.30) */ MMRESULT16 WINAPI acmFormatTagDetails16( HACMDRIVER16 had, LPACMFORMATTAGDETAILS16 paftd, DWORD fdwDetails) { FIXME("(0x%04x, %p, %ld): stub\n", had, paftd, fdwDetails); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatTagEnum (MSACM.31) */ MMRESULT16 WINAPI acmFormatTagEnum16( HACMDRIVER16 had, LPACMFORMATTAGDETAILS16 paftd, ACMFORMATTAGENUMCB16 fnCallback, DWORD dwInstance, DWORD fdwEnum) { FIXME("(0x%04x, %p, %p, %ld, %ld): stub\n", had, paftd, fnCallback, dwInstance, fdwEnum ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatChoose (MSACM.40) */ MMRESULT16 WINAPI acmFormatChoose16( LPACMFORMATCHOOSE16 pafmtc) { FIXME("(%p): stub\n", pafmtc); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatDetails (MSACM.41) */ MMRESULT16 WINAPI acmFormatDetails16( HACMDRIVER16 had, LPACMFORMATDETAILS16 pafd, DWORD fdwDetails) { FIXME("(0x%04x, %p, %ld): stub\n", had, pafd, fdwDetails); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatEnum (MSACM.42) */ MMRESULT16 WINAPI acmFormatEnum16( HACMDRIVER16 had, LPACMFORMATDETAILS16 pafd, ACMFORMATENUMCB16 fnCallback, DWORD dwInstance, DWORD fdwEnum) { FIXME("(0x%04x, %p, %p, %ld, %ld): stub\n", had, pafd, fnCallback, dwInstance, fdwEnum ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFormatSuggest (MSACM.45) */ MMRESULT16 WINAPI acmFormatSuggest16( HACMDRIVER16 had, LPWAVEFORMATEX pwfxSrc, LPWAVEFORMATEX pwfxDst, DWORD cbwfxDst, DWORD fdwSuggest) { FIXME("(0x%04x, %p, %p, %ld, %ld): stub\n", had, pwfxSrc, pwfxDst, cbwfxDst, fdwSuggest ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFilterTagDetails (MSACM.50) */ MMRESULT16 WINAPI acmFilterTagDetails16( HACMDRIVER16 had, LPACMFILTERTAGDETAILS16 paftd, DWORD fdwDetails) { FIXME("(0x%04x, %p, %ld): stub\n", had, paftd, fdwDetails); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFilterTagEnum (MSACM.51) */ MMRESULT16 WINAPI acmFilterTagEnum16( HACMDRIVER16 had, LPACMFILTERTAGDETAILS16 paftd, ACMFILTERTAGENUMCB16 fnCallback, DWORD dwInstance, DWORD fdwEnum) { FIXME("(0x%04x, %p, %p, %ld, %ld): stub\n", had, paftd, fnCallback, dwInstance, fdwEnum ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFilterChoose (MSACM.60) */ MMRESULT16 WINAPI acmFilterChoose16( LPACMFILTERCHOOSE16 pafltrc) { FIXME("(%p): stub\n", pafltrc); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFilterDetails (MSACM.61) */ MMRESULT16 WINAPI acmFilterDetails16( HACMDRIVER16 had, LPACMFILTERDETAILS16 pafd, DWORD fdwDetails) { FIXME("(0x%04x, %p, %ld): stub\n", had, pafd, fdwDetails); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmFilterEnum (MSACM.62) */ MMRESULT16 WINAPI acmFilterEnum16( HACMDRIVER16 had, LPACMFILTERDETAILS16 pafd, ACMFILTERENUMCB16 fnCallback, DWORD dwInstance, DWORD fdwEnum) { FIXME("(0x%04x, %p, %p, %ld, %ld): stub\n", had, pafd, fnCallback, dwInstance, fdwEnum ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamOpen (MSACM.70) */ MMRESULT16 WINAPI acmStreamOpen16( LPHACMSTREAM16 phas, HACMDRIVER16 had, LPWAVEFORMATEX pwfxSrc, LPWAVEFORMATEX pwfxDst, LPWAVEFILTER pwfltr, DWORD dwCallback, DWORD dwInstance, DWORD fdwOpen) { FIXME("(%p, 0x%04x, %p, %p, %p, %ld, %ld, %ld): stub\n", phas, had, pwfxSrc, pwfxDst, pwfltr, dwCallback, dwInstance, fdwOpen ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamClose (MSACM.71) */ MMRESULT16 WINAPI acmStreamClose16( HACMSTREAM16 has, DWORD fdwClose) { FIXME("(0x%04x, %ld): stub\n", has, fdwClose); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamSize (MSACM.72) */ MMRESULT16 WINAPI acmStreamSize16( HACMSTREAM16 has, DWORD cbInput, LPDWORD pdwOutputBytes, DWORD fdwSize) { FIXME("(0x%04x, %ld, %p, %ld): stub\n", has, cbInput, pdwOutputBytes, fdwSize ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamConvert (MSACM.75) */ MMRESULT16 WINAPI acmStreamConvert16( HACMSTREAM16 has, LPACMSTREAMHEADER16 pash, DWORD fdwConvert) { FIXME("(0x%04x, %p, %ld): stub\n", has, pash, fdwConvert); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamReset (MSACM.76) */ MMRESULT16 WINAPI acmStreamReset16( HACMSTREAM16 has, DWORD fdwReset) { FIXME("(0x%04x, %ld): stub\n", has, fdwReset); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamPrepareHeader (MSACM.77) */ MMRESULT16 WINAPI acmStreamPrepareHeader16( HACMSTREAM16 has, LPACMSTREAMHEADER16 pash, DWORD fdwPrepare) { FIXME("(0x%04x, %p, %ld): stub\n", has, pash, fdwPrepare); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * acmStreamUnprepareHeader (MSACM.78) */ MMRESULT16 WINAPI acmStreamUnprepareHeader16( HACMSTREAM16 has, LPACMSTREAMHEADER16 pash, DWORD fdwUnprepare) { FIXME("(0x%04x, %p, %ld): stub\n", has, pash, fdwUnprepare ); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return MMSYSERR_ERROR; } /*********************************************************************** * ACMAPPLICATIONEXIT (MSACM.150) * FIXME * No documentation found. */ /*********************************************************************** * ACMHUGEPAGELOCK (MSACM.175) *FIXME * No documentation found. */ /*********************************************************************** * ACMHUGEPAGEUNLOCK (MSACM.176) * FIXME * No documentation found. */ /*********************************************************************** * ACMOPENCONVERSION (MSACM.200) * FIXME * No documentation found. */ /*********************************************************************** * ACMCLOSECONVERSION (MSACM.201) * FIXME * No documentation found. */ /*********************************************************************** * ACMCONVERT (MSACM.202) * FIXME * No documentation found. */ /*********************************************************************** * ACMCHOOSEFORMAT (MSACM.203) * FIXME * No documentation found. */
425837.c
/* * FreeRTOS Kernel V10.4.6 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* Standard includes. */ #include <stdlib.h> /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" /* Machine includes */ #include <machine/counter.h> #include <machine/ic.h> /*-----------------------------------------------------------*/ /* The initial PSR has the Previous Interrupt Enabled (PIEN) flag set. */ #define portINITIAL_PSR ( 0x00020000 ) /*-----------------------------------------------------------*/ /* * Perform any hardware configuration necessary to generate the tick interrupt. */ static void prvSetupTimerInterrupt( void ); /*-----------------------------------------------------------*/ StackType_t *pxPortInitialiseStack( StackType_t * pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) { /* Make space on the stack for the context - this leaves a couple of spaces empty. */ pxTopOfStack -= 20; /* Fill the registers with known values to assist debugging. */ pxTopOfStack[ 16 ] = 0; pxTopOfStack[ 15 ] = portINITIAL_PSR; pxTopOfStack[ 14 ] = ( uint32_t ) pxCode; pxTopOfStack[ 13 ] = 0x00000000UL; /* R15. */ pxTopOfStack[ 12 ] = 0x00000000UL; /* R14. */ pxTopOfStack[ 11 ] = 0x0d0d0d0dUL; pxTopOfStack[ 10 ] = 0x0c0c0c0cUL; pxTopOfStack[ 9 ] = 0x0b0b0b0bUL; pxTopOfStack[ 8 ] = 0x0a0a0a0aUL; pxTopOfStack[ 7 ] = 0x09090909UL; pxTopOfStack[ 6 ] = 0x08080808UL; pxTopOfStack[ 5 ] = 0x07070707UL; pxTopOfStack[ 4 ] = 0x06060606UL; pxTopOfStack[ 3 ] = 0x05050505UL; pxTopOfStack[ 2 ] = 0x04040404UL; pxTopOfStack[ 1 ] = 0x03030303UL; pxTopOfStack[ 0 ] = ( uint32_t ) pvParameters; return pxTopOfStack; } /*-----------------------------------------------------------*/ BaseType_t xPortStartScheduler( void ) { /* Set-up the timer interrupt. */ prvSetupTimerInterrupt(); /* Integrated Interrupt Controller: Enable all interrupts. */ ic->ien = 1; /* Restore callee saved registers. */ portRESTORE_CONTEXT(); /* Should not get here. */ return 0; } /*-----------------------------------------------------------*/ static void prvSetupTimerInterrupt( void ) { /* Enable timer interrupts */ counter1->reload = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1; counter1->value = counter1->reload; counter1->mask = 1; /* Set the IRQ Handler priority and enable it. */ irq[ IRQ_COUNTER1 ].ien = 1; } /*-----------------------------------------------------------*/ /* Trap 31 handler. */ void interrupt31_handler( void ) __attribute__((naked)); void interrupt31_handler( void ) { portSAVE_CONTEXT(); __asm volatile ( "call vTaskSwitchContext" ); portRESTORE_CONTEXT(); } /*-----------------------------------------------------------*/ static void prvProcessTick( void ) __attribute__((noinline)); static void prvProcessTick( void ) { if( xTaskIncrementTick() != pdFALSE ) { vTaskSwitchContext(); } /* Clear the Tick Interrupt. */ counter1->expired = 0; } /*-----------------------------------------------------------*/ /* Timer 1 interrupt handler, used for tick interrupt. */ void interrupt7_handler( void ) __attribute__((naked)); void interrupt7_handler( void ) { portSAVE_CONTEXT(); prvProcessTick(); portRESTORE_CONTEXT(); } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* Nothing to do. Unlikely to want to end. */ } /*-----------------------------------------------------------*/
523854.c
// gcc -mpreferred-stack-boundary=2 -ggdb function.c -o function /* (gdb) disas function ;; function prelude ; push the stack base pointer so we can restore it after this function returns 0x080483fb <+0>: push %ebp ; save the stack pointer to the base pointer, so the base pointer ; points to the start of this function's stack frame 0x080483fc <+1>: mov %esp,%ebp ; grow the stack to allocate room for this function's locals ; (24 bits: 5 * 4 + 1, rounded up to 4 byte boundary) 0x080483fe <+3>: sub $0x1c,%esp ;; function body 0x08048401 <+6>: mov 0x8(%ebp),%edx 0x08048404 <+9>: mov 0xc(%ebp),%eax 0x08048407 <+12>: add %eax,%edx ; promote char to int 0x08048409 <+14>: movsbl -0x1(%ebp),%eax 0x0804840d <+18>: add %edx,%eax ;; function epilog ; restore esp and ebp to their state before this function call 0x08048401 <+6>: leave ; return to the next instruction after this function call ; (printf in main in this program) 0x08048402 <+7>: ret */ #include <stdio.h> int function(int a, int b) { int array[5]; char c; return a + b + c; } int main(void) { function(1, 2); printf("`function` return address points here\n"); }
54824.c
child_req
245695.c
/****************************************************************************** * Code generated with sympy 0.7.6 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'project' * ******************************************************************************/ #include "middle_prox_thumb_prox_side_1.h" #include <math.h> double middle_prox_thumb_prox_side_1() { double middle_prox_thumb_prox_side_1_result; middle_prox_thumb_prox_side_1_result = 0; return middle_prox_thumb_prox_side_1_result; }
485063.c
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: wmi.c Abstract: This module contains the code that handles the wmi IRPs for the serial driver. Environment: Kernel mode Revision History : --*/ #include "precomp.h" #include <wmistr.h> #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGESRP0, SerialSystemControlDispatch) #pragma alloc_text(PAGESRP0, SerialTossWMIRequest) #pragma alloc_text(PAGESRP0, SerialSetWmiDataItem) #pragma alloc_text(PAGESRP0, SerialSetWmiDataBlock) #pragma alloc_text(PAGESRP0, SerialQueryWmiDataBlock) #pragma alloc_text(PAGESRP0, SerialQueryWmiRegInfo) #endif NTSTATUS SerialSystemControlDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { SYSCTL_IRP_DISPOSITION disposition; NTSTATUS status; PSERIAL_DEVICE_EXTENSION pDevExt = (PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension; PAGED_CODE(); status = WmiSystemControl( &pDevExt->WmiLibInfo, DeviceObject, Irp, &disposition); switch(disposition) { case IrpProcessed: { // // This irp has been processed and may be completed or pending. break; } case IrpNotCompleted: { // // This irp has not been completed, but has been fully processed. // we will complete it now IoCompleteRequest(Irp, IO_NO_INCREMENT); break; } case IrpForward: case IrpNotWmi: { // // This irp is either not a WMI irp or is a WMI irp targetted // at a device lower in the stack. IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(pDevExt->LowerDeviceObject, Irp); break; } default: { // // We really should never get here, but if we do just forward.... ASSERT(FALSE); IoSkipCurrentIrpStackLocation(Irp); status = IoCallDriver(pDevExt->LowerDeviceObject, Irp); break; } } return(status); } #define WMI_SERIAL_PORT_NAME_INFORMATION 0 #define WMI_SERIAL_PORT_COMM_INFORMATION 1 #define WMI_SERIAL_PORT_HW_INFORMATION 2 #define WMI_SERIAL_PORT_PERF_INFORMATION 3 #define WMI_SERIAL_PORT_PROPERTIES 4 GUID SerialPortNameGuid = SERIAL_PORT_WMI_NAME_GUID; GUID SerialPortCommGuid = SERIAL_PORT_WMI_COMM_GUID; GUID SerialPortHWGuid = SERIAL_PORT_WMI_HW_GUID; GUID SerailPortPerfGuid = SERIAL_PORT_WMI_PERF_GUID; GUID SerialPortPropertiesGuid = SERIAL_PORT_WMI_PROPERTIES_GUID; WMIGUIDREGINFO SerialWmiGuidList[SERIAL_WMI_GUID_LIST_SIZE] = { { &SerialPortNameGuid, 1, 0 }, { &SerialPortCommGuid, 1, 0 }, { &SerialPortHWGuid, 1, 0 }, { &SerailPortPerfGuid, 1, 0 }, { &SerialPortPropertiesGuid, 1, 0} }; // // WMI System Call back functions // NTSTATUS SerialTossWMIRequest(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp, IN ULONG GuidIndex) { PSERIAL_DEVICE_EXTENSION pDevExt; NTSTATUS status; PAGED_CODE(); pDevExt = (PSERIAL_DEVICE_EXTENSION)PDevObj->DeviceExtension; switch (GuidIndex) { case WMI_SERIAL_PORT_NAME_INFORMATION: case WMI_SERIAL_PORT_COMM_INFORMATION: case WMI_SERIAL_PORT_HW_INFORMATION: case WMI_SERIAL_PORT_PERF_INFORMATION: case WMI_SERIAL_PORT_PROPERTIES: status = STATUS_INVALID_DEVICE_REQUEST; break; default: status = STATUS_WMI_GUID_NOT_FOUND; break; } status = WmiCompleteRequest(PDevObj, PIrp, status, 0, IO_NO_INCREMENT); return status; } NTSTATUS SerialSetWmiDataItem(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp, IN ULONG GuidIndex, IN ULONG InstanceIndex, IN ULONG DataItemId, IN ULONG BufferSize, IN PUCHAR PBuffer) /*++ Routine Description: This routine is a callback into the driver to set for the contents of a data block. When the driver has finished filling the data block it must call ClassWmiCompleteRequest to complete the irp. The driver can return STATUS_PENDING if the irp cannot be completed immediately. Arguments: PDevObj is the device whose data block is being queried PIrp is the Irp that makes this request GuidIndex is the index into the list of guids provided when the device registered InstanceIndex is the index that denotes which instance of the data block is being queried. DataItemId has the id of the data item being set BufferSize has the size of the data item passed PBuffer has the new values for the data item Return Value: status --*/ { PAGED_CODE(); // // Toss this request -- we don't support anything for it // return SerialTossWMIRequest(PDevObj, PIrp, GuidIndex); } NTSTATUS SerialSetWmiDataBlock(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp, IN ULONG GuidIndex, IN ULONG InstanceIndex, IN ULONG BufferSize, IN PUCHAR PBuffer) /*++ Routine Description: This routine is a callback into the driver to set the contents of a data block. When the driver has finished filling the data block it must call ClassWmiCompleteRequest to complete the irp. The driver can return STATUS_PENDING if the irp cannot be completed immediately. Arguments: PDevObj is the device whose data block is being queried PIrp is the Irp that makes this request GuidIndex is the index into the list of guids provided when the device registered InstanceIndex is the index that denotes which instance of the data block is being queried. BufferSize has the size of the data block passed PBuffer has the new values for the data block Return Value: status --*/ { PAGED_CODE(); // // Toss this request -- we don't support anything for it // return SerialTossWMIRequest(PDevObj, PIrp, GuidIndex); } NTSTATUS SerialQueryWmiDataBlock(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp, IN ULONG GuidIndex, IN ULONG InstanceIndex, IN ULONG InstanceCount, IN OUT PULONG InstanceLengthArray, IN ULONG OutBufferSize, OUT PUCHAR PBuffer) /*++ Routine Description: This routine is a callback into the driver to query for the contents of a data block. When the driver has finished filling the data block it must call ClassWmiCompleteRequest to complete the irp. The driver can return STATUS_PENDING if the irp cannot be completed immediately. Arguments: PDevObj is the device whose data block is being queried PIrp is the Irp that makes this request GuidIndex is the index into the list of guids provided when the device registered InstanceIndex is the index that denotes which instance of the data block is being queried. InstanceCount is the number of instnaces expected to be returned for the data block. InstanceLengthArray is a pointer to an array of ULONG that returns the lengths of each instance of the data block. If this is NULL then there was not enough space in the output buffer to fufill the request so the irp should be completed with the buffer needed. BufferAvail on has the maximum size available to write the data block. PBuffer on return is filled with the returned data block Return Value: status --*/ { NTSTATUS status; ULONG size = 0; PSERIAL_DEVICE_EXTENSION pDevExt = (PSERIAL_DEVICE_EXTENSION)PDevObj->DeviceExtension; PAGED_CODE(); switch (GuidIndex) { case WMI_SERIAL_PORT_NAME_INFORMATION: size = pDevExt->WmiIdentifier.Length; if (OutBufferSize < (size + sizeof(USHORT))) { size += sizeof(USHORT); status = STATUS_BUFFER_TOO_SMALL; break; } if (pDevExt->WmiIdentifier.Buffer == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; break; } // // First, copy the string over containing our identifier // *(USHORT *)PBuffer = (USHORT)size; (UCHAR *)PBuffer += sizeof(USHORT); RtlCopyMemory(PBuffer, pDevExt->WmiIdentifier.Buffer, size); // // Increment total size to include the WORD containing our len // size += sizeof(USHORT); *InstanceLengthArray = size; status = STATUS_SUCCESS; break; case WMI_SERIAL_PORT_COMM_INFORMATION: size = sizeof(SERIAL_WMI_COMM_DATA); if (OutBufferSize < size) { status = STATUS_BUFFER_TOO_SMALL; break; } *InstanceLengthArray = size; *(PSERIAL_WMI_COMM_DATA)PBuffer = pDevExt->WmiCommData; status = STATUS_SUCCESS; break; case WMI_SERIAL_PORT_HW_INFORMATION: size = sizeof(SERIAL_WMI_HW_DATA); if (OutBufferSize < size) { status = STATUS_BUFFER_TOO_SMALL; break; } *InstanceLengthArray = size; *(PSERIAL_WMI_HW_DATA)PBuffer = pDevExt->WmiHwData; status = STATUS_SUCCESS; break; case WMI_SERIAL_PORT_PERF_INFORMATION: size = sizeof(SERIAL_WMI_PERF_DATA); if (OutBufferSize < size) { status = STATUS_BUFFER_TOO_SMALL; break; } *InstanceLengthArray = size; *(PSERIAL_WMI_PERF_DATA)PBuffer = pDevExt->WmiPerfData; status = STATUS_SUCCESS; break; case WMI_SERIAL_PORT_PROPERTIES: size = sizeof(SERIAL_COMMPROP) + sizeof(ULONG); if (OutBufferSize < size) { status = STATUS_BUFFER_TOO_SMALL; break; } *InstanceLengthArray = size; SerialGetProperties( pDevExt, (PSERIAL_COMMPROP)PBuffer ); *((PULONG)(((PSERIAL_COMMPROP)PBuffer)->ProvChar)) = 0; status = STATUS_SUCCESS; break; default: status = STATUS_WMI_GUID_NOT_FOUND; break; } status = WmiCompleteRequest( PDevObj, PIrp, status, size, IO_NO_INCREMENT); return status; } NTSTATUS SerialQueryWmiRegInfo(IN PDEVICE_OBJECT PDevObj, OUT PULONG PRegFlags, OUT PUNICODE_STRING PInstanceName, OUT PUNICODE_STRING *PRegistryPath, OUT PUNICODE_STRING MofResourceName, OUT PDEVICE_OBJECT *Pdo) /*++ Routine Description: This routine is a callback into the driver to retrieve information about the guids being registered. Implementations of this routine may be in paged memory Arguments: DeviceObject is the device whose registration information is needed *RegFlags returns with a set of flags that describe all of the guids being registered for this device. If the device wants enable and disable collection callbacks before receiving queries for the registered guids then it should return the WMIREG_FLAG_EXPENSIVE flag. Also the returned flags may specify WMIREG_FLAG_INSTANCE_PDO in which case the instance name is determined from the PDO associated with the device object. Note that the PDO must have an associated devnode. If WMIREG_FLAG_INSTANCE_PDO is not set then Name must return a unique name for the device. These flags are ORed into the flags specified by the GUIDREGINFO for each guid. InstanceName returns with the instance name for the guids if WMIREG_FLAG_INSTANCE_PDO is not set in the returned *RegFlags. The caller will call ExFreePool with the buffer returned. *RegistryPath returns with the registry path of the driver. This is required *MofResourceName returns with the name of the MOF resource attached to the binary file. If the driver does not have a mof resource attached then this can be returned as NULL. *Pdo returns with the device object for the PDO associated with this device if the WMIREG_FLAG_INSTANCE_PDO flag is retured in *RegFlags. Return Value: status --*/ { PSERIAL_DEVICE_EXTENSION pDevExt = (PSERIAL_DEVICE_EXTENSION)PDevObj->DeviceExtension; PAGED_CODE(); *PRegFlags = WMIREG_FLAG_INSTANCE_PDO; *PRegistryPath = &SerialGlobals.RegistryPath; *Pdo = pDevExt->Pdo; return STATUS_SUCCESS; }
282495.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_Euclid.h" /* #include "Euclid_dh.h" */ /* #include "krylov_dh.h" */ /* #include "Mem_dh.h" */ /* #include "Parser_dh.h" */ /* #include "Mat_dh.h" */ #undef __FUNC__ #define __FUNC__ "bicgstab_euclid" void bicgstab_euclid(Mat_dh A, Euclid_dh ctx, HYPRE_Real *x, HYPRE_Real *b, HYPRE_Int *itsOUT) { START_FUNC_DH HYPRE_Int its, m = ctx->m; bool monitor; HYPRE_Int maxIts = ctx->maxIts; HYPRE_Real atol = ctx->atol, rtol = ctx->rtol; /* scalars */ HYPRE_Real alpha, alpha_1, beta_1, widget, widget_1, rho_1, rho_2, s_norm, eps, exit_a, b_iprod, r_iprod; /* vectors */ HYPRE_Real *t, *s, *s_hat, *v, *p, *p_hat, *r, *r_hat; monitor = Parser_dhHasSwitch(parser_dh, "-monitor"); /* allocate working space */ t = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); s = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); s_hat = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); v = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); p = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); p_hat = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); r = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); r_hat = (HYPRE_Real*)MALLOC_DH(m*sizeof(HYPRE_Real)); /* r = b - Ax */ Mat_dhMatVec(A, x, s); /* s = Ax */ CopyVec(m, b, r); /* r = b */ Axpy(m, -1.0, s, r); /* r = b-Ax */ CopyVec(m, r, r_hat); /* r_hat = r */ /* compute stopping criteria */ b_iprod = InnerProd(m, b, b); CHECK_V_ERROR; exit_a = atol*atol*b_iprod; CHECK_V_ERROR; /* absolute stopping criteria */ eps = rtol*rtol*b_iprod; /* relative stoping criteria (residual reduction) */ its = 0; while(1) { ++its; rho_1 = InnerProd(m, r_hat, r); if (rho_1 == 0) { SET_V_ERROR("(r_hat . r) = 0; method fails"); } if (its == 1) { CopyVec(m, r, p); /* p = r_0 */ CHECK_V_ERROR; } else { beta_1 = (rho_1/rho_2)*(alpha_1/widget_1); /* p_i = r_(i-1) + beta_(i-1)*( p_(i-1) - w_(i-1)*v_(i-1) ) */ Axpy(m, -widget_1, v, p); CHECK_V_ERROR; ScaleVec(m, beta_1, p); CHECK_V_ERROR; Axpy(m, 1.0, r, p); CHECK_V_ERROR; } /* solve M*p_hat = p_i */ Euclid_dhApply(ctx, p, p_hat); CHECK_V_ERROR; /* v_i = A*p_hat */ Mat_dhMatVec(A, p_hat, v); CHECK_V_ERROR; /* alpha_i = rho_(i-1) / (r_hat^T . v_i ) */ { HYPRE_Real tmp = InnerProd(m, r_hat, v); CHECK_V_ERROR; alpha = rho_1/tmp; } /* s = r_(i-1) - alpha_i*v_i */ CopyVec(m, r, s); CHECK_V_ERROR; Axpy(m, -alpha, v, s); CHECK_V_ERROR; /* check norm of s; if small enough: * set x_i = x_(i-1) + alpha_i*p_i and stop. * (Actually, we use the square of the norm) */ s_norm = InnerProd(m, s, s); if (s_norm < exit_a) { SET_INFO("reached absolute stopping criteria"); break; } /* solve M*s_hat = s */ Euclid_dhApply(ctx, s, s_hat); CHECK_V_ERROR; /* t = A*s_hat */ Mat_dhMatVec(A, s_hat, t); CHECK_V_ERROR; /* w_i = (t . s)/(t . t) */ { HYPRE_Real tmp1, tmp2; tmp1 = InnerProd(m, t, s); CHECK_V_ERROR; tmp2 = InnerProd(m, t, t); CHECK_V_ERROR; widget = tmp1/tmp2; } /* x_i = x_(i-1) + alpha_i*p_hat + w_i*s_hat */ Axpy(m, alpha, p_hat, x); CHECK_V_ERROR; Axpy(m, widget, s_hat, x); CHECK_V_ERROR; /* r_i = s - w_i*t */ CopyVec(m, s, r); CHECK_V_ERROR; Axpy(m, -widget, t, r); CHECK_V_ERROR; /* check convergence; continue if necessary; * for continuation it is necessary thea w != 0. */ r_iprod = InnerProd(m, r, r); CHECK_V_ERROR; if (r_iprod < eps) { SET_INFO("stipulated residual reduction achieved"); break; } /* monitor convergence */ if (monitor && myid_dh == 0) { hypre_fprintf(stderr, "[it = %i] %e\n", its, sqrt(r_iprod/b_iprod)); } /* prepare for next iteration */ rho_2 = rho_1; widget_1 = widget; alpha_1 = alpha; if (its >= maxIts) { its = -its; break; } } *itsOUT = its; FREE_DH(t); FREE_DH(s); FREE_DH(s_hat); FREE_DH(v); FREE_DH(p); FREE_DH(p_hat); FREE_DH(r); FREE_DH(r_hat); END_FUNC_DH } #undef __FUNC__ #define __FUNC__ "cg_euclid" void cg_euclid(Mat_dh A, Euclid_dh ctx, HYPRE_Real *x, HYPRE_Real *b, HYPRE_Int *itsOUT) { START_FUNC_DH HYPRE_Int its, m = A->m; HYPRE_Real *p, *r, *s; HYPRE_Real alpha, beta, gamma, gamma_old, eps, bi_prod, i_prod; bool monitor; HYPRE_Int maxIts = ctx->maxIts; /* HYPRE_Real atol = ctx->atol */ HYPRE_Real rtol = ctx->rtol; monitor = Parser_dhHasSwitch(parser_dh, "-monitor"); /* compute square of absolute stopping threshold */ /* bi_prod = <b,b> */ bi_prod = InnerProd(m, b, b); CHECK_V_ERROR; eps = (rtol*rtol)*bi_prod; p = (HYPRE_Real *) MALLOC_DH(m * sizeof(HYPRE_Real)); s = (HYPRE_Real *) MALLOC_DH(m * sizeof(HYPRE_Real)); r = (HYPRE_Real *) MALLOC_DH(m * sizeof(HYPRE_Real)); /* r = b - Ax */ Mat_dhMatVec(A, x, r); /* r = Ax */ CHECK_V_ERROR; ScaleVec(m, -1.0, r); /* r = b */ CHECK_V_ERROR; Axpy(m, 1.0, b, r); /* r = r + b */ CHECK_V_ERROR; /* solve Mp = r */ Euclid_dhApply(ctx, r, p); CHECK_V_ERROR; /* gamma = <r,p> */ gamma = InnerProd(m, r, p); CHECK_V_ERROR; its = 0; while (1) { ++its; /* s = A*p */ Mat_dhMatVec(A, p, s); CHECK_V_ERROR; /* alpha = gamma / <s,p> */ { HYPRE_Real tmp = InnerProd(m, s, p); CHECK_V_ERROR; alpha = gamma / tmp; gamma_old = gamma; } /* x = x + alpha*p */ Axpy(m, alpha, p, x); CHECK_V_ERROR; /* r = r - alpha*s */ Axpy(m, -alpha, s, r); CHECK_V_ERROR; /* solve Ms = r */ Euclid_dhApply(ctx, r, s); CHECK_V_ERROR; /* gamma = <r,s> */ gamma = InnerProd(m, r, s); CHECK_V_ERROR; /* set i_prod for convergence test */ i_prod = InnerProd(m, r, r); CHECK_V_ERROR; if (monitor && myid_dh == 0) { hypre_fprintf(stderr, "iter = %i rel. resid. norm: %e\n", its, sqrt(i_prod/bi_prod)); } /* check for convergence */ if (i_prod < eps) break; /* beta = gamma / gamma_old */ beta = gamma / gamma_old; /* p = s + beta p */ ScaleVec(m, beta, p); CHECK_V_ERROR; Axpy(m, 1.0, s, p); CHECK_V_ERROR; if (its >= maxIts) { its = -its; break; } } *itsOUT = its; FREE_DH(p); FREE_DH(s); FREE_DH(r); END_FUNC_DH }
625777.c
/* ====================================================================== clip.c Functions for LWO2 image references. Ernie Wright 17 Sep 00 ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* ====================================================================== lwFreeClip() Free memory used by an lwClip. ====================================================================== */ void lwFreeClip( lwClip *clip ){ if ( clip ) { lwListFree( clip->ifilter, (void *) lwFreePlugin ); lwListFree( clip->pfilter, (void *) lwFreePlugin ); switch ( clip->type ) { case ID_STIL: _pico_free( clip->source.still.name ); break; case ID_ISEQ: _pico_free( clip->source.seq.prefix ); _pico_free( clip->source.seq.suffix ); break; case ID_ANIM: _pico_free( clip->source.anim.name ); _pico_free( clip->source.anim.server ); _pico_free( clip->source.anim.data ); break; case ID_XREF: _pico_free( clip->source.xref.string ); break; case ID_STCC: _pico_free( clip->source.cycle.name ); break; default: break; } _pico_free( clip ); } } /* ====================================================================== lwGetClip() Read image references from a CLIP chunk in an LWO2 file. ====================================================================== */ lwClip *lwGetClip( picoMemStream_t *fp, int cksize ){ lwClip *clip; lwPlugin *filt; unsigned int id; unsigned short sz; int pos, rlen; /* allocate the Clip structure */ clip = _pico_calloc( 1, sizeof( lwClip ) ); if ( !clip ) { goto Fail; } clip->contrast.val = 1.0f; clip->brightness.val = 1.0f; clip->saturation.val = 1.0f; clip->gamma.val = 1.0f; /* remember where we started */ set_flen( 0 ); pos = _pico_memstream_tell( fp ); /* index */ clip->index = getI4( fp ); /* first subchunk header */ clip->type = getU4( fp ); sz = getU2( fp ); if ( 0 > get_flen() ) { goto Fail; } sz += sz & 1; set_flen( 0 ); switch ( clip->type ) { case ID_STIL: clip->source.still.name = getS0( fp ); break; case ID_ISEQ: clip->source.seq.digits = getU1( fp ); clip->source.seq.flags = getU1( fp ); clip->source.seq.offset = getI2( fp ); getU2( fp ); /* not sure what this is yet */ clip->source.seq.start = getI2( fp ); clip->source.seq.end = getI2( fp ); clip->source.seq.prefix = getS0( fp ); clip->source.seq.suffix = getS0( fp ); break; case ID_ANIM: clip->source.anim.name = getS0( fp ); clip->source.anim.server = getS0( fp ); rlen = get_flen(); clip->source.anim.data = getbytes( fp, sz - rlen ); break; case ID_XREF: clip->source.xref.index = getI4( fp ); clip->source.xref.string = getS0( fp ); break; case ID_STCC: clip->source.cycle.lo = getI2( fp ); clip->source.cycle.hi = getI2( fp ); clip->source.cycle.name = getS0( fp ); break; default: break; } /* error while reading current subchunk? */ rlen = get_flen(); if ( rlen < 0 || rlen > sz ) { goto Fail; } /* skip unread parts of the current subchunk */ if ( rlen < sz ) { _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); } /* end of the CLIP chunk? */ rlen = _pico_memstream_tell( fp ) - pos; if ( cksize < rlen ) { goto Fail; } if ( cksize == rlen ) { return clip; } /* process subchunks as they're encountered */ id = getU4( fp ); sz = getU2( fp ); if ( 0 > get_flen() ) { goto Fail; } while ( 1 ) { sz += sz & 1; set_flen( 0 ); switch ( id ) { case ID_TIME: clip->start_time = getF4( fp ); clip->duration = getF4( fp ); clip->frame_rate = getF4( fp ); break; case ID_CONT: clip->contrast.val = getF4( fp ); clip->contrast.eindex = getVX( fp ); break; case ID_BRIT: clip->brightness.val = getF4( fp ); clip->brightness.eindex = getVX( fp ); break; case ID_SATR: clip->saturation.val = getF4( fp ); clip->saturation.eindex = getVX( fp ); break; case ID_HUE: clip->hue.val = getF4( fp ); clip->hue.eindex = getVX( fp ); break; case ID_GAMM: clip->gamma.val = getF4( fp ); clip->gamma.eindex = getVX( fp ); break; case ID_NEGA: clip->negative = getU2( fp ); break; case ID_IFLT: case ID_PFLT: filt = _pico_calloc( 1, sizeof( lwPlugin ) ); if ( !filt ) { goto Fail; } filt->name = getS0( fp ); filt->flags = getU2( fp ); rlen = get_flen(); filt->data = getbytes( fp, sz - rlen ); if ( id == ID_IFLT ) { lwListAdd( (void *) &clip->ifilter, filt ); clip->nifilters++; } else { lwListAdd( (void *) &clip->pfilter, filt ); clip->npfilters++; } break; default: break; } /* error while reading current subchunk? */ rlen = get_flen(); if ( rlen < 0 || rlen > sz ) { goto Fail; } /* skip unread parts of the current subchunk */ if ( rlen < sz ) { _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); } /* end of the CLIP chunk? */ rlen = _pico_memstream_tell( fp ) - pos; if ( cksize < rlen ) { goto Fail; } if ( cksize == rlen ) { break; } /* get the next chunk header */ set_flen( 0 ); id = getU4( fp ); sz = getU2( fp ); if ( 6 != get_flen() ) { goto Fail; } } return clip; Fail: lwFreeClip( clip ); return NULL; } /* ====================================================================== lwFindClip() Returns an lwClip pointer, given a clip index. ====================================================================== */ lwClip *lwFindClip( lwClip *list, int index ){ lwClip *clip; clip = list; while ( clip ) { if ( clip->index == index ) { break; } clip = clip->next; } return clip; }
911793.c
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <assert.h> #include <limits.h> #include "config/aom_scale_rtcd.h" #include "aom_dsp/aom_dsp_common.h" #include "aom_dsp/psnr.h" #include "aom_mem/aom_mem.h" #include "aom_ports/mem.h" #include "av1/common/av1_loopfilter.h" #include "av1/common/onyxc_int.h" #include "av1/common/quant_common.h" #include "av1/encoder/av1_quantize.h" #include "av1/encoder/encoder.h" #include "av1/encoder/picklpf.h" static void yv12_copy_plane(const YV12_BUFFER_CONFIG *src_bc, YV12_BUFFER_CONFIG *dst_bc, int plane) { switch (plane) { case 0: aom_yv12_copy_y(src_bc, dst_bc); break; case 1: aom_yv12_copy_u(src_bc, dst_bc); break; case 2: aom_yv12_copy_v(src_bc, dst_bc); break; default: assert(plane >= 0 && plane <= 2); break; } } int av1_get_max_filter_level(const AV1_COMP *cpi) { if (cpi->oxcf.pass == 2) { return cpi->twopass.section_intra_rating > 8 ? MAX_LOOP_FILTER * 3 / 4 : MAX_LOOP_FILTER; } else { return MAX_LOOP_FILTER; } } static int64_t try_filter_frame(const YV12_BUFFER_CONFIG *sd, AV1_COMP *const cpi, int filt_level, int partial_frame, int plane, int dir) { AV1_COMMON *const cm = &cpi->common; int64_t filt_err; assert(plane >= 0 && plane <= 2); int filter_level[2] = { filt_level, filt_level }; if (plane == 0 && dir == 0) filter_level[1] = cm->lf.filter_level[1]; if (plane == 0 && dir == 1) filter_level[0] = cm->lf.filter_level[0]; // set base filters for use of get_filter_level when in DELTA_Q_LF mode switch (plane) { case 0: cm->lf.filter_level[0] = filter_level[0]; cm->lf.filter_level[1] = filter_level[1]; break; case 1: cm->lf.filter_level_u = filter_level[0]; break; case 2: cm->lf.filter_level_v = filter_level[0]; break; } // TODO(any): please enable multi-thread and remove the flag when loop // filter mask is compatible with multi-thread. #if LOOP_FILTER_BITMASK av1_loop_filter_frame(cm->frame_to_show, cm, &cpi->td.mb.e_mbd, plane, plane + 1, partial_frame); #else if (cpi->num_workers > 1) av1_loop_filter_frame_mt(cm->frame_to_show, cm, &cpi->td.mb.e_mbd, plane, plane + 1, partial_frame, cpi->workers, cpi->num_workers, &cpi->lf_row_sync); else av1_loop_filter_frame(cm->frame_to_show, cm, &cpi->td.mb.e_mbd, plane, plane + 1, partial_frame); #endif filt_err = aom_get_sse_plane(sd, cm->frame_to_show, plane, cm->seq_params.use_highbitdepth); // Re-instate the unfiltered frame yv12_copy_plane(&cpi->last_frame_uf, cm->frame_to_show, plane); return filt_err; } static int search_filter_level(const YV12_BUFFER_CONFIG *sd, AV1_COMP *cpi, int partial_frame, const int *last_frame_filter_level, double *best_cost_ret, int plane, int dir) { const AV1_COMMON *const cm = &cpi->common; const int min_filter_level = 0; const int max_filter_level = av1_get_max_filter_level(cpi); int filt_direction = 0; int64_t best_err; int filt_best; MACROBLOCK *x = &cpi->td.mb; // Start the search at the previous frame filter level unless it is now out of // range. int lvl; switch (plane) { case 0: lvl = last_frame_filter_level[dir]; break; case 1: lvl = last_frame_filter_level[2]; break; case 2: lvl = last_frame_filter_level[3]; break; default: assert(plane >= 0 && plane <= 2); return 0; } int filt_mid = clamp(lvl, min_filter_level, max_filter_level); int filter_step = filt_mid < 16 ? 4 : filt_mid / 4; // Sum squared error at each filter level int64_t ss_err[MAX_LOOP_FILTER + 1]; // Set each entry to -1 memset(ss_err, 0xFF, sizeof(ss_err)); yv12_copy_plane(cm->frame_to_show, &cpi->last_frame_uf, plane); best_err = try_filter_frame(sd, cpi, filt_mid, partial_frame, plane, dir); filt_best = filt_mid; ss_err[filt_mid] = best_err; while (filter_step > 0) { const int filt_high = AOMMIN(filt_mid + filter_step, max_filter_level); const int filt_low = AOMMAX(filt_mid - filter_step, min_filter_level); // Bias against raising loop filter in favor of lowering it. int64_t bias = (best_err >> (15 - (filt_mid / 8))) * filter_step; if ((cpi->oxcf.pass == 2) && (cpi->twopass.section_intra_rating < 20)) bias = (bias * cpi->twopass.section_intra_rating) / 20; // yx, bias less for large block size if (cm->tx_mode != ONLY_4X4) bias >>= 1; if (filt_direction <= 0 && filt_low != filt_mid) { // Get Low filter error score if (ss_err[filt_low] < 0) { ss_err[filt_low] = try_filter_frame(sd, cpi, filt_low, partial_frame, plane, dir); } // If value is close to the best so far then bias towards a lower loop // filter value. if (ss_err[filt_low] < (best_err + bias)) { // Was it actually better than the previous best? if (ss_err[filt_low] < best_err) { best_err = ss_err[filt_low]; } filt_best = filt_low; } } // Now look at filt_high if (filt_direction >= 0 && filt_high != filt_mid) { if (ss_err[filt_high] < 0) { ss_err[filt_high] = try_filter_frame(sd, cpi, filt_high, partial_frame, plane, dir); } // If value is significantly better than previous best, bias added against // raising filter value if (ss_err[filt_high] < (best_err - bias)) { best_err = ss_err[filt_high]; filt_best = filt_high; } } // Half the step distance if the best filter value was the same as last time if (filt_best == filt_mid) { filter_step /= 2; filt_direction = 0; } else { filt_direction = (filt_best < filt_mid) ? -1 : 1; filt_mid = filt_best; } } // Update best error best_err = ss_err[filt_best]; if (best_cost_ret) *best_cost_ret = RDCOST_DBL(x->rdmult, 0, best_err); return filt_best; } void av1_pick_filter_level(const YV12_BUFFER_CONFIG *sd, AV1_COMP *cpi, LPF_PICK_METHOD method) { AV1_COMMON *const cm = &cpi->common; const int num_planes = av1_num_planes(cm); struct loopfilter *const lf = &cm->lf; (void)sd; lf->sharpness_level = 0; if (method == LPF_PICK_MINIMAL_LPF) { lf->filter_level[0] = 0; lf->filter_level[1] = 0; } else if (method >= LPF_PICK_FROM_Q) { const int min_filter_level = 0; const int max_filter_level = av1_get_max_filter_level(cpi); const int q = av1_ac_quant_Q3(cm->base_qindex, 0, cm->seq_params.bit_depth); // These values were determined by linear fitting the result of the // searched level for 8 bit depth: // Keyframes: filt_guess = q * 0.06699 - 1.60817 // Other frames: filt_guess = q * 0.02295 + 2.48225 // // And high bit depth separately: // filt_guess = q * 0.316206 + 3.87252 int filt_guess; switch (cm->seq_params.bit_depth) { case AOM_BITS_8: filt_guess = (cm->frame_type == KEY_FRAME) ? ROUND_POWER_OF_TWO(q * 17563 - 421574, 18) : ROUND_POWER_OF_TWO(q * 6017 + 650707, 18); break; case AOM_BITS_10: filt_guess = ROUND_POWER_OF_TWO(q * 20723 + 4060632, 20); break; case AOM_BITS_12: filt_guess = ROUND_POWER_OF_TWO(q * 20723 + 16242526, 22); break; default: assert(0 && "bit_depth should be AOM_BITS_8, AOM_BITS_10 " "or AOM_BITS_12"); return; } if (cm->seq_params.bit_depth != AOM_BITS_8 && cm->frame_type == KEY_FRAME) filt_guess -= 4; // TODO(chengchen): retrain the model for Y, U, V filter levels lf->filter_level[0] = clamp(filt_guess, min_filter_level, max_filter_level); lf->filter_level[1] = clamp(filt_guess, min_filter_level, max_filter_level); lf->filter_level_u = clamp(filt_guess, min_filter_level, max_filter_level); lf->filter_level_v = clamp(filt_guess, min_filter_level, max_filter_level); } else { const int last_frame_filter_level[4] = { lf->filter_level[0], lf->filter_level[1], lf->filter_level_u, lf->filter_level_v }; lf->filter_level[0] = lf->filter_level[1] = search_filter_level(sd, cpi, method == LPF_PICK_FROM_SUBIMAGE, last_frame_filter_level, NULL, 0, 2); lf->filter_level[0] = search_filter_level(sd, cpi, method == LPF_PICK_FROM_SUBIMAGE, last_frame_filter_level, NULL, 0, 0); lf->filter_level[1] = search_filter_level(sd, cpi, method == LPF_PICK_FROM_SUBIMAGE, last_frame_filter_level, NULL, 0, 1); if (num_planes > 1) { lf->filter_level_u = search_filter_level(sd, cpi, method == LPF_PICK_FROM_SUBIMAGE, last_frame_filter_level, NULL, 1, 0); lf->filter_level_v = search_filter_level(sd, cpi, method == LPF_PICK_FROM_SUBIMAGE, last_frame_filter_level, NULL, 2, 0); } } }
999897.c
/* get short TIME format */ #include "fb.h" /*:::::*/ int fb_IntlGetTimeFormat( char *buffer, size_t len, int disallow_localized ) { if( fb_I18nGet() && !disallow_localized ) { if( fb_DrvIntlGetTimeFormat( buffer, len ) ) return TRUE; } if( len < 9 ) return FALSE; strcpy(buffer, "HH:mm:ss"); return TRUE; }
602031.c
/* * Copyright 2014 The Luvit Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "private.h" static uv_pipe_t* luv_check_pipe(lua_State* L, int index) { uv_pipe_t* handle = (uv_pipe_t*)luv_checkudata(L, index, "uv_pipe"); luaL_argcheck(L, handle->type == UV_NAMED_PIPE && handle->data, index, "Expected uv_pipe_t"); return handle; } static int luv_new_pipe(lua_State* L) { uv_pipe_t* handle; int ipc, ret; luv_ctx_t* ctx = luv_context(L); ipc = luv_optboolean(L, 1, 0); handle = (uv_pipe_t*)luv_newuserdata(L, sizeof(*handle)); ret = uv_pipe_init(ctx->loop, handle, ipc); if (ret < 0) { lua_pop(L, 1); return luv_error(L, ret); } handle->data = luv_setup_handle(L, ctx); return 1; } static int luv_pipe_open(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); uv_file file = luaL_checkinteger(L, 2); int ret = uv_pipe_open(handle, file); return luv_result(L, ret); } static int luv_pipe_bind(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); const char* name = luaL_checkstring(L, 2); int ret = uv_pipe_bind(handle, name); return luv_result(L, ret); } static int luv_pipe_connect(lua_State* L) { luv_ctx_t* ctx = luv_context(L); uv_pipe_t* handle = luv_check_pipe(L, 1); const char* name = luaL_checkstring(L, 2); int ref = luv_check_continuation(L, 3); uv_connect_t* req = (uv_connect_t*)lua_newuserdata(L, sizeof(*req)); req->data = luv_setup_req(L, ctx, ref); uv_pipe_connect(req, handle, name, luv_connect_cb); return 1; } static int luv_pipe_getsockname(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); size_t len = 2*PATH_MAX; char buf[2*PATH_MAX]; int ret = uv_pipe_getsockname(handle, buf, &len); if (ret < 0) return luv_error(L, ret); lua_pushlstring(L, buf, len); return 1; } #if LUV_UV_VERSION_GEQ(1, 3, 0) static int luv_pipe_getpeername(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); size_t len = 2*PATH_MAX; char buf[2*PATH_MAX]; int ret = uv_pipe_getpeername(handle, buf, &len); if (ret < 0) return luv_error(L, ret); lua_pushlstring(L, buf, len); return 1; } #endif static int luv_pipe_pending_instances(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); int count = luaL_checkinteger(L, 2); uv_pipe_pending_instances(handle, count); return 0; } static int luv_pipe_pending_count(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); lua_pushinteger(L, uv_pipe_pending_count(handle)); return 1; } static int luv_pipe_pending_type(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); uv_handle_type type = uv_pipe_pending_type(handle); const char* type_name; switch (type) { #define XX(uc, lc) \ case UV_##uc: type_name = #lc; break; UV_HANDLE_TYPE_MAP(XX) #undef XX default: return 0; } lua_pushstring(L, type_name); return 1; } #if LUV_UV_VERSION_GEQ(1,16,0) static const char *const luv_pipe_chmod_flags[] = { "r", "w", "rw", "wr", NULL }; static int luv_pipe_chmod(lua_State* L) { uv_pipe_t* handle = luv_check_pipe(L, 1); int flags; switch (luaL_checkoption(L, 2, NULL, luv_pipe_chmod_flags)) { case 0: flags = UV_READABLE; break; case 1: flags = UV_WRITABLE; break; case 2: case 3: flags = UV_READABLE | UV_WRITABLE; break; default: flags = 0; /* unreachable */ } int ret = uv_pipe_chmod(handle, flags); return luv_result(L, ret); } #endif #if LUV_UV_VERSION_GEQ(1,41,0) static int luv_pipe(lua_State* L) { int read_flags = 0, write_flags = 0; uv_file fds[2]; int ret; if (lua_type(L, 1) == LUA_TTABLE) { lua_getfield(L, 1, "nonblock"); if (lua_toboolean(L, -1)) read_flags |= UV_NONBLOCK_PIPE; lua_pop(L, 1); } else if (!lua_isnoneornil(L, 1)) { luv_arg_type_error(L, 1, "table or nil expected, got %s"); } if (lua_type(L, 2) == LUA_TTABLE) { lua_getfield(L, 2, "nonblock"); if (lua_toboolean(L, -1)) write_flags |= UV_NONBLOCK_PIPE; lua_pop(L, 1); } else if (!lua_isnoneornil(L, 2)) { luv_arg_type_error(L, 2, "table or nil expected, got %s"); } ret = uv_pipe(fds, read_flags, write_flags); if (ret < 0) return luv_error(L, ret); // return as a table with 'read' and 'write' keys containing the corresponding fds lua_createtable(L, 0, 2); lua_pushinteger(L, fds[0]); lua_setfield(L, -2, "read"); lua_pushinteger(L, fds[1]); lua_setfield(L, -2, "write"); return 1; } #endif
442263.c
/*- * Copyright (c) 2014-2016 MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "util.h" static int usage(void); int util_printlog(WT_SESSION *session, int argc, char *argv[]) { WT_DECL_RET; uint32_t flags; int ch; flags = 0; while ((ch = __wt_getopt(progname, argc, argv, "f:x")) != EOF) switch (ch) { case 'f': /* output file */ if (freopen(__wt_optarg, "w", stdout) == NULL) { fprintf(stderr, "%s: %s: reopen: %s\n", progname, __wt_optarg, strerror(errno)); return (1); } break; case 'x': /* hex output */ LF_SET(WT_TXN_PRINTLOG_HEX); break; case '?': default: return (usage()); } argc -= __wt_optind; argv += __wt_optind; /* There should not be any more arguments. */ if (argc != 0) return (usage()); if ((ret = __wt_txn_printlog(session, flags)) != 0) (void)util_err(session, ret, "printlog"); return (ret); } static int usage(void) { (void)fprintf(stderr, "usage: %s %s " "printlog [-x] [-f output-file]\n", progname, usage_prefix); return (1); }
465525.c
/* scdaemon.c - The GnuPG Smartcard Daemon * Copyright (C) 2001, 2002, 2004, 2005, * 2007, 2008, 2009 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG 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. * * GnuPG 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 <config.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <assert.h> #include <time.h> #include <fcntl.h> #ifndef HAVE_W32_SYSTEM #include <sys/socket.h> #include <sys/un.h> #endif /*HAVE_W32_SYSTEM*/ #include <unistd.h> #include <signal.h> #include <pth.h> #define JNLIB_NEED_LOG_LOGV #define JNLIB_NEED_AFLOCAL #include "scdaemon.h" #include <ksba.h> #include <gcrypt.h> #include <assuan.h> /* malloc hooks */ #include "i18n.h" #include "sysutils.h" #include "app-common.h" #include "iso7816.h" #include "apdu.h" #include "ccid-driver.h" #include "mkdtemp.h" #include "gc-opt-flags.h" enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aGPGConfList, aGPGConfTest, oOptions, oDebug, oDebugAll, oDebugLevel, oDebugWait, oDebugAllowCoreDump, oDebugCCIDDriver, oDebugLogTid, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oNoGrab, oLogFile, oServer, oMultiServer, oDaemon, oBatch, oReaderPort, oCardTimeout, octapiDriver, opcscDriver, oDisableCCID, oDisableOpenSC, oDisablePinpad, oAllowAdmin, oDenyAdmin, oDisableApplication, oEnablePinpadVarlen, oDebugDisableTicker }; static ARGPARSE_OPTS opts[] = { ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_group (301, N_("@Options:\n ")), ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")), ARGPARSE_s_n (oMultiServer, "multi-server", N_("run in multi server mode (foreground)")), ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_p_u (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level" , N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"), ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"), ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"), ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")), ARGPARSE_s_s (oReaderPort, "reader-port", N_("|N|connect to reader at port N")), ARGPARSE_s_s (octapiDriver, "ctapi-driver", N_("|NAME|use NAME as ct-API driver")), ARGPARSE_s_s (opcscDriver, "pcsc-driver", N_("|NAME|use NAME as PC/SC driver")), ARGPARSE_s_n (oDisableCCID, "disable-ccid", #ifdef HAVE_LIBUSB N_("do not use the internal CCID driver") #else "@" #endif /* end --disable-ccid */), ARGPARSE_s_u (oCardTimeout, "card-timeout", N_("|N|disconnect the card after N seconds of inactivity")), ARGPARSE_s_n (oDisablePinpad, "disable-pinpad", N_("do not use a reader's pinpad")), ARGPARSE_ignore (300, "disable-keypad"), ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"), ARGPARSE_s_n (oDenyAdmin, "deny-admin", N_("deny the use of admin card commands")), ARGPARSE_s_s (oDisableApplication, "disable-application", "@"), ARGPARSE_s_n (oEnablePinpadVarlen, "enable-pinpad-varlen", N_("use variable length input for pinpad")), ARGPARSE_end () }; /* The card driver we use by default for PC/SC. */ #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__) #define DEFAULT_PCSC_DRIVER "winscard.dll" #elif defined(__APPLE__) #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC" #elif defined(__GLIBC__) #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1" #else #define DEFAULT_PCSC_DRIVER "libpcsclite.so" #endif /* The timer tick used for housekeeping stuff. We poll every 500ms to let the user immediately know a status change. This is not too good for power saving but given that there is no easy way to block on card status changes it is the best we can do. For PC/SC we could in theory use an extra thread to wait for status changes but that requires a native thread because there is no way to make the underlying PC/SC card change function block using a Pth mechanism. Given that a native thread could only be used under W32 we don't do that at all. */ #define TIMERTICK_INTERVAL_SEC (0) #define TIMERTICK_INTERVAL_USEC (500000) /* Flag to indicate that a shutdown was requested. */ static int shutdown_pending; /* It is possible that we are currently running under setuid permissions */ static int maybe_setuid = 1; /* Flag telling whether we are running as a pipe server. */ static int pipe_server; /* Name of the communication socket */ static char *socket_name; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; /* Debug flag to disable the ticker. The ticker is in fact not disabled but it won't perform any ticker specific actions. */ static int ticker_disabled; static char *create_socket_name (int use_standard_socket, char *standard_name, char *template); static gnupg_fd_t create_server_socket (int is_standard_name, const char *name, assuan_sock_nonce_t *nonce); static void *start_connection_thread (void *arg); static void handle_connections (int listen_fd); /* Pth wrapper function definitions. */ ASSUAN_SYSTEM_PTH_IMPL; #if GCRYPT_VERSION_NUMBER < 0x010600 GCRY_THREAD_OPTION_PTH_IMPL; #if GCRY_THREAD_OPTION_VERSION < 1 static int fixed_gcry_pth_init (void) { return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0; } #endif #endif /*GCRYPT_VERSION_NUMBER < 0x010600*/ static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; if (maybe_setuid) { gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */ maybe_setuid = 0; } s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } static const char * my_strusage (int level) { static char *ver_gcry, *ver_ksba; const char *p; switch (level) { case 11: p = "scdaemon (GnuPG)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; case 21: if (!ver_ksba) ver_ksba = make_libversion ("libksba", ksba_check_version); p = ver_ksba; break; case 1: case 40: p = _("Usage: scdaemon [options] (-h for help)"); break; case 41: p = _("Syntax: scdaemon [options] [command [args]]\n" "Smartcard daemon for GnuPG\n"); break; default: p = NULL; } return p; } static unsigned long tid_log_callback (void) { #ifdef PTH_HAVE_PTH_THREAD_ID return pth_thread_id (); #else return (unsigned long)pth_self (); #endif } /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (const char *level) { int numok = (level && digitp (level)); int numlvl = numok? atoi (level) : 0; if (!level) ; else if (!strcmp (level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_ASSUAN_VALUE; else if (!strcmp (level, "advanced") || (numok && numlvl <= 5)) opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE; else if (!strcmp (level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE); else if (!strcmp (level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level `%s' given\n"), level); scd_exit(2); } if (opt.debug && !opt.verbose) opt.verbose = 1; if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_MPI_VALUE) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2); if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); if (opt.debug) log_info ("enabled debug flags:%s%s%s%s%s%s%s%s%s\n", (opt.debug & DBG_COMMAND_VALUE)? " command":"", (opt.debug & DBG_MPI_VALUE )? " mpi":"", (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"", (opt.debug & DBG_MEMORY_VALUE )? " memory":"", (opt.debug & DBG_CACHE_VALUE )? " cache":"", (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"", (opt.debug & DBG_HASHING_VALUE)? " hashing":"", (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"", (opt.debug & DBG_CARD_IO_VALUE)? " cardio":""); } static void cleanup (void) { if (socket_name && *socket_name) { char *p; remove (socket_name); p = strrchr (socket_name, '/'); if (p) { *p = 0; rmdir (socket_name); *p = '/'; } *socket_name = 0; } } int main (int argc, char **argv ) { ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; FILE *configfp = NULL; char *configname = NULL; const char *shell; unsigned int configlineno; int parse_debug = 0; const char *debug_level = NULL; int default_config =1; int greeting = 0; int nogreeting = 0; int multi_server = 0; int is_daemon = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; int debug_wait = 0; int gpgconf_list = 0; const char *config_filename = NULL; int allow_coredump = 0; int standard_socket = 0; struct assuan_malloc_hooks malloc_hooks; set_strusage (my_strusage); gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN); /* Please note that we may running SUID(ROOT), so be very CAREFUL when adding any stuff between here and the call to INIT_SECMEM() somewhere after the option parsing */ log_set_prefix ("scdaemon", 1|4); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (); #if GCRYPT_VERSION_NUMBER < 0x010600 /* Libgcrypt < 1.6 requires us to register the threading model first. Note that this will also do the pth_init. */ { gpg_error_t err; #if GCRY_THREAD_OPTION_VERSION < 1 gcry_threads_pth.init = fixed_gcry_pth_init; #endif err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth); if (err) { log_fatal ("can't register GNU Pth with Libgcrypt: %s\n", gpg_strerror (err)); } } #endif /*GCRYPT_VERSION_NUMBER < 0x010600*/ /* Check that the libraries are suitable. Do it here because the option parsing may need services of the library */ if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) ) { log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt", NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) ); } ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free); malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_assuan_log_prefix (log_get_prefix (NULL)); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_set_system_hooks (ASSUAN_SYSTEM_PTH); assuan_sock_init (); setup_libgcrypt_logging (); gcry_control (GCRYCTL_USE_SECURE_RNDPOOL); disable_core_dumps (); /* Set default options. */ opt.allow_admin = 1; opt.pcsc_driver = DEFAULT_PCSC_DRIVER; #ifdef HAVE_W32_SYSTEM standard_socket = 1; /* Under Windows we always use a standard socket. */ #endif shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; opt.homedir = default_homedir (); /* Check whether we have a config file on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */ while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; else if (pargs.r_opt == oOptions) { /* yes there is one, so we do not try the default one, but read the option file when it is encountered at the commandline */ default_config = 0; } else if (pargs.r_opt == oNoOptions) default_config = 0; /* --no-options */ else if (pargs.r_opt == oHomedir) opt.homedir = pargs.r.ret_str; } /* initialize the secure memory. */ gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); maybe_setuid = 0; /* Now we are working under our real uid */ if (default_config) configname = make_filename (opt.homedir, "scdaemon.conf", NULL ); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if( parse_debug ) log_info (_("NOTE: no default option file `%s'\n"), configname ); } else { log_error (_("option file `%s': %s\n"), configname, strerror(errno) ); exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname ) log_info (_("reading options from `%s'\n"), configname ); default_config = 0; } while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) ) { switch (pargs.r_opt) { case aGPGConfList: gpgconf_list = 1; break; case aGPGConfTest: gpgconf_list = 2; break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oBatch: opt.batch=1; break; case oDebug: opt.debug |= pargs.r.ret_ulong; break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs.r.ret_str; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oDebugAllowCoreDump: enable_core_dumps (); allow_coredump = 1; break; case oDebugCCIDDriver: #ifdef HAVE_LIBUSB ccid_set_debug_level (ccid_set_debug_level (-1)+1); #endif /*HAVE_LIBUSB*/ break; case oDebugDisableTicker: ticker_disabled = 1; break; case oDebugLogTid: log_set_get_tid_callback (tid_log_callback); break; case oOptions: /* config files may not be nested (silently ignore them) */ if (!configfp) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; break; case oNoOptions: break; /* no-options */ case oHomedir: opt.homedir = pargs.r.ret_str; break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oServer: pipe_server = 1; break; case oMultiServer: pipe_server = 1; multi_server = 1; break; case oDaemon: is_daemon = 1; break; case oReaderPort: opt.reader_port = pargs.r.ret_str; break; case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break; case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break; case oDisableCCID: opt.disable_ccid = 1; break; case oDisableOpenSC: break; case oDisablePinpad: opt.disable_pinpad = 1; break; case oAllowAdmin: /* Dummy because allow is now the default. */ break; case oDenyAdmin: opt.allow_admin = 0; break; case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break; case oDisableApplication: add_to_strlist (&opt.disabled_applications, pargs.r.ret_str); break; case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break; default: pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR; break; } } if (configfp) { fclose( configfp ); configfp = NULL; /* Keep a copy of the config name for use by --gpgconf-list. */ config_filename = configname; configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (log_get_errorcount(0)) exit(2); if (nogreeting ) greeting = 0; if (greeting) { fprintf (stderr, "%s %s; %s\n", strusage(11), strusage(13), strusage(14) ); fprintf (stderr, "%s\n", strusage(15) ); } #ifdef IS_DEVELOPMENT_VERSION log_info ("NOTE: this is a development version!\n"); #endif if (atexit (cleanup)) { log_error ("atexit failed\n"); cleanup (); exit (1); } set_debug (debug_level); initialize_module_command (); if (gpgconf_list == 2) scd_exit (0); if (gpgconf_list) { /* List options and default values in the GPG Conf format. */ char *filename = NULL; char *filename_esc; if (config_filename) filename = xstrdup (config_filename); else filename = make_filename (opt.homedir, "scdaemon.conf", NULL); filename_esc = percent_escape (filename, NULL); printf ("gpgconf-scdaemon.conf:%lu:\"%s\n", GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); xfree (filename); printf ("verbose:%lu:\n" "quiet:%lu:\n" "debug-level:%lu:\"none:\n" "log-file:%lu:\n", GC_OPT_FLAG_NONE, GC_OPT_FLAG_NONE, GC_OPT_FLAG_DEFAULT, GC_OPT_FLAG_NONE ); printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE ); printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE ); printf ("pcsc-driver:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER ); #ifdef HAVE_LIBUSB printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE ); #endif printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE ); printf ("disable-pinpad:%lu:\n", GC_OPT_FLAG_NONE ); printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0); printf ("enable-pinpad-varlen:%lu:\n", GC_OPT_FLAG_NONE ); scd_exit (0); } /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, 1|2|4); } if (debug_wait && pipe_server) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } if (pipe_server) { /* This is the simple pipe based server */ ctrl_t ctrl; pth_attr_t tattr; int fd = -1; #ifndef HAVE_W32_SYSTEM { struct sigaction sa; sa.sa_handler = SIG_IGN; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sigaction (SIGPIPE, &sa, NULL); } #endif /* If --debug-allow-core-dump has been given we also need to switch the working directory to a place where we can actually write. */ if (allow_coredump) { if (chdir("/tmp")) log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno)); else log_debug ("changed working directory to `/tmp'\n"); } /* In multi server mode we need to listen on an additional socket. Create that socket now before starting the handler for the pipe connection. This allows that handler to send back the name of that socket. */ if (multi_server) { socket_name = create_socket_name (standard_socket, "S.scdaemon", "/tmp/gpg-XXXXXX/S.scdaemon"); fd = FD2INT(create_server_socket (standard_socket, socket_name, &socket_nonce)); } tattr = pth_attr_new(); pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0); pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024); pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection"); ctrl = xtrycalloc (1, sizeof *ctrl); if ( !ctrl ) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); scd_exit (2); } ctrl->thread_startup.fd = GNUPG_INVALID_FD; if ( !pth_spawn (tattr, start_connection_thread, ctrl) ) { log_error ("error spawning pipe connection handler: %s\n", strerror (errno) ); xfree (ctrl); scd_exit (2); } /* We run handle_connection to wait for the shutdown signal and to run the ticker stuff. */ handle_connections (fd); if (fd != -1) close (fd); } else if (!is_daemon) { log_info (_("please use the option `--daemon'" " to run the program in the background\n")); } else { /* Regular server mode */ int fd; #ifndef HAVE_W32_SYSTEM pid_t pid; int i; #endif /* Create the socket. */ socket_name = create_socket_name (standard_socket, "S.scdaemon", "/tmp/gpg-XXXXXX/S.scdaemon"); fd = FD2INT (create_server_socket (standard_socket, socket_name, &socket_nonce)); fflush (NULL); #ifndef HAVE_W32_SYSTEM pid = fork (); if (pid == (pid_t)-1) { log_fatal ("fork failed: %s\n", strerror (errno) ); exit (1); } else if (pid) { /* we are the parent */ char *infostr; close (fd); /* create the info string: <name>:<pid>:<protocol_version> */ if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1", socket_name, (ulong) pid) < 0) { log_error ("out of core\n"); kill (pid, SIGTERM); exit (1); } *socket_name = 0; /* don't let cleanup() remove the socket - the child should do this from now on */ if (argc) { /* run the program given on the commandline */ if (putenv (infostr)) { log_error ("failed to set environment: %s\n", strerror (errno) ); kill (pid, SIGTERM ); exit (1); } execvp (argv[0], argv); log_error ("failed to run the command: %s\n", strerror (errno)); kill (pid, SIGTERM); exit (1); } else { /* Print the environment string, so that the caller can use shell's eval to set it */ if (csh_style) { *strchr (infostr, '=') = ' '; printf ( "setenv %s;\n", infostr); } else { printf ( "%s; export SCDAEMON_INFO;\n", infostr); } xfree (infostr); exit (0); } /* NOTREACHED */ } /* end parent */ /* This is the child. */ /* Detach from tty and put process into a new session. */ if (!nodetach ) { /* Close stdin, stdout and stderr unless it is the log stream. */ for (i=0; i <= 2; i++) { if ( log_test_fd (i) && i != fd) close (i); } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); cleanup (); exit (1); } } { struct sigaction sa; sa.sa_handler = SIG_IGN; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sigaction (SIGPIPE, &sa, NULL); } if (chdir("/")) { log_error ("chdir to / failed: %s\n", strerror (errno)); exit (1); } #endif /*!HAVE_W32_SYSTEM*/ handle_connections (fd); close (fd); } return 0; } void scd_exit (int rc) { apdu_prepare_exit (); #if 0 #warning no update_random_seed_file update_random_seed_file(); #endif #if 0 /* at this time a bit annoying */ if (opt.debug & DBG_MEMSTAT_VALUE) { gcry_control( GCRYCTL_DUMP_MEMORY_STATS ); gcry_control( GCRYCTL_DUMP_RANDOM_STATS ); } if (opt.debug) gcry_control (GCRYCTL_DUMP_SECMEM_STATS ); #endif gcry_control (GCRYCTL_TERM_SECMEM ); rc = rc? rc : log_get_errorcount(0)? 2 : 0; exit (rc); } static void scd_init_default_ctrl (ctrl_t ctrl) { ctrl->reader_slot = -1; } static void scd_deinit_default_ctrl (ctrl_t ctrl) { (void)ctrl; } /* Return the name of the socket to be used to connect to this process. If no socket is available, return NULL. */ const char * scd_get_socket_name () { if (socket_name && *socket_name) return socket_name; return NULL; } static void handle_signal (int signo) { switch (signo) { #ifndef HAVE_W32_SYSTEM case SIGHUP: log_info ("SIGHUP received - " "re-reading configuration and resetting cards\n"); /* reread_configuration (); */ break; case SIGUSR1: log_info ("SIGUSR1 received - printing internal information:\n"); pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); app_dump_state (); break; case SIGUSR2: log_info ("SIGUSR2 received - no action defined\n"); break; case SIGTERM: if (!shutdown_pending) log_info ("SIGTERM received - shutting down ...\n"); else log_info ("SIGTERM received - still %ld running threads\n", pth_ctrl( PTH_CTRL_GETTHREADS )); shutdown_pending++; if (shutdown_pending > 2) { log_info ("shutdown forced\n"); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); scd_exit (0); } break; case SIGINT: log_info ("SIGINT received - immediate shutdown\n"); log_info( "%s %s stopped\n", strusage(11), strusage(13)); cleanup (); scd_exit (0); break; #endif /*!HAVE_W32_SYSTEM*/ default: log_info ("signal %d received - no action defined\n", signo); } } static void handle_tick (void) { if (!ticker_disabled) scd_update_reader_status_file (); } /* Create a name for the socket. With USE_STANDARD_SOCKET given as true using STANDARD_NAME in the home directory or if given has false from the mkdir type name TEMPLATE. In the latter case a unique name in a unique new directory will be created. In both cases check for valid characters as well as against a maximum allowed length for a unix domain socket is done. The function terminates the process in case of an error. Retunrs: Pointer to an allcoated string with the absolute name of the socket used. */ static char * create_socket_name (int use_standard_socket, char *standard_name, char *template) { char *name, *p; if (use_standard_socket) name = make_filename (opt.homedir, standard_name, NULL); else { name = xstrdup (template); p = strrchr (name, '/'); if (!p) BUG (); *p = 0; if (!mkdtemp (name)) { log_error (_("can't create directory `%s': %s\n"), name, strerror (errno)); scd_exit (2); } *p = '/'; } if (strchr (name, PATHSEP_C)) { log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S); scd_exit (2); } if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) ) { log_error (_("name of socket too long\n")); scd_exit (2); } return name; } /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates whether a non-random socket is used. Returns the file descriptor or terminates the process in case of an error. */ static gnupg_fd_t create_server_socket (int is_standard_name, const char *name, assuan_sock_nonce_t *nonce) { struct sockaddr_un *serv_addr; socklen_t len; gnupg_fd_t fd; int rc; fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == GNUPG_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); scd_exit (2); } serv_addr = xmalloc (sizeof (*serv_addr)); memset (serv_addr, 0, sizeof *serv_addr); serv_addr->sun_family = AF_UNIX; assert (strlen (name) + 1 < sizeof (serv_addr->sun_path)); strcpy (serv_addr->sun_path, name); len = SUN_LEN (serv_addr); rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len); if (is_standard_name && rc == -1 && errno == EADDRINUSE) { remove (name); rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len); } if (rc != -1 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { log_error (_("error binding socket to `%s': %s\n"), serv_addr->sun_path, gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); scd_exit (2); } if (listen (FD2INT(fd), 5 ) == -1) { log_error (_("listen() failed: %s\n"), gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); scd_exit (2); } if (opt.verbose) log_info (_("listening on socket `%s'\n"), serv_addr->sun_path); return fd; } /* This is the standard connection thread's main function. */ static void * start_connection_thread (void *arg) { ctrl_t ctrl = arg; if (ctrl->thread_startup.fd != GNUPG_INVALID_FD && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT(ctrl->thread_startup.fd), strerror (errno)); assuan_sock_close (ctrl->thread_startup.fd); xfree (ctrl); return NULL; } scd_init_default_ctrl (ctrl); if (opt.verbose) log_info (_("handler for fd %d started\n"), FD2INT(ctrl->thread_startup.fd)); /* If this is a pipe server, we request a shutdown if the command handler asked for it. With the next ticker event and given that no other connections are running the shutdown will then happen. */ if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd)) && pipe_server) shutdown_pending = 1; if (opt.verbose) log_info (_("handler for fd %d terminated\n"), FD2INT (ctrl->thread_startup.fd)); scd_deinit_default_ctrl (ctrl); xfree (ctrl); return NULL; } /* Connection handler loop. Wait for connection requests and spawn a thread after accepting a connection. LISTEN_FD is allowed to be -1 in which case this code will only do regular timeouts and handle signals. */ static void handle_connections (int listen_fd) { pth_attr_t tattr; pth_event_t ev, time_ev; sigset_t sigs; int signo; struct sockaddr_un paddr; socklen_t plen; fd_set fdset, read_fdset; int ret; int fd; int nfd; tattr = pth_attr_new(); pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0); pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024); #ifndef HAVE_W32_SYSTEM /* fixme */ sigemptyset (&sigs ); sigaddset (&sigs, SIGHUP); sigaddset (&sigs, SIGUSR1); sigaddset (&sigs, SIGUSR2); sigaddset (&sigs, SIGINT); sigaddset (&sigs, SIGTERM); pth_sigmask (SIG_UNBLOCK, &sigs, NULL); ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo); #else sigs = 0; ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo); #endif time_ev = NULL; FD_ZERO (&fdset); nfd = 0; if (listen_fd != -1) { FD_SET (listen_fd, &fdset); nfd = listen_fd; } for (;;) { sigset_t oldsigs; if (shutdown_pending) { if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1) break; /* ready */ /* Do not accept anymore connections but wait for existing connections to terminate. We do this by clearing out all file descriptors to wait for, so that the select will be used to just wait on a signal or timeout event. */ FD_ZERO (&fdset); listen_fd = -1; } /* Create a timeout event if needed. Round it up to the next microsecond interval to help with power saving. */ if (!time_ev) { pth_time_t nexttick = pth_timeout (TIMERTICK_INTERVAL_SEC, TIMERTICK_INTERVAL_USEC/2); if ((nexttick.tv_usec % (TIMERTICK_INTERVAL_USEC/2)) > 10) { nexttick.tv_usec = ((nexttick.tv_usec /(TIMERTICK_INTERVAL_USEC/2)) + 1) * (TIMERTICK_INTERVAL_USEC/2); if (nexttick.tv_usec >= 1000000) { nexttick.tv_sec++; nexttick.tv_usec = 0; } } time_ev = pth_event (PTH_EVENT_TIME, nexttick); } /* POSIX says that fd_set should be implemented as a structure, thus a simple assignment is fine to copy the entire set. */ read_fdset = fdset; if (time_ev) pth_event_concat (ev, time_ev, NULL); ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev); if (time_ev) pth_event_isolate (time_ev); if (ret == -1) { if (pth_event_occurred (ev) || (time_ev && pth_event_occurred (time_ev))) { if (pth_event_occurred (ev)) handle_signal (signo); if (time_ev && pth_event_occurred (time_ev)) { pth_event_free (time_ev, PTH_FREE_ALL); time_ev = NULL; handle_tick (); } continue; } log_error (_("pth_select failed: %s - waiting 1s\n"), strerror (errno)); pth_sleep (1); continue; } if (pth_event_occurred (ev)) { handle_signal (signo); } if (time_ev && pth_event_occurred (time_ev)) { pth_event_free (time_ev, PTH_FREE_ALL); time_ev = NULL; handle_tick (); } /* We now might create new threads and because we don't want any signals - we are handling here - to be delivered to a new thread. Thus we need to block those signals. */ pth_sigmask (SIG_BLOCK, &sigs, &oldsigs); if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset)) { ctrl_t ctrl; plen = sizeof paddr; fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen); if (fd == -1) { log_error ("accept failed: %s\n", strerror (errno)); } else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) ) { log_error ("error allocating connection control data: %s\n", strerror (errno) ); close (fd); } else { char threadname[50]; snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd); threadname[sizeof threadname -1] = 0; pth_attr_set (tattr, PTH_ATTR_NAME, threadname); ctrl->thread_startup.fd = INT2FD (fd); if (!pth_spawn (tattr, start_connection_thread, ctrl)) { log_error ("error spawning connection handler: %s\n", strerror (errno) ); xfree (ctrl); close (fd); } } fd = -1; } /* Restore the signal mask. */ pth_sigmask (SIG_SETMASK, &oldsigs, NULL); } pth_event_free (ev, PTH_FREE_ALL); if (time_ev) pth_event_free (time_ev, PTH_FREE_ALL); cleanup (); log_info (_("%s %s stopped\n"), strusage(11), strusage(13)); }
715280.c
/*++ Copyright (c) 2011 - 2020, Intel Corporation. All rights reserved SPDX-License-Identifier: BSD-2-Clause-Patent Module Name: IgdOpRegion.c Abstract: This is part of the implementation of an Intel Graphics drivers OpRegion / Software SCI interface between system BIOS, ASL code, and Graphics drivers. The code in this file will load the driver and initialize the interface Supporting Specifiction: OpRegion / Software SCI SPEC 0.70 Acronyms: IGD: Internal Graphics Device NVS: ACPI Non Volatile Storage OpRegion: ACPI Operational Region VBT: Video BIOS Table (OEM customizable data) --*/ // // Include files // #include "IgdOpRegion.h" #include "VlvPlatformInit.h" #include <PiDxe.h> #include <PchRegs.h> #include <Protocol/IgdOpRegion.h> #include <Protocol/FirmwareVolume2.h> #include <Protocol/PlatformGopPolicy.h> #include <Protocol/PciIo.h> #include <Protocol/CpuIo2.h> #include <Protocol/GlobalNvsArea.h> #include <Protocol/DxeSmmReadyToLock.h> #include <Protocol/PciRootBridgeIo.h> #include <Library/MemoryAllocationLib.h> #include <Library/BaseLib.h> #include <Library/S3BootScriptLib.h> #include <Library/IoLib.h> #include <Library/DevicePathLib.h> #include <Protocol/DriverBinding.h> #include <Library/PrintLib.h> #include <Library/BaseMemoryLib.h> UINT8 gSVER[12] = "Intel"; extern DXE_VLV_PLATFORM_POLICY_PROTOCOL *DxePlatformSaPolicy; // // Global variables // IGD_OPREGION_PROTOCOL mIgdOpRegion; EFI_EVENT mConOutEvent; EFI_EVENT mSetGOPverEvent; VOID *mConOutReg; #define DEFAULT_FORM_BUFFER_SIZE 0xFFFF #ifndef ECP_FLAG #if 0 /** Get the HII protocol interface @param Hii HII protocol interface @retval Status code **/ static EFI_STATUS GetHiiInterface ( OUT EFI_HII_PROTOCOL **Hii ) { EFI_STATUS Status; // // There should only be one HII protocol // Status = gBS->LocateProtocol ( &gEfiHiiProtocolGuid, NULL, (VOID **) Hii ); return Status;; } #endif #endif /** Get VBT data. @param[in] VbtFileBuffer Pointer to VBT data buffer. @retval EFI_SUCCESS VBT data was returned. @retval EFI_NOT_FOUND VBT data not found. @exception EFI_UNSUPPORTED Invalid signature in VBT data. **/ EFI_STATUS GetIntegratedIntelVbtPtr ( OUT VBIOS_VBT_STRUCTURE **VbtFileBuffer ) { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS VbtAddress = 0; UINTN FvProtocolCount; EFI_HANDLE *FvHandles; EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; UINTN Index; UINT32 AuthenticationStatus; UINT8 *Buffer; UINTN VbtBufferSize = 0; Buffer = 0; FvHandles = NULL; *VbtFileBuffer = NULL; Status = gBS->LocateHandleBuffer ( ByProtocol, &gEfiFirmwareVolume2ProtocolGuid, NULL, &FvProtocolCount, &FvHandles ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < FvProtocolCount; Index++) { Status = gBS->HandleProtocol ( FvHandles[Index], &gEfiFirmwareVolume2ProtocolGuid, (VOID **) &Fv ); VbtBufferSize = 0; Status = Fv->ReadSection ( Fv, &gBmpImageGuid, EFI_SECTION_RAW, 0, (void **)&Buffer, &VbtBufferSize, &AuthenticationStatus ); if (!EFI_ERROR (Status)) { VbtAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; Status = EFI_SUCCESS; break; } } } else { Status = EFI_NOT_FOUND; } if (FvHandles != NULL) { FreePool(FvHandles); FvHandles = NULL; } // // Check VBT signature // *VbtFileBuffer = (VBIOS_VBT_STRUCTURE *) (UINTN) VbtAddress; if (*VbtFileBuffer != NULL) { if ((*((UINT32 *) ((*VbtFileBuffer)->HeaderSignature))) != VBT_SIGNATURE) { if (*VbtFileBuffer != NULL) { *VbtFileBuffer = NULL; } return EFI_UNSUPPORTED; } // // Check VBT size // if ((*VbtFileBuffer)->HeaderVbtSize > VbtBufferSize) { (*VbtFileBuffer)->HeaderVbtSize = (UINT16) VbtBufferSize; } } return EFI_SUCCESS; } // // Function implementations. // /** Get a pointer to an uncompressed image of the Intel video BIOS. Note: This function would only be called if the video BIOS at 0xC000 is missing or not an Intel video BIOS. It may not be an Intel video BIOS if the Intel graphic contoller is considered a secondary adapter. @param VBiosROMImage Pointer to an uncompressed Intel video BIOS. This pointer must be set to NULL if an uncompressed image of the Intel Video BIOS is not obtainable. @retval EFI_SUCCESS VBiosPtr is updated. **/ EFI_STATUS GetIntegratedIntelVBiosPtr ( INTEL_VBIOS_OPTION_ROM_HEADER **VBiosImage ) { EFI_HANDLE *HandleBuffer; UINTN HandleCount; UINTN Index; INTEL_VBIOS_PCIR_STRUCTURE *PcirBlockPtr; EFI_STATUS Status; EFI_PCI_IO_PROTOCOL *PciIo; INTEL_VBIOS_OPTION_ROM_HEADER *VBiosRomImage; // // Set as if an umcompressed Intel video BIOS image was not obtainable. // VBiosRomImage = NULL; *VBiosImage = NULL; // // Get all PCI IO protocols // Status = gBS->LocateHandleBuffer ( ByProtocol, &gEfiPciIoProtocolGuid, NULL, &HandleCount, &HandleBuffer ); ASSERT_EFI_ERROR (Status); // // Find the video BIOS by checking each PCI IO handle for an Intel video // BIOS OPROM. // for (Index = 0; Index < HandleCount; Index++) { Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiPciIoProtocolGuid, (void **)&PciIo ); ASSERT_EFI_ERROR (Status); VBiosRomImage = PciIo->RomImage; // // If this PCI device doesn't have a ROM image, skip to the next device. // if (!VBiosRomImage) { continue; } // // Get pointer to PCIR structure // PcirBlockPtr = (INTEL_VBIOS_PCIR_STRUCTURE *)((UINT8 *) VBiosRomImage + VBiosRomImage->PcirOffset); // // Check if we have an Intel video BIOS OPROM. // if ((VBiosRomImage->Signature == OPTION_ROM_SIGNATURE) && (PcirBlockPtr->VendorId == IGD_VID) && (PcirBlockPtr->ClassCode[0] == 0x00) && (PcirBlockPtr->ClassCode[1] == 0x00) && (PcirBlockPtr->ClassCode[2] == 0x03) ) { // // Found Intel video BIOS. // *VBiosImage = VBiosRomImage; return EFI_SUCCESS; } } // // No Intel video BIOS found. // // // Free any allocated buffers // return EFI_UNSUPPORTED; } EFI_STATUS SearchChildHandle( EFI_HANDLE Father, EFI_HANDLE *Child ) { EFI_STATUS Status; UINTN HandleIndex; EFI_GUID **ProtocolGuidArray = NULL; UINTN ArrayCount; UINTN ProtocolIndex; UINTN OpenInfoCount; UINTN OpenInfoIndex; EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo = NULL; UINTN mHandleCount; EFI_HANDLE *mHandleBuffer= NULL; // // Retrieve the list of all handles from the handle database // Status = gBS->LocateHandleBuffer ( AllHandles, NULL, NULL, &mHandleCount, &mHandleBuffer ); for (HandleIndex = 0; HandleIndex < mHandleCount; HandleIndex++) { // // Retrieve the list of all the protocols on each handle // Status = gBS->ProtocolsPerHandle ( mHandleBuffer[HandleIndex], &ProtocolGuidArray, &ArrayCount ); if (!EFI_ERROR (Status)) { for (ProtocolIndex = 0; ProtocolIndex < ArrayCount; ProtocolIndex++) { Status = gBS->OpenProtocolInformation ( mHandleBuffer[HandleIndex], ProtocolGuidArray[ProtocolIndex], &OpenInfo, &OpenInfoCount ); if (!EFI_ERROR (Status)) { for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) { if(OpenInfo[OpenInfoIndex].AgentHandle == Father) { if ((OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) == EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) { *Child = mHandleBuffer[HandleIndex]; Status = EFI_SUCCESS; goto TryReturn; } } } Status = EFI_NOT_FOUND; } } if(OpenInfo != NULL) { FreePool(OpenInfo); OpenInfo = NULL; } } FreePool (ProtocolGuidArray); ProtocolGuidArray = NULL; } TryReturn: if(OpenInfo != NULL) { FreePool (OpenInfo); OpenInfo = NULL; } if(ProtocolGuidArray != NULL) { FreePool(ProtocolGuidArray); ProtocolGuidArray = NULL; } if(mHandleBuffer != NULL) { FreePool (mHandleBuffer); mHandleBuffer = NULL; } return Status; } EFI_STATUS JudgeHandleIsPCIDevice( EFI_HANDLE Handle, UINT8 Device, UINT8 Funs ) { EFI_STATUS Status; EFI_DEVICE_PATH *DPath; Status = gBS->HandleProtocol ( Handle, &gEfiDevicePathProtocolGuid, (VOID **) &DPath ); if(!EFI_ERROR(Status)) { while(!IsDevicePathEnd(DPath)) { if((DPath->Type == HARDWARE_DEVICE_PATH) && (DPath->SubType == HW_PCI_DP)) { PCI_DEVICE_PATH *PCIPath; PCIPath = (PCI_DEVICE_PATH*) DPath; DPath = NextDevicePathNode(DPath); if(IsDevicePathEnd(DPath) && (PCIPath->Device == Device) && (PCIPath->Function == Funs)) { return EFI_SUCCESS; } } else { DPath = NextDevicePathNode(DPath); } } } return EFI_UNSUPPORTED; } EFI_STATUS GetDriverName( EFI_HANDLE Handle, CHAR16 *GopVersion ) { EFI_DRIVER_BINDING_PROTOCOL *BindHandle = NULL; EFI_STATUS Status; UINT32 Version; UINT16 *Ptr; Status = gBS->OpenProtocol( Handle, &gEfiDriverBindingProtocolGuid, (VOID**)&BindHandle, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR(Status)) { return EFI_NOT_FOUND; } Version = BindHandle->Version; Ptr = (UINT16*)&Version; UnicodeSPrint(GopVersion, 40, L"7.0.%04d", *(Ptr)); return EFI_SUCCESS; } EFI_STATUS GetGOPDriverVersion( CHAR16 *GopVersion ) { UINTN HandleCount; EFI_HANDLE *Handles= NULL; UINTN Index; EFI_STATUS Status; EFI_HANDLE Child = 0; Status = gBS->LocateHandleBuffer( ByProtocol, &gEfiDriverBindingProtocolGuid, NULL, &HandleCount, &Handles ); for (Index = 0; Index < HandleCount ; Index++) { Status = SearchChildHandle(Handles[Index], &Child); if(!EFI_ERROR(Status)) { Status = JudgeHandleIsPCIDevice(Child, 0x02, 0x00); if(!EFI_ERROR(Status)) { return GetDriverName(Handles[Index], GopVersion); } } } return EFI_UNSUPPORTED; } /** Get Intel GOP driver version and copy it into IGD OpRegion GVER. This version is picked up by IGD driver and displayed in CUI. @param Event A pointer to the Event that triggered the callback. @param Context A pointer to private data registered with the callback function. @retval EFI_SUCCESS Video BIOS VBT information returned. @retval EFI_UNSUPPORTED Could not find VBT information (*VBiosVbtPtr = NULL). **/ EFI_STATUS EFIAPI SetGOPVersionCallback ( IN EFI_EVENT Event, IN VOID *Context ) { CHAR16 GopVersion[16]; EFI_STATUS Status; ZeroMem (GopVersion, sizeof (GopVersion)); Status = GetGOPDriverVersion(GopVersion); if(!EFI_ERROR(Status)) { StrCpyS ((CHAR16*)&(mIgdOpRegion.OpRegion->Header.GOPV[0]), 16, GopVersion); return Status; } return EFI_UNSUPPORTED; } /** Get Intel video BIOS VBT information (i.e. Pointer to VBT and VBT size). The VBT (Video BIOS Table) is a block of customizable data that is built within the video BIOS and edited by customers. @param Event A pointer to the Event that triggered the callback. @param Context A pointer to private data registered with the callback function. @retval EFI_SUCCESS Video BIOS VBT information returned. @retval EFI_UNSUPPORTED Could not find VBT information (*VBiosVbtPtr = NULL). **/ EFI_STATUS GetVBiosVbtCallback ( IN EFI_EVENT Event, IN VOID *Context ) { INTEL_VBIOS_PCIR_STRUCTURE *PcirBlockPtr; UINT16 PciVenderId; UINT16 PciDeviceId; INTEL_VBIOS_OPTION_ROM_HEADER *VBiosPtr; VBIOS_VBT_STRUCTURE *VBiosVbtPtr; VBIOS_VBT_STRUCTURE *VbtFileBuffer = NULL; VBiosPtr = (INTEL_VBIOS_OPTION_ROM_HEADER *)(UINTN)(VBIOS_LOCATION_PRIMARY); PcirBlockPtr = (INTEL_VBIOS_PCIR_STRUCTURE *)((UINT8 *)VBiosPtr + VBiosPtr->PcirOffset); PciVenderId = PcirBlockPtr->VendorId; PciDeviceId = PcirBlockPtr->DeviceId; // // If the video BIOS is not at 0xC0000 or it is not an Intel video BIOS get // the integrated Intel video BIOS (must be uncompressed). // if ((VBiosPtr->Signature != OPTION_ROM_SIGNATURE) || (PciVenderId != IGD_VID) || (PciDeviceId != IGD_DID_VLV)) { GetIntegratedIntelVBiosPtr (&VBiosPtr); if(VBiosPtr) { // // Video BIOS found. // PcirBlockPtr = (INTEL_VBIOS_PCIR_STRUCTURE *)((UINT8 *)VBiosPtr + VBiosPtr->PcirOffset); PciVenderId = PcirBlockPtr->VendorId; if( (VBiosPtr->Signature != OPTION_ROM_SIGNATURE) || (PciVenderId != IGD_VID)) { // // Intel video BIOS not found. // VBiosVbtPtr = NULL; return EFI_UNSUPPORTED; } } else { // // No Video BIOS found, try to get VBT from FV. // GetIntegratedIntelVbtPtr (&VbtFileBuffer); if (VbtFileBuffer != NULL) { // // Video BIOS not found, use VBT from FV // DEBUG ((EFI_D_ERROR, "VBT data found\n")); (gBS->CopyMem) ( mIgdOpRegion.OpRegion->VBT.GVD1, VbtFileBuffer, VbtFileBuffer->HeaderVbtSize ); FreePool (VbtFileBuffer); return EFI_SUCCESS; } } if (VBiosPtr == NULL) { // // Intel video BIOS not found. // VBiosVbtPtr = NULL; return EFI_UNSUPPORTED; } } DEBUG ((EFI_D_ERROR, "VBIOS found at 0x%X\n", VBiosPtr)); VBiosVbtPtr = (VBIOS_VBT_STRUCTURE *) ((UINT8 *) VBiosPtr + VBiosPtr->VbtOffset); if ((*((UINT32 *) (VBiosVbtPtr->HeaderSignature))) != VBT_SIGNATURE) { return EFI_UNSUPPORTED; } // // Initialize Video BIOS version with its build number. // mIgdOpRegion.OpRegion->Header.VVER[0] = VBiosVbtPtr->CoreBlockBiosBuild[0]; mIgdOpRegion.OpRegion->Header.VVER[1] = VBiosVbtPtr->CoreBlockBiosBuild[1]; mIgdOpRegion.OpRegion->Header.VVER[2] = VBiosVbtPtr->CoreBlockBiosBuild[2]; mIgdOpRegion.OpRegion->Header.VVER[3] = VBiosVbtPtr->CoreBlockBiosBuild[3]; (gBS->CopyMem) ( mIgdOpRegion.OpRegion->VBT.GVD1, VBiosVbtPtr, VBiosVbtPtr->HeaderVbtSize ); // // Return final status // return EFI_SUCCESS; } /** Graphics OpRegion / Software SCI driver installation function. @param ImageHandle Handle for this drivers loaded image protocol. @param SystemTable EFI system table. @retval EFI_SUCCESS The driver installed without error. @retval EFI_ABORTED The driver encountered an error and could not complete installation of the ACPI tables. **/ EFI_STATUS IgdOpRegionInit ( void ) { EFI_HANDLE Handle; EFI_STATUS Status; EFI_GLOBAL_NVS_AREA_PROTOCOL *GlobalNvsArea; UINT32 DwordData; EFI_CPU_IO2_PROTOCOL *CpuIo; UINT16 Data16; UINT16 AcpiBase; VOID *gConOutNotifyReg; // // Locate the Global NVS Protocol. // Status = gBS->LocateProtocol ( &gEfiGlobalNvsAreaProtocolGuid, NULL, (void **)&GlobalNvsArea ); ASSERT_EFI_ERROR (Status); // // Allocate an ACPI NVS memory buffer as the IGD OpRegion, zero initialize // the first 1K, and set the IGD OpRegion pointer in the Global NVS // area structure. // Status = (gBS->AllocatePool) ( EfiACPIMemoryNVS, sizeof (IGD_OPREGION_STRUC), (void **)&mIgdOpRegion.OpRegion ); ASSERT_EFI_ERROR (Status); (gBS->SetMem) ( mIgdOpRegion.OpRegion, sizeof (IGD_OPREGION_STRUC), 0 ); GlobalNvsArea->Area->IgdOpRegionAddress = (UINT32)(UINTN)(mIgdOpRegion.OpRegion); // // If IGD is disabled return // if (IgdMmPci32 (0) == 0xFFFFFFFF) { return EFI_SUCCESS; } // // Initialize OpRegion Header // (gBS->CopyMem) ( mIgdOpRegion.OpRegion->Header.SIGN, HEADER_SIGNATURE, sizeof(HEADER_SIGNATURE) ); // // Set OpRegion Size in KBs // mIgdOpRegion.OpRegion->Header.SIZE = HEADER_SIZE/1024; // // FIXME: Need to check Header OVER Field and the supported version. // mIgdOpRegion.OpRegion->Header.OVER = (UINT32) (LShiftU64 (HEADER_OPREGION_VER, 16) + LShiftU64 (HEADER_OPREGION_REV, 8)); #ifdef ECP_FLAG CopyMem(mIgdOpRegion.OpRegion->Header.SVER, gSVER, sizeof(gSVER)); #else gBS->CopyMem( mIgdOpRegion.OpRegion->Header.SVER, gSVER, sizeof(gSVER) ); #endif DEBUG ((EFI_D_ERROR, "System BIOS ID is %a\n", mIgdOpRegion.OpRegion->Header.SVER)); mIgdOpRegion.OpRegion->Header.MBOX = HEADER_MBOX_SUPPORT; if( 1 == DxePlatformSaPolicy->IdleReserve) { mIgdOpRegion.OpRegion->Header.PCON = (mIgdOpRegion.OpRegion->Header.PCON & 0xFFFC) | BIT1; } else { mIgdOpRegion.OpRegion->Header.PCON = (mIgdOpRegion.OpRegion->Header.PCON & 0xFFFC) | (BIT1 | BIT0); } // //For graphics driver to identify if LPE Audio/HD Audio is enabled on the platform // mIgdOpRegion.OpRegion->Header.PCON &= AUDIO_TYPE_SUPPORT_MASK; mIgdOpRegion.OpRegion->Header.PCON &= AUDIO_TYPE_FIELD_MASK; if ( 1 == DxePlatformSaPolicy->AudioTypeSupport ) { mIgdOpRegion.OpRegion->Header.PCON = HD_AUDIO_SUPPORT; mIgdOpRegion.OpRegion->Header.PCON |= AUDIO_TYPE_FIELD_VALID; } // // Initialize OpRegion Mailbox 1 (Public ACPI Methods). // //<TODO> The initial setting of mailbox 1 fields is implementation specific. // Adjust them as needed many even coming from user setting in setup. // //Workaround to solve LVDS is off after entering OS in desktop platform // mIgdOpRegion.OpRegion->MBox1.CLID = DxePlatformSaPolicy->IgdPanelFeatures.LidStatus; // // Initialize OpRegion Mailbox 3 (ASLE Interrupt and Power Conservation). // //<TODO> The initial setting of mailbox 3 fields is implementation specific. // Adjust them as needed many even coming from user setting in setup. // // // Do not initialize TCHE. This field is written by the graphics driver only. // // // The ALSI field is generally initialized by ASL code by reading the embedded controller. // mIgdOpRegion.OpRegion->MBox3.BCLP = BACKLIGHT_BRIGHTNESS; mIgdOpRegion.OpRegion->MBox3.PFIT = (FIELD_VALID_BIT | PFIT_STRETCH); if ( DxePlatformSaPolicy->IgdPanelFeatures.PFITStatus == 2) { // // Center // mIgdOpRegion.OpRegion->MBox3.PFIT = (FIELD_VALID_BIT | PFIT_CENTER); } else if (DxePlatformSaPolicy->IgdPanelFeatures.PFITStatus == 1) { // // Stretch // mIgdOpRegion.OpRegion->MBox3.PFIT = (FIELD_VALID_BIT | PFIT_STRETCH); } else { // // Auto // mIgdOpRegion.OpRegion->MBox3.PFIT = (FIELD_VALID_BIT | PFIT_SETUP_AUTO); } // // Set Initial current Brightness // mIgdOpRegion.OpRegion->MBox3.CBLV = (INIT_BRIGHT_LEVEL | FIELD_VALID_BIT); // // <EXAMPLE> Create a static Backlight Brightness Level Duty cycle Mapping Table // Possible 20 entries (example used 10), each 16 bits as follows: // [15] = Field Valid bit, [14:08] = Level in Percentage (0-64h), [07:00] = Desired duty cycle (0 - FFh). // // % Brightness mIgdOpRegion.OpRegion->MBox3.BCLM[0] = ( ( 0 << 8 ) + ( 0xFF - 0xFC ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[1] = ( ( 1 << 8 ) + ( 0xFF - 0xFC ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[2] = ( ( 10 << 8 ) + ( 0xFF - 0xE5 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[3] = ( ( 19 << 8 ) + ( 0xFF - 0xCE ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[4] = ( ( 28 << 8 ) + ( 0xFF - 0xB7 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[5] = ( ( 37 << 8 ) + ( 0xFF - 0xA0 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[6] = ( ( 46 << 8 ) + ( 0xFF - 0x89 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[7] = ( ( 55 << 8 ) + ( 0xFF - 0x72 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[8] = ( ( 64 << 8 ) + ( 0xFF - 0x5B ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[9] = ( ( 73 << 8 ) + ( 0xFF - 0x44 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[10] = ( ( 82 << 8 ) + ( 0xFF - 0x2D ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[11] = ( ( 91 << 8 ) + ( 0xFF - 0x16 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.BCLM[12] = ( (100 << 8 ) + ( 0xFF - 0x00 ) + WORD_FIELD_VALID_BIT); mIgdOpRegion.OpRegion->MBox3.PCFT = ((UINT32) GlobalNvsArea->Area->IgdPowerConservation) | BIT31; // // Create the notification and register callback function on the PciIo installation, // // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_CALLBACK, (EFI_EVENT_NOTIFY)GetVBiosVbtCallback, NULL, &mConOutEvent ); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { return Status; } Status = gBS->RegisterProtocolNotify ( #ifdef ECP_FLAG &gExitPmAuthProtocolGuid, #else &gEfiDxeSmmReadyToLockProtocolGuid, #endif mConOutEvent, &gConOutNotifyReg ); Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_CALLBACK, (EFI_EVENT_NOTIFY)SetGOPVersionCallback, NULL, &mSetGOPverEvent ); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { return Status; } Status = gBS->RegisterProtocolNotify ( &gEfiGraphicsOutputProtocolGuid, mSetGOPverEvent, &gConOutNotifyReg ); // // Initialize hardware state: // Set ASLS Register to the OpRegion physical memory address. // Set SWSCI register bit 15 to a "1" to activate SCI interrupts. // IgdMmPci32 (IGD_ASLS_OFFSET) = (UINT32)(UINTN)(mIgdOpRegion.OpRegion); IgdMmPci16AndThenOr (IGD_SWSCI_OFFSET, ~(BIT0), BIT15); DwordData = IgdMmPci32 (IGD_ASLS_OFFSET); S3BootScriptSavePciCfgWrite ( S3BootScriptWidthUint32, (UINTN) (EFI_PCI_ADDRESS (IGD_BUS, IGD_DEV, IGD_FUN_0, IGD_ASLS_OFFSET)), 1, &DwordData ); DwordData = IgdMmPci32 (IGD_SWSCI_OFFSET); S3BootScriptSavePciCfgWrite ( S3BootScriptWidthUint32, (UINTN) (EFI_PCI_ADDRESS (IGD_BUS, IGD_DEV, IGD_FUN_0, IGD_SWSCI_OFFSET)), 1, &DwordData ); AcpiBase = MmPci16 ( 0, DEFAULT_PCI_BUS_NUMBER_PCH, PCI_DEVICE_NUMBER_PCH_LPC, PCI_FUNCTION_NUMBER_PCH_LPC, R_PCH_LPC_ACPI_BASE ) & B_PCH_LPC_ACPI_BASE_BAR; // // Find the CPU I/O Protocol. ASSERT if not found. // Status = gBS->LocateProtocol ( &gEfiCpuIo2ProtocolGuid, NULL, (void **)&CpuIo ); ASSERT_EFI_ERROR (Status); CpuIo->Io.Read ( CpuIo, EfiCpuIoWidthUint16, AcpiBase + R_PCH_ACPI_GPE0a_STS, 1, &Data16 ); // // Clear the B_PCH_ACPI_GPE0a_STS_GUNIT_SCI bit in R_PCH_ACPI_GPE0a_STS by writing a '1'. // Data16 |= B_PCH_ACPI_GPE0a_STS_GUNIT_SCI; CpuIo->Io.Write ( CpuIo, EfiCpuIoWidthUint16, AcpiBase + R_PCH_ACPI_GPE0a_STS, 1, &Data16 ); // // Install OpRegion / Software SCI protocol // Handle = NULL; Status = gBS->InstallMultipleProtocolInterfaces ( &Handle, &gIgdOpRegionProtocolGuid, &mIgdOpRegion, NULL ); ASSERT_EFI_ERROR (Status); // // Return final status // return EFI_SUCCESS; }
214955.c
#include "stm32f0xx_hal.h" /** * @brief Handle SPI FIFO Communication Timeout. * @param hspi pointer to a SPI_HandleTypeDef structure that contains * the configuration information for SPI module. * @param Fifo Fifo to check * @param State Fifo state to check * @param Timeout Timeout duration * @param Tickstart tick start value * @retval HAL status */ static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Fifo, uint32_t State, uint32_t Timeout, uint32_t Tickstart) { while ((hspi->Instance->SR & Fifo) != State) { if ((Fifo == SPI_SR_FRLVL) && (State == SPI_FRLVL_EMPTY)) { /* Read 8bit CRC to flush Data Register */ READ_REG(*((__IO uint8_t *)&hspi->Instance->DR)); } if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - Tickstart) >= Timeout) || (Timeout == 0U)) { /* Disable the SPI and reset the CRC: the CRC value should be cleared on both master and slave sides in order to resynchronize the master and slave for their respective CRC calculation */ /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE) || (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) { /* Disable SPI peripheral */ __HAL_SPI_DISABLE(hspi); } /* Reset CRC Calculation */ if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SPI_RESET_CRC(hspi); } hspi->State = HAL_SPI_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hspi); return HAL_TIMEOUT; } } } return HAL_OK; } /** * @brief Handle SPI Communication Timeout. * @param hspi pointer to a SPI_HandleTypeDef structure that contains * the configuration information for SPI module. * @param Flag SPI flag to check * @param State flag state to check * @param Timeout Timeout duration * @param Tickstart tick start value * @retval HAL status */ static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus State, uint32_t Timeout, uint32_t Tickstart) { while ((__HAL_SPI_GET_FLAG(hspi, Flag) ? SET : RESET) != State) { if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - Tickstart) >= Timeout) || (Timeout == 0U)) { /* Disable the SPI and reset the CRC: the CRC value should be cleared on both master and slave sides in order to resynchronize the master and slave for their respective CRC calculation */ /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE) || (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) { /* Disable SPI peripheral */ __HAL_SPI_DISABLE(hspi); } /* Reset CRC Calculation */ if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SPI_RESET_CRC(hspi); } hspi->State = HAL_SPI_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hspi); return HAL_TIMEOUT; } } } return HAL_OK; } /** * @brief Handle the check of the RXTX or TX transaction complete. * @param hspi SPI handle * @param Timeout Timeout duration * @param Tickstart tick start value * @retval HAL status */ static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) { /* Control if the TX fifo is empty */ if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FTLVL, SPI_FTLVL_EMPTY, Timeout, Tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); return HAL_TIMEOUT; } /* Control the BSY flag */ if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); return HAL_TIMEOUT; } /* Control if the RX fifo is empty */ if (SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, Timeout, Tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); return HAL_TIMEOUT; } return HAL_OK; } /** * @brief Transmit an amount of data in blocking mode. * @param hspi pointer to a SPI_HandleTypeDef structure that contains * the configuration information for SPI module. * @param pData pointer to data buffer * @param Size amount of data to be sent * @param Timeout Timeout duration * @retval HAL status */ HAL_StatusTypeDef disp_HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart; HAL_StatusTypeDef errorcode = HAL_OK; uint16_t initial_TxXferCount; if ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) || ((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (Size > 1U))) { /* in this case, 16-bit access is performed on Data So, check Data is 16-bit aligned address */ assert_param(IS_SPI_16BIT_ALIGNED_ADDRESS(pData)); } /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); /* Process Locked */ __HAL_LOCK(hspi); /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); initial_TxXferCount = Size; if (hspi->State != HAL_SPI_STATE_READY) { errorcode = HAL_BUSY; goto error; } if ((pData == NULL) || (Size == 0U)) { errorcode = HAL_ERROR; goto error; } /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; hspi->pTxBuffPtr = (uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; /*Init field not used in handle to zero */ hspi->pRxBuffPtr = (uint8_t *)NULL; hspi->RxXferSize = 0U; hspi->RxXferCount = 0U; hspi->TxISR = NULL; hspi->RxISR = NULL; /* Configure communication direction : 1Line */ if (hspi->Init.Direction == SPI_DIRECTION_1LINE) { SPI_1LINE_TX(hspi); } #if (USE_SPI_CRC != 0U) /* Reset CRC Calculation */ if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SPI_RESET_CRC(hspi); } #endif /* USE_SPI_CRC */ /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) { /* Enable SPI peripheral */ __HAL_SPI_ENABLE(hspi); } /* Transmit data in 16 Bit mode */ if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } /* Transmit data in 16 Bit mode */ while (hspi->TxXferCount > 0U) { /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } else { /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { errorcode = HAL_TIMEOUT; goto error; } } } } /* Transmit data in 8 Bit mode */ else { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { if (hspi->TxXferCount > 1U) { /* write on the data register in packing mode */ hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } else { *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); hspi->pTxBuffPtr ++; hspi->TxXferCount--; } } while (hspi->TxXferCount > 0U) { /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; } else { /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { errorcode = HAL_TIMEOUT; goto error; } } } } #if (USE_SPI_CRC != 0U) /* Enable CRC Transmission */ if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } #endif /* USE_SPI_CRC */ /* Check the end of the transaction */ if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK) { hspi->ErrorCode = HAL_SPI_ERROR_FLAG; } /* Clear overrun flag in 2 Lines communication mode because received is not read */ if (hspi->Init.Direction == SPI_DIRECTION_2LINES) { __HAL_SPI_CLEAR_OVRFLAG(hspi); } if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { errorcode = HAL_ERROR; } error: hspi->State = HAL_SPI_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hspi); return errorcode; }
821264.c
#include "ckcsym.h" int xcmdsrc = 0; #ifdef NOICP int cmdsrc() { return(0); } #endif /* NOICP */ /* C K U U S 5 -- "User Interface" for C-Kermit, part 5 */ /* Authors: Frank da Cruz <[email protected]>, The Kermit Project, New York City Jeffrey E Altman <[email protected]> Secure Endpoints Inc., New York City Copyright (C) 1985, 2021, Trustees of Columbia University in the City of New York. All rights reserved. See the C-Kermit COPYING.TXT file or the copyright text in the ckcmai.c module for disclaimer and permissions. */ /* Includes */ #include "ckcdeb.h" #include "ckcasc.h" #include "ckcker.h" #include "ckuusr.h" #ifdef DCMDBUF char *line; /* Character buffer for anything */ char *tmpbuf; #else char line[LINBUFSIZ+1]; char tmpbuf[TMPBUFSIZ+1]; /* Temporary buffer */ #endif /* DCMDBUF */ char lasttakeline[TMPBUFSIZ+1]; /* Last TAKE-file line */ #ifndef NOICP #include "ckcnet.h" #ifndef NOCSETS #include "ckcxla.h" #endif /* NOCSETS */ #ifdef MAC #include "ckmasm.h" #endif /* MAC */ #ifdef CK_SSL #include "ck_ssl.h" #endif /* CK_SSL */ extern char * ck_cryear; /* (ckcmai.c) Latest C-Kermit copyright year */ #ifdef OS2 #include "ckoetc.h" #ifndef NT #define INCL_NOPM #define INCL_VIO /* Needed for ckocon.h */ #include <os2.h> #undef COMMENT #else /* NT */ #include <windows.h> #define TAPI_CURRENT_VERSION 0x00010004 #include <tapi.h> #include <mcx.h> #include "ckntap.h" #define APIRET ULONG extern int DialerHandle; extern int StartedFromDialer; #endif /* NT */ #include "ckocon.h" #include "ckokey.h" #ifdef KUI #include "ikui.h" #endif /* KUI */ #ifdef putchar #undef putchar #endif /* putchar */ #define putchar(x) conoc(x) extern int cursor_save ; extern bool cursorena[] ; #endif /* OS2 */ /* 2010-03-09 SMS. VAX C V3.1-051 needs <stat.h> for off_t. */ #ifdef VMS #include <stat.h> #endif /* def VMS */ /* For formatted screens, "more?" prompting, etc. */ #ifdef FT18 #define isxdigit(c) isdigit(c) #endif /* FT18 */ #ifdef STRATUS /* Stratus Computer, Inc. VOS */ #ifdef putchar #undef putchar #endif /* putchar */ #define putchar(x) conoc(x) #ifdef getchar #undef getchar #endif /* getchar */ #define getchar(x) coninc(0) #endif /* STRATUS */ /* External variables */ extern int carrier, cdtimo, local, quiet, backgrd, bgset, sosi, xsuspend, binary, escape, xargs, flow, cmdmsk, duplex, ckxech, seslog, what, inserver, diractive, tlevel, cwdf, nfuncs, msgflg, remappd, hints, mdmtyp, zincnt, cmask, rcflag, success, xitsta, pflag, tnlm, tn_nlm, xitwarn, debses, xaskmore, parity, saveask, wasclosed, whyclosed, cdactive, rcdactive, keepallchars, cmd_err; #ifdef LOCUS extern int locus, autolocus; #endif /* LOCUS */ #ifndef NOMSEND extern int addlist; #endif /* NOMSEND */ #ifdef CK_SPEED extern int prefixing; #endif /* CK_SPEED */ extern int g_matchdot; #ifdef RECURSIVE extern int recursive; #endif /* RECURSIVE */ extern int xfiletype; #ifdef IKSDCONF extern char * iksdconf; extern int iksdcf; #endif /* IKSDCONF */ #ifdef CK_RECALL extern int on_recall; #endif /* CK_RECALL */ extern int ngetpath, exitonclose; extern char * getpath[]; extern CHAR * epktmsg; extern char * snd_move; extern char * snd_rename; extern char * rcv_move; extern char * rcv_rename; extern char * g_snd_move; extern char * g_snd_rename; extern char * g_rcv_move; extern char * g_rcv_rename; extern char * nm[]; #ifdef CK_UTSNAME extern char unm_mch[]; extern char unm_mod[]; extern char unm_nam[]; extern char unm_rel[]; extern char unm_ver[]; #endif /* CK_UTSNAME */ #ifndef NOPUSH #ifndef NOFRILLS extern char editor[]; extern char editfile[]; extern char editopts[]; #ifdef BROWSER extern char browser[]; extern char browsopts[]; extern char browsurl[]; #endif /* BROWSER */ #endif /* NOFRILLS */ #endif /* NOPUSH */ #ifndef NOFRILLS #ifndef NORENAME _PROTOTYP(VOID shorename, (void)); #endif /* NORENAME */ #endif /* NOFRILLS */ #ifndef NOSERVER extern char * x_user, * x_passwd, * x_acct; #endif /* NOSERVER */ #ifdef CKLOGDIAL extern int dialog; extern char diafil[]; #endif /* CKLOGDIAL */ #ifdef CKROOT extern int ckrooterr; #endif /* CKROOT */ #ifndef NOSPL extern int cfilef, xxdot, vareval; extern char cmdfil[]; struct localvar * localhead[CMDSTKL]; struct localvar * localtail = NULL; struct localvar * localnext = NULL; _PROTOTYP( VOID shosexp, (void) ); _PROTOTYP( static VOID shoinput, (void) ); _PROTOTYP( static char gettok, (void) ); _PROTOTYP( static VOID factor, (void) ); _PROTOTYP( static VOID term, (void) ); _PROTOTYP( static VOID termp, (void) ); _PROTOTYP( static VOID exprp, (void) ); _PROTOTYP( static VOID expr, (void) ); _PROTOTYP( static VOID simple, (void) ); _PROTOTYP( static VOID simpler, (void) ); _PROTOTYP( static VOID simplest, (void) ); _PROTOTYP( static CK_OFF_T xparse, (void) ); #endif /* NOSPL */ #ifndef NOSHOW _PROTOTYP( int sho_iks, (void) ); #endif /* NOSHOW */ #ifdef MAC char * ckprompt = "Mac-Kermit>"; /* Default prompt for Macintosh */ char * ikprompt = "IKSD>"; #else /* Not MAC */ #ifdef NOSPL #ifdef OS2 char * ckprompt = "K-95> "; /* Default prompt for Win32 */ char * ikprompt = "IKSD> "; #else char * ckprompt = "C-Kermit>"; char * ikprompt = "IKSD>"; #endif /* NT */ #else /* NOSPL */ #ifdef OS2 /* Default prompt for OS/2 and Win32 */ /* fdc 2013-12-06 - C-Kermit 9.0 and later is just "C-Kermit" */ #ifdef NT #ifdef COMMENT char * ckprompt = "[\\freplace(\\flongpath(\\v(dir)),/,\\\\)] K-95> "; #else char * ckprompt = "[\\freplace(\\flongpath(\\v(dir)),/,\\\\)] C-Kermit> "; #endif /* COMMENT */ char * ikprompt = "[\\freplace(\\flongpath(\\v(dir)),/,\\\\)] IKSD> "; #else /* NT */ #ifdef COMMENT char * ckprompt = "[\\freplace(\\v(dir),/,\\\\)] K-95> "; #else char * ckprompt = "[\\freplace(\\v(dir),/,\\\\)] C-Kermit> "; #endif /* COMMENT */ char * ikprompt = "[\\freplace(\\v(dir),/,\\\\)] IKSD> "; #endif /* NT */ #else /* OS2 */ #ifdef VMS char * ckprompt = "\\v(dir) C-Kermit>"; /* Default prompt VMS */ char * ikprompt = "\\v(dir) IKSD>"; #else #ifdef UNIX /* Note: parens, not brackets, because of ISO646 */ /* Collapse long paths using ~ notation if in home directory tree */ char * ckprompt = "(\\freplace(\\v(dir),\\fpathname(\\v(home)),~/)) C-Kermit>"; char * ikprompt = "(\\freplace(\\v(dir),\\fpathname(\\v(home)),~/)) IKSD>"; #else /* Default prompt for other platforms */ char * ckprompt = "(\\v(dir)) C-Kermit>"; /* Default prompt for others */ char * ikprompt = "(\\v(dir)) IKSD>"; #endif /* UNIX */ #endif /* VMS */ #endif /* NT */ #endif /* NOSPL */ #endif /* MAC */ #ifndef CCHMAXPATH #define CCHMAXPATH 257 #endif /* CCHMAXPATH */ char inidir[CCHMAXPATH] = { NUL, NUL }; /* Directory INI file executed from */ #ifdef TNCODE extern int tn_b_nlm; /* TELNET BINARY newline mode */ #endif /* TNCODE */ #ifndef NOKVERBS extern struct keytab kverbs[]; /* Table of \Kverbs */ extern int nkverbs; /* Number of \Kverbs */ #endif /* NOKVERBS */ #ifndef NOPUSH extern int nopush; #endif /* NOPUSH */ #ifdef CK_RECALL extern int cm_recall; #endif /* CK_RECALL */ extern char *ccntab[]; /* Printer stuff */ extern char *printername; extern int printpipe; #ifdef BPRINT extern int printbidi, pportparity, pportflow; extern long pportspeed; #endif /* BPRINT */ #ifdef OS2 _PROTOTYP (int os2getcp, (void) ); _PROTOTYP (int os2getcplist, (int *, int) ); #ifdef OS2MOUSE extern int tt_mouse; #endif /* OS2MOUSE */ extern int tt_update, tt_updmode, updmode, tt_utf8; #ifndef IKSDONLY extern int tt_status[]; #endif /* IKSDONLY */ #ifdef PCFONTS extern struct keytab term_font[]; #else #ifdef KUI extern struct keytab * term_font; #endif /* KUI */ #endif /* PCFONTS */ extern int ntermfont, tt_font, tt_font_size; extern unsigned char colornormal, colorunderline, colorstatus, colorhelp, colorselect, colorborder, colorgraphic, colordebug, colorreverse, colorcmd, coloritalic; extern int priority; extern struct keytab prtytab[]; extern int nprty; char * cmdmac = NULL; #endif /* OS2 */ #ifdef VMS _PROTOTYP (int zkermini, (char *, int, char *) ); #endif /* VMS */ extern long vernum; extern int inecho, insilence, inbufsize, nvars, inintr; extern char *protv, *fnsv, *cmdv, *userv, *ckxv, *ckzv, *ckzsys, *xlav, *cknetv, *clcmds; #ifdef OS2 extern char *ckyv; #endif /* OS2 */ #ifdef CK_AUTHENTICATION extern char * ckathv; #endif /* CK_AUTHENTICATION */ #ifdef CK_SSL extern char * cksslv; #endif /* CK_SSL */ #ifdef CK_ENCRYPTION #ifndef CRYPT_DLL extern char * ckcrpv; #endif /* CRYPT_DLL */ #endif /* CK_ENCRYPTION */ #ifdef SSHBUILTIN extern char *cksshv; #ifdef SFTP_BUILTIN extern char *cksftpv; #endif /* SFTP_BUILTIN */ #endif /* SSHBUILTIN */ #ifdef TNCODE extern char *cktelv; #endif /* TNCODE */ #ifndef NOFTP #ifndef SYSFTP extern char * ckftpv; #endif /* SYSFTP */ #endif /* NOFTP */ extern int srvidl; #ifdef OS2 extern char *ckonetv; extern int interm; #ifdef CK_NETBIOS extern char *ckonbiv; #endif /* CK_NETBIOS */ #ifdef OS2MOUSE extern char *ckomouv; #endif /* OS2MOUSE */ #endif /* OS2 */ #ifndef NOLOCAL extern char *connv; #endif /* NOLOCAL */ #ifndef NODIAL extern char *dialv; #endif /* NODIAL */ #ifndef NOSCRIPT extern char *loginv; extern int secho; #endif /* NOSCRIPT */ #ifndef NODIAL extern int nmdm, dirline; extern struct keytab mdmtab[]; #endif /* NODIAL */ extern int network, nettype, ttnproto; #ifdef OS2 #ifndef NOTERM /* SET TERMINAL items... */ extern int tt_type, tt_arrow, tt_keypad, tt_wrap, tt_answer, tt_scrsize[]; extern int tt_bell, tt_roll[], tt_ctstmo, tt_cursor, tt_pacing, tt_type_mode; extern char answerback[]; extern struct tt_info_rec tt_info[]; /* Indexed by terminal type */ extern int max_tt; #endif /* NOTERM */ #endif /* OS2 */ _PROTOTYP( VOID shotrm, (void) ); _PROTOTYP( int shofea, (void) ); #ifdef OS2 extern int tt_rows[], tt_cols[]; #else /* OS2 */ extern int tt_rows, tt_cols; #endif /* OS2 */ extern int cmd_rows, cmd_cols; #ifdef CK_TMPDIR extern int f_tmpdir; /* Directory changed temporarily */ extern char savdir[]; /* Temporary directory */ #endif /* CK_TMPDIR */ #ifndef NOLOCAL extern int tt_crd, tt_lfd, tt_escape; #endif /* NOLOCAL */ #ifndef NOCSETS extern int language, nfilc, tcsr, tcsl, tcs_transp, fcharset; extern struct keytab fcstab[]; extern struct csinfo fcsinfo[]; #ifndef MAC extern struct keytab ttcstab[]; #endif /* MAC */ #endif /* NOCSETS */ extern long speed; #ifndef NOXMIT extern int xmitf, xmitl, xmitp, xmitx, xmits, xmitw, xmitt; extern char xmitbuf[]; #endif /* NOXMIT */ extern char **xargv, *versio, *ckxsys, *dftty, *lp; #ifdef DCMDBUF extern char *cmdbuf, *atmbuf; /* Command buffers */ #ifndef NOSPL extern char *savbuf; /* Command buffers */ #endif /* NOSPL */ #else extern char cmdbuf[], atmbuf[]; /* Command buffers */ #ifndef NOSPL extern char savbuf[]; /* Command buffers */ #endif /* NOSPL */ #endif /* DCMDBUF */ extern char toktab[], ttname[], psave[]; extern CHAR sstate, feol; extern int cmflgs, techo, repars, ncmd; extern struct keytab cmdtab[]; #ifndef NOSETKEY KEY *keymap; #ifndef OS2 #define mapkey(x) keymap[x] #endif /* OS2 */ MACRO *macrotab; _PROTOTYP( VOID shostrdef, (CHAR *) ); #endif /* NOSETKEY */ extern int cmdlvl; #ifndef NOSPL extern struct mtab *mactab; extern struct keytab mackey[]; extern struct keytab vartab[], fnctab[], iftab[]; extern int maclvl, nmac, mecho, fndiags, fnerror, fnsuccess, nif; #endif /* NOSPL */ FILE *tfile[MAXTAKE]; /* TAKE file stack */ char *tfnam[MAXTAKE]; /* Name of TAKE file */ int tfline[MAXTAKE]; /* Current line number */ int tfblockstart[MAXTAKE]; /* Current block-start line */ int topcmd = -1; /* cmdtab index of current command */ int havetoken = 0; extern int dblquo; /* Doublequoting enabled */ #ifdef DCMDBUF /* Initialization filespec */ char *kermrc = NULL; #else char kermrcb[KERMRCL]; char *kermrc = kermrcb; #endif /* DCMDBUF */ int noherald = 0; int cm_retry = 1; /* Command retry enabled */ xx_strp xxstring = zzstring; #ifndef NOXFER extern int displa, bye_active, protocol, pktlog, remfile, rempipe, unkcs, keep, lf_opts, fncnv, pktpaus, autodl, xfrcan, xfrchr, xfrnum, srvtim, srvdis, query, retrans, streamed, reliable, crunched, timeouts, fnrpath, autopath, rpackets, spackets, epktrcvd, srvping; #ifdef CK_AUTODL extern int inautodl, cmdadl; #endif /* CK_AUTODL */ #ifndef NOSERVER extern int en_asg, en_cwd, en_cpy, en_del, en_dir, en_fin, en_bye, en_ret, en_get, en_hos, en_que, en_ren, en_sen, en_set, en_spa, en_typ, en_who, en_mai, en_pri, en_mkd, en_rmd, en_xit, en_ena; #endif /* NOSERVER */ extern int atcapr, atenci, atenco, atdati, atdato, atleni, atleno, atblki, atblko, attypi, attypo, atsidi, atsido, atsysi, atsyso, atdisi, atdiso; #ifdef STRATUS extern int atfrmi, atfrmo, atcrei, atcreo, atacti, atacto; #endif /* STRATUS */ #ifdef CK_PERMS extern int atlpri, atlpro, atgpri, atgpro; #endif /* CK_PERMS */ #ifdef CK_LOGIN extern char * anonfile; /* Anonymous login init file */ extern char * anonroot; /* Anonymous file-system root */ extern char * userfile; /* Forbidden user file */ extern int isguest; /* Flag for anonymous user */ #endif /* CK_LOGIN */ #endif /* NOXFER */ #ifdef DCMDBUF int *xquiet = NULL; int *xvarev = NULL; #else int xquiet[CMDSTKL]; int xvarev[CMDSTKL]; #endif /* DCMDBUF */ char * prstring[CMDSTKL]; #ifndef NOSPL extern long ck_alarm; extern char alrm_date[], alrm_time[]; /* Local declarations */ static int nulcmd = 0; /* Flag for next cmd to be ignored */ /* Definitions for predefined macros */ /* First, the single-line macros, installed with addmac()... */ /* IBM-LINEMODE macro */ char *m_ibm = "set parity mark, set dupl half, set handsh xon, set flow none"; /* FATAL macro */ char *m_fat = "if def \\%1 echo \\%1, if not = \\v(local) 0 hangup, stop 1"; #ifdef CK_SPEED #ifdef IRIX65 char *m_fast = "set win 30, set rec pack 4000, set prefix cautious"; #else #ifdef IRIX /* Because of bug in telnet server */ char *m_fast = "set window 30, set rec pack 4000, set send pack 4000,\ set pref cautious"; #else #ifdef pdp11 char *m_fast = "set win 3, set rec pack 1024, set prefix cautious"; #else #ifdef BIGBUFOK char *m_fast = "set win 30, set rec pack 4000, set prefix cautious"; #else char *m_fast = "set win 4, set rec pack 2200, set prefix cautious"; #endif /* BIGBUFOK */ #endif /* IRIX */ #endif /* IRIX65 */ #endif /* pdp11 */ #ifdef pdp11 char *m_cautious = "set win 2, set rec pack 512, set prefixing cautious"; #else char *m_cautious = "set win 4, set rec pack 1000, set prefixing cautious"; #endif /* pdp11 */ char *m_robust = "set win 1, set rec pack 90, set prefixing all, \ set reliable off, set clearchannel off, set send timeout 20 fixed"; #else #ifdef BIGBUFOK #ifdef IRIX65 char *m_fast = "set win 30, set rec pack 4000"; #else #ifdef IRIX char *m_fast = "set win 30, set rec pack 4000, set send pack 4000"; #else char *m_fast = "set win 30, set rec pack 4000"; #endif /* IRIX */ #endif /* IRIX65 */ #else /* Not BIGBUFOK */ char *m_fast = "set win 4, set rec pack 2200"; #endif /* BIGBUFOK */ char *m_cautious = "set win 4, set rec pack 1000"; char *m_robust = "set win 1, set rec pack 90, set reliable off,\ set send timeout 20 fixed"; #endif /* CK_SPEED */ #ifdef VMS char *m_purge = "run purge \\%*"; #endif /* VMS */ #ifdef OS2 char *m_manual = "browse \\v(exedir)docs/manual/kermit95.htm"; #endif /* OS2 */ /* Now the multiline macros, defined with addmmac()... */ /* Kermit's scripting language is so much more powerful than C that it was about a thousand time easier to implement FOR, WHILE, IF, and SWITCH commands as internal Kermit macros. This was done in 1996 for C-Kermit 6.0. The following definitions, down to #ifdef COMMENT, are from C-Kermit 9.0.304 Dev.22, April 2017, where the command parser was changed to not evaluate macro arguments on the DO command line, but to defer evaluation until after the arguments had been separated and counted. This change required subtle modifications to the internal macro templates. IMPORTANT: Internal macros must have names that start with '_', followed by three letters, e.g. _whi for WHILE. The definitions below are just templates for some other code that constructs the actual menu to be executed by filling in the \%x variables. The generated macros have names like _whil2, _whil3, etc, where the trailing number is the execution stack level. The reason for the strict naming convention is so internal macros can be parsed differently than regular ones. See ckuusr.c:isinternalmacro(), which determines the type of macro. */ /* The WHILE macro: \%1 = Loop condition \%2 = Loop body */ char *whil_def[] = { "_assign _whi\\v(cmdlevel) {_getargs,", ":_..inc,\\fcontents(\\%1),\\fcontents(\\%2),goto _..inc,:_..bot,_putargs},", "_define break goto _..bot, _define continue goto _..inc,", "do _whi\\v(cmdlevel),_assign _whi\\v(cmdlevel)", ""}; /* FOR macro for \%i-style loop variables (see dofor()...) \%1 = Loop variable \%2 = Initial value (can be an expression) \%3 = Loop exit value \%4 = Loop increment \%5 = > or < \%6 = Loop body */ char *for_def[] = { "_assign _for\\v(cmdlevel) { _getargs,", "define \\\\\\%1 \\feval(\\%2),:_..top,if \\%5 \\\\\\%1 \\%3 goto _..bot,", "\\fcontents(\\%6),:_..inc,incr \\\\\\%1 \\%4,goto _..top,:_..bot,_putargs},", "define break goto _..bot, define continue goto _..inc,", "do _for\\v(cmdlevel) \\\\%1 \\%2 \\%3 \\%4 { \\%5 },_assign _for\\v(cmdlevel)", ""}; /* FOR macro when the loop variable is itself a macro, with same arguments but slightly different quoting. */ char *foz_def[] = { "_assign _for\\v(cmdlevel) { _getargs,", "def \\%1 \\feval(\\%2),:_..top,if \\%5 \\%1 \\%3 goto _..bot,", "\\fcontents(\\%6),:_..inc,incr \\%1 \\%4,goto _..top,:_..bot,_putargs},", "def break goto _..bot, def continue goto _..inc,", "do _for\\v(cmdlevel) \\%1 \\%2 \\%3 \\%4 { \\%5 },_assign _for\\v(cmdlevel)", ""}; /* SWITCH macro \%1 = Switch variable \%2 = Switch body */ char *sw_def[] = { "_assign _sw_\\v(cmdlevel) {_getargs,", "_forward {\\fcontents(\\%1)},\\fcontents(\\%2),:default,:_..bot,_putargs},_def break goto _..bot,", "do _sw_\\v(cmdlevel),_assign _sw_\\v(cmdlevel)", ""}; /* IF macro /%1 = Commands to execute (IF part and ELSE part if any) */ char *xif_def[] = { "_assign _if_\\v(cmdlevel) {_getargs,\\fcontents(\\%1),_putargs},", "do _if_\\v(cmdlevel),_assign _if\\v(cmdlevel)", ""}; #ifdef COMMENT /* Internal macro definitions for C-Kermit 6.0 through 9.0.302 */ char *for_def[] = { "_assign _for\\v(cmdlevel) { _getargs,", "def \\\\\\%1 \\feval(\\%2),:_..top,if \\%5 \\\\\\%1 \\%3 goto _..bot,", "\\%6,:_..inc,incr \\\\\\%1 \\%4,goto _..top,:_..bot,_putargs},", "def break goto _..bot, def continue goto _..inc,", "do _for\\v(cmdlevel) \\%1 \\%2 \\%3 \\%4 { \\%5 },_assign _for\\v(cmdlevel)", ""}; char *foz_def[] = { "_assign _for\\v(cmdlevel) { _getargs,", "def \\%1 \\feval(\\%2),:_..top,if \\%5 \\%1 \\%3 goto _..bot,", "\\%6,:_..inc,incr \\%1 \\%4,goto _..top,:_..bot,_putargs},", "def break goto _..bot, def continue goto _..inc,", "do _for\\v(cmdlevel) \\%1 \\%2 \\%3 \\%4 { \\%5 },_assign _for\\v(cmdlevel)", ""}; /* SWITCH macro */ char *sw_def[] = { "_assign _sw_\\v(cmdlevel) {_getargs,", "_forward {\\%1},\\%2,:default,:_..bot,_putargs},_def break goto _..bot,", "do _sw_\\v(cmdlevel),_assign _sw_\\v(cmdlevel)", ""}; /* XIF macro */ char *xif_def[] = { "_assign _if\\v(cmdlevel) {_getargs,\\%1,_putargs},", "do _if\\v(cmdlevel),_assign _if\\v(cmdlevel)", ""}; #endif /* COMMENT */ /* Variables declared here for use by other ckuus*.c modules. Space is allocated here to save room in ckuusr.c. */ #ifdef DCMDBUF struct cmdptr *cmdstk; int *ifcmd = NULL, *count = NULL, *iftest = NULL, *intime = NULL, *inpcas = NULL, *takerr = NULL, *merror = NULL; #else struct cmdptr cmdstk[CMDSTKL]; int ifcmd[CMDSTKL], count[CMDSTKL], iftest[CMDSTKL], intime[CMDSTKL], inpcas[CMDSTKL], takerr[CMDSTKL], merror[CMDSTKL]; #endif /* DCMDBUF */ /* Macro stack */ #ifdef COMMENT char *topline = NULL; /* Program invocation arg line */ char *m_line[MACLEVEL] = { NULL, NULL }; /* Stack of macro invocation lines */ #endif /* COMMENT */ char **m_xarg[MACLEVEL]; /* Pointers to arg vector arrays */ int n_xarg[MACLEVEL]; /* Sizes of arg vector arrays */ char *m_arg[MACLEVEL][NARGS]; /* Args of each level */ int macargc[MACLEVEL]; /* Argc of each level */ char *macp[MACLEVEL]; /* Current position in each macro */ char *macx[MACLEVEL]; /* Beginning of each macro def */ char *mrval[MACLEVEL]; /* RETURN value at each level */ int lastcmd[MACLEVEL]; /* Last command at each level */ int topargc = 0; /* Argc at top level */ char **topxarg = NULL; /* Argv at top level */ char *toparg[MAXARGLIST+2]; /* Global Variables */ char *g_var[GVARS+1]; /* Global \%a..z pointers */ extern char varnam[]; /* \%x variable name buffer */ /* Arrays -- Dimension must be 'z' - ARRAYBASE + 1 */ /* Note: a_link[x] < 0 means no link; >= 0 is a link */ char **a_ptr[32]; /* Array pointers, for arrays a-z */ int a_dim[32]; /* Dimensions for each array */ int a_link[32]; /* Link (index of linked-to-array) */ char **aa_ptr[CMDSTKL][32]; /* Array stack for automatic arrays */ int aa_dim[CMDSTKL][32]; /* Dimensions for each array */ /* INPUT command buffers and variables */ char * inpbuf = NULL; /* Buffer for INPUT and REINPUT */ extern char * inpbp; /* Global/static pointer to it */ char inchar[2] = { NUL, NUL }; /* Last character that was INPUT */ int incount = 0; /* INPUT character count */ extern int instatus; /* INPUT status */ static char * i_text[] = { /* INPUT status text */ "success", "timeout", "interrupted", "internal error", "i/o error" }; char lblbuf[LBLSIZ]; /* Buffer for labels */ #else /* NOSPL */ int takerr[MAXTAKE]; #endif /* NOSPL */ static char *prevdir = NULL; int pacing = 0; /* OUTPUT pacing */ char *tp; /* Temporary buffer pointer */ int timelimit = 0, asktimer = 0; /* Timers for time-limited commands */ #ifdef CK_APC /* Application Program Command (APC) */ int apcactive = APC_INACTIVE; int apcstatus = APC_OFF; /* OFF by default everywhere */ #ifdef DCMDBUF char *apcbuf; #else char apcbuf[APCBUFLEN]; #endif /* DCMDBUF */ #endif /* CK_APC */ extern char pktfil[], #ifdef DEBUG debfil[], #endif /* DEBUG */ #ifdef TLOG trafil[], #endif /* TLOG */ sesfil[]; #ifndef NOFRILLS extern int rmailf, rprintf; /* REMOTE MAIL & PRINT items */ extern char optbuf[]; #endif /* NOFRILLS */ extern int noinit; /* Flat to skip init file */ #ifndef NOSPL static struct keytab kcdtab[] = { /* Symbolic directory names */ #ifdef NT { "appdata", VN_APPDATA, 0 }, { "common", VN_COMMON, 0 }, { "desktop", VN_DESKTOP, 0 }, #endif /* NT */ { "download", VN_DLDIR, 0 }, #ifdef OS2ORUNIX { "exedir", VN_EXEDIR, 0 }, #endif /* OS2ORUNIX */ { "home", VN_HOME, 0 }, { "inidir", VN_INI, 0 }, #ifdef UNIX { "lockdir", VN_LCKDIR, 0 }, #endif /* UNIX */ #ifdef NT { "my_documents",VN_PERSONAL, 0 }, { "personal", VN_PERSONAL, CM_INV }, #endif /* NT */ { "startup", VN_STAR, 0 }, { "textdir", VN_TXTDIR, 0 }, { "tmpdir", VN_TEMP, 0 } }; static int nkcdtab = (sizeof(kcdtab) / sizeof(struct keytab)); #endif /* NOSPL */ #ifndef NOSPL _PROTOTYP( VOID freelocal, (int) ); _PROTOTYP( static CK_OFF_T expon, (CK_OFF_T, CK_OFF_T) ); _PROTOTYP( static CK_OFF_T gcd, (CK_OFF_T, CK_OFF_T) ); _PROTOTYP( static CK_OFF_T fact, (CK_OFF_T) ); int /* Initialize macro data structures. */ macini() { /* Allocate mactab and preset the first element. */ int i; if (!(mactab = (struct mtab *) malloc(sizeof(struct mtab) * MAC_MAX))) return(-1); mactab[0].kwd = NULL; mactab[0].mval = NULL; mactab[0].flgs = 0; for (i = 0; i < MACLEVEL; i++) localhead[i] = NULL; return(0); } #endif /* NOSPL */ /* C M D S R C -- Returns current command source */ /* 0 = top level, 1 = file, 2 = macro, -1 = error (shouldn't happen) */ /* As of 19 Aug 2000 this routine is obsolete. The scalar global variable xcmdsrc can be checked instead to save the overhead of a function call. */ int cmdsrc() { #ifdef COMMENT return(xcmdsrc); #else #ifndef NOSPL if (cmdlvl == 0) return(0); else if (cmdstk[cmdlvl].src == CMD_MD) return(2); else if (cmdstk[cmdlvl].src == CMD_TF) return(1); else return(-1); #else if (tlevel < 0) return(0); else return(1); #endif /* NOSPL */ #endif /* COMMENT */ } /* C M D I N I -- Initialize the interactive command parser */ static int cmdinited = 0; /* Command parser initialized */ extern int cmdint; /* Interrupts are allowed */ #ifdef CK_AUTODL int cmdadl = 1; /* Autodownload */ #else int cmdadl = 0; #endif /* CK_AUTODL */ char * k_info_dir = NULL; /* Where to find text files */ #ifdef UNIX static char * txtdir[] = { "/usr/local/doc/", /* Linux, SunOS, ... */ "/usr/share/lib/", /* HP-UX 10.xx... */ "/usr/share/doc/", /* Other possibilities... */ "/usr/local/lib/", /* NOTE: Each of these is tried */ "/usr/local/share/", /* as is, and also with a kermit */ "/usr/local/share/doc/", /* subdirectory. */ "/usr/local/share/lib/", "/opt/kermit/", /* Solaris */ "/opt/kermit/doc/", "/opt/", "/usr/doc/", "/doc/", "" }; #endif /* UNIX */ /* lookup() cache to speed up script execution. This is a static cache. Items are stored in decreasing frequency of reference based on statistics from a range of scripts. This gives better performance than a dynamic cache, which would require a lot more code and also would require system-dependent elements including system calls (e.g. to get subsecond times for entry aging). */ #ifdef USE_LUCACHE /* Set in ckuusr.h */ #define LUCACHE 32 /* Change this to reduce cache size */ int lusize = 0; char * lucmd[LUCACHE]; int luval[LUCACHE]; int luidx[LUCACHE]; struct keytab * lutab[LUCACHE]; #endif /* USE_LUCACHE */ static VOID luinit() { /* Initialize lookup() cache */ int x, y; #ifdef USE_LUCACHE x = lookup(cmdtab,"if",ncmd,&y); lucmd[lusize] = "if"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(iftab,"not",nif,&y); lucmd[lusize] = "not"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = iftab; if (++lusize > LUCACHE) return; x = lookup(vartab,"cmdlevel",nvars,&y); lucmd[lusize] = "cmdlevel"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = vartab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"goto",ncmd,&y); lucmd[lusize] = "goto"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(iftab,">",nif,&y); lucmd[lusize] = ">"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = iftab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"incr",ncmd,&y); lucmd[lusize] = "incr"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"def",ncmd,&y); lucmd[lusize] = "def"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"_assign",ncmd,&y); lucmd[lusize] = "_assign"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"echo",ncmd,&y); lucmd[lusize] = "echo"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(fnctab,"eval",nfuncs,&y); lucmd[lusize] = "eval"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = fnctab; if (++lusize > LUCACHE) return; x = lookup(fnctab,"lit",nfuncs,&y); lucmd[lusize] = "lit"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = fnctab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"do",ncmd,&y); lucmd[lusize] = "do"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"_getargs",ncmd,&y); lucmd[lusize] = "_getargs"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(iftab,"<",nif,&y); lucmd[lusize] = "<"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = iftab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"_putargs",ncmd,&y); lucmd[lusize] = "_putargs"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"asg",ncmd,&y); lucmd[lusize] = "asg"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; if (++lusize > LUCACHE) return; x = lookup(cmdtab,"else",ncmd,&y); lucmd[lusize] = "else"; luval[lusize] = x; luidx[lusize] = y; lutab[lusize] = cmdtab; #endif /* USE_LUCACHE */ } VOID cmdini() { int i = 0, x = 0, y = 0, z = 0, skip = 0; char * p; #ifdef TTSPDLIST long * ss = NULL; extern int nspd; extern struct keytab * spdtab; #endif /* TTSPDLIST */ #ifndef NOSPL /* On stack to allow recursion! */ char vnambuf[VNAML]; /* Buffer for variable names */ #endif /* NOSPL */ if (cmdinited) /* Already initialized */ return; /* Don't do it again */ for (i = 0; i < CMDSTKL; i++) /* Prompt strings for each */ prstring[i] = NULL; /* command level */ #ifndef NOCSETS p = getenv("K_CHARSET"); /* Set default file character set */ if (p) { /* from environment */ x = lookup(fcstab,p,nfilc,&y); if (x > -1) fcharset = x; } #endif /* NOCSETS */ p = getenv("K_INFO_DIRECTORY"); /* Find Kermit info directory */ if (p && *p && strlen(p) <= CKMAXPATH) makestr(&k_info_dir,p); if (!k_info_dir) { p = getenv("K_INFO_DIR"); if (p && *p && strlen(p) <= CKMAXPATH) makestr(&k_info_dir,p); } #ifdef UNIX if (k_info_dir) { /* Look for Kermit docs directory */ if (zchki(k_info_dir) == -2) { char xbuf[CKMAXPATH+32], *s = ""; if (ckrchar(k_info_dir) != '/') s = "/"; ckmakmsg(xbuf,CKMAXPATH+32,k_info_dir,s,"ckubwr.txt",NULL); if (zchki(xbuf) < 0) makestr(&k_info_dir,NULL); } } if (!k_info_dir) { char xbuf[CKMAXPATH+32]; int i; for (i = 0; *(txtdir[i]); i++) { ckmakmsg(xbuf,CKMAXPATH+32,txtdir[i],"ckubwr.txt",NULL,NULL); if (zchki(xbuf) > 0) { makestr(&k_info_dir,txtdir[i]); debug(F110,"k_info_dir 1",k_info_dir,0); break; } ckmakmsg(xbuf,CKMAXPATH+32, txtdir[i],"kermit/","ckubwr.txt",NULL); if (zchki(xbuf) > 0) { ckmakmsg(xbuf,CKMAXPATH+32,txtdir[i],"kermit/",NULL,NULL); makestr(&k_info_dir,xbuf); debug(F110,"k_info_dir 2",k_info_dir,0); break; } ckmakmsg(xbuf,CKMAXPATH+32, txtdir[i],"ckermit/","ckubwr.txt",NULL); if (zchki(xbuf) > 0) { ckmakmsg(xbuf,CKMAXPATH+32,txtdir[i],"ckermit/",NULL,NULL); makestr(&k_info_dir,xbuf); debug(F110,"k_info_dir 3",k_info_dir,0); break; } } if (k_info_dir) { /* Make sure it ends with "/" */ if (ckrchar(k_info_dir) != '/') { char xbuf[CKMAXPATH+32]; ckmakmsg(xbuf,CKMAXPATH+32,k_info_dir,"/",NULL,NULL); makestr(&k_info_dir,xbuf); } } } #else #ifdef OS2 { char xdir[CKMAXPATH+8], *s = ""; extern char startupdir[]; xdir[0] = NUL; if (ckrchar(startupdir) != '/') s = "/"; if (strlen(s) + strlen(startupdir) + 5 < CKMAXPATH + 8 ) ckmakmsg(xdir,CKMAXPATH+8,s,startupdir,"DOC/",NULL); makestr(&k_info_dir,xdir); } #endif /* OS2 */ #endif /* UNIX */ #ifdef TTSPDLIST if (!spdtab && (ss = ttspdlist())) { /* Get speed list if necessary */ int j, k, m = 0, n; /* Create sorted keyword table */ char buf[16]; char * p; if ((spdtab = (struct keytab *) malloc(sizeof(struct keytab) * ss[0]))) { for (i = 1; i <= ss[0]; i++) { /* ss[0] = number of elements */ if (ss[i] < 1L) break; /* Shouldn't happen */ buf[0] = NUL; /* Make string */ sprintf(buf,"%ld",ss[i]); /* SAFE */ if (ss[i] == 8880L) ckstrncpy(buf,"75/1200",sizeof(buf)); if (ss[i] == 134L) ckstrncat(buf,".5",16); n = strlen(buf); if ((n > 0) && (p = (char *)malloc(n+1))) { if (m > 0) { /* Have at least one in list */ for (j = 0; /* Find slot */ j < m && strcmp(buf,spdtab[j].kwd) > 0; j++ ) ; if (j < m) { /* Must insert */ for (k = m-1; k >= j; k--) { /* Move others down */ spdtab[k+1].kwd = spdtab[k].kwd; spdtab[k+1].flgs = spdtab[k].flgs; spdtab[k+1].kwval = spdtab[k].kwval; } } } else /* First one */ j = 0; ckstrncpy(p,buf,n+1); /* Add new speed */ spdtab[j].kwd = p; spdtab[j].flgs = 0; spdtab[j].kwval = (int) ss[i] / 10; m++; /* Count this one */ } } } nspd = m; } #endif /* TTSPDLIST */ #ifndef NOSPL /* Allocate INPUT command buffer */ if (!inpbuf) { if (!(inpbuf = (char *) malloc(INPBUFSIZ+8))) fatal("cmdini: no memory for INPUT buffer"); } for (x = 0; x < INPBUFSIZ; x++) /* Initialize it */ inpbuf[x] = NUL; inpbp = inpbuf; /* Initialize pointer */ inbufsize = INPBUFSIZ; /* and size. */ #endif /* NOSPL */ #ifdef DCMDBUF if (cmsetup() < 0) fatal("Can't allocate command buffers!"); #ifndef NOSPL /* Allocate command stack allowing command parser to call itself */ if (!(cmdstk = (struct cmdptr *) malloc(sizeof(struct cmdptr)*CMDSTKL))) fatal("cmdini: no memory for cmdstk"); if (!(ifcmd = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for ifcmd"); if (!(count = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for count"); if (!(iftest = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for iftest"); if (!(intime = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for intime"); if (!(inpcas = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for inpcas"); if (!(takerr = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for takerr"); if (!(merror = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for merror"); if (!(xquiet = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for xquiet"); if (!(xvarev = (int *) malloc(sizeof(int)*CMDSTKL))) fatal("cmdini: no memory for xvarev"); if (!kermrc) if (!(kermrc = (char *) malloc(KERMRCL+1))) fatal("cmdini: no memory for kermrc"); #ifdef CK_APC /* Application Program Command buffer */ if (!(apcbuf = malloc(APCBUFLEN + 1))) fatal("cmdini: no memory for apcbuf"); #endif /* CK_APC */ #endif /* NOSPL */ /* line[] and tmpbuf[] are the two string buffers used by the command parser */ if (!(line = malloc(LINBUFSIZ + 1))) fatal("cmdini: no memory for line"); if (!(tmpbuf = malloc(LINBUFSIZ + 1))) fatal("cmdini: no memory for tmpbuf"); #endif /* DCMDBUF */ #ifndef NOSPL #ifdef CK_MINPUT { /* Initialize MINPUT pointers */ int i; extern char *ms[]; for (i = 0; i < MINPMAX; i++) ms[i] = NULL; } #endif /* CK_MINPUT */ if (macini() < 0) /* Allocate macro buffers */ fatal("Can't allocate macro buffers!"); ifcmd[0] = 0; /* Command-level related variables. */ iftest[0] = 0; /* Initialize variables at top level */ count[0] = 0; /* of stack... */ intime[0] = 0; inpcas[0] = 0; takerr[0] = 0; merror[0] = 0; xquiet[0] = quiet; xvarev[0] = vareval; #endif /* NOSPL */ #ifndef NOSPL cmdlvl = 0; /* Initialize the command stack */ xcmdsrc = CMD_KB; cmdstk[cmdlvl].src = CMD_KB; /* Source is console */ cmdstk[cmdlvl].lvl = 0; /* Level is 0 */ cmdstk[cmdlvl].ccflgs = 0; /* No flags */ #endif /* NOSPL */ tlevel = -1; /* Take file level = keyboard */ for (i = 0; i < MAXTAKE; i++) /* Initialize command file names */ tfnam[i] = NULL; cmsetp(ckprompt); /* Set up C-Kermit's prompt */ /* Can't set IKSD prompt here since */ /* we do not yet know if we are IKSD */ #ifndef NOSPL initmac(); /* Initialize macro table */ /* Predefine built-in one-line macros */ addmac("ibm-linemode",m_ibm); /* IBM-LINEMODE */ addmac("fatal",m_fat); /* FATAL macro */ y = addmac("fast",m_fast); /* FAST macro */ addmac("cautious",m_cautious); /* CAUTIOUS macro */ addmac("robust",m_robust); /* ROBUST macro */ #ifdef OS2 addmac("manual",m_manual); /* MANUAL macro */ #endif /* OS2 */ #ifdef VMS addmac("purge",m_purge); /* PURGE macro */ #endif /* VMS */ /* Predefine built-in multiline macros; these are top-level commands that are implemented internally as macros. NOTE: When adding a new one of these, remember to update the END and RETURN commands to account for it, or else END and RETURN from within it won't work right. */ x = addmmac("_forx",for_def); /* FOR macro */ if (x > -1) mactab[x].flgs = CM_INV; x = addmmac("_forz",foz_def); /* Other FOR macro */ if (x > -1) mactab[x].flgs = CM_INV; x = addmmac("_xif",xif_def); /* XIF macro */ if (x > -1) mactab[x].flgs = CM_INV; x = addmmac("_while",whil_def); /* WHILE macro */ if (x > -1) mactab[x].flgs = CM_INV; x = addmmac("_switx",sw_def); /* SWITCH macro */ if (x > -1) mactab[x].flgs = CM_INV; /* Fill in command-line argument vector */ sprintf(vnambuf,"\\&@[%d]",xargs); /* SAFE */ if (inserver) { /* But hidden in IKSD */ y = -1; xargs = 0; } else y = arraynam(vnambuf,&x,&z); /* goes in array \&@[] */ tmpbuf[0] = NUL; if (y > -1) { int j = -1; int yy = 0; dclarray((char)x,z); /* Declare the array */ #ifndef NOTAKEARGS /* Macro argument vector */ sprintf(vnambuf,"\\&_[%d]",z); /* SAFE */ yy = arraynam(vnambuf,&x,&z); /* goes in array \&_[] */ if (yy > -1) /* Name is OK */ dclarray((char)x,z); /* Declare the array */ #endif /* NOTAKEARGS */ skip = 0; for (i = 0; i < xargs; i++) { /* Fill the arrays */ sprintf(vnambuf,"\\&@[%d]",i); /* SAFE */ addmac(vnambuf,xargv[i]); if (cfilef && i == 0) continue; #ifdef KERBANG if (skip) { j = 0; skip = 0; continue; } #endif /* KERBANG */ if (j < 0 && /* Assign items after "=" or "--"*/ (!strcmp(xargv[i],"=") || !strcmp(xargv[i],"--")) ) { j = 0; /* to \%1..\%9 */ #ifdef KERBANG } else if (j < 0 && (!strcmp(xargv[i],"+") || !strncmp(xargv[i],"+ ",2) || !strncmp(xargv[i],"+\t",2)) ) { skip = 1; continue; #endif /* KERBANG */ } else if (j > -1) { j++; if (j <= 9) { vnambuf[0] = '\\'; vnambuf[1] = '%'; vnambuf[2] = (char)(j+'0'); vnambuf[3] = NUL; addmac(vnambuf,xargv[i]); } if (yy > -1) { char c, * p; int flag = 0; p = xargv[i]; makestr(&(toparg[j]),p); while ((c = *p++)) { if (c == SP) { flag++; break; } } if (flag) ckstrncat(tmpbuf,"\"",TMPBUFSIZ); ckstrncat(tmpbuf,xargv[i],TMPBUFSIZ); if (flag) ckstrncat(tmpbuf,"\"",TMPBUFSIZ); ckstrncat(tmpbuf," ",TMPBUFSIZ); } } } if (cfilef) { addmac("\\%0",cmdfil); if (yy > -1) makestr(&(toparg[0]),cmdfil); } else { addmac("\\%0",xargv[0]); if (yy > -1) makestr(&(toparg[0]),xargv[0]); } if (yy > -1) { topargc = (j < 0) ? 1 : j + 1; topxarg = toparg; #ifdef COMMENT /* This needs work */ if (!cfilef) makestr(&topline,tmpbuf); #endif /* COMMENT */ } else { topargc = 0; topxarg = NULL; } a_dim[0] = topargc - 1; a_ptr[0] = topxarg; debug(F111,"a_dim[0]","A",a_dim[0]); } *vnambuf = NUL; #endif /* NOSPL */ luinit(); /* Initialize lookup() cache */ /* Get our home directory now. This needed in lots of places. */ cmdinited = 1; } #ifdef NT _PROTOTYP(char * GetAppData,(int)); #endif /* NT */ VOID doinit() { #ifdef CKROOT extern int ckrooterr; #endif /* CKROOT */ int x = 0, ok = 0; #ifdef OS2 char * ptr = 0; #endif /* OS2 */ if (!cmdinited) cmdini(); #ifdef MAC return; /* Mac Kermit has no init file */ #else /* !MAC */ /* If skipping init file ('-Y' on Kermit command line), return now. */ if (noinit) { kermrc[0] = '\0'; inidir[0] = '\0'; /* But returning from here results in inidir[] never being set to anything. Instead it should be set to wherever the init file *would* have been executed from. So this bit of code should be removed, and then we should sprinkle "if (noinit)" tests throughout the following code until we have set inidir[], and then return without actually taking the init file. */ return; } #ifdef OS2 /* The -y init file must be fully specified or in the current directory. KERMRC is looked for via INIT, DPATH and PATH in that order. Finally, our own executable file path is taken and the .EXE suffix is replaced by .INI and this is tried as the initialization file. */ #ifdef CK_LOGIN debug(F101,"doinit inserver","",inserver); debug(F101,"doinit isguest","",isguest); debug(F110,"doinit anonfile",anonfile,0); if (isguest && anonfile) { ckstrncpy(line, anonfile, LINBUFSIZ+1); } else #endif /* CK_LOGIN */ if (rcflag) { ckstrncpy(line,kermrc,LINBUFSIZ+1); #ifdef CK_LOGIN } else if (inserver) { char * appdata = NULL; #ifdef NT appdata = GetAppData(1); if ( appdata ) { ckmakmsg(line,LINBUFSIZ+1,appdata, "Kermit 95/k95.ini",NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } if (line[0] == 0) { appdata = GetAppData(0); if ( appdata ) { ckmakmsg(line,LINBUFSIZ+1,appdata, "Kermit 95/k95.ini",NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } } #endif /* NT */ if (line[0] == 0) { appdata = zhome(); if ( appdata ) { ckmakmsg(line,LINBUFSIZ+1,appdata, #ifdef NT "k95.ini", #else /* NT */ "k2.ini", #endif /* NT */ NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } } debug(F110,"doinit inserver inifile",line,0); #endif /* CK_LOGIN */ } else { char * env = 0; #ifdef NT env = getenv("K95.KSC"); #else env = getenv("K2.KSC"); #endif /* NT */ if (!env) { #ifdef NT env = getenv("K95.INI"); #else env = getenv("K2.INI"); #endif /* NT */ } if (!env) env = getenv("CKERMIT.INI"); if (!env) env = getenv("CKERMIT_INI"); line[0] = '\0'; debug(F110,"doinit env",env,0); if (env) ckstrncpy(line,env,LINBUFSIZ+1); #ifdef NT if (line[0] == 0) { env = GetAppData(1); if ( env ) { ckmakmsg(line,LINBUFSIZ+1,env,"Kermit 95/k95.ini",NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } } if (line[0] == 0) { env = GetAppData(0); if ( env ) { ckmakmsg(line,LINBUFSIZ+1,env,"Kermit 95/k95.ini",NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } } #endif /* NT */ if (line[0] == 0) { env = zhome(); if ( env ) { ckmakmsg(line,LINBUFSIZ+1,env, #ifdef NT "k95.ini", #else /* NT */ "k2.ini", #endif /* NT */ NULL,NULL); if ( zchki(line) < 0 ) line[0] = '\0'; } } if (line[0] == 0) _searchenv(kermrc,"INIT",line); if (line[0] == 0) _searchenv(kermrc,"DPATH",line); if (line[0] == 0) _searchenv(kermrc,"PATH",line); if (line[0] == 0) { char *pgmptr = GetLoadPath(); if (pgmptr && strlen(pgmptr) < LINBUFSIZ-8) { lp = strrchr(pgmptr, '\\'); if (lp) { strncpy(line, pgmptr, lp - pgmptr); #ifdef NT strcpy(line + (lp - pgmptr), "/k95.ini"); #else /* NT */ strcpy(line + (lp - pgmptr), "/k2.ini"); #endif /* NT */ } else { lp = strrchr(pgmptr, '.'); if (lp) { strncpy(line, pgmptr, lp - pgmptr); strcpy(line + (lp - pgmptr), ".ini"); } } } } } #ifdef CKROOT if (!zinroot(line)) { debug(F110,"doinit setroot violation",line,0); return; } #endif /* CKROOT */ debug(F110,"doinit fopen()",line,0); if ((tfile[0] = fopen(line,"r")) != NULL) { ok = 1; tlevel = 0; tfline[tlevel] = 0; tfblockstart[tlevel] = 1; if (tfnam[tlevel] = malloc(strlen(line)+1)) strcpy(tfnam[tlevel],line); /* safe */ #ifndef NOSPL cmdlvl++; xcmdsrc = CMD_TF; cmdstk[cmdlvl].src = CMD_TF; cmdstk[cmdlvl].lvl = tlevel; cmdstk[cmdlvl].ccflgs = 0; ifcmd[cmdlvl] = 0; iftest[cmdlvl] = 0; count[cmdlvl] = count[cmdlvl-1]; /* Inherit from previous level */ intime[cmdlvl] = intime[cmdlvl-1]; inpcas[cmdlvl] = inpcas[cmdlvl-1]; takerr[cmdlvl] = takerr[cmdlvl-1]; merror[cmdlvl] = merror[cmdlvl-1]; xquiet[cmdlvl] = quiet; xvarev[cmdlvl] = vareval; #endif /* NOSPL */ debug(F110,"doinit init file",line,0); } else { debug(F100,"doinit no init file","",0); } ckstrncpy(kermrc,line,KERMRCL); for (ptr = kermrc; *ptr; ptr++) /* Convert backslashes to slashes */ if (*ptr == '\\') *ptr = '/'; #else /* not OS2 */ lp = line; lp[0] = '\0'; debug(F101,"doinit rcflag","",rcflag); #ifdef GEMDOS zkermini(line, rcflag, kermrc); #else #ifdef VMS { int x; x = zkermini(line,LINBUFSIZ,kermrc); debug(F111,"CUSTOM zkermini",line,x); if (x == 0) line[0] = NUL; } #else /* not VMS */ #ifdef CK_LOGIN debug(F101,"doinit isguest","",isguest); if (isguest) ckstrncpy(lp, anonfile ? anonfile : kermrc, LINBUFSIZ); else #endif /* CK_LOGIN */ if (rcflag) { /* If init file name from cmd line */ ckstrncpy(lp,kermrc,LINBUFSIZ); /* use it, */ } else { /* otherwise... */ #ifdef CK_INI_A /* If we've a system-wide init file */ /* And it takes precedence over the user's... */ ckstrncpy(lp,CK_SYSINI,KERMRCL); /* Use it */ if (zchki(lp) < 0) { /* (if it exists...) */ #endif /* CK_INI_A */ char * homdir; char * env = 0; line[0] = NUL; /* Add support for environment variable */ env = getenv("CKERMIT.INI"); if (!env) env = getenv("CKERMIT_INI"); if (env) ckstrncpy(lp,env,KERMRCL); if (lp[0] == 0) { homdir = zhome(); if (homdir) { /* Home directory for init file. */ ckstrncpy(lp,homdir,KERMRCL); #ifdef STRATUS ckstrncat(lp,">",KERMRCL);/* VOS dirsep */ #else if (lp[0] == '/') ckstrncat(lp,"/",KERMRCL); #endif /* STRATUS */ } ckstrncat(lp,kermrc,KERMRCL);/* Append default file name */ } #ifdef CK_INI_A } #endif /* CK_INI_A */ #ifdef CK_INI_B /* System-wide init defined? */ /* But user's ini file takes precedence */ if (zchki(lp) < 0) /* If user doesn't have her own, */ ckstrncpy(lp,CK_SYSINI,KERMRCL); /* use system-wide one. */ #endif /* CK_INI_B */ } #endif /* VMS */ #endif /* GEMDOS */ #ifdef AMIGA reqoff(); /* Disable requestors */ #endif /* AMIGA */ #ifdef USE_CUSTOM /* If no init file was found, execute the customization file */ debug(F111,"CUSTOM 1",line,rcflag); if ((!line[0] || zchki(line) < 0) && !rcflag) { int x; #ifdef OS2 x = ckmakestr(line,LINBUFSIZ,GetAppData(1),"/","K95CUSTOM.INI",NULL); debug(F111,"CUSTOM 2",line,x); if (zchki(line) < 0) { x = ckmakestr(line,LINBUFSIZ,GetAppData(0),"/","K95USER.INI",NULL); debug(F111,"CUSTOM 3",line,x); } #else /* OS2 */ x = ckstrncpy(line,zhome(),LINBUFSIZ); #ifndef VMS /* VMS zhome() returns "SYS$LOGIN:" */ if (line[x-1] != DIRSEP) { line[x++] = DIRSEP; line[x] = NUL; } #endif /* VMS */ x = ckstrncat(line,MYCUSTOM,LINBUFSIZ); debug(F111,"CUSTOM 4",line,x); #endif /* OS2 */ } debug(F110,"CUSTOM 5",line,0); #endif /* USE_CUSTOM */ #ifdef CKROOT if (!zinroot(line)) { debug(F110,"doinit setroot violation",line,0); return; } #endif /* CKROOT */ debug(F110,"doinit ini file is",line,0); if ((tfile[0] = fopen(line,"r")) != NULL) { /* Try to open init file. */ ok = 1; tlevel = 0; tfline[tlevel] = 0; tfblockstart[tlevel] = 1; if ((tfnam[tlevel] = malloc(strlen(line)+1))) strcpy(tfnam[tlevel],line); /* safe */ ckstrncpy(kermrc,line,KERMRCL); #ifndef NOSPL cmdlvl++; ifcmd[cmdlvl] = 0; iftest[cmdlvl] = 0; count[cmdlvl] = count[cmdlvl-1]; /* Inherit from previous level */ intime[cmdlvl] = intime[cmdlvl-1]; inpcas[cmdlvl] = inpcas[cmdlvl-1]; takerr[cmdlvl] = takerr[cmdlvl-1]; merror[cmdlvl] = merror[cmdlvl-1]; xquiet[cmdlvl] = quiet; xvarev[cmdlvl] = vareval; debug(F101,"doinit open ok","",cmdlvl); xcmdsrc = CMD_TF; cmdstk[cmdlvl].src = CMD_TF; cmdstk[cmdlvl].lvl = tlevel; cmdstk[cmdlvl].ccflgs = 0; #endif /* NOSPL */ } else if (rcflag) { /* Print an error message only if a specific file was asked for. */ printf("?%s - %s\n", ck_errstr(), line); } #ifdef datageneral /* If CKERMIT.INI not found in home directory, look in searchlist */ if (/* homdir && */ (tlevel < 0)) { ckstrncpy(lp,kermrc,LINBUFSIZ); if ((tfile[0] = fopen(line,"r")) != NULL) { ok = 1; tlevel = 0; tfline[tlevel] = 0; tfblockstart[tlevel] = 1; if (tfnam[tlevel] = malloc(strlen(line)+1)) strcpy(tfnam[tlevel],line); /* safe */ #ifndef NOSPL cmdlvl++; xcmdsrc = CMD_TF; cmdstk[cmdlvl].src = CMD_TF; cmdstk[cmdlvl].lvl = tlevel; cmdstk[cmdlvl].ccflgs = 0; ifcmd[cmdlvl] = 0; iftest[cmdlvl] = 0; count[cmdlvl] = count[cmdlvl-1]; /* Inherit from previous level */ intime[cmdlvl] = intime[cmdlvl-1]; inpcas[cmdlvl] = inpcas[cmdlvl-1]; takerr[cmdlvl] = takerr[cmdlvl-1]; merror[cmdlvl] = merror[cmdlvl-1]; xquiet[cmdlvl] = quiet; xvarev[cmdlvl] = vareval; #endif /* NOSPL */ } } #endif /* datageneral */ #ifdef AMIGA /* Amiga... */ reqpop(); /* Restore requestors */ #endif /* AMIGA */ #endif /* OS2 */ #endif /* MAC */ /* Assign value to inidir */ if (!ok) { inidir[0] = NUL; } else { ckstrncpy(inidir, kermrc, CCHMAXPATH); x = strlen(inidir); if (x > 0) { int i; for (i = x - 1; i > 0; i-- ) { if (ISDIRSEP(inidir[i])) { inidir[i+1] = NUL; break; } } } #ifdef NT GetShortPathName(inidir,inidir,CCHMAXPATH); #endif /* NT */ } } VOID doiksdinit() { #ifdef CK_SSL /* IKSD doesn't request client certs */ ssl_verify_flag = SSL_VERIFY_NONE; #endif /* CK_SSL */ if (!cmdinited) cmdini(); #ifdef IKSDCONF #ifdef OS2 line[0] = '\0'; _searchenv(iksdconf,"INIT",line); if (line[0] == 0) _searchenv(iksdconf,"DPATH",line); if (line[0] == 0) _searchenv(iksdconf,"PATH",line); if (line[0] == 0) { char *pgmptr = GetLoadPath(); if (pgmptr && strlen(pgmptr) < LINBUFSIZ-8) { lp = strrchr(pgmptr, '\\'); if (lp) { strncpy(line, pgmptr, lp - pgmptr); strcpy(line + (lp - pgmptr), "\\"); strcpy(line + (lp - pgmptr + 1), iksdconf); } else { lp = strrchr(pgmptr, '.'); if (lp) { strncpy(line, pgmptr, lp - pgmptr); strcpy(line + (lp - pgmptr), ".ksc"); } } } } debug(F110,"doiksdinit() line",line,0); tfile[0] = fopen(line,"r"); #else /* OS2 */ tfile[0] = fopen(iksdconf,"r"); #endif /* OS2 */ if (tfile[0] != NULL) { tlevel = 0; tfline[tlevel] = 0; tfblockstart[tlevel] = 1; #ifdef OS2 if (tfnam[tlevel] = malloc(strlen(line)+1)) strcpy(tfnam[tlevel],line); #else /* OS2 */ if ((tfnam[tlevel] = malloc(strlen(iksdconf)+1))) strcpy(tfnam[tlevel],iksdconf); #endif /* OS2 */ #ifndef NOSPL cmdlvl++; xcmdsrc = CMD_TF; cmdstk[cmdlvl].src = CMD_TF; cmdstk[cmdlvl].lvl = tlevel; cmdstk[cmdlvl].ccflgs = 0; ifcmd[cmdlvl] = 0; iftest[cmdlvl] = 0; count[cmdlvl] = count[cmdlvl-1]; /* Inherit from previous level */ intime[cmdlvl] = intime[cmdlvl-1]; inpcas[cmdlvl] = inpcas[cmdlvl-1]; takerr[cmdlvl] = takerr[cmdlvl-1]; merror[cmdlvl] = merror[cmdlvl-1]; xquiet[cmdlvl] = quiet; xvarev[cmdlvl] = vareval; #endif /* NOSPL */ debug(F110,"doiksdinit file ok",tfnam[tlevel],0); } else { debug(F110,"doiksdinit open failed",tfnam[tlevel],0); } #endif /* IKSDCONF */ } #ifndef NOSPL /* G E T N C M Get next command from current macro definition. Command is copied into string pointed to by argument s, max length n. Returns: 0 if a string was copied; -1 if there was no string to copy. */ int getncm(s,n) char *s; int n; { int y = 0; /* Character counter */ int quote = 0; int kp = 0; /* Brace up-down counter */ int pp = 0; /* Parenthesis up-down counter */ #ifndef NODQMACRO int dq = 0; /* Doublequote counter */ #endif /* NODQMACRO */ char *s2; /* Copy of destination pointer */ s2 = s; /* Initialize string pointers */ *s = NUL; /* and destination buffer */ /* debug(F010,"getncm entry",macp[maclvl],0); */ for (y = 0; /* Loop for n bytes max */ macp[maclvl] && *macp[maclvl] && y < n; y++, s++, macp[maclvl]++) { *s = *macp[maclvl]; /* Get next char from macro def */ #ifndef COMMENT /* This is to allow quoting of parentheses, commas, etc, in function arguments, but it breaks just about everything else. DON'T REMOVE THIS COMMENT! (Otherwise you'll wind up adding the same code again and breaking everything again.) <-- The preceding warning should be obsolete since the statements below have been fixed, but in case of fire, remove the "n" from the <#>ifndef above. NEW WARNING: code added 12 Apr 2002 to exempt the opening brace in \{nnn} from being treated as a quoted brace. */ if (!quote && *s == CMDQ) { quote = 1; continue; } if (quote) { int notquote = 0; quote = 0; if (*s == '{') { /* Check for \{nnn} (8.0.203) */ char c, * p; p = macp[maclvl] + 1; while ((c = *p++)) { if (isdigit(c)) continue; else if (c == '}') { notquote++; break; } else { break; } } } if (notquote == 0) continue; } #endif /* COMMENT */ /* Allow braces around macro definition to prevent commas from being turned to end-of-lines and also treat any commas within parens as text so that multiple-argument functions won't cause the command to break prematurely. 19 Oct 2001: Similar treatment was added for doublequotes, so define foo { echo "one, two, three" } would work as expected. This doesn't seem to have broken anything but if something comes up later, rebuild with NODQMACRO defined. */ if (*s == '{') kp++; /* Count braces */ if (*s == '}' && kp > 0) kp--; if (*s == '(') pp++; /* Count parentheses. */ if (*s == ')' && pp > 0) pp--; #ifndef NODQMACRO #ifndef COMMENT /* Too many false positives */ /* No, not really -- this is indeed the best we can do */ /* Reverted to this method Sun May 11 18:43:45 2003 */ if (*s == '"') dq = 1 - dq; /* Account for doublequotes */ #else /* Fri Apr 4 13:21:29 2003 */ /* The code below breaks the SWITCH statement */ /* There is no way to make this work -- it would require */ /* building in all the knowledge of command parser. */ if (dblquo && (*s == '"')) { /* Have doublequote */ if (dq == 1) { /* Close quote only if... */ if ((*(macp[maclvl]+1) == SP) || /* followed by space or... */ (!*(macp[maclvl]+1)) || /* at end or ... */ /* Next char is command separator... */ /* Sun May 11 17:24:12 2003 */ (kp < 1 && pp < 1 && (*(macp[maclvl]+1) == ',')) ) dq = 0; /* Close the quote */ } else if (dq == 0) { /* Open quote only if at beginning or preceded by space */ if (s > s2) { if (*(s-1) == SP) dq = 1; } else if (s == s2) { dq = 1; } } } #endif /* COMMENT */ #endif /* NODQMACRO */ if (*s == ',' && pp <= 0 && kp <= 0 #ifndef NODQMACRO && dq == 0 #endif /* NODQMACRO */ ) { macp[maclvl]++; /* Comma not in {} or () */ /* debug(F110,"next cmd",s,0); */ kp = pp = 0; /* so we have the next command */ break; } } /* Reached end. */ #ifdef COMMENT /* DON'T DO THIS - IT BREAKS EVERYTHING */ *s = NUL; #endif /* COMMENT */ if (*s2 == NUL) { /* If nothing was copied, */ /* debug(F100,"getncm eom","",0); */ popclvl(); /* pop command level. */ return(-1); } else { /* otherwise, tack CR onto end */ *s++ = CR; *s = '\0'; /* debug(F110,"getncm OK",s,0); */ if (mecho && pflag) /* If MACRO ECHO ON, echo the cmd */ printf("%s\n",s2); } return(0); } /* D O M A C -- Define and then execute a macro */ int domac(name, def, flags) char *name, *def; int flags; { int x, m; #ifndef NOLOCAL #ifdef OS2 extern int term_io; int term_io_sav = term_io; term_io = 0; /* Disable Terminal Emulator I/O */ #endif /* OS2 */ #endif /* NOLOCAL */ m = maclvl; /* Current macro stack level */ x = addmac(name, def); /* Define a new macro */ if (x > -1) { /* If successful, */ dodo(x,NULL,flags); /* start it (increments maclvl). */ while (maclvl > m) { /* Keep going till done with it, */ debug(F101,"domac loop maclvl 1","",maclvl); sstate = (CHAR) parser(1); /* parsing & executing each command, */ debug(F101,"domac loop maclvl 2","",maclvl); if (sstate) proto(); /* including protocol commands. */ } debug(F101,"domac loop exit maclvl","",maclvl); } #ifndef NOLOCAL #ifdef OS2 term_io = term_io_sav; #endif /* OS2 */ #endif /* NOLOCAL */ return(success); } #endif /* NOSPL */ /* G E T N C T Get next command from TAKE (command) file. Call with: s Pointer to buffer to read into n Length of buffer f File descriptor of file to read from flag 0 == keep line terminator on and allow continuation 1 == discard line terminator and don't allow continuation Call with flag == 0 to read a command from a TAKE file; Call with flag != 0 to read a line from a dialing or network directory. In both cases, trailing comments and/or trailing whitespace is/are stripped. If flag == 0, continued lines are combined into one line. A continued line is one that ends in hypen, or any line in a "block", which starts with "{" at the end of a line and ends with a matching "}" at the beginning of a subsequent line; blocks may be nested. Returns: 0 if a string was copied, -1 on EOF, -2 on malloc failure -3 if line is not properly terminated -4 if (possibly continued) line is too long. */ static int lpxlen = 0; int getnct(s,n,f,flag) char *s; int n; FILE *f; int flag; { int i = 0, len = 0, buflen = 0; char c = NUL, cc = NUL, ccl = NUL, ccx = NUL, *s2 = NULL; char *lp = NULL, *lpx = NULL, *lp2 = NULL, *lp3 = NULL, *lastcomma = NULL; char * prev = NULL; int bc = 0; /* Block counter */ int firstread = 1; s2 = s; /* Remember original pointer */ prev = s2; /* Here too */ buflen = n; /* Remember original buffer length */ if (n < 0) return(-2); /* Allocate a line buffer only if we don't have one that's big enough */ debug(F111,"getnct",ckitoa(lpxlen),n); if (lpx && (n > lpxlen)) { /* Have one already */ debug(F101,"getnct new buffer","",lpxlen); free(lpx); /* But it's not big enough */ lpx = NULL; /* Free current one */ lpxlen = 0; } if (!lpx) { /* Get new one */ if (!(lpx = (char *) malloc(n))) { debug(F101,"getnct malloc failure","",0); printf("?Memory allocation failure [getnct:%d]\n",n); return(-2); } lpxlen = n; } lp2 = lpx; #ifdef KLUDGE /* NOTE: No longer used as of 14 Aug 2000 */ lp2++; #endif /* KLUDGE */ while (1) { /* Loop to read lines from file */ debug(F101,"getnct while (1)","",n); if (fgets(lp2,n,f) == NULL) { /* Read a line into lp2 */ debug(F110,"getnct EOF",s2,0); /* EOF */ free(lpx); /* Free temporary storage */ lpx = NULL; *s = NUL; /* Make destination be empty */ return(-1); /* Return failure code */ } if (firstread) { /* Beginning of a block or statement */ tfblockstart[tlevel] = tfline[tlevel]; firstread = 0; } #ifndef NODIAL if (flag) /* Count this line */ dirline++; else #endif /* NODIAL */ tfline[tlevel]++; len = strlen(lp2) - 1; /* Position of line terminator */ if (len == 0 && lp2[0] != '\n') { /* Last line in file has one char */ lp2[++len] = '\n'; /* that is not a newline */ lp2[len] = NUL; } debug(F010,"getnct",lp2,0); if (len < 0) len = 0; if (techo && pflag) { /* If TAKE ECHO ON, */ if (flag) { printf("%3d. %s", /* echo it this line. */ #ifndef NODIAL flag ? dirline : #endif /* NODIAL */ tfline[tlevel], lp2 ); } else { printf("%3d. %3d. %s", /* echo it this line. */ tfline[tlevel], tfblockstart[tlevel], lp2 ); } } lp3 = lp2; /* Working pointer */ i = len; /* Get first nonwhitespace character */ while (i > 0 && (*lp3 == SP || *lp3 == HT)) { i--; lp3++; } if (i == 0 && bc > 0) /* Blank line in {...} block */ continue; /* Isolate, remove, and check terminator */ c = lp2[len]; /* Value of line terminator */ /* debug(F101,"getnct terminator","",c); */ if (c < LF || c > CR) { /* It's not a terminator */ /* debug(F111,"getnct bad line",lp2,c); */ if (feof(f) && len > 0 && len < n) { /* Kludge Alert... */ if (!quiet) printf("WARNING: Last line of %s lacks terminator\n", s2 == cmdbuf ? "command file" : "directory file"); c = lp2[++len] = '\n'; /* No big deal - supply one. */ } else { /* Something's wrong, fail. */ free(lpx); lpx = NULL; return(-3); } } /* Trim trailing whitespace */ for (i = len - 1; i > -1 && lp2[i] <= SP; i--) /* Trim */ ; /* debug(F101,"getnct i","",i); */ lp2[i+1] = NUL; /* Terminate the string */ /* debug(F110,"getnct lp2",lp2,0); */ lp = lp2; /* Make a working pointer */ /* Remove trailing or full-line comment */ while ((cc = *lp)) { if (cc == ';' || cc == '#') { /* Comment introducer? */ if (lp == lp2) { /* First char on line */ *lp = NUL; break; } else if (*(lp - 1) == SP || *(lp - 1) == HT) { lp--; *lp = NUL; /* Or preceded by whitespace */ break; } } lp++; } if (lp > lp2) lp--; /* Back up over the NUL */ /* Now trim any space that preceded the comment */ while ((*lp == SP || *lp == HT) && lp >= lp2) { *lp = NUL; if (lp <= lp2) break; lp--; } /* debug(F110,"getnct comment trimmed",lp2,0); */ len = strlen(lp2); /* Length after trimming */ if (n - len < 2) { /* Check remaining space */ debug(F111,"getnct command too long",s2,buflen); printf("?Line too long, maximum length: %d.\n",buflen); free(lpx); return(-4); } ccl = (len > 0) ? lp2[len-1] : 0; /* Last character in line */ ccx = (len > 1) ? lp2[len-2] : 0; /* Penultimate char in line */ #ifdef COMMENT /* Line containing only whitespace and ,- */ if ((len > 1) && (lp3 == lp2+len-2) && (ccl == '-') && (ccx == ',')) continue; #endif /* COMMENT */ #ifdef KLUDGE /* If it is a command and it begins with a token (like ! or .) that is not followed by a space, insert a space now; otherwise cmkey() can get mighty confused. */ if (s == s2 && !flag) { char *p = toktab; while (*p) { if (*p == *lp3 && *(p+1) != SP) { debug(F110,"getnct token",p,0); *lp3-- = SP; *lp3 = *p; if (lp3 < lp2) { lp2--; len++; } break; } else p++; } } #endif /* KLUDGE */ lp = lp2; while ((*s++ = *lp++)) /* Copy result to target buffer */ n--; /* accounting for length */ s--; /* Back up over the NUL */ /* Check whether this line is continued */ if (flag) /* No line continuation when flag=1 */ break; /* So break out of read-lines loop */ #ifdef COMMENT debug(F000,"getnct first char","",*lp3); debug(F000,"getnct last char","",ccl); debug(F000,"getnct next-to-last char","",ccx); #endif /* COMMENT */ if (bc > 0 && *lp3 == '}') { /* First char on line is '}' */ bc--; /* Decrement block counter */ } if (bc == 0 && /* Line is continued if bc > 0 */ #ifdef COMMENT /* Not supported as of C-Kermit 6.0 */ ccl != CMDQ && /* or line ends with CMDQ */ #endif /* COMMENT */ ccl != '-' && /* or line ends with dash */ ccl != '{') { /* or line ends with opening brace */ break; /* None of those, we're done. */ } if (ccl == '-' || ccl == '{') /* Continuation character */ if (ccx == CMDQ) /* But it's quoted */ break; /* so ignore it */ if (ccl == '{') { /* Last char on line is '{'? */ bc++; /* Count the block opener. */ } else if (ccl == '-') { /* Explicit continue? */ char c, * ss; int state = 0, nn; s--; /* Yes, back up over terminators */ n++; /* and over continuation character */ nn = n; /* Save current count */ ss = s; /* and pointer */ s--; /* Back up over dash */ n++; while (state < 2 && s >= prev) { /* Check for "{,-" */ n++; c = *s--; if (c <= SP) continue; if (c != ',' && c != '{') break; switch (state) { case 0: /* Looking for comma */ if (c == ',') state = 1; break; case 1: /* Looking for left brace */ if (c == '{') { state = 2; s += 2; *s = NUL; bc++; } break; } } if (state != 2) { s = ss; n = nn; } *s = NUL; } else { /* None of those but (bc > 0) */ lastcomma = s; *s++ = ','; /* and insert a comma */ n--; } #ifdef COMMENT debug(F101,"getnct bc","",bc); debug(F100,"getnct continued","",0); #endif /* COMMENT */ *s = NUL; prev = s; } /* read-lines while loop */ if (lastcomma) *lastcomma = SP; if (!flag) /* Tack line terminator back on */ *s++ = c; *s++ = NUL; /* Terminate the string */ untab(s2); /* Done, convert tabs to spaces */ #ifdef DEBUG if (!flag) { debug(F010,"CMD(F)",s2,0); } #endif /* DEBUG */ { int i = 0; char *s = s2; char prev = '\0'; char c = '\0'; while (*s) { /* Save beginning of this command for error messages */ c = *s++; if (c == '\n' || c == '\r') c = SP; if (c == SP && prev == SP) /* Squeeze spaces */ continue; lasttakeline[i++] = c; prev = c; if (i > TMPBUFSIZ-5) { lasttakeline[i++] = '.'; lasttakeline[i++] = '.'; lasttakeline[i++] = '.'; lasttakeline[i++] = NUL; break; } } i = (int)strlen((char *)lasttakeline) - 1; while (i > 0 && lasttakeline[i] == SP) { /* Trim treailing spaces */ lasttakeline[i] = NUL; i--; } } free(lpx); /* Free temporary storage */ return(0); /* Return success */ } VOID shostack() { /* Dump the command stack */ int i; char *p; #ifndef NOSPL for (i = cmdlvl; i > 0; i--) { if (cmdstk[i].src == CMD_TF) { p = tfnam[cmdstk[i].lvl]; if (zfnqfp(p,TMPBUFSIZ,tmpbuf)) p = tmpbuf; printf(" %2d. File : %s (line %d)\n", i, p, tfline[cmdstk[i].lvl] ); } else if (cmdstk[i].src == CMD_MD) { char * m; m = m_arg[cmdstk[i].lvl][0]; /* Name of this macro */ if (i > 0) { /* Special handling for 2-level */ char *s; /* built-in macros... */ s = m_arg[cmdstk[i-1].lvl][0]; /* Name next level up */ if (s && cmdstk[i-1].src == CMD_MD) { if (!strcmp(s,"_forx")) m = "FOR"; else if (!strcmp(s,"_xif")) m = "XIF"; else if (!strcmp(s,"_while")) m = "WHILE"; else if (!strcmp(s,"_switx")) m = "SWITCH"; } } printf(" %2d. Macro : %s\n",i,m); } else if (cmdstk[i].src == CMD_KB) { printf(" %2d. Prompt:\n",i); } else { printf(" %2d. ERROR : Command source unknown\n",i); } } #else for (i = tlevel; i > -1; i--) { p = tfnam[i]; if (zfnqfp(p,TMPBUFSIZ,tmpbuf)) p = tmpbuf; printf(" %2d. File : %s (line %d)\n", i, p, tfline[i] ); } #endif /* NOSPL */ if (i == 0) printf(" %2d. Prompt: (top level)\n",0); } /* For command error messages - avoid dumping out the contents of some */ /* some huge FOR loop if it contains a syntax error. */ static char * cmddisplay(s, cx) char * s; int cx; { static char buf[80]; if ((int)strlen(s) > 70) { sprintf(buf,"%.64s...",s); /* SAFE */ s = buf; } return(s); } static VOID cmderr() { if (xcmdsrc > 0) { switch (cmd_err) { /* SET COMMAND ERROR-DISPLAY */ case 0: break; case 1: case 2: if (tlevel > -1) { #ifndef NOSPL if (xcmdsrc == 2) printf( "In macro or block defined in file: %s starting about line %d\n", tfnam[tlevel] ? tfnam[tlevel] : "", tfline[tlevel] ); else #endif /* NOSPL */ printf("File: %s, Line: %d\n", tfnam[tlevel] ? tfnam[tlevel] : "", tfline[tlevel] ); } #ifndef NOSPL if (cmd_err == 2) { if (cmdstk[cmdlvl].src == CMD_MD) { /* Executing a macro? */ int m; m = cmdstk[cmdlvl].lvl; if (mlook(mactab,m_arg[m][0],nmac) >= 0) printf("Macro name: %s\n", m_arg[m][0]); } } #endif /* NOSPL */ break; case 3: printf("Command stack:\n"); shostack(); } } } /* P A R S E R -- Top-level interactive command parser. */ /* Call with: m = 0 for normal behavior: keep parsing and executing commands until an action command is parsed, then return with a Kermit start-state as the value of this function. m = 1 to parse only one command, can also be used to call parser() recursively. m = 2 to read but do not execute one command. In all cases, parser() returns: 0 if no Kermit protocol action required > 0 with a Kermit protocol start-state. < 0 upon error. */ int parser(m) int m; { int tfcode, xx, yy, zz; /* Workers */ int is_tn = 0; int cdlost = 0; #ifndef NOSPL int inlevel; /* Level we were called at */ extern int askflag, echostars; #endif /* NOSPL */ char *cbp; /* Command buffer pointer */ #ifdef MAC extern char *lfiles; /* Fake extern cast */ #endif /* MAC */ extern int interrupted; #ifndef NOXFER extern int sndcmd, getcmd, fatalio, clearrq; #endif /* NOXFER */ #ifdef AMIGA reqres(); /* Restore AmigaDOS requestors */ #endif /* AMIGA */ #ifdef OS2 if (cursor_save > -1) { /* Restore cursor if it was */ cursorena[VCMD] = cursor_save; /* turned off during file transfer */ cursor_save = -1; } #endif /* OS2 */ #ifdef IKSDB if (ikdbopen) slotstate(what,"COMMAND PROMPT","",""); /* IKSD database */ #endif /* IKSDB */ is_tn = (local && network && IS_TELNET()) || (!local && sstelnet); if (!xcmdsrc) /* If at top (interactive) level ... */ concb((char)escape); /* put console in 'cbreak' mode. */ #ifdef CK_TMPDIR /* If we were cd'd temporarily to another device or directory ... */ if (f_tmpdir) { int x; x = zchdir((char *) savdir); /* ... restore previous directory */ f_tmpdir = 0; /* and remember we did it. */ debug(F111,"parser tmpdir restoring",savdir,x); } #endif /* CK_TMPDIR */ #ifndef NOSPL inlevel = cmdlvl; /* Current macro level */ #ifdef DEBUG if (deblog) { debug(F101,"&parser entry maclvl","",maclvl); debug(F101,"&parser entry inlevel","",inlevel); debug(F101,"&parser entry tlevel","",tlevel); debug(F101,"&parser entry cmdlvl","",cmdlvl); debug(F101,"&parser entry m","",m); } #endif /* DEBUG */ #endif /* NOSPL */ #ifndef NOXFER ftreset(); /* Reset global file settings */ #endif /* NOXFER */ /* sstate becomes nonzero when a command has been parsed that requires some action from the protocol module. Any non-protocol actions, such as local directory listing or terminal emulation, are invoked directly from below. */ sstate = 0; /* Start with no start state. */ #ifndef NOXFER #ifndef NOSPL query = 0; /* QUERY not active */ #endif /* NOSPL */ #ifndef NOHINTS if (!success) { if (local && !network && carrier != CAR_OFF) { int x; /* Serial connection */ x = ttgmdm(); /* with carrier checking */ if (x > -1) { if (!(x & BM_DCD)) { cdlost = 1; fatalio = 1; } } } } #ifdef DEBUG if (deblog) { debug(F101,"parser top what","",what); debug(F101,"parser top interrupted","",interrupted); debug(F101,"parser top cdlost","",cdlost); debug(F101,"parser top sndcmd","",sndcmd); debug(F101,"parser top getcmd","",getcmd); } #endif /* DEBUG */ if (cdlost && !interrupted && (sndcmd || getcmd)) { printf("?Connection broken (carrier signal lost)\n"); } if (sndcmd && protocol == PROTO_K && !success && hints && !interrupted && !fatalio && !xcmdsrc) { int x = 0, n = 0; printf("\n*************************\n"); printf("SEND-class command failed.\n"); printf(" Packets sent: %d\n", spackets); printf(" Retransmissions: %d\n",retrans); printf(" Timeouts: %d\n", timeouts); printf(" Damaged packets: %d\n", crunched); if (epktrcvd) { printf(" Transfer canceled by receiver.\n"); printf(" Receiver's message: \"%s\"\n",(char *)epktmsg); n++; } else { if (epktmsg) if (*epktmsg) { printf(" Fatal Kermit Protocol Error: %s\n",epktmsg); n++; } } if (local && !network && carrier != CAR_OFF) { int xx; /* Serial connection */ xx = ttgmdm(); /* with carrier checking */ if (xx > -1) { if (!(xx & BM_DCD)) cdlost = 1; } } #ifdef UNIX if (errno != 0) #endif /* UNIX */ { printf(" Most recent local OS error: \"%s\"\n",ck_errstr()); n++; } printf( "\nHINTS... If the preceding error message%s not explain the failure:\n", (n > 1) ? "s do" : " does" ); #ifndef NOLOCAL if (local) { if (rpackets == 0) { printf(" . Did you start a Kermit receiver on the far end?\n"); } else { printf( " . Try changing the remote Kermit's FLOW-CONTROL setting.\n"); if (!network && mdmtyp > 0) if ((3 * crunched) > spackets) printf( " . Try placing a new call to get a cleaner connection.\n"); } } else if (rpackets > 0) { if (flow == FLO_NONE) printf(" . Give me a SET FLOW XON/XOFF command and try again.\n"); else printf(" . Give me a SET FLOW NONE command and try again.\n"); } x++; #endif /* NOLOCAL */ if ((3 * timeouts) > spackets) printf(" . Adjust the timeout method (see HELP SET SEND).\n"); if ((3 * retrans) > spackets) printf(" . Increase the retry limit (see HELP SET RETRY).\n"); #ifdef CK_SPEED if (prefixing != PX_ALL && rpackets > 2) { printf(" . Try it again with: SET PREFIXING ALL\n"); x++; } #endif /* CK_SPEED */ #ifdef STREAMING if (streamed) { printf(" . Try it again with: SET STREAMING OFF\n"); x++; } else if (reliable) { printf(" . Try it again with: SET RELIABLE OFF\n"); x++; } #endif /* STREAMING */ #ifdef CK_SPEED if (clearrq > 0 && prefixing == PX_NON) { printf(" . Try it again with: SET CLEAR-CHANNEL OFF\n"); x++; } #endif /* CK_SPEED */ if (!parity) { printf(" . Try it again with: SET PARITY SPACE\n"); x++; } printf(" . %sive a ROBUST command and try again.\n", (x > 0) ? "As a last resort, g" : "G" ); printf("Also:\n"); printf(" . Be sure the source file has read permission.\n"); printf(" . Be sure the target directory has write permission.\n"); /* if the file was 2G or larger make sure other Kermit supports LFs... */ printf(" . Be sure the target disk has sufficient space.\n"); printf("(Use SET HINTS OFF to suppress hints.)\n"); printf("*************************\n\n"); } debug(F101,"topcmd","",topcmd); if (getcmd && protocol == PROTO_K && !success && hints && !interrupted && !fatalio && !xcmdsrc) { int x = 0; extern int urpsiz, wslotr; printf("\n*************************\n"); printf("RECEIVE- or GET-class command failed.\n"); printf(" Packets received: %d\n", rpackets); printf(" Damaged packets: %d\n", crunched); printf(" Timeouts: %d\n", timeouts); if (rpackets > 0) printf(" Packet length: %d\n", urpsiz); if (epktrcvd) { printf(" Transfer canceled by sender.\n"); printf(" Sender's message: \"%s\"\n",(char *)epktmsg); if (ckindex("not found",(char *)epktmsg,0,0,0) || ckindex("no such",(char *)epktmsg,0,0,0)) { printf(" Did you spell the filename right?\n"); printf(" Is the other Kermit CD'd to the right directory?\n"); } } #ifdef UNIX if (errno != 0) #endif /* UNIX */ { (VOID) ckstrncpy(tmpbuf,ck_errstr(),TMPBUFSIZ); printf(" Most recent local error: \"%s\"\n",tmpbuf); } #ifdef COMMENT printf( "\nHINTS... If the preceding error message%s not explain the failure:\n", epktrcvd ? "s do" : " does" ); #ifndef NOLOCAL if (local) { if (topcmd == XXGET) printf(" . Did you start a Kermit SERVER on the far end?\n"); if (rpackets == 0) { if (topcmd != XXGET) printf(" . Did you start a Kermit SENDer on the far end?\n"); } else { printf( " . Choose a different FLOW-CONTROL setting and try again.\n"); } } else if (topcmd == XXGET) printf(" . Is the other Kermit in (or does it have) SERVER mode?\n"); if (rpackets > 0 && urpsiz > 90) printf(" . Try smaller packets (SET RECEIVE PACKET-LENGTH).\n"); if (rpackets > 0 && wslotr > 1 && !streamed) printf(" . Try a smaller window size (SET WINDOW).\n"); if (!local && rpackets > 0) { if (flow == FLO_NONE) printf(" . Give me a SET FLOW XON/XOFF command and try again.\n"); else printf(" . Give me a SET FLOW NONE command and try again.\n"); } x++; #endif /* NOLOCAL */ #ifdef STREAMING if (streamed) { printf(" . Try it again with: SET STREAMING OFF\n"); x++; } else if (reliable && local) { printf(" . Try it again with: SET RELIABLE OFF\n"); x++; } else #endif /* STREAMING */ if (!parity) { printf(" . Try it again with: SET PARITY SPACE\n"); x++; } printf((x > 0) ? " . As a last resort, give a ROBUST command and try again.\n" : " . Give a ROBUST command and try again.\n" ); #endif /* COMMENT */ printf("Also:\n"); printf(" . Be sure the target directory has write permission.\n"); printf(" . Be sure the target disk has sufficient space.\n"); printf(" . Try telling the %s to SET PREFIXING ALL.\n", topcmd == XXGET ? "server" : "sender" ); printf(" . Try giving a ROBUST command to the %s.\n", topcmd == XXGET ? "server" : "sender" ); printf("(Use SET HINTS OFF to suppress hints.)\n"); printf("*************************\n\n"); } #endif /* NOHINTS */ getcmd = 0; sndcmd = 0; interrupted = 0; #endif /* NOXFER */ while (sstate == 0) { /* Parse cmds until action requested */ debug(F100,"parse top","",0); what = W_COMMAND; /* Now we're parsing commands. */ rcdactive = 0; /* REMOTE CD not active */ keepallchars = 0; /* MINPUT not active */ #ifdef OS2 if (apcactive == APC_INACTIVE) WaitCommandModeSem(-1); #endif /* OS2 */ #ifdef IKS_OPTION if ((local && !xcmdsrc && is_tn && TELOPT_ME(TELOPT_KERMIT) && TELOPT_SB(TELOPT_KERMIT).kermit.me_start) || (!local && !cmdadl && TELOPT_ME(TELOPT_KERMIT) && TELOPT_SB(TELOPT_KERMIT).kermit.me_start) ) { tn_siks(KERMIT_STOP); } #endif /* IKS_OPTION */ #ifndef NOXFER if (autopath) { fnrpath = PATH_AUTO; autopath = 0; } remfile = 0; /* Clear these in case REMOTE */ remappd = 0; /* command was interrupted... */ rempipe = 0; makestr(&snd_move,g_snd_move); /* Restore these */ makestr(&rcv_move,g_rcv_move); makestr(&snd_rename,g_snd_rename); makestr(&rcv_rename,g_rcv_rename); #endif /* NOXFER */ /* Take requested action if there was an error in the previous command */ setint(); debug(F101,"parser tlevel","",tlevel); debug(F101,"parser cmd_rows","",cmd_rows); #ifndef NOLOCAL debug(F101,"parser wasclosed","",wasclosed); if (wasclosed) { /* If connection was just closed */ #ifndef NOSPL int k; k = mlook(mactab,"on_close",nmac); /* Look up "on_close" */ if (k >= 0) { /* If found, */ /* printf("ON_CLOSE CMD LOOP\n"); */ dodo(k,ckitoa(whyclosed),0); /* Set it up */ } #endif /* NOSPL */ whyclosed = WC_REMO; wasclosed = 0; } #endif /* NOLOCAL */ #ifndef NOSPL xxdot = 0; /* Clear this... */ debug(F101,"parser success","",success); if (success == 0) { if (cmdstk[cmdlvl].src == CMD_TF && takerr[cmdlvl]) { printf("Command file terminated by error.\n"); popclvl(); if (cmdlvl == 0) return(0); } if (cmdstk[cmdlvl].src == CMD_MD && merror[cmdlvl]) { printf("Command error: macro terminated.\n"); popclvl(); if (m && (cmdlvl < inlevel)) return((int) sstate); } } nulcmd = (m == 2); debug(F101,"parser nulcmd","",nulcmd); #else if (success == 0 && tlevel > -1 && takerr[tlevel]) { printf("Command file terminated by error.\n"); popclvl(); cmini(ckxech); /* Clear the cmd buffer. */ if (tlevel < 0) /* Just popped out of cmd files? */ return(0); /* End of init file or whatever. */ } #endif /* NOSPL */ #ifdef MAC /* Check for TAKE initiated by menu. */ if ((tlevel == -1) && lfiles) startlfile(); #endif /* MAC */ /* If in TAKE file, check for EOF */ #ifndef NOSPL #ifdef MAC if #else while #endif /* MAC */ ((cmdstk[cmdlvl].src == CMD_TF) /* If end of take file */ && (tlevel > -1) && feof(tfile[tlevel])) { popclvl(); /* pop command level */ cmini(ckxech); /* and clear the cmd buffer. */ if (cmdlvl == 0) { /* Just popped out of all cmd files? */ return(0); /* End of init file or whatever. */ } } #ifdef MAC miniparser(1); if (sstate == 'a') { /* if cmd-. cancel */ debug(F100, "parser: cancel take due to sstate", "", sstate); sstate = '\0'; dostop(); return(0); /* End of init file or whatever. */ } #endif /* MAC */ #else /* NOSPL */ if ((tlevel > -1) && feof(tfile[tlevel])) { /* If end of take */ popclvl(); /* Pop up one level. */ cmini(ckxech); /* and clear the cmd buffer. */ if (tlevel < 0) /* Just popped out of cmd files? */ return(0); /* End of init file or whatever. */ } #endif /* NOSPL */ #ifndef NOSPL debug(F101,"parser cmdlvl","",cmdlvl); debug(F101,"parser cmdsrc","",cmdstk[cmdlvl].src); if (cmdstk[cmdlvl].src == CMD_MD) { /* Executing a macro? */ debug(F100,"parser macro","",0); maclvl = cmdstk[cmdlvl].lvl; /* Get current level */ debug(F101,"parser maclvl","",maclvl); cbp = cmdbuf; /* Copy next cmd to command buffer. */ *cbp = NUL; if (*savbuf) { /* In case then-part of 'if' command */ ckstrncpy(cbp,savbuf,CMDBL); /* was saved, restore it. */ *savbuf = '\0'; } else { /* Else get next cmd from macro def */ if (getncm(cbp,CMDBL) < 0) { #ifdef DEBUG if (deblog) { debug(F101,"parser end of macro m","",m); debug(F101,"parser end of macro cmdlvl","",cmdlvl); debug(F101,"parser end of macro inlevel","",inlevel); } #endif /* DEBUG */ if (m && (cmdlvl < inlevel)) return((int) sstate); else /* if (!m) */ continue; } } debug(F010,"CMD(M)",cmdbuf,0); } else if (cmdstk[cmdlvl].src == CMD_TF) #else if (tlevel > -1) #endif /* NOSPL */ { #ifndef NOSPL debug(F111,"parser savbuf",savbuf,tlevel); if (*savbuf) { /* In case THEN-part of IF command */ ckstrncpy(cmdbuf,savbuf,CMDBL); /* was saved, restore it. */ *savbuf = '\0'; } else #endif /* NOSPL */ /* Get next line from TAKE file */ if ((tfcode = getnct(cmdbuf,CMDBL,tfile[tlevel],0)) < 0) { debug(F111,"parser tfcode",tfile[tlevel],tfcode); if (tfcode < -1) { /* Error */ printf("?Error in TAKE command file: %s\n", (tfcode == -2) ? "Memory allocation failure" : "Line too long or contains NUL characters" ); dostop(); } continue; /* -1 means EOF */ } /* If interactive, get next command from user. */ } else { /* User types it in. */ if (pflag) prompt(xxstring); cmini(ckxech); } /* Now we know where next command is coming from. Parse and execute it. */ repars = 1; /* 1 = command needs parsing */ #ifndef NOXFER displa = 0; /* Assume no file transfer display */ #endif /* NOXFER */ while (repars) { /* Parse this cmd until entered. */ debug(F101,"parser top of while loop","",0); xaskmore = saveask; /* Restore global more-prompting */ diractive = 0; /* DIR command not active */ cdactive = 0; /* CD command not active */ #ifndef NOSPL askflag = 0; /* ASK command not active */ echostars = 0; /* Nor ASKQ */ debok = 1; /* Undisable debugging */ #endif /* NOSPL */ #ifdef RECURSIVE /* In case of "send /recursive ./?<Ctrl-U>" etc */ recursive = 0; /* This is never sticky */ #endif /* RECURSIVE */ xfiletype = -1; /* Reset this between each command */ #ifndef NOMSEND addlist = 0; #endif /* NOMSEND */ #ifdef CK_RECALL on_recall = 1; #endif /* CK_RECALL */ /* This might have been changed by a switch */ if (g_matchdot > -1) { matchdot = g_matchdot; g_matchdot = -1; } cmres(); /* Reset buffer pointers. */ #ifdef OS2 #ifdef COMMENT /* we check to see if a macro is waiting to be executed */ /* if so, we call domac on it */ if (cmdmac) { ckstrncpy(cmdbuf, cmdmac, CMDBL); free(cmdmac); cmdmac = NULL; } #endif /* COMMENT */ #endif /* OS2 */ #ifndef NOXFER bye_active = 0; #endif /* NOXFER */ havetoken = 0; xx = cmkey2(cmdtab,ncmd,"Command","",toktab,xxstring,1); debug(F101,"top-level cmkey2","",xx); if (xx == -5) { yy = chktok(toktab); debug(F101,"top-level cmkey token","",yy); #ifndef COMMENT /* Either way makes absolutely no difference */ debug(F110,"NO UNGWORD",atmbuf,0); /* ungword(); */ #else debug(F110,"TOKEN UNGWORD",atmbuf,0); ungword(); #endif /* COMMENT */ switch (yy) { case '#': xx = XXCOM; break; /* Comment */ case ';': xx = XXCOM; break; /* Comment */ #ifndef NOSPL case '.': xx = XXDEF; xxdot = 1; break; /* Assignment */ case ':': xx = XXLBL; break; /* GOTO label */ #endif /* NOSPL */ #ifndef NOPUSH #ifdef CK_REDIR case '<': #endif /* CK_REDIR */ case '@': case '!': if (nopush) { char *s; int x; if ((x = cmtxt("Text to be ignored","",&s,NULL)) < 0) return(x); success = 0; xx = XXCOM; } else { switch(yy) { #ifdef CK_REDIR case '<': xx = XXFUN; break; /* REDIRECT */ #endif /* CK_REDIR */ case '@': case '!': xx = XXSHE; break; /* Shell escape */ } } break; #endif /* NOPUSH */ #ifdef CK_RECALL case '^': xx = XXREDO; break; #endif /* CK_RECALL */ #ifndef NOSPL case '{': xx = XXMACRO; break; case '(': xx = XXSEXP; break; #endif /* NOSPL */ default: if (!quiet && !cmd_err) { printf("\n?Not a valid command or token - \"%s\"\n", cmddisplay((char *)cmdbuf,xx) ); /* cmderr(); */ newerrmsg(""); } xx = -2; } havetoken = 1; debug(F101,"HAVE TOKEN","",xx); } if (xx > -1) { topcmd = xx; /* Top-level command index */ #ifndef NOSPL if (maclvl > -1) lastcmd[maclvl] = xx; #endif /* NOSPL */ debug(F101,"topcmd","",topcmd); debug(F101,"cmflgs","",cmflgs); } #ifndef NOSPL /* Special handling for IF..ELSE */ debug(F101,"cmdlvl","",cmdlvl); debug(F101,"ifcmd[cmdlvl]","",ifcmd[cmdlvl]); if (ifcmd[cmdlvl]) /* Count stmts after IF */ ifcmd[cmdlvl]++; if (ifcmd[cmdlvl] > 2 && xx != XXELS && xx != XXCOM) ifcmd[cmdlvl] = 0; /* Execute the command and take action based on return code. */ if (nulcmd) { /* Ignoring this command? */ xx = XXCOM; /* Make this command a comment. */ } fnsuccess = 1; /* For catching \function() errors */ #endif /* NOSPL */ debug(F101,"calling docmd()","",xx); zz = docmd(xx); /* Parse rest of command & execute. */ #ifndef NOSPL { /* For \v(lastcommand) */ extern char * prevcmd; /* The exception list kind of a hack but let's try it... */ if (ckstrcmp(cmdbuf,"_getarg",7,0) && ckstrcmp(cmdbuf,"if ",3,0) && ckstrcmp(cmdbuf,"xif ",4,0) && ckstrcmp(cmdbuf,"do _if",6,0) && ckstrcmp(cmdbuf,"_assign _if",11,0)) ckstrncpy(prevcmd,cmdbuf,CMDBL); } #endif /* NOSPL */ #ifndef NOSPL if (fnerror && !fnsuccess) success = 0; #endif /* NOSPL */ debug(F101,"docmd returns","",zz); /* debug(F011,"cmdbuf",cmdbuf,30); */ /* debug(F011,"atmbuf",atmbuf,30); */ #ifdef MAC if (tlevel > -1) { if (sstate == 'a') { /* if cmd-. cancel */ debug(F110, "parser: cancel take, sstate:", "a", 0); sstate = '\0'; dostop(); return(0); /* End of init file or whatever. */ } } #endif /* MAC */ switch (zz) { case -4: /* EOF (e.g. on redirected stdin) */ doexit(GOOD_EXIT,xitsta); /* ...exit successfully */ case -1: /* Reparse needed */ repars = 1; /* Just set reparse flag and... */ continue; #ifdef OS2 case -7: /* They typed a disk letter */ if (!zchdir((char *)cmdbuf)) { perror((char *)cmdbuf); success = 0; } else success = 1; repars = 0; continue; #endif /* OS2 */ /* Changed 2013-12-06 fdc: Previously the failing command was echoed only in the -6 and -9 cases. This made it difficult to know exactly which command had failed when a macro or command file was being executed and the failing command had already issued its own error message and returned -9. Now we include -9 in the caselist for this code, but we echo the failing command only if Kermit is not at top level. So now, even though the error message is imprecise about *where* the failing command was, at least it shows the failing command. */ case -9: /* Bad, error message already done */ case -6: /* Invalid command given w/no args */ case -2: /* Invalid command given w/args */ if (zz == -2 || zz == -6 || (zz == -9 && cmdlvl > 0)) { int x = 0; char * eol = ""; x = strlen(cmdbuf); /* Avoid blank line */ #ifdef COMMENT if (x > 0) { if (cmdbuf[x-1] != LF) eol = "\n"; printf("?Invalid: %s%s", cmddisplay(cmdbuf,xx),eol ); } else printf("?Invalid\n"); #else if (x > 0) newerrmsg("Syntax error"); #endif /* COMMENT */ } success = 0; debug(F110,"top-level cmkey failed",cmdbuf,0); /* If in background w/ commands coming stdin, terminate */ if (pflag == 0 && tlevel < 0) fatal("Kermit command error in background execution"); /* Command retry feature, edit 190. If we're at interactive prompting level, reprompt the user with as much of the command as didn't fail. */ #ifdef CK_RECALL if (cm_retry && !xcmdsrc) { /* If at top level */ int len; char *p, *s; len = strlen(cmdbuf); /* Length of command buffer */ p = malloc(len + 1); /* Allocate space for copy */ if (p) { /* If we got the space copy */ strcpy(p,cmdbuf); /* the command buffer (SAFE). */ /* Chop off final field, the one that failed. */ s = p + len - 1; /* Point to end */ while (*s == SP && s > p) /* Trim blanks */ s--; while (*s != SP && s > p) /* Trim last field */ s--; if (s > p) /* Keep the space */ s++; /* after last good field */ if (s >= p) /* Cut off remainder */ *s = NUL; cmini(ckxech); /* Reinitialize the parser */ ckstrncpy(cmdbuf,p,CMDBL); /* Copy result back */ free(p); /* Free temporary storage */ p = NULL; prompt(xxstring); /* Reprint the prompt */ printf("%s",cmdbuf); /* Reprint partial command */ repars = 1; /* Force reparse */ continue; } } else #endif /* CK_RECALL */ /* cmderr(); */ newerrmsg(""); cmini(ckxech); /* (fall thru) */ case -3: /* Empty command OK at top level */ repars = 0; /* Don't need to reparse. */ continue; /* Go back and get another command. */ default: /* Command was successful. */ #ifndef NOSPL debug(F101,"parser preparing to continue","",maclvl); #endif /* NOSPL */ debug(F101,"parser success","",success); repars = 0; /* Don't need to reparse. */ continue; /* Go back and get another command. */ } } #ifndef NOSPL debug(F101,"parser breaks out of while loop","",maclvl); if (m && (cmdlvl < inlevel)) return((int) sstate); #endif /* NOSPL */ } /* Got an action command, return start state. */ return((int) sstate); } #ifndef NOSPL /* OUTPUT command. Buffering and pacing added by L.I. Kirby, 5A(189), June 1993. */ #define OBSIZE 80 /* Size of local character buffer */ static int obn; /* Buffer offset (high water mark) */ static char obuf[OBSIZE+1]; /* OUTPUT buffer. */ static char *obp; /* Pointer to output buffer. */ _PROTOTYP( static int oboc, (char) ); _PROTOTYP( static int xxout, (char *, int) ); static int #ifdef CK_ANSIC xxout(char *obuf, int obsize) #else xxout(obuf, obsize) char *obuf; int obsize; #endif /* CK_ANSIC */ /* xxout */ { /* OUTPUT command's output function */ int i, rc; debug(F101,"xxout obsize","",obsize); debug(F101,"xxout pacing","",pacing); debug(F111,"xxout string",obuf,strlen(obuf)); rc = 0; /* Initial return code. */ if (!obuf || (obsize <= 0)) /* Nothing to output. */ goto xxout_x; /* Return successfully */ rc = -1; /* Now assume failure */ if (pacing == 0) { /* Is pacing enabled? */ if ((local ? /* No, write entire string at once */ ttol((CHAR *)obuf, obsize) : /* to communications device */ conxo(obsize, obuf)) /* or to console */ != obsize) goto xxout_x; } else { for (i = 0; i < obsize; i++) { /* Write individual chars */ if ((local ? ttoc(obuf[i]) : conoc(obuf[i])) < 0) goto xxout_x; msleep(pacing); } } if (duplex) { #ifdef OS2 if (inecho && local) { #ifndef NOLOCAL for (i = 0; i < obsize; i++) { /* Write to emulator */ scriptwrtbuf((USHORT)obuf[i]); /* which also logs session */ } #endif /* NOLOCAL */ conxo(obsize,obuf); } else if (seslog) { /* or log session here */ logstr((char *) obuf, obsize); } #else /* OS2 */ if (seslog) { logstr((char *) obuf, obsize); } if (inecho && local) { conxo(obsize,obuf); } #endif /* OS2 */ } rc = 0; /* Success */ xxout_x: obn = 0; /* Reset count */ obp = obuf; /* and pointers */ return(rc); /* return our return code */ } #ifdef COMMENT /* Macros for OUTPUT command execution, to make it go faster. */ #define obfls() ((xxout(obuf,obn)<0)?-1:0) #define oboc(c) ((*obp++=(char)(c)),*obp=0,(((++obn)>=OBSIZE)?obfls():0)) #else /* The macros cause some compilers to generate bad code. */ static int #ifdef CK_ANSIC oboc(char c) #else oboc(c) char c; #endif /* CK_ANSIC */ /* oboc */ { /* OUTPUT command's output function */ *obp++ = c; /* Deposit character */ *obp = NUL; /* Flush buffer if it's now full */ return(((++obn) >= OBSIZE) ? xxout(obuf,obn) : 0); } #endif /* COMMENT */ /* Routines for handling local variables -- also see popclvl(). */ VOID freelocal(m) int m; { /* Free local variables */ struct localvar * v, * tv; /* at macro level m... */ debug(F101,"freelocal level","",m); if (m < 0) return; v = localhead[m]; /* List head for level m */ while (v) { if (v->lv_name) /* Variable name */ free(v->lv_name); if (v->lv_value) /* Value */ free(v->lv_value); tv = v; /* Save pointer to this node */ v = v->lv_next; /* Get next one */ if (tv) /* Free this one */ free((char *)tv); } localhead[m] = (struct localvar *) NULL; /* Done, set list head to NULL */ } #define MAXLOCALVAR 64 /* Return a pointer to the definition of a user-defined variable */ static char * vardef(s,isarray,x1,x2) char * s; int * isarray, * x1, * x2; { char * p; char c; *isarray = 0; if (!s) return(NULL); if (!*s) return(NULL); p = s; if (*s == CMDQ) { p++; if (!*p) return(NULL); if ((c = *p) == '%') { /* Scalar variable. */ c = *++p; /* Get ID character. */ p = ""; /* Assume definition is empty */ if (!c) return(NULL); if (c >= '0' && c <= '9') { /* Digit for macro arg */ if (maclvl < 0) /* Digit variables are global */ return(g_var[c]); /* if no macro is active */ else /* otherwise */ return(m_arg[maclvl][c - '0']); /* they're on the stack */ } else if (isalpha(c)) { if (isupper(c)) c -= ('a'-'A'); return(g_var[c]); /* Letter for global variable */ } else return(NULL); } else if (c == '&') { /* Array reference. */ int x, vbi, d; x = arraynam(p,&vbi,&d); /* Get name and subscript */ if (x > -1 || d == -17) { *isarray = 1; *x1 = vbi; *x2 = (d == -17) ? 0 : d; } if (x < 0) return(NULL); if (chkarray(vbi,d) >= 0) { /* Array is declared? */ vbi -= ARRAYBASE; /* Convert name to index */ if (a_dim[vbi] >= d) { /* If subscript in range */ char **ap; ap = a_ptr[vbi]; return((ap) ? ap[d] : NULL); } } } return(NULL); } else { int k; k = mxlook(mactab,s,nmac); return((k > -1) ? mactab[k].mval : NULL); } } int addlocal(p) char * p; { int x, z, isarray = 0; char * s; struct localvar * v, *prev = (struct localvar *)NULL; extern int tra_asg; int tra_tmp; tra_tmp = tra_asg; s = vardef(p,&isarray,&x,&z); /* Get definition of variable */ if (isarray) { /* Arrays are handled specially */ pusharray(x,z); return(0); } if (!s) s = ""; if ((v = localhead[cmdlvl])) { /* Already have some at this level? */ while (v) { /* Find end of list */ prev = v; v = v->lv_next; } } v = (struct localvar *) malloc(sizeof(struct localvar)); if (!v) { printf("?Failure to allocate storage for local variables"); return(-9); } if (!localhead[cmdlvl]) /* If first, set list head */ localhead[cmdlvl] = v; else /* Otherwise link previous to this */ prev->lv_next = v; prev = v; /* And make this previous */ v->lv_next = (struct localvar *) NULL; /* No next yet */ if (!(v->lv_name = (char *) malloc((int) strlen(p) + 1))) return(-1); strcpy(v->lv_name, p); /* Copy name into new node (SAFE) */ if (*s) { if (!(v->lv_value = (char *) malloc((int) strlen(s) + 1))) return(-1); strcpy(v->lv_value, s); /* Copy value into new node (SAFE) */ } else v->lv_value = NULL; tra_asg = 0; delmac(p,1); /* Delete the original macro */ tra_asg = tra_tmp; return(0); } int dolocal() { /* Do the LOCAL command */ int i, x; char * s; char * list[MAXLOCALVAR+2]; /* Up to 64 variables per line */ if ((x = cmtxt("Variable name(s)","",&s,NULL)) < 0) return(x); xwords(s,MAXLOCALVAR,list,0); /* Break up line into "words" */ /* Note: Arrays do not use the localhead list, but have their own stack */ for (i = 1; i < MAXLOCALVAR && list[i]; i++) { /* Go through the list */ if (addlocal(list[i]) < 0) goto localbad; } return(success = 1); localbad: printf("?Failure to allocate storage for local variables"); freelocal(cmdlvl); return(-9); } /* D O O U T P U T -- Returns 0 on failure, 1 on success */ #ifndef NOKVERBS #define K_BUFLEN 30 #define SEND_BUFLEN 255 #define sendbufd(x) { osendbuf[sendndx++] = x;\ if (sendndx == SEND_BUFLEN) {dooutput(s,cx); sendndx = 0;}} #endif /* NOKVERBS */ int outesc = 1; /* Process special OUTPUT escapes */ int dooutput(s, cx) char *s; int cx; { #ifdef SSHBUILTIN extern int ssh_cas; extern char * ssh_cmd; #endif /* SSHBUILTIN */ int x, xx, y, quote; /* Workers */ int is_tn = 0; is_tn = (local && network && IS_TELNET()) || (!local && sstelnet); debug(F111,"dooutput s",s,(int)strlen(s)); if (local) { /* Condition external line */ #ifdef NOLOCAL goto outerr; #else if (ttchk() < 0) { if (!network) { if (carrier != CAR_OFF) { int x; x = ttgmdm(); if ((x > -1) && ((x & BM_DCD) == 0)) { printf( "?Carrier signal required but not present - Try SET CARRIER-WATCH OFF.\n" ); return(0); } } else { printf( "?Problem with serial port or modem or cable - Try SHOW COMMUNICATIONS.\n" ); return(0); } } printf("?Connection %s %s is not open or not functioning.\n", network ? "to" : "on", ttname ); return(0); } if (ttvt(speed,flow) < 0) { printf("?OUTPUT initialization error\n"); return(0); } #endif /* NOLOCAL */ } #ifdef SSHBUILTIN if ( network && nettype == NET_SSH && ssh_cas && ssh_cmd && !(strcmp(ssh_cmd,"kermit") && strcmp(ssh_cmd,"sftp"))) { if (!quiet) printf("?SSH Subsystem active: %s\n", ssh_cmd); return(0); } #endif /* SSHBUILTIN */ if (!cmdgquo()) { /* COMMAND QUOTING OFF */ x = strlen(s); /* Just send the string literally */ xx = local ? ttol((CHAR *)s,x) : conxo(x,s); return(success = (xx == x) ? 1 : 0); } quote = 0; /* Initialize backslash (\) quote */ obn = 0; /* Reset count */ obp = obuf; /* and pointers */ outagain: while ((x = *s++)) { /* Loop through the string */ y = 0; /* Error code, 0 = no error. */ debug(F000,"dooutput","",x); if (quote) { /* This character is quoted */ #ifndef NOKVERBS if (x == 'k' || x == 'K') { /* \k or \K */ extern struct keytab kverbs[]; extern int nkverbs; extern char * keydefptr; extern int keymac; extern int keymacx; int x, y, brace = 0; int pause; char * p, * b; char kbuf[K_BUFLEN + 1]; /* Key verb name buffer */ char osendbuf[SEND_BUFLEN +1]; int sendndx = 0; if (xxout(obuf,obn) < 0) /* Flush buffer */ goto outerr; debug(F100,"OUTPUT KVERB","",0); /* Send a KVERB */ { /* Have K verb? */ if (!*s) { break; } /* We assume that the verb name is {braced}, or it extends to the end of the string, s, or it ends with a space, control character, or backslash. */ p = kbuf; /* Copy verb name into local buffer */ x = 0; while ((x++ < K_BUFLEN) && (*s > SP) && (*s != CMDQ)) { if (brace && *s == '}') { break; } *p++ = *s++; } if (*s && !brace) /* If we broke because of \, etc, */ s--; /* back up so we get another look. */ brace = 0; *p = NUL; /* Terminate. */ p = kbuf; /* Point back to beginning */ debug(F110,"dooutput kverb",p,0); y = xlookup(kverbs,p,nkverbs,&x); /* Look it up */ debug(F101,"dooutput lookup",0,y); if (y > -1) { if (sendndx) { dooutput(osendbuf,cx); sendndx = 0; } dokverb(VCMD,y); #ifndef NOSPL } else { /* Is it a macro? */ y = mxlook(mactab,p,nmac); if (y > -1) { cmpush(); keymac = 1; /* Flag for key macro active */ keymacx = y; /* Key macro index */ keydefptr = s; /* Where to resume next time */ debug(F111,"dooutput mxlook",keydefptr,y); parser(1); cmpop(); } #endif /* NOSPL */ } } quote = 0; continue; } else #endif /* NOKVERBS */ if (outesc && (x == 'n' || x == 'N')) { /* \n or \N */ if (xxout(obuf,obn) < 0) /* Flush buffer */ goto outerr; debug(F100,"OUTPUT NUL","",0); /* Send a NUL */ if (local) ttoc(NUL); else conoc(NUL); quote = 0; continue; } else if (outesc && (x == 'b' || x == 'B')) { /* \b or \B */ if (xxout(obuf,obn) < 0) /* Flush buffer first */ goto outerr; debug(F100,"OUTPUT BREAK","",0); #ifndef NOLOCAL ttsndb(); /* Send BREAK signal */ #else if (local) ttoc(NUL); else conoc(NUL); #endif /* NOLOCAL */ quote = 0; /* Turn off quote flag */ continue; /* and not the b or B */ #ifdef CK_LBRK } else if (outesc && (x == 'l' || x == 'L')) { /* \l or \L */ if (xxout(obuf,obn) < 0) /* Flush buffer first */ goto outerr; debug(F100,"OUTPUT Long BREAK","",0); #ifndef NOLOCAL ttsndlb(); /* Send Long BREAK signal */ #else if (local) ttoc(NUL); else conoc(NUL); #endif /* NOLOCAL */ quote = 0; /* Turn off quote flag */ continue; /* and not the l or L */ #endif /* CK_LBRK */ } else if (x == CMDQ) { /* Backslash itself */ debug(F100,"OUTPUT CMDQ","",0); xx = oboc(dopar(CMDQ)); /* Output the backslash. */ if (xx < 0) goto outerr; quote = 0; continue; } else { /* if \ not followed by special esc */ /* Note: Atari ST compiler won't allow macro call in "if ()" */ xx = oboc(dopar(CMDQ)); /* Output the backslash. */ if (xx < 0) goto outerr; quote = 0; /* Turn off quote flag */ } } else if (x == CMDQ) { /* This is the quote character */ quote = 1; /* Go back and get next character */ continue; /* which is quoted */ } xx = oboc(dopar((char)x)); /* Output this character */ debug(F111,"dooutput",obuf,obn); if (xx < 0) goto outerr; #ifdef COMMENT if (seslog && duplex) { /* Log the character if log is on */ logchar((char)x); } #endif /* COMMENT */ if (x == '\015') { /* String contains carriage return */ int stuff = -1, stuff2 = -1; if (tnlm) { /* TERMINAL NEWLINE ON */ stuff = LF; /* Stuff LF */ } #ifdef TNCODE /* TELNET NEWLINE ON/OFF/RAW */ if (is_tn) { switch (TELOPT_ME(TELOPT_BINARY) ? /* NVT or BINARY */ tn_b_nlm : tn_nlm ) { case TNL_CR: break; case TNL_CRNUL: stuff2 = stuff; stuff = NUL; break; case TNL_CRLF: stuff2 = stuff; stuff = LF; break; } } #endif /* TNCODE */ if (stuff > -1) { /* Stuffing another character... */ xx = oboc(dopar((CHAR)stuff)); if (xx < 0) goto outerr; #ifdef COMMENT if (seslog && duplex) { /* Log stuffed char if appropriate */ logchar((char)stuff); } #endif /* COMMENT */ } if (stuff2 > -1) { /* Stuffing another character... */ xx = oboc(dopar((CHAR)stuff2)); if (xx < 0) goto outerr; #ifdef COMMENT if (seslog && duplex) { /* Log stuffed char if appropriate */ logchar((char)stuff2); } #endif /* COMMENT */ } if (xxout(obuf,obn) < 0) /* Flushing is required here! */ goto outerr; } } if (cx == XXLNOUT) { s = "\015"; cx = 0; goto outagain; } if (quote == 1) /* String ended with backslash */ xx = oboc(dopar(CMDQ)); if (obn > 0) /* OUTPUT done */ if (xxout(obuf,obn) < 0) /* Flush the buffer if necessary. */ goto outerr; return(1); outerr: /* OUTPUT command error handler */ if (msgflg) printf("?OUTPUT execution error\n"); return(0); /* Remove "local" OUTPUT macro defininitions */ #ifdef COMMENT /* No more macros ... */ #undef oboc #undef obfls #endif /* COMMENT */ } #endif /* NOSPL */ /* Display version herald and initial prompt */ VOID herald() { int x = 0, i; extern int srvcdmsg; extern char * cdmsgfile[]; char * ssl; char * krb4; char * krb5; #ifndef NOCMDL extern char * bannerfile; debug(F110,"herald bannerfile",bannerfile,0); if (bannerfile) { concb((char)escape); if (dotype(bannerfile,1,0,0,NULL,0,NULL,0,0,NULL,0) > 0) { debug(F111,"herald","srvcdmsg",srvcdmsg); if (srvcdmsg) { for (i = 0; i < 8; i++) { debug(F111,"herald cdmsgfile[i]",cdmsgfile[i],i); if (zchki(cdmsgfile[i]) > -1) { printf("\n"); dotype(cdmsgfile[i], xaskmore,0,0,NULL,0,NULL,0,0,NULL,0); break; } } } return; } } #endif /* NOCMDL */ #ifdef COMMENT /* The following generates bad code in SCO compilers. */ /* Observed in both OSR5 and Unixware 2 -- after executing this */ /* statement when all conditions are false, x has a value of -32. */ if (noherald || quiet || bgset > 0 || (bgset != 0 && backgrd != 0)) x = 1; #else x = 0; if (noherald || quiet) x = 1; else if (bgset > 0) x = 1; else if (bgset < 0 && backgrd > 0) x = 1; #endif /* COMMENT */ ssl = ""; krb4 = ""; krb5 = ""; #ifdef CK_AUTHENTICATION #ifdef CK_SSL ssl = "+SSL"; #endif /* CK_SSL */ #ifdef KRB4 krb4 = "+KRB4"; #endif /* KRB4 */ #ifdef KRB5 krb5 = "+KRB5"; #endif /* KRB5 */ #endif /* CK_AUTHENTICATION */ if (x == 0) { #ifdef datageneral printf("%s, for%s\n",versio,ckxsys); #else #ifdef OSK printf("%s, for%s\n",versio,ckxsys); #else #ifdef CK_64BIT printf("%s, for%s%s%s%s (64-bit)\n\r",versio,ckxsys,ssl,krb4,krb5); #else printf("%s, for%s%s%s%s\n\r",versio,ckxsys,ssl,krb4,krb5); #endif/* CK_64BIT */ #endif /* OSK */ #endif /* datageneral */ printf(" Copyright (C) 1985, %s,\n", ck_cryear); printf(" Trustees of Columbia University in the City of New York.\n"); #ifdef COMMENT #ifdef OS2 shoreg(); #endif /* OS2 */ #endif /* COMMENT */ if (!quiet && !backgrd) { #ifdef COMMENT /* "Default file-transfer mode is AUTOMATIC" is useless information... */ char * s; extern int xfermode; #ifdef VMS s = "AUTOMATIC"; #else if (xfermode == XMODE_A) { s = "AUTOMATIC"; } else { s = gfmode(binary,1); } if (!s) s = ""; #endif /* VMS */ if (*s) printf("Default file-transfer mode is %s\n", s); #endif /* COMMENT */ debug(F111,"herald","srvcdmsg",srvcdmsg); if (srvcdmsg) { for (i = 0; i < 8; i++) { debug(F111,"herald cdmsgfile[i]",cdmsgfile[i],i); if (zchki(cdmsgfile[i]) > -1) { printf("\n"); dotype(cdmsgfile[i], xaskmore,0,0,NULL,0,NULL,0,0,NULL,0); break; } } } printf("Type ? or HELP for help.\n"); } } } /* G F M O D E -- Get File (transfer) Mode */ char * gfmode(binary,upcase) int binary, upcase; { char * s; switch (binary) { case XYFT_T: s = upcase ? "TEXT" : "text"; break; #ifdef VMS case XYFT_B: s = upcase ? "BINARY FIXED" : "binary fixed"; break; case XYFT_I: s = upcase ? "IMAGE" : "image"; break; case XYFT_L: s = upcase ? "LABELED" : "labeled"; break; case XYFT_U: s = upcase ? "BINARY UNDEF" : "binary undef"; break; #else #ifdef MAC case XYFT_B: s = upcase ? "BINARY" : "binary"; break; case XYFT_M: s = upcase ? "MACBINARY" : "macbinary"; break; #else case XYFT_B: s = upcase ? "BINARY" : "binary"; break; #ifdef CK_LABELED case XYFT_L: s = upcase ? "LABELED" : "labeled"; break; #endif /* CK_LABELED */ #endif /* MAC */ #endif /* VMS */ case XYFT_X: s = upcase ? "TENEX" : "tenex"; break; default: s = ""; } return(s); } #ifndef NOSPL static int isaa(s) char * s; { /* Is associative array */ char c; int x; if (!s) s = ""; if (!*s) return(0); s++; while ((c = *s++)) { if (c == '<') { x = strlen(s); return ((*(s+x-1) == '>') ? 1 : 0); } } return(0); } /* M L O O K -- Lookup the macro name in the macro table */ /* Call this way: v = mlook(table,word,n); table - a 'struct mtab' table. word - the target string to look up in the table. n - the number of elements in the table. The keyword table must be arranged in ascending alphabetical order, and all letters must be lowercase. Returns the table index, 0 or greater, if the name was found, or: -3 if nothing to look up (target was null), -2 if ambiguous, -1 if not found. A match is successful if the target matches a keyword exactly, or if the target is a prefix of exactly one keyword. It is ambiguous if the target matches two or more keywords from the table. */ int mlook(table,cmd,n) struct mtab table[]; char *cmd; int n; { register int i; int v, w, cmdlen = 0; char c = 0, c1, * s; if (!cmd) cmd = ""; for (s = cmd; *s; s++) cmdlen++; /* (instead of strlen) */ debug(F111,"MLOOK",cmd,cmdlen); c1 = *cmd; if (isupper(c1)) c1 = tolower(c1); if (cmdlen < 1) return(-3); /* Not null, look it up */ if (n < 12) { /* Not worth it for small tables */ i = 0; } else { /* Binary search for where to start */ int lo = 0; int hi = n; int count = 0; while (lo+2 < hi && ++count < 12) { i = lo + ((hi - lo) / 2); c = *(table[i].kwd); if (isupper(c)) c = tolower(c); if (c < c1) { lo = i; } else { hi = i; } } i = (c < c1) ? lo+1 : lo; } for ( ; i < n-1; i++) { s = table[i].kwd; if (!s) s = ""; if (!*s) continue; /* Empty table entry */ c = *s; if (isupper(c)) c = tolower(c); if (c1 != c) continue; /* First char doesn't match */ if (!ckstrcmp(s,cmd,-1,0)) /* Have exact match? */ return(i); v = !ckstrcmp(s,cmd,cmdlen,0); w = ckstrcmp(table[i+1].kwd,cmd,cmdlen,0); if (v && w) /* Have abbreviated match? */ return(i); if (v) /* Ambiguous? */ return(-2); if (w > 0) /* Past our alphabetic area? */ return(-1); } /* Last (or only) element */ if (!ckstrcmp(table[n-1].kwd,cmd,cmdlen,0)) return(n-1); return(-1); } /* mxlook is like mlook, but an exact full-length match is required */ int mxlook(table,cmd,n) char *cmd; struct mtab table[]; int n; { register int i; int w, cmdlen = 0, one = 0; register char c = 0, c1, * s; if (!cmd) cmd = ""; /* Check args */ for (s = cmd; *s; s++) cmdlen++; /* (instead of strlen) */ debug(F111,"MXLOOK",cmd,cmdlen); c1 = *cmd; /* First char of string to look up */ if (isupper(c1)) c1 = tolower(c1); if (!*(cmd+1)) /* Special handling for 1-char names */ one = 1; if (cmdlen < 1) /* Nothing to look up */ return(-3); if (n < 12) { /* Not worth it for small tables */ i = 0; } else { /* Binary search for where to start */ int lo = 0; int hi = n; int count = 0; while (lo+2 < hi && ++count < 12) { i = lo + ((hi - lo) / 2); c = *(table[i].kwd); if (isupper(c)) c = tolower(c); if (c < c1) { lo = i; } else { hi = i; } } i = (c < c1) ? lo+1 : lo; } for ( ; i < n; i++) { /* Look thru table */ s = table[i].kwd; /* This entry */ if (!s) s = ""; if (!*s) continue; /* Empty table entry */ c = *s; if (isupper(c)) c = tolower(c); if (c1 != c) continue; /* First char doesn't match */ if (one) { /* Name is one char long */ if (!*(s+1)) return(i); /* So is table entry */ } #ifdef COMMENT if (((int)strlen(s) == cmdlen) && (!ckstrcmp(s,cmd,cmdlen,0))) return(i); #else w = ckstrcmp(s,cmd,-1,0); if (!w) { debug(F111,"MXLOOK",mactab[i].mval,i); return(i); } if (w > 0) return(-1); #endif /* COMMENT */ } return(-1); } /* mxxlook is like mxlook, but case-sensitive */ int mxxlook(table,cmd,n) char *cmd; struct mtab table[]; int n; { int i, cmdlen; if (!cmd) cmd = ""; if (((cmdlen = strlen(cmd)) < 1) || (n < 1)) return(-3); /* debug(F111,"mxxlook target",cmd,n); */ for (i = 0; i < n; i++) { if (((int)strlen(table[i].kwd) == cmdlen) && (!strncmp(table[i].kwd,cmd,cmdlen))) return(i); } return(-1); } static int traceval(nam, val) char * nam, * val; { /* For TRACE command */ if (val) printf(">>> %s: \"%s\"\n", nam, val); else printf(">>> %s: (undef)\n", nam); return(0); } #ifdef USE_VARLEN /* Not used */ /* V A R L E N -- Get length of variable's value. Given a variable name, return the length of its definition or 0 if the variable is not defined. If it is defined, set argument s to point to its definition. Otherwise set s to NULL. */ int varlen(nam,s) char *nam; char **s; { /* Length of value of variable */ int x, z; char *p = NULL, c; *s = NULL; if (!nam) return(0); /* Watch out for null pointer */ if (*nam == CMDQ) { nam++; if (*nam == '%') { /* If it's a variable name */ if (!(c = *(nam+1))) return(0); /* Get letter or digit */ p = (char *)0; /* Initialize value pointer */ if (maclvl > -1 && c >= '0' && c <= '9') { /* Digit? */ p = m_arg[maclvl][c - '0']; /* Pointer from macro-arg table */ } else { /* It's a global variable */ if (c < 33 || c > GVARS) return(0); p = g_var[c]; /* Get pointer from global-var table */ } } else if (*nam == '&') { /* An array reference? */ char **q; if (arraynam(nam,&x,&z) < 0) /* If syntax is bad */ return(-1); /* return -1. */ x -= ARRAYBASE; /* Convert name to number. */ if ((q = a_ptr[x]) == NULL) /* If array not declared, */ return(0); /* return -2. */ if (z > a_dim[x]) /* If subscript out of range, */ return(0); /* return -3. */ p = q[z]; } } else { /* Macro */ z = isaa(nam); x = z ? mxxlook(mactab,nam,nmac) : mlook(mactab,nam,nmac); if (x < 0) return(0); p = mactab[x].mval; } if (p) *s = p; else p = ""; return((int)strlen(p)); } #endif /* USE_VARLEN */ /* This routine is for the benefit of those compilers that can't handle long string constants or continued lines within them. Long predefined macros like FOR, WHILE, and XIF have their contents broken up into arrays of string pointers. This routine concatenates them back into a single string again, and then calls the real addmac() routine to enter the definition into the macro table. */ int addmmac(nam,s) char *nam, *s[]; { /* Add a multiline macro definition */ int i, x, y; char *p; x = 0; /* Length counter */ for (i = 0; (y = (int)strlen(s[i])) > 0; i++) { /* Add up total length */ debug(F111,"addmmac line",s[i],y); x += y; } debug(F101,"addmmac lines","",i); debug(F101,"addmmac loop exit","",y); debug(F111,"addmmac length",nam,x); if (x < 0) return(-1); p = malloc(x+1); /* Allocate space for all of it. */ if (!p) { printf("?addmmac malloc error: %s\n",nam); debug(F110,"addmmac malloc error",nam,0); return(-1); } *p = '\0'; /* Start off with null string. */ for (i = 0; *s[i]; i++) /* Concatenate them all together. */ ckstrncat(p,s[i],x+1); y = (int)strlen(p); /* Final precaution. */ debug(F111,"addmmac constructed string",p,y); if (y == x) { y = addmac(nam,p); /* Add result to the macro table. */ } else { debug(F100,"addmmac length mismatch","",0); printf("\n!addmmac internal error!\n"); y = -1; } free(p); /* Free the temporary copy. */ return(y); } static char evalmacrobuf[TMPBUFSIZ]; VOID evalmacroarg(p) char **p; { char * s = evalmacrobuf; int t = TMPBUFSIZ; (VOID) zzstring(*p,&s,&t); *p = evalmacrobuf; } /* Here is the real addmac routine. */ /* Returns -1 on failure, macro table index >= 0 on success. */ int mtchanged = 0; int addmac(nam,def) char *nam, *def; { /* Add a macro to the macro table */ int i, x, y, z, namlen, deflen, flag = 0; int replacing = 0, deleting = 0; char * p = NULL, c, *s; extern int tra_asg; int tra_tmp; if (!nam) return(-1); if (!*nam) return(-1); #ifdef IKSD if (inserver && #ifdef IKSDCONF iksdcf #else /* IKSDCONF */ 1 #endif /* IKSDCONF */ ) { if (!ckstrcmp("on_exit",nam,-1,0) || !ckstrcmp("on_logout",nam,-1,0)) return(-1); } #endif /* IKSD */ namlen = 0; p = nam; while (*p++) namlen++; /* (instead of strlen) */ tra_tmp = tra_asg; /* trace... */ debug(F111,"addmac nam",nam,namlen); if (!def) { /* Watch out for null pointer */ deflen = 0; debug(F111,"addmac def","(null pointer)",deflen); } else { deflen = 0; p = def; while (*p++) deflen++; /* (instead of strlen) */ debug(F010,"addmac def",def,0); } #ifdef USE_VARLEN /* NOT USED */ /* This does not boost performance much because varlen() does a lot */ x = varlen(nam,&s); if (x > 0 && x >= deflen) { strcpy(s,def); /* NOT USED */ flag = 1; p = s; } #endif /* USE_VARLEN */ if (*nam == CMDQ) nam++; /* Backslash quote? */ if (*nam == '%') { /* Yes, if it's a variable name, */ if (!(c = *(nam + 1))) return(-1); /* Variable name letter or digit */ if (!flag) { tra_asg = 0; delmac(nam,0); /* Delete any old value. */ tra_asg = tra_tmp; } if (deflen < 1) { /* Null definition */ p = NULL; /* Better not malloc or strcpy! */ } else if (!flag) { /* A substantial definition */ p = malloc(deflen + 1); /* Allocate space for it */ if (!p) { printf("?addmac malloc error 2\n"); return(-1); } else strcpy(p,def); /* Copy def into new space (SAFE) */ } /* Now p points to the definition, or is a null pointer */ if (c >= '0' && c <= '9') { /* \%0-9 variable */ if (maclvl < 0) { /* Are we calling or in a macro? */ g_var[c] = p; /* No, it's top level one */ makestr(&(toparg[c - '0']),p); /* Take care \&_[] too */ } else { /* Yes, it's a macro argument */ m_arg[maclvl][c - '0'] = p; /* Assign the value */ makestr(&(m_xarg[maclvl][c - '0']),p); /* And a copy here */ } } else { /* It's a \%a-z variable */ if (c < 33 || (unsigned int)c > GVARS) return(-1); if (isupper(c)) c = (char) tolower(c); g_var[c] = p; /* Put pointer in global-var table */ } if (tra_asg) traceval(nam,p); return(0); } else if (*nam == '&') { /* An array reference? */ char **q = NULL; int rc = 0; if ((y = arraynam(nam,&x,&z)) < 0) /* If syntax is bad */ return(-1); /* return -1. */ if (chkarray(x,z) < 0) /* If array not declared or */ rc = -2; /* subscript out of range, ret -2 */ if (!flag) { tra_asg = 0; delmac(nam,0); /* Delete any old value. */ tra_asg = tra_tmp; } x -= ARRAYBASE; /* Convert name letter to index. */ if (x > 'z' - ARRAYBASE + 1) rc = -1; if (rc != -1) { if ((q = a_ptr[x]) == NULL) /* If array not declared, */ return(-3); /* return -3. */ } if (rc < 0) return(rc); if (!flag) { if (deflen > 0) { if ((p = malloc(deflen+1)) == NULL) { /* Allocate space */ printf("addmac macro error 7: %s\n",nam); return(-4); /* for new def, return -4 on fail. */ } strcpy(p,def); /* Copy def into new space (SAFE). */ } else p = NULL; } q[z] = p; /* Store pointer to it. */ if (x == 0) { /* Arg vector array */ if (z >= 0 && z <= 9) { /* Copy values to corresponding */ if (maclvl < 0) { /* \%1..9 variables. */ makestr(&(toparg[z]),p); } else { makestr(&(m_arg[maclvl][z]),p); } } } if (tra_asg) traceval(nam,p); return(0); /* Done. */ } /* Not a macro argument or a variable, so it's a macro definition */ #ifdef USE_VARLEN if (flag) { if (tra_asg) traceval(nam,p); return(0); } #endif /* USE_VARLEN */ x = isaa(nam) ? /* If it's an associative array */ mxxlook(mactab,nam,nmac) : /* look it up this way */ mxlook(mactab,nam,nmac); /* otherwise this way. */ if (x > -1) { /* If found... */ if (deflen > 0) /* and a new definition was given */ replacing = 1; /* we're replacing */ else /* otherwise */ deleting = 1; /* we're deleting */ } if (deleting) { /* Deleting... */ if (delmac(nam,0) < 0) return(-1); mtchanged++; if (tra_asg) traceval(nam,p); return(0); } else if (deflen < 1) /* New macro with no definition */ return(0); /* Nothing to do. */ if (replacing) { /* Replacing an existing macro */ if (mactab[x].mval) { /* If it currently has a definition, */ free(mactab[x].mval); /* free it. */ mactab[x].mval = NULL; } mtchanged++; y = x; /* Replacement index. */ } else { /* Adding a new macro... */ char c1, c2; /* Use fast lookup to find the */ c1 = *nam; /* alphabetical slot. */ if (isupper(c1)) c1 = (char) tolower(c1); if (nmac < 5) { /* Not worth it for small tables */ y = 0; } else { /* First binary search to find */ int lo = 0; /* where to start */ int hi = nmac; int count = 0; char c = 0; while (lo+2 < hi && ++count < 12) { y = lo + ((hi - lo) / 2); c = *(mactab[y].kwd); if (isupper(c)) c = (char) tolower(c); if (c < c1) { lo = y; } else { hi = y; } } y = (c < c1) ? lo+1 : lo; } /* Now search linearly from starting location */ for ( ; y < MAC_MAX && mactab[y].kwd != NULL; y++) { c2 = *(mactab[y].kwd); if (isupper(c2)) c2 = (char) tolower(c2); if (c1 > c2) continue; if (c1 < c2) break; if (ckstrcmp(nam,mactab[y].kwd,-1,0) <= 0) break; } if (y == MAC_MAX) { /* Macro table is full. */ debug(F101,"addmac table overflow","",y); printf("?Macro table overflow\n"); return(-1); } if (mactab[y].kwd != NULL) { /* Must insert */ for (i = nmac; i > y; i--) { /* Move the rest down one slot */ mactab[i].kwd = mactab[i-1].kwd; mactab[i].mval = mactab[i-1].mval; mactab[i].flgs = mactab[i-1].flgs; } } mtchanged++; p = malloc(namlen + 1); /* Allocate space for name */ if (!p) { printf("?Addmac: Out of memory - \"%s\"\n",nam); return(-1); } strcpy(p,nam); /* Copy name into new space (SAFE) */ mactab[y].kwd = p; /* Add pointer to table */ } if (deflen > 0) { /* If we have a definition */ p = malloc(deflen + 1); /* Get space */ if (p == NULL) { printf("?Space exhausted - \"%s\"\n", nam); if (mactab[y].kwd) { free(mactab[y].kwd); mactab[y].kwd = NULL; } return(-1); } else { strcpy(p,def); /* Copy the definition (SAFE) */ } } else { /* definition is empty */ p = NULL; } mactab[y].mval = p; /* Macro points to definition */ mactab[y].flgs = 0; /* No flags */ if (!replacing) /* If new macro */ nmac++; /* count it */ if (tra_asg) traceval(nam,p); return(y); } int xdelmac(x) int x; { /* Delete a macro given its index */ int i; extern int tra_asg; if (x < 0) return(x); if (tra_asg) traceval(mactab[x].kwd,NULL); if (mactab[x].kwd) { /* Free the storage for the name */ free(mactab[x].kwd); mactab[x].kwd = NULL; } if (mactab[x].mval) { /* and for the definition */ free(mactab[x].mval); mactab[x].mval = NULL; } for (i = x; i < nmac; i++) { /* Now move up the others. */ mactab[i].kwd = mactab[i+1].kwd; mactab[i].mval = mactab[i+1].mval; mactab[i].flgs = mactab[i+1].flgs; } nmac--; /* One less macro */ mactab[nmac].kwd = NULL; /* Delete last item from table */ mactab[nmac].mval = NULL; mactab[nmac].flgs = 0; mtchanged++; return(0); } int delmac(nam,exact) char *nam; int exact; { /* Delete the named macro */ int x, z; char *p, c; extern int tra_asg; if (!nam) return(0); /* Watch out for null pointer */ debug(F110,"delmac nam",nam,0); #ifdef IKSD if ( inserver && #ifdef IKSDCONF iksdcf #else /* IKSDCONF */ 1 #endif /* IKSDCONF */ ) { if (!ckstrcmp("on_exit",nam,-1,0) || !ckstrcmp("on_logout",nam,-1,0)) return(-1); } #endif /* IKSD */ if (*nam == CMDQ) nam++; if (*nam == '%') { /* If it's a variable name */ if (!(c = *(nam+1))) return(0); /* Get variable name letter or digit */ p = (char *)0; /* Initialize value pointer */ if (maclvl < 0 && c >= '0' && c <= '9') { /* Top-level digit? */ p = toparg[c - '0']; if (p) if (p != g_var[c]) { free(p); toparg[c - '0'] = NULL; } p = g_var[c]; g_var[c] = NULL; /* Zero the table entry */ } else if (maclvl > -1 && c >= '0' && c <= '9') { /* Digit? */ p = m_xarg[maclvl][c - '0']; if (p) if (p != g_var[c]) { free(p); m_xarg[maclvl][c - '0'] = NULL; } p = m_arg[maclvl][c - '0']; /* Get pointer from macro-arg table */ m_arg[maclvl][c - '0'] = NULL; /* Zero the table pointer */ } else { /* It's a global variable */ if (c < 33 || (unsigned int)c > GVARS) return(0); p = g_var[c]; /* Get pointer from global-var table */ g_var[c] = NULL; /* Zero the table entry */ } if (p) { debug(F010,"delmac def",p,0); free(p); /* Free the storage */ p = NULL; } else debug(F110,"delmac def","(null pointer)",0); if (tra_asg) traceval(nam,NULL); return(0); } if (*nam == '&') { /* An array reference? */ char **q; if (arraynam(nam,&x,&z) < 0) /* If syntax is bad */ return(-1); /* return -1. */ x -= ARRAYBASE; /* Convert name to number. */ if ((q = a_ptr[x]) == NULL) /* If array not declared, */ return(-2); /* return -2. */ if (z > a_dim[x]) /* If subscript out of range, */ return(-3); /* return -3. */ if (q[z]) { /* If there is an old value, */ debug(F010,"delmac def",q[z],0); if (x != 0) /* Macro arg vector is just a copy */ free(q[z]); /* Others are real so free them */ q[z] = NULL; if (x == 0) { /* Arg vector array */ if (z >= 0 && z <= 9) { /* Copy values to corresponding */ if (maclvl < 0) { /* \%1..9 variables. */ makestr(&(toparg[z]),NULL); } else { makestr(&(m_arg[maclvl][z]),NULL); } } } if (tra_asg) traceval(nam,NULL); } else debug(F010,"delmac def","(null pointer)",0); } /* Not a variable or an array, so it must be a macro. */ z = isaa(nam); debug(F111,"delmac isaa",nam,z); debug(F111,"delmac exact",nam,exact); x = z ? mxxlook(mactab,nam,nmac) : exact ? mxlook(mactab,nam,nmac) : mlook(mactab,nam,nmac); if (x < 0) { debug(F111,"delmac mlook",nam,x); return(x); } return(xdelmac(x)); } VOID initmac() { /* Init macro & variable tables */ int i, j, x; nmac = 0; /* No macros */ for (i = 0; i < MAC_MAX; i++) { /* Initialize the macro table */ mactab[i].kwd = NULL; mactab[i].mval = NULL; mactab[i].flgs = 0; } mtchanged++; x = (MAXARGLIST + 1) * sizeof(char **); for (i = 0; i < MACLEVEL; i++) { /* Init the macro argument tables */ m_xarg[i] = (char **) malloc(x); mrval[i] = NULL; /* Macro return value */ /* Pointer to entire argument vector, level i, for \&_[] array */ for (j = 0; j <= MAXARGLIST; j++) { /* Macro argument list */ if (j < 10) /* For the \%0..\%9 variables */ m_arg[i][j] = NULL; /* Pointer to arg j, level i. */ if (m_xarg[i]) /* For \&_[] - all args. */ m_xarg[i][j] = NULL; } } for (i = 0; i < GVARS; i++) { /* And the global variables table */ g_var[i] = NULL; } /* And the table of arrays */ for (i = 0; i < (int) 'z' - ARRAYBASE + 1; i++) { a_ptr[i] = (char **) NULL; /* Null pointer for each */ a_dim[i] = 0; /* and a dimension of zero */ a_link[i] = -1; for (j = 0; j < CMDSTKL; j++) { aa_ptr[j][i] = (char **) NULL; aa_dim[j][i] = 0; } } } int popclvl() { /* Pop command level, return cmdlvl */ extern int tra_cmd; struct localvar * v; int i, topcmd; debug(F101,"popclvl cmdlvl","",cmdlvl); if (cmdlvl > 0) { if ((v = localhead[cmdlvl])) { /* Did we save any variables? */ while (v) { /* Yes */ if (v->lv_value) /* Copy old ones back */ addmac(v->lv_name,v->lv_value); else delmac(v->lv_name,1); v = v->lv_next; } freelocal(cmdlvl); /* Free local storage */ } /* Automatic arrays do not use the localhead list */ for (i = 0; i < 28; i++) { /* Free any local arrays */ if (aa_ptr[cmdlvl][i]) { /* Does this one exist? */ dclarray((char)(i+ARRAYBASE),-1); /* Destroy global one */ a_ptr[i] = aa_ptr[cmdlvl][i]; a_dim[i] = aa_dim[cmdlvl][i]; aa_ptr[cmdlvl][i] = (char **)NULL; aa_dim[cmdlvl][i] = 0; } else if (aa_dim[cmdlvl][i] == -23) { /* Secret code */ /* A local array declared at this level when there was no array of the same name at any higher level. See comment in pusharray(). */ dclarray((char)(i+ARRAYBASE),-1); a_ptr[i] = (char **)NULL; /* Delete top-level array */ a_dim[i] = 0; /* created by pusharray - Feb 2016 */ aa_ptr[cmdlvl][i] = (char **)NULL; aa_dim[cmdlvl][i] = 0; } /* Otherwise do nothing - it is a local array that was declared */ /* at a level above this one so leave it alone. */ } } if (cmdlvl < 1) { /* If we're already at top level */ cmdlvl = 0; /* just make sure all the */ tlevel = -1; /* stack pointers are set right */ maclvl = -1; /* and return */ } else if (cmdstk[cmdlvl].src == CMD_TF) { /* Reading from TAKE file? */ debug(F101,"popclvl tlevel","",tlevel); if (tlevel > -1) { /* Yes, */ fclose(tfile[tlevel]); /* close it */ if (tra_cmd) printf("[%d] -F: \"%s\"\n",cmdlvl,tfnam[tlevel]); debug(F111,"CMD -F",tfnam[tlevel],cmdlvl); if (tfnam[tlevel]) { /* free storage for name */ free(tfnam[tlevel]); tfnam[tlevel] = NULL; } tlevel--; /* and pop take level */ cmdlvl--; /* and command level */ quiet = xquiet[cmdlvl]; vareval = xvarev[cmdlvl]; } else tlevel = -1; } else if (cmdstk[cmdlvl].src == CMD_MD) { /* In a macro? */ topcmd = lastcmd[maclvl]; debug(F101,"popclvl maclvl","",maclvl); if (maclvl > -1) { /* Yes, */ #ifdef COMMENT int i; char **q; #endif /* COMMENT */ macp[maclvl] = ""; /* set macro pointer to null string */ *cmdbuf = '\0'; /* clear the command buffer */ if ((maclvl > 0) && /* 2 May 1999 */ (m_arg[maclvl-1][0]) && (!strncmp(m_arg[maclvl-1][0],"_xif",4) || !strncmp(m_arg[maclvl-1][0],"_for",4) || !strncmp(m_arg[maclvl-1][0],"_swi",4) || !strncmp(m_arg[maclvl-1][0],"_whi",4)) && mrval[maclvl+1]) { makestr(&(mrval[maclvl-1]),mrval[maclvl+1]); } if (maclvl+1 < MACLEVEL) { if (mrval[maclvl+1]) { /* Free any deeper return values. */ free(mrval[maclvl+1]); mrval[maclvl+1] = NULL; } } if (tra_cmd) printf("[%d] -M: \"%s\"\n",cmdlvl,m_arg[cmdstk[cmdlvl].lvl][0]); debug(F111,"CMD -M",m_arg[cmdstk[cmdlvl].lvl][0],cmdlvl); maclvl--; /* Pop macro level */ cmdlvl--; /* and command level */ debug(F101,"popclvl mac new maclvl","",maclvl); debug(F010,"popclvl mac mrval[maclvl+1]",mrval[maclvl+2],0); quiet = xquiet[cmdlvl]; vareval = xvarev[cmdlvl]; if (maclvl > -1) { a_ptr[0] = m_xarg[maclvl]; a_dim[0] = n_xarg[maclvl] - 1; debug(F111,"a_dim[0]","B",a_dim[0]); } else { a_ptr[0] = topxarg; a_dim[0] = topargc - 1; debug(F111,"a_dim[0]","C",a_dim[0]); } } else { maclvl = -1; } #ifndef NOSEXP debug(F101,"popclvl topcmd","",topcmd); if (topcmd == XXSEXP) { extern char * sexpval; makestr(&(mrval[maclvl+1]),sexpval); } #endif /* NOSEXP */ } else { cmdlvl--; } debug(F101,"popclvl cmdlvl","",cmdlvl); if (prstring[cmdlvl]) { cmsetp(prstring[cmdlvl]); makestr(&(prstring[cmdlvl]),NULL); } #ifndef MAC if (cmdlvl < 1 || xcmdsrc == CMD_KB) { /* If at prompt */ setint(); concb((char)escape); /* Go into cbreak mode */ } #endif /* MAC */ xcmdsrc = cmdstk[cmdlvl].src; debug(F101,"popclvl xcmdsrc","",xcmdsrc); debug(F101,"popclvl tlevel","",tlevel); return(cmdlvl < 1 ? 0 : cmdlvl); /* Return command level */ } #else /* No script programming language */ int popclvl() { /* Just close current take file. */ if (tlevel > -1) { /* if any... */ if (tfnam[tlevel]) { free(tfnam[tlevel]); tfnam[tlevel] = NULL; } fclose(tfile[tlevel--]); } if (tlevel == -1) { /* And if back at top level */ setint(); concb((char)escape); /* and go back into cbreak mode. */ } xcmdsrc = tlevel > -1 ? CMD_TF : 0; return(tlevel + 1); } #endif /* NOSPL */ #ifndef NOSPL static int iseom(m) char * m; { /* Test if at end of macro def */ if (!m) m = ""; debug(F111,"iseom",m,maclvl); while (*m) { /* Anything but Space and Comma means more macro is left */ if ((*m > SP) && (*m != ',')) { debug(F111,"iseom return",m,0); return(0); } m++; } debug(F111,"iseom return",m,1); return(1); /* Nothing left */ } #endif /* NOSPL */ /* Pop all command levels that can be popped */ int prepop() { if (cmdlvl > 0) { /* If command level is > 0 and... */ while ( #ifndef NOSPL ((cmdstk[cmdlvl].src == CMD_TF) && /* Command source is file */ #endif /* NOSPL */ (tlevel > -1) && feof(tfile[tlevel])) /* And at end of file... */ #ifndef NOSPL /* Or command source is macro... */ || ((cmdstk[cmdlvl].src == CMD_MD) && (maclvl > -1) && iseom(macp[maclvl]))) /* and at end of macro, then... */ #endif /* NOSPL */ { popclvl(); /* pop command level. */ } } return(cmdlvl < 1 ? 0 : cmdlvl); /* Return command level */ } /* STOP - get back to C-Kermit prompt, no matter where from. */ int dostop() { extern int cmddep; while (popclvl()) ; /* Pop all macros & take files */ #ifndef NOSPL if (cmddep > -1) /* And all recursive cmd pkg invocations */ while (cmpop() > -1) ; #endif /* NOSPL */ cmini(ckxech); /* Clear the command buffer. */ return(0); } /* Close the given log */ int doclslog(x) int x; { int y; switch (x) { #ifdef DEBUG case LOGD: if (deblog <= 0) { printf("?Debugging log wasn't open\n"); return(0); } debug(F100,"Debug Log Closed","",0L); *debfil = '\0'; deblog = 0; return(zclose(ZDFILE)); #endif /* DEBUG */ #ifndef NOXFER case LOGP: if (pktlog <= 0) { printf("?Packet log wasn't open\n"); return(0); } *pktfil = '\0'; pktlog = 0; return(zclose(ZPFILE)); #endif /* NOXFER */ #ifndef NOLOCAL case LOGS: if (seslog <= 0) { printf("?Session log wasn't open\n"); return(0); } *sesfil = '\0'; setseslog(0); return(zclose(ZSFILE)); #endif /* NOLOCAL */ #ifdef TLOG case LOGT: { #ifdef IKSD extern int iklogopen, xferlog; #endif /* IKSD */ if (tralog <= 0 #ifdef IKSD && !iklogopen #endif /* IKSD */ ) { if (msgflg) printf("?Transaction log wasn't open\n"); return(0); } #ifdef IKSD if (iklogopen && !inserver) { close(xferlog); iklogopen = 0; } #endif /* IKSD */ if (tralog) { tlog(F100,"Transaction Log Closed","",0L); zclose(ZTFILE); } *trafil = '\0'; tralog = 0; return(1); } #endif /* TLOG */ #ifdef CKLOGDIAL case LOGM: if (dialog <= 0) { if (msgflg) printf("?Connection log wasn't open\n"); return(0); } *diafil = '\0'; dialog = 0; return(zclose(ZDIFIL)); #endif /* CKLOGDIAL */ #ifndef NOSPL case LOGW: /* WRITE file */ case LOGR: /* READ file */ y = (x == LOGR) ? ZRFILE : ZWFILE; if (chkfn(y) < 1) /* If no file to close */ return(1); /* succeed silently. */ return(zclose(y)); /* Otherwise, close the file. */ #endif /* NOSPL */ default: printf("\n?Unexpected log designator - %d\n", x); return(0); } } static int slc = 0; /* Screen line count */ char * showstring(s) char * s; { return(s ? s : "(null)"); } char * showoff(x) int x; { return(x ? "on" : "off"); } char * showooa(x) int x; { switch (x) { case SET_OFF: return("off"); case SET_ON: return("on"); case SET_AUTO: return("automatic"); default: return("(unknown)"); } } #ifdef GEMDOS isxdigit(c) int c; { return(isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } #endif /* GEMDOS */ #ifndef NOSETKEY #ifdef OS2 static struct keytab shokeytab[] = { /* SHOW KEY modes */ "all", 1, 0, "one", 0, 0 }; static int nshokey = (sizeof(shokeytab) / sizeof(struct keytab)); #define SHKEYDEF TT_MAX+5 struct keytab shokeymtab[] = { "aaa", TT_AAA, CM_INV, /* AnnArbor */ "adm3a", TT_ADM3A, 0, /* LSI ADM-3A */ "adm5", TT_ADM5, 0, /* LSI ADM-5 */ "aixterm", TT_AIXTERM, 0, /* IBM AIXterm */ "annarbor", TT_AAA, 0, /* AnnArbor */ "ansi-bbs", TT_ANSI, 0, /* ANSI.SYS (BBS) */ "at386", TT_AT386, 0, /* Unixware ANSI */ "avatar/0+", TT_ANSI, 0, /* AVATAR/0+ */ "ba80", TT_BA80, 0, /* Nixdorf BA80 */ "be", TT_BEOS, CM_INV|CM_ABR, "beos-ansi", TT_BEOS, CM_INV, /* BeOS ANSI */ "beterm", TT_BEOS, 0, /* BeOS Console */ "d200", TT_DG200, CM_INV|CM_ABR, /* Data General DASHER 200 */ "d210", TT_DG210, CM_INV|CM_ABR, /* Data General DASHER 210 */ "d217", TT_DG217, CM_INV|CM_ABR, /* Data General DASHER 217 */ "default", SHKEYDEF, 0, "dg200", TT_DG200, 0, /* Data General DASHER 200 */ "dg210", TT_DG210, 0, /* Data General DASHER 210 */ "dg217", TT_DG217, 0, /* Data General DASHER 217 */ "emacs", TT_KBM_EMACS, 0, /* Emacs mode */ "h19", TT_H19, CM_INV, /* Heath-19 */ "heath19", TT_H19, 0, /* Heath-19 */ "hebrew", TT_KBM_HEBREW, 0, /* Hebrew mode */ "hft", TT_HFT, 0, /* IBM HFT */ "hp2621a", TT_HP2621, 0, /* HP 2621A */ "hpterm", TT_HPTERM, 0, /* HP TERM */ "hz1500", TT_HZL1500, 0, /* Hazeltine 1500 */ "ibm3151", TT_IBM31, 0, /* IBM 3101-xx,3161 */ "linux", TT_LINUX, 0, /* Linux */ "qansi", TT_QANSI, 0, /* QNX ANSI */ "qnx", TT_QNX, 0, /* QNX */ "russian", TT_KBM_RUSSIAN, 0, /* Russian mode */ "scoansi", TT_SCOANSI, 0, /* SCO ANSI */ "sni-97801", TT_97801, 0, /* Sinix 97801 */ "sun", TT_SUN, 0, /* Sun Console */ #ifdef OS2PM #ifdef COMMENT "tek4014", TT_TEK40, 0, #endif /* COMMENT */ #endif /* OS2PM */ "tty", TT_NONE, 0, "tvi910+", TT_TVI910, 0, "tvi925", TT_TVI925, 0, "tvi950", TT_TVI950, 0, "vc404", TT_VC4404, 0, "vc4404", TT_VC4404, CM_INV, "vip7809", TT_VIP7809, 0, "vt100", TT_VT100, 0, "vt102", TT_VT102, 0, "vt220", TT_VT220, 0, "vt220pc", TT_VT220PC, 0, "vt320", TT_VT320, 0, "vt320pc", TT_VT320PC, 0, "vt52", TT_VT52, 0, "wp", TT_KBM_WP, 0, "wy160", TT_WY160, 0, "wy30", TT_WY30, 0, "wy370", TT_WY370, 0, "wy50", TT_WY50, 0, "wy60", TT_WY60, 0, "wyse30", TT_WY30, CM_INV, "wyse370", TT_WY370, CM_INV, "wyse50", TT_WY50, CM_INV, "wyse60", TT_WY60, CM_INV }; int nshokeym = (sizeof(shokeymtab) / sizeof(struct keytab)); #endif /* OS2 */ VOID #ifdef OS2 shokeycode(c,m) int c, m; #else shokeycode(c) int c; #endif /* shokeycode */ { KEY ch; CHAR *s; #ifdef OS2 int i; con_event km; #else /* OS2 */ int km; #endif /* OS2 */ #ifdef OS2 extern int mskkeys; char * mstr = ""; if (c >= KMSIZE) { bleep(BP_FAIL); return; } #else /* OS2 */ printf(" Key code \\%d => ", c); #endif /* OS2 */ #ifndef OS2 km = mapkey(c); #ifndef NOKVERBS if (IS_KVERB(km)) { /* \Kverb? */ int i, kv; kv = km & ~(F_KVERB); printf("Verb: "); for (i = 0; i < nkverbs; i++) if (kverbs[i].kwval == kv) { printf("\\K%s",kverbs[i].kwd); break; } printf("\n"); } else #endif /* NOKVERBS */ if (IS_CSI(km)) { int xkm = km & 0xFF; if (xkm <= 32 || xkm >= 127) printf("String: \\{27}[\\{%d}\n",xkm); else printf("String: \\{27}[%c\n",xkm); } else if (IS_ESC(km)) { int xkm = km & 0xFF; if (xkm <= 32 || xkm >= 127) printf("String: \\{27}\\{%d}\n",xkm); else printf("String: \\{27}%c\n",xkm); } else if (macrotab[c]) { /* See if there's a macro */ printf("String: "); /* If so, display its definition */ s = macrotab[c]; shostrdef(s); printf("\n"); #ifndef NOKVERBS } else if (km >= 0x100) { /* This means "undefined" */ printf("Undefined\n"); #endif /* NOKVERBS */ } else { /* No macro, show single character */ printf("Character: "); ch = km; if (ch < 32 || ch == 127 #ifdef OS2 || ch > 255 #endif /* OS2 */ #ifndef NEXT #ifndef AUX #ifndef XENIX #ifndef OS2 || (ch > 127 && ch < 160) #endif /* OS2 */ #endif /* XENIX */ #endif /* AUX */ #endif /* NEXT */ ) /* These used to be %d, but gcc 1.93 & later complain about type mismatches. %u is supposed to be totally portable. */ printf("\\%u",(unsigned int) ch); else printf("%c \\%u",(CHAR) (ch & 0xff),(unsigned int) ch); if (ch == (KEY) c) printf(" (self, no translation)\n"); else printf("\n"); } #else /* OS2 */ if (m < 0) { km = mapkey(c); mstr = "default"; } else { km = maptermkey(c,m); for (i = 0; i < nshokeym; i++) { if (m == shokeymtab[i].kwval) { mstr = shokeymtab[i].kwd; break; } } } s = keyname(c); debug(F111,"shokeycode mstr",mstr,m); debug(F111,"shokeycode keyname",s,c); printf(" %sKey code \\%d %s (%s) => ", mskkeys ? "mskermit " : "", mskkeys ? cktomsk(c) : c, s == NULL ? "" : s, mstr); switch (km.type) { #ifndef NOKVERBS case kverb: { int i, kv; kv = km.kverb.id & ~(F_KVERB); printf("Verb: "); for (i = 0; i < nkverbs; i++) { if (kverbs[i].kwval == kv) { printf("\\K%s",kverbs[i].kwd); break; } } printf("\n"); break; } #endif /* NOKVERBS */ case csi: { int xkm = km.csi.key & 0xFF; if (xkm <= 32 || xkm >= 127) printf("String: \\{27}[\\{%d}\n",xkm); else printf("String: \\{27}[%c\n",xkm); break; } case esc: { int xkm = km.esc.key & 0xFF; if (xkm <= 32 || xkm >= 127) printf("String: \\{%d}\\{%d}\n",ISDG200(tt_type)?30:27,xkm); else printf("String: \\{%d}%c\n",ISDG200(tt_type)?30:27,xkm); break; } case macro: { printf("String: "); /* Macro, display its definition */ shostrdef(km.macro.string); printf("\n"); break; } case literal: { printf("Literal string: "); /* Literal, display its definition */ shostrdef(km.literal.string); printf("\n"); break; } case error: { if (c >= 0x100) { printf("Undefined\n"); } else { printf("Character: "); ch = c; if (ch < 32 || ch == 127 || ch > 255 #ifndef NEXT #ifndef AUX #ifndef XENIX #ifndef OS2 || (ch > 127 && ch < 160) #endif /* OS2 */ #endif /* XENIX */ #endif /* AUX */ #endif /* NEXT */ ) /* These used to be %d, but gcc 1.93 & later complain about type mismatches. %u is supposed to be totally portable. */ printf("\\%u",(unsigned int) ch); else printf("%c \\%u",(CHAR) (ch & 0xff),(unsigned int) ch); printf(" (self, no translation)\n"); } break; } case key: { printf("Character: "); ch = km.key.scancode; if (ch < 32 || ch == 127 || ch > 255 #ifndef NEXT #ifndef AUX #ifndef XENIX #ifndef OS2 || (ch > 127 && ch < 160) #else || (ch > 127) #endif /* OS2 */ #endif /* XENIX */ #endif /* AUX */ #endif /* NEXT */ ) /* These used to be %d, but gcc 1.93 & later complain about type mismatches. %u is supposed to be totally portable. */ printf("\\%u",(unsigned int) ch); else printf("%c \\%u",(CHAR) (ch & 0xff),(unsigned int) ch); if (ch == (KEY) c) printf(" (self, no translation)\n"); else printf("\n"); break; } } #endif /* OS2 */ } #endif /* NOSETKEY */ VOID shostrdef(s) CHAR * s; { CHAR ch; if (!s) s = (CHAR *)""; while ((ch = *s++)) { if (ch < 32 || ch == 127 || ch == 255 /* Systems whose native character sets have graphic characters in C1... */ #ifndef NEXT /* NeXT */ #ifndef AUX /* Macintosh */ #ifndef XENIX /* IBM PC */ #ifdef OS2 /* It doesn't matter whether the local host can display 8-bit characters; they are not portable among character-sets and fonts. Who knows what would be displayed... */ || (ch > 127) #else /* OS2 */ || (ch > 127 && ch < 160) #endif /* OS2 */ #endif /* XENIX */ #endif /* AUX */ #endif /* NEXT */ ) printf("\\{%d}",ch); /* Display control characters */ else putchar((char) ch); /* in backslash notation */ } } #define xxdiff(v,sys) strncmp(v,sys,strlen(sys)) #ifndef NOSHOW VOID shover() { #ifdef OS2 extern char ckxsystem[]; #endif /* OS2 */ extern char *ck_patch, * cklibv; printf("\nVersions:\n %s\n",versio); printf(" Numeric: %ld\n",vernum); #ifdef OS2 printf(" Operating System: %s\n", ckxsystem); #else /* OS2 */ printf(" Built for: %s\n", ckxsys); #ifdef CK_UTSNAME if (unm_nam[0]) printf(" Running on: %s %s %s %s\n", unm_nam,unm_ver,unm_rel,unm_mch); #endif /* CK_UTSNAME */ printf(" Patches: %s\n", *ck_patch ? ck_patch : "(none)"); #endif /* OS2 */ if (xxdiff(ckxv,ckxsys)) printf(" %s for%s\n",ckxv,ckxsys); else printf(" %s\n",ckxv); if (xxdiff(ckzv,ckzsys)) printf(" %s for%s\n",ckzv,ckzsys); else printf(" %s\n",ckzv); printf(" %s\n",cklibv); printf(" %s\n",protv); printf(" %s\n",fnsv); printf(" %s\n %s\n",cmdv,userv); #ifndef NOCSETS printf(" %s\n",xlav); #endif /* NOCSETS */ #ifndef MAC #ifndef NOLOCAL printf(" %s\n",connv); #ifdef OS2 printf(" %s\n",ckyv); #endif /* OS2 */ #endif /* NOLOCAL */ #endif /* MAC */ #ifndef NODIAL printf(" %s\n",dialv); #endif /* NODIAL */ #ifndef NOSCRIPT printf(" %s\n",loginv); #endif /* NOSCRIPT */ #ifdef NETCONN printf(" %s\n",cknetv); #ifdef OS2 printf(" %s\n",ckonetv); #ifdef CK_NETBIOS printf(" %s\n",ckonbiv); #endif /* CK_NETBIOS */ #endif /* OS2 */ #endif /* NETCONN */ #ifdef TNCODE printf(" %s\n",cktelv); #endif /* TNCODE */ #ifdef SSHBUILTIN printf(" %s\n",cksshv); #ifdef SFTP_BUILTIN printf(" %s\n",cksftpv); #endif /* SFTP_BUILTIN */ #endif /* SSHBUILTIN */ #ifdef OS2 #ifdef OS2MOUSE printf(" %s\n",ckomouv); #endif /* OS2MOUSE */ #endif /* OS2 */ #ifdef NEWFTP printf(" %s\n",ckftpv); #endif /* NEWFTP */ #ifdef CK_AUTHENTICATION printf(" %s\n",ckathv); #endif /* CK_AUTHENTICATION */ #ifdef CK_ENCRYPTION #ifdef CRYPT_DLL printf(" %s\n",ck_crypt_dll_version()); #else /* CRYPT_DLL */ printf(" %s\n",ckcrpv); #endif /* CRYPT_DLL */ #endif /* CK_ENCRYPTION */ #ifdef CK_SSL printf(" %s\n",cksslv); #endif /* CK_SSL */ printf("\n"); } #ifdef CK_LABELED VOID sholbl() { #ifdef VMS printf("VMS Labeled File Features:\n"); printf(" acl %s (ACL info %s)\n", showoff(lf_opts & LBL_ACL), lf_opts & LBL_ACL ? "preserved" : "discarded"); printf(" backup-date %s (backup date/time %s)\n", showoff(lf_opts & LBL_BCK), lf_opts & LBL_BCK ? "preserved" : "discarded"); printf(" name %s (original filename %s)\n", showoff(lf_opts & LBL_NAM), lf_opts & LBL_NAM ? "preserved" : "discarded"); printf(" owner %s (original file owner id %s)\n", showoff(lf_opts & LBL_OWN), lf_opts & LBL_OWN ? "preserved" : "discarded"); printf(" path %s (original file's disk:[directory] %s)\n", showoff(lf_opts & LBL_PTH), lf_opts & LBL_PTH ? "preserved" : "discarded"); #else #ifdef OS2 printf("OS/2 Labeled File features (attributes):\n"); printf(" archive: %s\n", showoff(lf_opts & LBL_ARC)); printf(" extended: %s\n", showoff(lf_opts & LBL_EXT)); printf(" hidden: %s\n", showoff(lf_opts & LBL_HID)); printf(" read-only: %s\n", showoff(lf_opts & LBL_RO )); printf(" system: %s\n", showoff(lf_opts & LBL_SYS)); #endif /* OS2 */ #endif /* VMS */ } #endif /* CK_LABELED */ VOID shotcs(csl,csr) int csl, csr; { /* Show terminal character set */ #ifndef NOCSETS #ifdef OS2 #ifndef NOTERM extern struct _vtG G[4], *GL, *GR; extern int decnrcm, sni_chcode; extern int tt_utf8, dec_nrc, dec_kbd, dec_lang; extern prncs; printf(" Terminal character-sets:\n"); if (IS97801(tt_type_mode)) { if (cmask == 0377) printf(" Mode: 8-bit Mode\n"); else printf(" Mode: 7-bit Mode\n"); printf(" CH.CODE is %s\n",sni_chcode?"On":"Off"); } else if (ISVT100(tt_type_mode)) { if (decnrcm) printf(" Mode: 7-bit National Mode\n"); else printf(" Mode: 8-bit Multinational Mode\n"); } if ( ck_isunicode() ) printf(" Local: Unicode display / %s input\n", csl == TX_TRANSP ? "transparent" : csl == TX_UNDEF ? "undefined" : txrinfo[csl]->keywd); else printf(" Local: %s\n", csl == TX_TRANSP ? "transparent" : csl == TX_UNDEF ? "undefined" : txrinfo[csl]->keywd); if ( tt_utf8 ) { printf(" Remote: UTF-8\n"); } else { printf(" Remote: %sG0: %s (%s)\n", GL == &G[0] ? "GL->" : GR == &G[0] ? "GR->" : " ", txrinfo[G[0].designation]->keywd, G[0].designation == TX_TRANSP ? "" : G[0].size == cs94 ? "94 chars" : G[0].size == cs96 ? "96 chars" : "multi-byte"); printf(" %sG1: %s (%s)\n", GL == &G[1] ? "GL->" : GR == &G[1] ? "GR->" : " ", txrinfo[G[1].designation]->keywd, G[1].designation == TX_TRANSP ? "" : G[1].size == cs94 ? "94 chars" : G[1].size == cs96 ? "96 chars" : "multi-byte"); printf(" %sG2: %s (%s)\n", GL == &G[2] ? "GL->" : GR == &G[2] ? "GR->" : " ", txrinfo[G[2].designation]->keywd, G[2].designation == TX_TRANSP ? "" : G[2].size == cs94 ? "94 chars" : G[2].size == cs96 ? "96 chars" : "multi-byte"); printf(" %sG3: %s (%s)\n", GL == &G[3] ? "GL->" : GR == &G[3] ? "GR->" : " ", txrinfo[G[3].designation]->keywd, G[3].designation == TX_TRANSP ? "" : G[3].size == cs94 ? "94 chars" : G[3].size == cs96 ? "96 chars" : "multi-byte"); } printf("\n"); printf(" Keyboard character-sets:\n"); printf(" Multinational: %s\n",txrinfo[dec_kbd]->keywd); printf(" National: %s\n",txrinfo[dec_nrc]->keywd); printf("\n"); printf(" Printer character-set: %s\n",txrinfo[prncs]->keywd); #endif /* NOTERM */ #else /* OS2 */ #ifndef MAC char *s; debug(F101,"TERM LOCAL CSET","",csl); debug(F101,"TERM REMOTE CSET","",csr); printf(" Terminal character-set: "); if (tcs_transp) { /* No translation */ printf("transparent\n"); } else { /* Translation */ printf("%s (remote) %s (local)\n", fcsinfo[csr].keyword,fcsinfo[csl].keyword); if (csr != csl) { switch(gettcs(csr,csl)) { case TC_USASCII: s = "ascii"; break; case TC_1LATIN: s = "latin1-iso"; break; case TC_2LATIN: s = "latin2-iso"; break; case TC_CYRILL: s = "cyrillic-iso"; break; case TC_JEUC: s = "japanese-euc"; break; case TC_HEBREW: s = "hebrew-iso"; break; case TC_GREEK: s = "greek-iso"; break; case TC_9LATIN: s = "latin9-iso"; break; default: s = "transparent"; break; } if (strcmp(s,fcsinfo[csl].keyword) && strcmp(s,fcsinfo[csr].keyword)) printf(" (via %s)\n",s); } } #endif /* MAC */ #endif /* OS2 */ #endif /* NOCSETS */ } #ifndef NOLOCAL #ifdef OS2 extern char htab[]; VOID shotabs() { int i,j,k,n; printf("Tab Stops:\n\n"); for (i = 0, j = 1, k = VscrnGetWidth(VCMD); i < MAXTERMCOL; ) { do { printf("%c",htab[++i]=='T'?'T':'-'); } while (i % k && i < MAXTERMCOL); printf("\n"); for ( ; j <= i; j++) { switch ( j%10 ) { case 1: printf("%c",j == 1 ? '1' : '.'); break; case 2: case 3: case 4: case 5: case 6: case 7: printf("%c",'.'); break; case 8: n = (j+2)/100; if (n) printf("%d",n); else printf("%c",'.'); break; case 9: n = (j+1)%100/10; if (n) printf("%d",n); else if (j>90) printf("0"); else printf("%c",'.'); break; case 0: printf("0"); break; } } printf("\n"); } #ifdef COMMENT for (i = 1; i <= 70; i++) printf("%c",htab[i]=='T'?'T':'-'); printf("\n1.......10........20........30........40........50........60\ ........70\n\n"); for (; i <= 140; i++) printf("%c",htab[i]=='T'?'T':'-'); printf("\n........80........90.......100.......110.......120.......130\ .......140\n\n"); for (; i <= 210; i++) printf("%c",htab[i]=='T'?'T':'-'); printf("\n.......150.......160.......170.......180.......190.......200\ .......210\n\n"); for (; i <= 255; i++) printf("%c",htab[i]=='T'?'T':'-'); printf("\n.......220.......230.......240.......250..255\n"); #endif } #endif /* OS2 */ #endif /* NOLOCAL */ #ifdef OS2MOUSE VOID shomou() { int button, event, id, i; char * name = ""; printf("Mouse settings:\n"); printf(" Button Count: %d\n",mousebuttoncount()); printf(" Active: %s\n\n",showoff(tt_mouse)); for (button = 0; button < MMBUTTONMAX; button++) for (event = 0; event < MMEVENTSIZE; event++) if (mousemap[button][event].type != error) switch (mousemap[button][event].type) { case key: printf(" %s = Character: %c \\%d\n", mousename(button,event), mousemap[button][event].key.scancode, mousemap[button][event].key.scancode ); break; case kverb: id = mousemap[button][event].kverb.id & ~(F_KVERB); if (id != K_IGNORE) { for (i = 0; i< nkverbs; i++) if (id == kverbs[i].kwval) { name = kverbs[i].kwd; break; } printf(" %s = Kverb: \\K%s\n", mousename(button,event), name ); } break; case macro: printf(" %s = Macro: ", mousename(button,event) ); shostrdef(mousemap[button][event].macro.string); printf("\n"); break; } } #endif /* OS2MOUSE */ #ifndef NOLOCAL VOID shotrm() { char *s; extern char * getiact(); extern int tt_print, adl_err; #ifndef NOTRIGGER extern char * tt_trigger[]; #endif /* NOTRIGGER */ #ifdef CKTIDLE extern char * tt_idlesnd_str; extern int tt_idlesnd_tmo; extern int tt_idlelimit, tt_idleact; #endif /* CKTIDLE */ #ifdef OS2 extern int wy_autopage, autoscroll, sgrcolors, colorreset, user_erasemode, decscnm, decscnm_usr, tt_diff_upd, tt_senddata, wy_blockend, marginbell, marginbellcol, tt_modechg, dgunix; int lines = 0; #ifdef KUI extern CKFLOAT tt_linespacing[]; extern tt_cursor_blink; #endif /* KUI */ #ifdef PCFONTS int i; char *font; if (IsOS2FullScreen()) { /* Determine the font name */ if (!os2LoadPCFonts()) { for (i = 0; i < ntermfont; i++) { if (tt_font == term_font[i].kwval) { font = term_font[i].kwd; break; } } } else { font = "(DLL not available)"; } } else { font = "(full screen only)"; } #endif /* PCFONTS */ #ifdef KUI char font[64] = "(unknown)"; if ( ntermfont > 0 ) { int i; for (i = 0; i < ntermfont; i++) { if (tt_font == term_font[i].kwval) { ckstrncpy(font,term_font[i].kwd,59); ckstrncat(font," ",64); ckstrncat(font,ckitoa(tt_font_size/2),64); if ( tt_font_size % 2 ) ckstrncat(font,".5",64); break; } } } #endif /* KUI */ printf("Terminal parameters:\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %1d%-12s %13s: %1d%-14s\n", "Bytesize: Command", (cmdmsk == 0377) ? 8 : 7, " bits","Terminal", (cmask == 0377) ? 8 : 7," bits"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s","Type", (tt_type >= 0 && tt_type <= max_tt) ? tt_info[tt_type].x_name : "unknown" ); if (tt_type >= 0 && tt_type <= max_tt) if (strlen(tt_info[tt_type].x_id)) printf(" %13s: <ESC>%s","ID",tt_info[tt_type].x_id); printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Echo", duplex ? "local" : "remote","Locking-shift",showoff(sosi)); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Newline-mode", showoff(tnlm), "Cr-display",tt_crd ? "crlf" : "normal"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Cursor", #ifdef KUI (tt_cursor == 2) ? (tt_cursor_blink ? "full (*)" : "full (.)") : (tt_cursor == 1) ? (tt_cursor_blink ? "half (*)" : "half (.)") : (tt_cursor_blink ? "underline (*)" : "underline (.)"), #else /* KUI */ (tt_cursor == 2) ? "full" : (tt_cursor == 1) ? "half" : "underline", #endif /* KUI */ #ifdef CK_AUTODL "autodownload",autodl == TAD_ON ? (adl_err ? "on, error stop" : "on, error continue") : autodl == TAD_ASK ? (adl_err ? "ask, error stop" : "ask, error continue") : "off" #else /* CK_AUTODL */ "", "" #endif /* CK_AUTODL */ ); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Arrow-keys", tt_arrow ? "application" : "cursor", "Keypad-mode", tt_keypad ? "application" : "numeric" ); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Just to make sure we are using current info */ updanswerbk(); /* This line doesn't end with '\n' because the answerback string is terminated with a newline */ printf(" %19s: %-13s %13s: %-15s","Answerback", showoff(tt_answer),"response",answerback); switch (tt_bell) { case XYB_NONE: s = "none"; break; case XYB_VIS: s= "visible"; break; case XYB_AUD | XYB_BEEP: s="beep"; break; case XYB_AUD | XYB_SYS: s="system sounds"; break; default: s="(unknown)"; } printf(" %19s: %-13s %13s: %-15s\n","Bell",s, "Wrap",showoff(tt_wrap)); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Autopage",showoff(wy_autopage), "Autoscroll",showoff(autoscroll)); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","SGR Colors",showoff(sgrcolors), "ESC[0m color",colorreset?"default-color":"current-color"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n", "Erase color",user_erasemode?"default-color":"current-color", "Screen mode",decscnm?"reverse":"normal"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13d %13s: %-15d\n","Transmit-timeout",tt_ctstmo, "Output-pacing",tt_pacing); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13d %13s: %s\n","Idle-timeout",tt_idlelimit, "Idle-action", getiact()); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Send data", showoff(tt_senddata),"End of Block", wy_blockend?"crlf/etx":"us/cr"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #ifndef NOTRIGGER printf(" %19s: %-13s %13s: %d seconds\n","Auto-exit trigger", tt_trigger[0],"Output pacing",tt_pacing ); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #endif /* NOTRIGGER */ printf(" %19s: %-13s %13s: %-15d\n","Margin bell", showoff(marginbell),"at column", marginbellcol); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } switch (tt_modechg) { case TVC_DIS: s = "disabled"; break; case TVC_ENA: s = "enabled"; break; case TVC_W95: s = "win95-restricted"; break; default: s = "(unknown)"; } printf(" %19s: %-13s %13s: %-15s\n","DG Unix mode", showoff(dgunix),"Video change", s); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #ifdef CK_APC if (apcstatus == APC_ON) s = "on"; else if (apcstatus == APC_OFF) s = "off"; else if (apcstatus == APC_ON|APC_UNCH) s = "unchecked"; else if (apcstatus == APC_ON|APC_NOINP) s = "no-input"; else if (apcstatus == APC_ON|APC_UNCH|APC_NOINP) s = "unchecked-no-input"; printf(" %19s: %-13s %13s: %-15s\n", "APC", s, #ifdef PCFONTS "Font (VGA)",font #else /* PCFONTS */ #ifdef KUI "Font",font #else "Font","(not supported)" #endif /* KUI */ #endif /* PCFONTS */ ); #endif /* CK_APC */ if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #ifdef CK_TTGWSIZ /* Console terminal screen size */ if (tt_cols[VTERM] < 0 || tt_rows[VTERM] < 0) ttgwsiz(); /* Try to get latest size */ #endif /* CK_TTGWSIZ */ printf(" %19s: %-13d %13s: %-15d\n","Height",tt_rows[VTERM], "Width",tt_cols[VTERM]); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #ifdef KUI printf(" %19s: %-12f %14s: %-15d\n","Line spacing",tt_linespacing[VTERM], "Display Height",VscrnGetDisplayHeight(VTERM)); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #endif /* KUI */ printf(" %19s: %-13s %13s: %d lines\n","Roll-mode", tt_roll[VTERM]?"insert":"overwrite","Scrollback", tt_scrsize[VTERM]); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } if (updmode == tt_updmode) if (updmode == TTU_FAST) s = "fast (fast)"; else s = "smooth (smooth)"; else if (updmode == TTU_FAST) s = "fast (smooth)"; else s = "smooth (fast)"; printf(" %19s: %-13s %13s: %d ms\n","Screen-update: mode",s, "interval",tt_update); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n", "Screen-optimization",showoff(tt_diff_upd), "Status line",showoff(tt_status[VTERM])); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" %19s: %-13s %13s: %-15s\n","Debug", showoff(debses),"Session log", seslog? sesfil : "(none)" ); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Display colors (should become SHOW COLORS) */ { USHORT row, col; char * colors[16] = { "black","blue","green","cyan","red","magenta","brown","lgray", "dgray","lblue","lgreen","lcyan","lred","lmagent","yellow","white" }; printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" Color:"); #ifndef ONETERMUPD GetCurPos(&row, &col); WrtCharStrAtt("border", 6, row, 9, &colorborder ); WrtCharStrAtt("debug", 5, row, 17, &colordebug ); WrtCharStrAtt("helptext", 8, row, 25, &colorhelp ); WrtCharStrAtt("reverse", 7, row, 34, &colorreverse ); WrtCharStrAtt("select", 6, row, 42, &colorselect ); WrtCharStrAtt("status", 6, row, 50, &colorstatus ); WrtCharStrAtt("terminal", 8, row, 58, &colornormal ); WrtCharStrAtt("underline", 9, row, 67, &colorunderline ); #endif /* ONETERMUPD */ row = VscrnGetCurPos(VCMD)->y+1; VscrnWrtCharStrAtt(VCMD, "border", 6, row, 9, &colorborder ); VscrnWrtCharStrAtt(VCMD, "debug", 5, row, 17, &colordebug ); VscrnWrtCharStrAtt(VCMD, "helptext", 8, row, 25, &colorhelp ); VscrnWrtCharStrAtt(VCMD, "reverse", 7, row, 34, &colorreverse ); VscrnWrtCharStrAtt(VCMD, "select", 6, row, 42, &colorselect ); VscrnWrtCharStrAtt(VCMD, "status", 6, row, 50, &colorstatus ); VscrnWrtCharStrAtt(VCMD, "terminal", 8, row, 58, &colornormal ); VscrnWrtCharStrAtt(VCMD, "underline", 9, row, 67, &colorunderline ); printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Foreground color names */ printf("%6s: %-8s%-8s%-9s%-8s%-8s%-8s%-9s%-9s\n","fore", "", colors[colordebug&0x0F], colors[colorhelp&0x0F], colors[colorreverse&0x0F], colors[colorselect&0x0F], colors[colorstatus&0x0F], colors[colornormal&0x0F], colors[colorunderline&0x0F]); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Background color names */ printf("%6s: %-8s%-8s%-9s%-8s%-8s%-8s%-9s%-9s\n","back", colors[colorborder], colors[colordebug>>4], colors[colorhelp>>4], colors[colorreverse>>4], colors[colorselect>>4], colors[colorstatus>>4], colors[colornormal>>4], colors[colorunderline>>4] ); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" Color:"); #ifndef ONETERMUPD GetCurPos(&row, &col); WrtCharStrAtt("graphic", 7, row, 9, &colorgraphic ); WrtCharStrAtt("command", 7, row, 17, &colorcmd ); WrtCharStrAtt("italic", 6, row, 26, &coloritalic ); #endif /* ONETERMUPD */ row = VscrnGetCurPos(VCMD)->y+1; VscrnWrtCharStrAtt(VCMD, "graphic", 7, row, 9, &colorgraphic ); VscrnWrtCharStrAtt(VCMD, "command", 7, row, 17, &colorcmd ); VscrnWrtCharStrAtt(VCMD, "italic", 6, row, 26, &coloritalic ); printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Foreground color names */ printf("%6s: %-8s%-8s%-8s\n","fore", colors[colorgraphic&0x0F], colors[colorcmd&0x0F], colors[coloritalic&0x0F]); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } /* Background color names */ printf("%6s: %-8s%-8s%-8s\n","back", colors[colorgraphic>>4], colors[colorcmd>>4], colors[coloritalic>>4]); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } } printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } { extern int trueblink, truedim, truereverse, trueunderline, trueitalic; printf( " Attribute: \ blink: %-3s dim: %-3s italic: %-3s reverse: %-3s underline: %-3s\n", trueblink?"on":"off", truedim?"on":"off", trueitalic?"on":"off", truereverse?"on":"off", trueunderline?"on":"off"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } } { extern vtattrib WPattrib; printf(" ASCII Protected chars: %s%s%s%s%s%s%s\n", WPattrib.blinking?"blink ":"", WPattrib.italic?"italic ":"", WPattrib.reversed?"reverse ":"", WPattrib.underlined?"underline ":"", WPattrib.bold?"bold ":"", WPattrib.dim?"dim ":"", WPattrib.invisible?"invisible ":""); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } } printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } (VOID) shoesc(escape); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } printf(" See SHOW CHARACTER-SETS for character-set info\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return; else lines = 0; } #else /* OS2 */ /* Beginning of new non-OS2 version */ printf("\n"); printf("Terminal parameters:\n"); printf(" %19s: %1d%-12s %13s: %1d%-14s\n", "Bytesize: Command", (cmdmsk == 0377) ? 8 : 7, " bits","Terminal", (cmask == 0377) ? 8 : 7," bits"); s = getenv("TERM"); #ifdef XPRINT printf(" %19s: %-13s %13s: %-15s\n", "Type", s ? s : "(unknown)", "Print", showoff(tt_print) ); #else printf(" %19s: %-13s\n","Type", s ? s : "(unknown)"); #endif /* XPRINT */ printf(" %19s: %-13s %13s: %-15s\n","Echo", duplex ? "local" : "remote","Locking-shift",showoff(sosi)); printf(" %19s: %-13s %13s: %-15s\n","Newline-mode", showoff(tnlm),"Cr-display",tt_crd ? "crlf" : "normal"); #ifdef CK_APC if (apcstatus == APC_ON) s = "on"; else if (apcstatus == APC_OFF) s = "off"; else if (apcstatus == (APC_ON|APC_UNCH)) s = "unchecked"; else if (apcstatus == (APC_ON|APC_NOINP)) s = "no-input"; else if (apcstatus == (APC_ON|APC_UNCH|APC_NOINP)) s = "unchecked-no-input"; printf(" %19s: %-13s %13s: %-15s\n", "APC", s, #ifdef CK_AUTODL "Autodownload", autodl ? (adl_err ? "on, error stop" : "on, error continue") : "off" #else "","" #endif /* CK_AUTODL */ ); #endif /* CK_APC */ #ifdef CK_TTGWSIZ /* Console terminal screen size */ ttgwsiz(); /* Try to get latest size */ printf(" %19s: %-13d %13s: %-15d\n","Height",tt_rows, "Width", tt_cols); #endif /* CK_TTGWSIZ */ printf(" %19s: %-13s %13s: %-15s\n","Debug", showoff(debses),"Session log", seslog? sesfil : "(none)" ); #ifdef CKTIDLE printf(" %19s: %-13d %13s: %s\n","Idle-timeout",tt_idlelimit, "Idle-action", getiact()); #endif /* CKTIDLE */ printf(" %19s: %-13s ","Lf-display", tt_lfd ? "crlf" : "normal"); #ifdef UNIX #ifndef NOJC printf("%13s: %-15s","Suspend", showoff(xsuspend)); #endif /* NOJC */ #endif /* UNIX */ printf("\n"); #ifndef NOTRIGGER printf(" %19s: %-13s\n","Trigger", tt_trigger[0] ? tt_trigger[0] : "(none)"); #endif /* NOTRIGGER */ printf("\n"); (VOID) shoesc(escape); #ifndef NOCSETS shotcs(tcsl,tcsr); /* Show terminal character sets */ #endif /* NOCSETS */ #endif /* OS2 */ } VOID shmdmlin() { /* Briefly show modem & line */ #ifndef NODIAL #ifndef MINIDIAL #ifdef OLDTBCODE extern int tbmodel; _PROTOTYP( char * gtbmodel, (void) ); #endif /* OLDTBCODE */ #endif /* MINIDIAL */ #endif /* NODIAL */ if (local) #ifdef OS2 printf(" Port: %s, Modem type: ",ttname); #else printf(" Line: %s, Modem type: ",ttname); #endif /* OS2 */ else printf( #ifdef OS2 " Communication device not yet selected with SET PORT\n Modem type: " #else " Communication device not yet selected with SET LINE\n Modem type: " #endif /* OS2 */ ); #ifndef NODIAL printf("%s",gmdmtyp()); #ifndef MINIDIAL #ifdef OLDTBCODE if (tbmodel) printf(" (%s)",gtbmodel()); /* Telebit model info */ #endif /* OLDTBCODE */ #endif /* MINIDIAL */ #else printf("(disabled)"); #endif /* NODIAL */ } #ifdef CK_TAPI void shotapi(int option) { int rc=0,k ; char *s=NULL; LPDEVCFG lpDevCfg = NULL; LPCOMMCONFIG lpCommConfig = NULL; LPMODEMSETTINGS lpModemSettings = NULL; DCB * lpDCB = NULL; extern struct keytab * tapiloctab; /* Microsoft TAPI Locations */ extern int ntapiloc; extern struct keytab * tapilinetab; /* Microsoft TAPI Line Devices */ extern int ntapiline; extern int tttapi; /* TAPI in use */ extern int tapipass; /* TAPI Passthrough mode */ extern int tapiconv; /* TAPI Conversion mode */ extern int tapilights; extern int tapipreterm; extern int tapipostterm; extern int tapimanual; extern int tapiinactivity; extern int tapibong; extern int tapiusecfg; extern char tapiloc[]; extern int tapilocid; extern int TAPIAvail; if (!TAPIAvail) { printf("TAPI Support not enabled\r\n"); return; } switch (option) { case 0: printf("TAPI Settings:\n"); printf(" Line: %s\n", tttapi ? ttname : "(none in use)"); cktapiBuildLocationTable(&tapiloctab, &ntapiloc); if (tapilocid == -1) tapilocid = cktapiGetCurrentLocationID(); /* Find the current tapiloc entry */ /* and use it as the default. */ for (k = 0; k < ntapiloc; k++) { if (tapiloctab[k].kwval == tapilocid) break; } if (k >= 0 && k < ntapiloc) s = tapiloctab[k].kwd; else s = "(unknown)"; printf(" Location: %s\n",s); printf(" Modem-dialing: %s\n",tapipass?"off":"on"); printf(" Phone-number-conversions: %s\n", tapiconv==CK_ON?"on":tapiconv==CK_AUTO?"auto":"off"); printf(" Modem-lights: %s %s\n",tapilights?"on ":"off", tapipass?"(n/a)":""); printf(" Predial-terminal: %s %s\n",tapipreterm?"on ":"off", tapipass?"(n/a)":""); printf(" Postdial-terminal: %s %s\n",tapipostterm?"on ":"off", tapipass?"(n/a)":""); printf(" Manual-dial: %s %s\n",tapimanual?"on ":"off", tapipass?"(n/a)":""); printf(" Inactivity-timeout: %d seconds %s\n",tapiinactivity, tapipass?"(n/a)":""); printf(" Wait-for-bong: %d seconds %s\n",tapibong, tapipass?"(n/a)":""); printf(" Use-windows-configuration: %s %s\n", tapiusecfg?"on ":"off", tapipass?"(n/a)":""); printf("\n"); #ifdef BETATEST if (tapipass) { printf("K-95 uses the TAPI Line in an exclusive mode. Other applications\n"); printf("may open the device but may not place calls nor answer calls.\n"); printf("Dialing is performed using the K-95 dialing procedures. SET MODEM\n"); printf("TYPE TAPI after the SET TAPI LINE command to activate the modem\n"); printf("definition associated with the active TAPI LINE device.\n\n"); } else { printf("K-95 uses the TAPI Line in a cooperative mode. Other applications\n"); printf("may open the device, place and answer calls. Dialing is performed\n"); printf("by TAPI. K-95 SET MODEM commands are not used.\n\n"); } if (tapiconv == CK_ON || tapiconv == CK_AUTO && !tapipass) { printf( "Phone numbers are converted from canonical to dialable form by TAPI\n"); printf("using the dialing rules specified in the TAPI Dialing Properties\n"); printf("dialog.\n\n"); } else { printf( "Phone numbers are converted from canonical to dialable form by K-95\n"); printf( "using the dialing rules specified with the SET DIAL commands. TAPI\n"); printf( "Dialing Properties are imported automaticly upon startup and whenever\n"); printf("the TAPI Dialing Properties are altered or when the TAPI Location\n"); printf("is changed.\n\n"); } #endif /* BETATEST */ if (tapipass) { printf("Type SHOW MODEM to see MODEM configuration.\n"); if (tapiconv == CK_ON) printf("Type SHOW DIAL to see DIAL-related items.\n"); } else { if (tapiconv == CK_ON || tapiconv == CK_AUTO) printf("Type SHOW DIAL to see DIAL-related items.\n"); } break; case 1: cktapiDisplayTapiLocationInfo(); break; case 2: rc = cktapiGetModemSettings(&lpDevCfg,&lpModemSettings, &lpCommConfig,&lpDCB); if (rc) { cktapiDisplayModemSettings(lpDevCfg,lpModemSettings, lpCommConfig,lpDCB); } else { printf("?Unable to retrieve Modem Settings\n"); } break; case 3: { HANDLE hModem = GetModemHandleFromLine((HLINE)0); if (hModem) DisplayCommProperties(hModem); else printf("?Unable to retrieve a valid Modem Handle\n"); CloseHandle(hModem); break; } } printf("\n"); } #endif /* CK_TAPI */ #endif /* NOLOCAL */ #ifdef PATTERNS static VOID shopat() { extern char * binpatterns[], * txtpatterns[]; extern int patterns, filepeek; char **p, *s; int i, j, k, n, flag, width; #ifdef CK_TTGWSIZ ttgwsiz(); /* Try to get latest size */ #ifdef OS2 width = tt_cols[VCMD]; #else /* OS2 */ width = tt_cols; #endif /* OS2 */ if (width < 1) #endif /* CK_TTGWSIZ */ width = 80; printf("\n"); printf(" Set file type: %s\n",gfmode(binary,1)); printf(" Set file patterns: %s", showooa(patterns)); #ifdef CK_LABELED if (binary == XYFT_L) printf(" (but SET FILE TYPE LABELED overrides)\n"); else #endif /* CK_LABELED */ #ifdef VMS if (binary == XYFT_I) printf(" (but SET FILE TYPE IMAGE overrides)\n"); else #endif /* VMS */ if (filepeek) printf(" (but SET FILE SCAN ON overrides)\n"); else printf("\n"); printf(" Maximum patterns allowed: %d\n", FTPATTERNS); for (k = 0; k < 2; k++) { /* For each kind of patter */ printf("\n"); if (k == 0) { /* binary... */ printf(" File binary-patterns: "); p = binpatterns; } else { /* text... */ printf(" File text-patterns: "); p = txtpatterns; } if (!p[0]) { printf("(none)\n"); } else { printf("\n "); n = 2; for (i = 0; i < FTPATTERNS; i++) { /* For each pattern */ if (!p[i]) /* Done */ break; s = p[i]; /* Look for embedded space */ for (j = 0, flag = 1; *s; s++, j++) /* and also get length */ if (*s == SP) flag = 3; n += j + flag; /* Length of this line */ if (n >= width - 1) { printf("\n "); n = j+2; } printf(flag == 3 ? " {%s}" : " %s", p[i]); } if (n > 2) printf("\n"); } } printf("\n"); } #endif /* PATTERNS */ #ifndef NOSPL static VOID shooutput() { printf(" Output pacing: %d (milliseconds)\n",pacing); printf(" Output special-escapes: %s\n", showoff(outesc)); } static VOID shoinput() { #ifdef CKFLOAT extern char * inpscale; #endif /* CKFLOAT */ #ifdef CK_AUTODL printf(" Input autodownload: %s\n", showoff(inautodl)); #endif /* CK_AUTODL */ printf(" Input cancellation: %s\n", showoff(inintr)); printf(" Input case: %s\n", inpcas[cmdlvl] ? "observe" : "ignore"); printf(" Input buffer-length: %d\n", inbufsize); printf(" Input echo: %s\n", showoff(inecho)); printf(" Input silence: %d (seconds)\n", insilence); #ifdef OS2 printf(" Input terminal: %s\n", showoff(interm)); #endif /* OS2 */ printf(" Input timeout: %s\n", intime[cmdlvl] ? "quit" : "proceed"); #ifdef CKFLOAT printf(" Input scale-factor: %s\n", inpscale ? inpscale : "1.0"); #endif /* CKFLOAT */ if (instatus < 0) printf(" Last INPUT: -1 (INPUT command not yet given)\n"); else printf(" Last INPUT: %d (%s)\n", instatus,i_text[instatus]); } #endif /* NOSPL */ #ifndef NOSPL int showarray() { #ifdef COMMENT char * p, * q, ** ap; int i; #endif /* COMMENT */ char *s; int x = 0, y; int range[2]; if ((y = cmfld("Array name","",&s,NULL)) < 0) if (y != -3) return(y); ckstrncpy(line,s,LINBUFSIZ); s = line; if ((y = cmcfm()) < 0) return(y); if (*s) { char ** ap; if ((x = arraybounds(s,&(range[0]),&(range[1]))) < 0) { printf("?Bad array: %s\n",s); return(-9); } ap = a_ptr[x]; if (!ap) { printf("Array not declared: %s\n", s); return(success = 1); } else { int i, n, max; max = (range[1] > 0) ? range[1] : ((range[0] > 0) ? range[0] : a_dim[x]); if (range[0] < 0) range[0] = 0; if (max > a_dim[x]) max = a_dim[x]; n = 1; printf("\\&%c[]: Dimension = %d",arrayitoa(x),a_dim[x]); if (a_link[x] > -1) printf(" (Link to \\&%c[])",arrayitoa(a_link[x])); printf("\n"); for (i = range[0]; i <= max; i++) { if (ap[i]) { printf("%3d. %s\n",i,ap[i]); if (xaskmore) { if (cmd_cols > 0) { x = strlen(ap[i]) + 5; y = (x % cmd_cols) ? 1 : 0; n += (x / cmd_cols) + y; } else { n++; } if (n > (cmd_rows - 3)) { if (!askmore()) break; else n = 0; } } } } } return(1); } /* All arrays - just show name and dimension */ for (y = 0; y < (int) 'z' - ARRAYBASE + 1; y++) { if (a_ptr[y]) { if (x == 0) printf("Declared arrays:\n"); x = 1; printf(" \\&%c[%d]", (y == 1) ? 64 : y + ARRAYBASE, a_dim[y]); if (a_link[y] > -1) printf(" => \\&%c[]",arrayitoa(a_link[y])); printf("\n"); } if (!x) printf(" No arrays declared\n"); } return(1); } #endif /* NOSPL */ int doshow(x) int x; { int y, z, i; long zz; extern int optlines; char *s; #ifdef OS2 extern int os2gks; extern int tt_kb_mode; #endif /* OS2 */ extern int srvcdmsg; extern char * cdmsgstr, * ckcdpath; char fnbuf[100]; #ifndef NOSETKEY if (x == SHKEY) { /* SHOW KEY */ int c; #ifdef OS2 if ((x = cmkey(shokeytab,nshokey,"How many keys should be shown?", "one",xxstring)) < 0) return(x); switch (tt_kb_mode) { case KBM_EM: s = "emacs"; break; case KBM_HE: s = "hebrew"; break; case KBM_RU: s = "russian"; break; case KBM_EN: default: s = "default"; break; } if ((z = cmkey(shokeymtab,nshokeym,"Which definition should be shown?", s,xxstring)) < 0) return(z); if (z == SHKEYDEF) z = -1; #endif /* OS2 */ if ((y = cmcfm()) < 0) return(y); #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ #ifdef MAC printf("Not implemented\n"); return(0); #else /* Not MAC */ #ifdef OS2 if (x) { con_event evt; for (c = 0; c < KMSIZE; c++) { evt = (z < 0) ? mapkey(c) : maptermkey(c,z); if (evt.type != error) { shokeycode(c,z); } } } else { #endif /* OS2 */ printf(" Press key: "); #ifdef UNIX #ifdef NOSETBUF fflush(stdout); #endif /* NOSETBUF */ #endif /* UNIX */ conbin((char)escape); /* Put terminal in binary mode */ #ifdef OS2 os2gks = 0; /* Raw scancode processing */ #endif /* OS2 */ c = congks(0); /* Get character or scan code */ #ifdef OS2 os2gks = 1; /* Cooked scancode processing */ #endif /* OS2 */ concb((char)escape); /* Restore terminal to cbreak mode */ if (c < 0) { /* Check for error */ printf("?Error reading key\n"); return(0); } #ifndef OS2 /* Do NOT mask when it can be a raw scan code, perhaps > 255 */ c &= cmdmsk; /* Apply command mask */ #endif /* OS2 */ printf("\n"); #ifdef OS2 shokeycode(c,z); #else /* OS2 */ shokeycode(c); #endif /* OS2 */ #ifdef OS2 } #endif /* OS2 */ return(1); #endif /* MAC */ } #ifndef NOKVERBS if (x == SHKVB) { /* SHOW KVERBS */ if ((y = cmcfm()) < 0) return(y); #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ printf("\nThe following %d keyboard verbs are available:\n\n",nkverbs); kwdhelp(kverbs,nkverbs,"","\\K","",3,0); printf("\n"); return(1); } #ifdef OS2 if (x == SHUDK) { /* SHOW UDKs */ extern void showudk(void); if ((y = cmcfm()) < 0) return(y); #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ showudk(); return(1); } #endif /* OS2 */ #endif /* NOKVERBS */ #endif /* NOSETKEY */ #ifndef NOSPL if (x == SHMAC) { /* SHOW MACRO */ struct FDB kw, fl, cm; int i, k, n = 0, left, flag, confirmed = 0; char * p, *q[64]; for (i = 0; i < nmac; i++) { /* copy the macro table */ mackey[i].kwd = mactab[i].kwd; /* into a regular keyword table */ mackey[i].kwval = i; /* with value = pointer to macro tbl */ mackey[i].flgs = mactab[i].flgs; } p = line; left = LINBUFSIZ; while (!confirmed && n < 64) { cmfdbi(&kw, /* First FDB - macro table */ _CMKEY, /* fcode */ "Macro name", /* hlpmsg */ "", /* default */ "", /* addtl string data */ nmac, /* addtl numeric data 1: tbl size */ 0, /* addtl numeric data 2: 4 = cmswi */ xxstring, /* Processing function */ mackey, /* Keyword table */ &fl /* Pointer to next FDB */ ); cmfdbi(&fl, /* 2nd FDB - something not in mactab */ _CMFLD, /* fcode */ "", /* hlpmsg */ "", /* default */ "", /* addtl string data */ 0, /* addtl numeric data 1 */ 0, /* addtl numeric data 2 */ xxstring, NULL, &cm ); cmfdbi(&cm, /* 3rd FDB - Confirmation */ _CMCFM, /* fcode */ "", /* hlpmsg */ "", /* default */ "", /* addtl string data */ 0, /* addtl numeric data 1 */ 0, /* addtl numeric data 2 */ NULL, NULL, NULL ); x = cmfdb(&kw); /* Parse something */ if (x < 0) return(x); s = atmbuf; /* What the user typed */ switch (cmresult.fcode) { case _CMKEY: /* If it was a keyword */ y = mlook(mactab,atmbuf,nmac); /* get full name */ if (y > -1) s = mactab[y].kwd; /* (fall thru on purpose...) */ case _CMFLD: k = ckstrncpy(p,s,left) + 1; /* Copy result to list */ left -= k; if (left <= 0) { *p = NUL; break; } q[n++] = p; /* Point to this item */ p += k; /* Move buffer pointer past it */ break; case _CMCFM: /* End of command */ confirmed++; default: break; } } if (n == 0) { printf("Macros:\n"); slc = 1; for (y = 0; y < nmac; y++) if (shomac(mactab[y].kwd,mactab[y].mval) < 0) break; return(1); } slc = 0; for (i = 0; i < n; i++) { flag = 0; s = q[i]; if (!s) s = ""; if (!*s) continue; if (iswild(s)) { /* Pattern match */ for (k = 0, x = 0; x < nmac; x++) { if (ckmatch(s,mactab[x].kwd,0,1)) { shomac(mactab[x].kwd,mactab[x].mval); k++; } } if (!k) x = -1; else continue; } else { /* Exact match */ x = mxlook(mactab,s,nmac); flag = 1; } if (flag && x == -1) x = mlook(mactab,s,nmac); switch (x) { case -3: /* Nothing to look up */ case -1: /* Not found */ printf("%s - (not defined)\n",s); break; case -2: /* Ambiguous, matches more than one */ printf("%s - ambiguous\n",s); break; default: /* Matches one exactly */ shomac(mactab[x].kwd,mactab[x].mval); break; } } return(1); } #endif /* NOSPL */ /* Other SHOW commands only have two fields. Get command confirmation here, then handle with big switch() statement. */ #ifndef NOSPL if (x != SHBUI && x != SHARR) #endif /* NOSPL */ if (x == SHFUN) { /* For SHOW FUNCTIONS */ int y; if ((y = cmtxt("Match string for function names","",&s,NULL)) < 0) return(y); fnbuf[0] = NUL; if (!s) s = ""; if (*s) ckstrncpy(fnbuf,s,100); } else { if ((y = cmcfm()) < 0) return(y); } #ifdef COMMENT /* This restriction is too general. */ #ifdef IKSD if (inserver && #ifdef CK_LOGIN isguest #else 0 #endif /* CK_LOGIN */ ) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ #endif /* COMMENT */ switch (x) { #ifdef ANYX25 #ifndef IBMX25 case SHPAD: shopad(0); break; #endif /* IBMX25 */ #endif /* ANYX25 */ case SHNET: #ifdef NOLOCAL printf(" No network support in this version of C-Kermit.\n"); #else #ifndef NETCONN printf(" No network support in this version of C-Kermit.\n"); #else shonet(); #endif /* NETCONN */ #endif /* NOLOCAL */ break; case SHPAR: shopar(); break; #ifndef NOXFER case SHATT: shoatt(); break; #endif /* NOXFER */ #ifndef NOSPL case SHCOU: printf(" %d\n",count[cmdlvl]); break; #endif /* NOSPL */ #ifndef NOSERVER case SHSER: /* Show Server */ i = 0; #ifndef NOFRILLS printf("Function: Status:\n"); i++; printf(" GET %s\n",nm[en_get]); i++; printf(" SEND %s\n",nm[en_sen]); i++; printf(" MAIL %s\n",nm[inserver ? 0 : en_mai]); i++; printf(" PRINT %s\n",nm[inserver ? 0 : en_pri]); i++; #ifndef NOSPL printf(" REMOTE ASSIGN %s\n",nm[en_asg]); i++; #endif /* NOSPL */ printf(" REMOTE CD/CWD %s\n",nm[en_cwd]); i++; #ifdef ZCOPY printf(" REMOTE COPY %s\n",nm[en_cpy]); i++; #endif /* ZCOPY */ printf(" REMOTE DELETE %s\n",nm[en_del]); printf(" REMOTE DIRECTORY %s\n",nm[en_dir]); printf(" REMOTE HOST %s\n",nm[inserver ? 0 : en_hos]); i += 3; #ifndef NOSPL printf(" REMOTE QUERY %s\n",nm[en_que]); i++; #endif /* NOSPL */ printf(" REMOTE MKDIR %s\n",nm[en_mkd]); printf(" REMOTE RMDIR %s\n",nm[en_rmd]); printf(" REMOTE RENAME %s\n",nm[en_ren]); printf(" REMOTE SET %s\n",nm[en_set]); printf(" REMOTE SPACE %s\n",nm[en_spa]); printf(" REMOTE TYPE %s\n",nm[en_typ]); printf(" REMOTE WHO %s\n",nm[inserver ? 0 : en_who]); printf(" BYE %s\n",nm[en_bye]); printf(" FINISH %s\n",nm[en_fin]); printf(" EXIT %s\n",nm[en_xit]); printf(" ENABLE %s\n",nm[en_ena]); i += 11; #endif /* NOFRILLS */ if (i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server timeout: %d\n",srvtim); if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server idle-timeout: %d\n",srvidl); if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server keepalive %s\n", showoff(srvping)); if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server cd-message %s\n", showoff(srvcdmsg)); if (srvcdmsg && cdmsgstr) printf("Server cd-message %s\n", cdmsgstr); if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server display: %s\n", showoff(srvdis)); if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server login: "); if (!x_user) { printf("(none)\n"); } else { printf("\"%s\", \"%s\", \"%s\"\n", x_user, x_passwd ? x_passwd : "", x_acct ? x_acct : "" ); } if (++i > cmd_rows - 3) { if (!askmore()) return(1); else i = 0; } printf("Server get-path: "); if (ngetpath == 0) { printf(" (none)\n"); } else { printf("\n"); i += 3; for (x = 0; x < ngetpath; x++) { if (getpath[x]) printf(" %d. %s\n", x, getpath[x]); if (++i > (cmd_rows - 3)) { /* More than a screenful... */ if (!askmore()) break; else i = 0; } } } break; #endif /* NOSERVER */ case SHSTA: /* Status of last command */ printf(" %s\n", success ? "SUCCESS" : "FAILURE"); return(0); /* Don't change it */ case SHSTK: { /* Stack for MAC debugging */ #ifdef MAC long sp; sp = -1; loadA0 ((char *)&sp); /* set destination address */ SPtoaA0(); /* move SP to destination */ printf("Stack at 0x%x\n", sp); show_queue(); /* more debugging */ break; #else shostack(); #endif /* MAC */ break; } #ifndef NOLOCAL #ifdef OS2 case SHTAB: /* SHOW TABS */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotabs(); break; #endif /* OS2 */ case SHTER: /* SHOW TERMINAL */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotrm(); break; #ifdef OS2 case SHVSCRN: /* SHOW Virtual Screen - for debug */ shovscrn(); break; #endif /* OS2 */ #endif /* NOLOCAL */ #ifdef OS2MOUSE case SHMOU: /* SHOW MOUSE */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shomou(); break; #endif /* OS2MOUSE */ #ifndef NOFRILLS case SHVER: shover(); break; #endif /* NOFRILLS */ #ifndef NOSPL case SHBUI: /* Built-in variables */ line[0] = NUL; if ((y = cmtxt("Variable name or pattern","",&s,xxstring)) < 0) return(y); ckstrncpy(line,s,LINBUFSIZ); /* if (line[0]) ckstrncat(line,"*",LINBUFSIZ); */ case SHFUN: /* or built-in functions */ #ifdef CK_TTGWSIZ #ifdef OS2 if (tt_cols[VTERM] < 0 || tt_rows[VTERM] < 0) ttgwsiz(); #else /* OS2 */ if (ttgwsiz() > 0) { /* Get current screen size */ if (tt_rows > 0 && tt_cols > 0) { cmd_rows = tt_rows; cmd_cols = tt_cols; } } #endif /* OS2 */ #endif /* CK_TTGWSIZ */ if (x == SHFUN) { /* Functions */ printf("\nThe following functions are available:\n\n"); kwdhelp(fnctab,nfuncs,(char *)fnbuf,"\\F","()",3,8); printf("\n"); #ifndef NOHELP printf( "HELP FUNCTION <name> gives the calling conventions of the given function.\n\n" ); #endif /* NOHELP */ break; } else { /* Variables */ int j, flag = 0, havearg = 0; struct stringarray * q = NULL; char ** pp; if (line[0]) { /* Have something to search for */ havearg = 1; /* Maybe a list of things */ q = cksplit(1,0,line,NULL,"_-^$*?[]{}",0,0,0,0); if (!q) break; pp = q->a_head; } i = 0; for (y = 0; y < nvars; y++) { if ((vartab[y].flgs & CM_INV)) continue; if (havearg) { /* If I have something to match */ char * s2; for (flag = 0, j = 1; j <= q->a_size && !flag; j++) { s2 = pp[j] ? pp[j] : ""; #ifdef COMMENT /* This is not needed because it's what the 4 arg does in ckmatch() */ len = strlen(s2); if (len > 0) { if (s2[len-1] != '$') {/* To allow anchors */ ckmakmsg(line,LINBUFSIZ,pp[j],"*",NULL,NULL); s2 = line; } } #endif /* COMMENT */ if (ckmatch(s2,vartab[y].kwd,0,4) > 0) { flag = 1; /* Matches */ break; } } if (!flag) /* Doesn't match */ continue; } s = nvlook(vartab[y].kwd); printf(" \\v(%s) = ",vartab[y].kwd); if (vartab[y].kwval == VN_NEWL) { /* \v(newline) */ while (*s) /* Show control chars symbolically */ printf("\\{%d}",*s++); printf("\n"); } else if (vartab[y].kwval == VN_IBUF || /* \v(input) */ vartab[y].kwval == VN_QUE || /* \v(query) */ #ifdef OS2 vartab[y].kwval == VN_SELCT || /* \v(select) */ #endif /* OS2 */ (vartab[y].kwval >= VN_M_AAA && /* modem ones */ vartab[y].kwval <= VN_M_ZZZ) ) { int r = 12; /* This one can wrap around */ char buf[10]; while (*s) { if (isprint(*s)) { buf[0] = *s; buf[1] = NUL; r++; } else { sprintf(buf,"\\{%d}",*s); /* SAFE */ r += (int) strlen(buf); } if (r >= cmd_cols - 1) { printf("\n"); r = 0; i++; } printf("%s",buf); s++; } printf("\n"); } else printf("%s\n",s); if (++i > (cmd_rows - 3)) { /* More than a screenful... */ if ((y >= nvars - 1) || !askmore()) break; else i = 0; } } } break; case SHVAR: /* Global variables */ x = 0; /* Variable count */ slc = 1; /* Screen line count for "more?" */ for (y = 33; y < GVARS; y++) if (g_var[y]) { if (x++ == 0) printf("Global variables:\n"); sprintf(line," \\%%%c",y); /* SAFE */ if (shomac(line,g_var[y]) < 0) break; } if (!x) printf(" No variables defined\n"); break; case SHARG: { /* Args */ char * s, * s1, * s2, * tmpbufp; int t; if (maclvl > -1) { printf("Macro arguments at level %d (\\v(argc) = %d):\n", maclvl, macargc[maclvl] ); for (y = 0; y < macargc[maclvl]; y++) { s1 = m_arg[maclvl][y]; if (!s1) s1 = "(NULL)"; s2 = m_xarg[maclvl][y]; if (!s2) s2 = "(NULL)"; #ifdef COMMENT if (y < 10) printf(" \\%%%d = %s\n",y,s1); else printf(" \\&_[%d] = %s\n",y,s2); #else printf(" \\&_[%d] = %s\n",y,s2); #endif /* COMMENT */ } } else { printf("Top-level arguments (\\v(argc) = %d):\n", topargc); for (y = 0; y < topargc; y++) { s1 = g_var[y + '0']; if (!s1) s1 = "(NULL)"; s2 = toparg[y]; if (!s2) s2 = "(NULL)"; if (y < 10 && g_var[y]) printf(" \\%%%d = %s\n",y,s1); if (toparg[y]) printf(" \\&_[%d] = %s\n",y,s2); } } } break; case SHARR: /* Arrays */ return(showarray()); #endif /* NOSPL */ #ifndef NOXFER case SHPRO: /* Protocol parameters */ shoparp(); printf("\n"); break; #endif /* NOXFER */ #ifndef NOLOCAL case SHCOM: /* Communication parameters */ printf("\n"); shoparc(); #ifdef OS2 { int i; char *s = "(unknown)"; for (i = 0; i < nprty; i++) if (prtytab[i].kwval == priority) { s = prtytab[i].kwd; break; } printf(" Priority: %s\n", s ); } #endif /* OS2 */ printf("\n"); #ifdef NETCONN if (!network #ifdef IKSD && !inserver #endif /* IKSD */ ) { #endif /* NETCONN */ shomdm(); printf("\n"); #ifdef NETCONN } #endif /* NETCONN */ #ifndef NODIAL #ifdef IKSD if ( !inserver ) #endif /* IKSD */ { printf("Type SHOW DIAL to see DIAL-related items.\n"); printf("Type SHOW MODEM to see modem-related items.\n"); #ifdef CK_TAPI printf("Type SHOW TAPI to see TAPI-related items.\n"); #endif /* CK_TAPI */ printf("\n"); } #endif /* NODIAL */ break; #endif /* NOLOCAL */ case SHFIL: /* File parameters */ shofil(); /* printf("\n"); */ /* (out o' space) */ break; #ifndef NOCSETS case SHLNG: /* Languages */ shoparl(); break; #endif /* NOCSETS */ #ifndef NOSPL case SHSCR: /* Scripts */ printf(" Command quoting: %s\n", showoff(cmdgquo())); printf(" Take echo: %s\n", showoff(techo)); printf(" Take error: %s\n", showoff(takerr[cmdlvl])); printf(" Macro echo: %s\n", showoff(mecho)); printf(" Macro error: %s\n", showoff(merror[cmdlvl])); printf(" Quiet: %s\n", showoff(quiet)); printf(" Variable evaluation: %s [\\%%x and \\&x[] variables]\n", vareval ? "recursive" : "simple"); printf(" Function diagnostics: %s\n", showoff(fndiags)); printf(" Function error: %s\n", showoff(fnerror)); #ifdef CKLEARN { extern char * learnfile; extern int learning; if (learnfile) { printf(" LEARN file: %s (%s)\n", learnfile, learning ? "ON" : "OFF" ); } else printf(" LEARN file: (none)\n"); } #endif /* CKLEARN */ shoinput(); shooutput(); #ifndef NOSCRIPT printf(" Script echo: %s\n", showoff(secho)); #endif /* NOSCRIPT */ printf(" Command buffer length: %d\n", CMDBL); printf(" Atom buffer length: %d\n", ATMBL); break; #endif /* NOSPL */ #ifndef NOXMIT case SHXMI: printf("\n"); printf(" File type: %s\n", binary ? "binary" : "text"); #ifndef NOCSETS printf(" File character-set: %s\n", fcsinfo[fcharset].keyword); #ifdef OS2 if ( ck_isunicode() ) { printf(" Terminal Character (remote): %s\n", tt_utf8 ? "utf-8" : tcsr == TX_TRANSP ? "transparent" : tcsr == TX_UNDEF ? "undefined" : txrinfo[tcsr]->keywd); printf(" Terminal Character (local): %s\n", tcsl == TX_TRANSP ? "transparent" : tcsl == TX_UNDEF ? "undefined" : txrinfo[tcsl]->keywd); } else { printf(" Terminal Character (remote): %s\n", tt_utf8 ? "utf-8" : tcsr == TX_TRANSP ? "transparent" : tcsr == TX_UNDEF ? "undefined" : txrinfo[tcsr]->keywd); printf(" Terminal Character (local): %s\n", tcsl == TX_TRANSP ? "transparent" : tcsl == TX_UNDEF ? "undefined" : txrinfo[tcsl]->keywd); } #else /* OS2 */ printf(" Terminal character-set (remote): %s\n", fcsinfo[tcsr].keyword); printf(" Terminal character-set (local): %s\n", fcsinfo[tcsl].keyword); #endif /* OS2 */ #endif /* NOCSETS */ printf(" Terminal bytesize: %d\n", (cmask == 0xff) ? 8 : 7); printf(" Terminal echo: %s\n", duplex ? "local" : "remote"); printf(" Transmit EOF: "); if (*xmitbuf == NUL) { printf("(none)\n"); } else { char *p; p = xmitbuf; while (*p) { if (*p < SP) printf("^%c",ctl(*p)); else printf("%c",*p); p++; } printf("\n"); } if (xmitf) printf(" Transmit Fill: %d\n", xmitf); else printf(" Transmit Fill: (none)\n"); printf(" Transmit Linefeed: %s\n",showoff(xmitl)); if (xmitp) printf(" Transmit Prompt: %d (%s)\n", xmitp, chartostr(xmitp) ); else printf(" Transmit Prompt: (none)\n"); printf(" Transmit Echo: %s\n", showoff(xmitx)); printf(" Transmit Locking-Shift: %s\n", showoff(xmits)); printf(" Transmit Pause: %d (millisecond%s)\n", xmitw, (xmitw == 1) ? "" : "s" ); printf(" Transmit Timeout: %d (second%s)\n", xmitt, (xmitt == 1) ? "" : "s" ); printf("\n"); break; #endif /* NOXMIT */ #ifndef NODIAL case SHMOD: /* SHOW MODEM */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shomodem(); /* Show SET MODEM items */ break; #endif /* NODIAL */ #ifndef MAC case SHDFLT: printf("%s\n",zgtdir()); break; #endif /* MAC */ #ifndef NOLOCAL case SHESC: #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ return(shoesc(escape)); #ifndef NODIAL case SHDIA: /* SHOW DIAL */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shmdmlin(); printf(", speed: "); if ((zz = ttgspd()) < 0) { printf("unknown"); } else { if (zz == 8880) printf("75/1200"); else printf("%ld",zz); } if (carrier == CAR_OFF) s = "off"; else if (carrier == CAR_ON) s = "on"; else if (carrier == CAR_AUT) s = "auto"; else s = "unknown"; printf(", carrier: %s", s); if (carrier == CAR_ON) { if (cdtimo) printf(", timeout: %d sec", cdtimo); else printf(", timeout: none"); } printf("\n"); doshodial(); if (local #ifdef NETCONN && !network #endif /* NETCONN */ ) { printf("Type SHOW MODEM to see modem settings.\n"); #ifdef CK_TAPI printf("Type SHOW TAPI to see TAPI-related items\n"); #endif /* CK_TAPI */ printf("Type SHOW COMMUNICATIONS to see modem signals.\n"); } break; #endif /* NODIAL */ #endif /* NOLOCAL */ #ifndef NOXFER #ifdef CK_LABELED case SHLBL: /* Labeled file info */ sholbl(); break; #endif /* CK_LABELED */ #endif /* NOXFER */ case SHCSE: /* Character sets */ #ifdef NOCSETS printf( " Character set translation is not supported in this version of C-Kermit\n"); #else shocharset(); #ifndef NOXFER printf("\n Unknown-Char-Set: %s\n", unkcs ? "Keep" : "Discard"); #endif /* NOXFER */ #ifdef OS2 printf("\n"); #endif /* OS2 */ shotcs(tcsl,tcsr); printf("\n"); #ifdef OS2 /* PC Code Page information */ { char cpbuf[128]; int cplist[16], cps; int activecp; cps = os2getcplist(cplist, sizeof(cplist)); sprintf(cpbuf, /* SAFE */ "%3d,%3d,%3d,%3d,%3d,%3d,%3d,%3d,%3d,%3d,%3d,%3d", cps > 1 ? cplist[1] : 0, cps > 2 ? cplist[2] : 0, cps > 3 ? cplist[3] : 0, cps > 4 ? cplist[4] : 0, cps > 5 ? cplist[5] : 0, cps > 6 ? cplist[6] : 0, cps > 7 ? cplist[7] : 0, cps > 8 ? cplist[8] : 0, cps > 9 ? cplist[9] : 0, cps > 10 ? cplist[10] : 0, cps > 11 ? cplist[11] : 0, cps > 12 ? cplist[12] : 0 ); printf(" Code Pages:\n"); activecp = os2getcp(); if ( activecp ) { printf(" Active: %d\n",activecp); if (!isWin95()) printf(" Available: %s\n",cpbuf); } else printf(" Active: n/a\n"); printf("\n"); } #endif /* OS2 */ #endif /* NOCSETS */ break; case SHFEA: /* Features */ shofea(); break; #ifdef CK_SPEED case SHCTL: /* Control-Prefix table */ shoctl(); break; #endif /* CK_SPEED */ case SHEXI: { extern int exithangup, exitmsg; printf("\n Exit warning %s\n", xitwarn ? (xitwarn == 1 ? "on" : "always") : "off"); printf(" Exit message: %s\n", exitmsg ? (exitmsg == 1 ? "on" : "stderr") : "off"); printf(" Exit on-disconnect: %s\n", showoff(exitonclose)); printf(" Exit hangup: %s\n", showoff(exithangup)); printf(" Current exit status: %d\n\n", xitsta); break; } case SHPRT: { #ifdef PRINTSWI extern int printtimo, printertype, noprinter; extern char * printterm, * printsep; extern int prncs; #ifdef BPRINT extern int printbidi; #endif /* BPRINT */ #endif /* PRINTSWI */ #ifdef IKSD if (inserver && #ifdef CK_LOGIN isguest #else /* CK_LOGIN */ 0 #endif /* CK_LOGIN */ ) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ #ifdef PRINTSWI if (noprinter) { printf("Printer: (none)\n\n"); break; } #endif /* PRINTSWI */ printf("Printer: %s%s\n", printpipe ? "| " : "", printername ? printername : #ifdef OS2 "PRN" #else "(default)" #endif /* OS2 */ ); #ifdef PRINTSWI #ifdef BPRINT if (printbidi) { printf(" /BIDIRECTIONAL\n"); if (pportspeed > 0) printf(" /SPEED:%ld\n",pportspeed); printf(" /PARITY:%s\n",parnam((char)pportparity)); printf(" /FLOW:%s\n", pportflow == FLO_NONE ? "NONE" : (pportflow == FLO_RTSC ? "RTS/CTS" : "XON/XOFF") ); } else printf(" /OUTPUT-ONLY\n"); #endif /* BPRINT */ switch (printertype) { case PRT_NON: printf(" /NONE\n"); break; case PRT_FIL: printf(" /FILE\n"); break; case PRT_PIP: printf(" /PIPE\n"); break; case PRT_DOS: printf(" /DOS-DEVICE\n"); break; case PRT_WIN: printf(" /WINDOWS-QUEUE\n"); break; } printf(" /TIMEOUT:%d\n",printtimo); if (printterm) { printf(" /END-OF-JOB-STRING:"); shostrdef(printterm); printf("\n"); } else printf(" /END-OF-JOB-STRING:(none)\n"); printf(" /JOB-HEADER-FILE:%s\n",printsep ? printsep : "(none)"); printf(" /CHARACTER-SET: %s\n",txrinfo[prncs]->keywd); #endif /* PRINTSWI */ printf("\n"); break; } case SHCMD: { #ifdef DOUBLEQUOTING extern int dblquo; #endif /* DOUBLEQUOTING */ #ifdef CK_AUTODL printf(" Command autodownload: %s\n",showoff(cmdadl)); #else printf(" Command autodownload: (not available)\n"); #endif /* CK_AUTODL */ printf(" Command bytesize: %d bits\n", (cmdmsk == 0377) ? 8 : 7); printf(" Command error-display: %d\n", cmd_err); #ifdef CK_RECALL printf(" Command recall-buffer-size: %d\n",cm_recall); #else printf(" Command recall-buffer not available in this version\n"); #endif /* CK_RECALL */ #ifdef CK_RECALL printf(" Command retry: %s\n",showoff(cm_retry)); #else printf(" Command retry not available in this version\n"); #endif /* CK_RECALL */ printf(" Command interruption: %s\n", showoff(cmdint)); printf(" Command quoting: %s\n", showoff(cmdgquo())); #ifdef DOUBLEQUOTING printf(" Command doublequoting: %s\n", showoff(dblquo)); #endif /* DOUBLEQUOTING */ printf(" Command more-prompting: %s\n", showoff(xaskmore)); printf(" Command height: %d\n", cmd_rows); printf(" Command width: %d\n", cmd_cols); #ifndef IKSDONLY #ifdef OS2 printf(" Command statusline: %s\n",showoff(tt_status[VCMD])); #endif /* OS2 */ #endif /* IKSDONLY */ #ifdef LOCUS printf(" Locus: %s", autolocus ? (autolocus == 2 ? "ask" : "auto") : (locus ? "local" : "remote")); if (autolocus) printf(" (%s)", locus ? "local" : "remote"); printf("\n"); #endif /* LOCUS */ printf(" Hints: %s\n", showoff(hints)); printf(" Quiet: %s\n", showoff(quiet)); printf(" Maximum command length: %d\n", CMDBL); #ifndef NOSPL { char * s; int k; printf(" Maximum number of macros: %d\n", MAC_MAX); printf(" Macros defined: %d\n", nmac); printf(" Maximum macro depth: %d\n", MACLEVEL); printf(" Maximum TAKE depth: %d\n", MAXTAKE); s = "(not defined)"; k = mlook(mactab,"on_unknown_command",nmac); if (k > -1) if (mactab[k].mval) s = mactab[k].mval; printf(" ON_UNKNOWN_COMMAND: %s\n",s); } #endif /* NOSPL */ #ifdef UNIX #ifndef NOJC printf(" Suspend: %s\n", showoff(xsuspend)); #endif /* NOJC */ #endif /* UNIX */ printf(" Access to external commands and programs%s allowed\n", #ifndef NOPUSH !nopush ? "" : #endif /* NOPUSH */ " not"); break; } #ifndef NOSPL case SHALRM: if (ck_alarm) printf("Alarm at %s %s\n",alrm_date,alrm_time); else printf("(no alarm set)\n"); break; #endif /* NOSPL */ #ifndef NOMSEND case SHSFL: { extern struct filelist * filehead; if (!filehead) { printf("send-list is empty\n"); } else { struct filelist * flp; char * s; flp = filehead; while (flp) { s = flp->fl_alias; if (!s) s = "(none)"; printf("%s, mode: %s, alias: %s\n", flp->fl_name, gfmode(flp->fl_mode,0), s ); flp = flp->fl_next; } } } break; #endif /* NOMSEND */ #ifdef CKXXCHAR case SHDBL: shodbl(); break; #endif /* CKXXCHAR */ #ifndef NOPUSH #ifndef NOFRILLS case SHEDIT: if (!editor[0]) { s = getenv("EDITOR"); if (s) ckstrncpy(editor,s,CKMAXPATH); } printf("\n editor: %s\n", editor[0] ? editor : "(none)"); if (editor[0]) { printf(" options: %s\n", editopts[0] ? editopts : "(none)"); printf(" file: %s\n", editfile[0] ? editfile : "(none)"); } printf("\n"); break; #ifdef BROWSER case SHBROWSE: if (!browser[0]) { s = getenv("BROWSER"); if (s) ckstrncpy(browser,s,CKMAXPATH); } printf("\n browser: %s\n", browser[0] ? browser : "(none)"); if (browser[0]) { printf(" options: %s\n", browsopts[0] ? browsopts : "(none)"); printf(" url: %s\n", browsurl[0] ? browsurl : "(none)"); } printf("\n"); break; #endif /* BROWSER */ #endif /* NOFRILLS */ #endif /* NOPUSH */ #ifndef NOLOCAL #ifdef CK_TAPI case SHTAPI: /* TAPI options */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotapi(0); break; case SHTAPI_L: /* TAPI Locations */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotapi(1); break; case SHTAPI_M: /* TAPI Modem */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotapi(2); break; case SHTAPI_C: /* TAPI Comm */ #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ shotapi(3); break; #endif /* CK_TAPI */ case SHTCP: /* SHOTCP */ printf("\n"); shotcp(0); printf("\n"); break; #ifdef TNCODE case SHTEL: /* TELNET */ printf("\n"); shotel(0); printf("\n"); break; case SHTOPT: /* TELNET OPTIONS */ printf("\n"); shotopt(0); printf("\n"); break; #endif /* TNCODE */ case SHOTMPDIR: /* TEMPORARY DIRECTORY */ { extern char * tempdir; if (!tempdir) { printf(" (none)\n"); } else if (!*tempdir) { printf(" (none)\n"); } else { printf(" %s\n", tempdir); } break; } #ifdef CK_TRIGGER case SHTRIG: { extern char * tt_trigger[], * triggerval; int i; if (!tt_trigger[0]) { printf(" Triggers: (none)\n"); } else { printf(" Triggers:\n"); for (i = 0; i < TRIGGERS; i++) { if (!tt_trigger[i]) break; printf(" \"%s\"\n",tt_trigger[i]); } printf(" Most recent trigger encountered: "); if (triggerval) printf("\"%s\"\n",triggerval); else printf("(none)\n"); } break; } #endif /* CK_TRIGGER */ #endif /* NOLOCAL */ #ifndef NOSPL case SHINP: shoinput(); break; #endif /* NOSPL */ case SHLOG: { #ifndef MAC #ifdef IKSD if (inserver && #ifdef CK_LOGIN isguest #else /* CK_LOGIN */ 0 #endif /* CK_LOGIN */ ) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ #ifdef DEBUG printf("\n Debug log: %s", deblog ? debfil : "(none)"); { extern int debtim; if (debtim) printf(" (timestamps)"); printf("\n"); } #endif /* DEBUG */ #ifndef NOXFER printf(" Packet log: %s\n", pktlog ? pktfil : "(none)"); #endif /* NOXFER */ #ifndef NOLOCAL printf(" Session log: %s", seslog ? sesfil : "(none)"); { extern int sessft, slogts, slognul; switch (sessft) { case XYFT_T: printf(" (text)"); break; case XYFT_B: printf(" (binary)"); break; case XYFT_D: printf(" (debug)"); break; } if (slogts) printf("(timestamped)"); if (slognul) printf("(null-padded)"); printf("\n"); } #endif /* NOLOCAL */ #ifdef TLOG printf(" Transaction log: %s (%s)\n", (tralog ? (*trafil ? trafil : "(none)") : "(none)"), (tlogfmt ? ((tlogfmt == 2) ? "ftp" : "verbose") : "brief") ); #endif /* TLOG */ #ifdef CKLOGDIAL printf(" Connection log: %s\n", dialog ? diafil : "(none)"); #endif /* CKLOGDIAL */ printf("\n"); #endif /* MAC */ break; } #ifndef NOSPL case SHOUTP: /* OUTPUT */ shooutput(); break; #endif /* NOSPL */ #ifdef PATTERNS case SHOPAT: /* PATTERNS */ shopat(); break; #endif /* PATTERNS */ #ifdef STREAMING case SHOSTR: { /* STREAMING */ extern int streamrq, clearrq, cleared; extern long tfcps; debug(F101,"SHOW RELIABLE reliable","",reliable); printf("\n Reliable: %s\n",showooa(reliable)); printf(" Clearchannel: %s\n",showooa(clearrq)); printf(" Streaming: %s\n\n",showooa(streamrq)); if ((!local && (streamrq == SET_ON)) || (streamrq == SET_AUTO && reliable)) printf(" Streaming will be done if requested.\n"); else if ((streamrq == SET_OFF) || ((streamrq == SET_AUTO) && !reliable)) printf(" Streaming will not be requested and will not be done.\n"); else if ((streamrq == SET_ON) || ((streamrq == SET_AUTO) && reliable)) printf( " Streaming will be requested and will be done if the other Kermit agrees.\n"); printf(" Last transfer: %sstreaming%s, %ld cps.\n", streamed > 0 ? "" : "no ", cleared ? ", clearchannel" : "", tfcps ); printf("\n"); break; } #endif /* STREAMING */ case SHOIKS: return(sho_iks()); break; #ifdef CK_AUTHENTICATION case SHOAUTH: return(sho_auth(0)); #endif /* CK_AUTHENTICATION */ #ifndef NOFTP case SHOFTP: { #ifdef IKSD if (inserver) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ #ifdef SYSFTP { extern char ftpapp[], ftpopts[]; printf(" ftp-client: %s\n", ftpapp[0] ? ftpapp : "(none)"); if (ftpapp[0]) printf(" ftp options: %s\n", ftpopts[0] ? ftpopts : "(none)"); } #else #ifdef NEWFTP shoftp(0); #else printf("(No FTP client included in this version of Kermit.)\n"); #endif /* NEWFTP */ #endif /* SYSFTP */ break; } #endif /* NOFTP */ #ifndef NOCMDL case SHXOPT: { #ifdef IKSDB extern int dbenabled; extern char * dbfile, * dbdir; #endif /* IKSDB */ #ifdef CKWTMP extern int ckxwtmp; extern char * wtmpfile; #endif /* CKWTMP */ #ifdef CK_LOGIN extern int ckxanon, xferlog, logintimo; extern char * xferfile; #ifdef UNIX extern int ckxpriv; #endif /* UNIX */ #ifdef CK_PERMS extern int ckxperms; #endif /* CK_PERMS */ #endif /* CK_LOGIN */ extern char * bannerfile, * helpfile; #ifdef IKSD if (inserver && #ifdef CK_LOGIN isguest #else /* CK_LOGIN */ 0 #endif /* CK_LOGIN */ ) { printf("Sorry, command disabled.\r\n"); return(success = 0); } #endif /* IKSD */ printf("\n"); if (!cmdint) printf(" --nointerrupts\n"); printf(" --bannerfile=%s\n",bannerfile ? bannerfile : "(null)"); printf(" --cdfile:%s\n",cdmsgstr ? cdmsgstr : "(null)"); printf(" --cdmessage:%d\n",srvcdmsg); printf(" --helpfile:%d\n",helpfile); if (inserver) { printf("\n"); break; } #ifdef CKSYSLOG #ifdef SYSLOGLEVEL printf(" --syslog:%d (forced)\n",ckxsyslog); #else printf(" --syslog:%d\n",ckxsyslog); #endif /* SYSLOGLEVEL */ #endif /* CKSYSLOG */ #ifdef CKWTMP printf(" --wtmplog:%d\n",ckxwtmp); printf(" --wtmpfile=%s\n",wtmpfile ? wtmpfile : "(null)"); #endif /* CKWTMP */ #ifdef IKSD #ifdef CK_LOGIN printf(" --anonymous:%d\n",ckxanon); #ifdef UNIX printf(" --privid:%d\n",ckxpriv); #endif /* UNIX */ #ifdef CK_PERMS printf(" --permission:%04o\n",ckxperms); #endif /* CK_PERMS */ printf(" --initfile:%s\n",anonfile ? anonfile : "(null)"); printf(" --userfile:%s\n",userfile ? userfile : "(null)"); printf(" --root:%s\n",anonroot ? anonroot : "(null)"); printf(" --xferlog=%d\n",xferlog); printf(" --xferfile=%s\n",xferfile ? xferfile : "(null)"); printf(" --timeout=%d\n",logintimo); #endif /* CK_LOGIN */ #ifdef IKSDB printf(" --database=%d\n",dbenabled); printf(" --dbfile=%s\n",dbfile ? dbfile : "(null)"); if (dbdir) printf(" (db directory=[%s])\n",dbdir); #endif /* IKSDB */ #ifdef IKSDCONF printf(" IKSD conf=%s\n",iksdconf); #endif /* IKSDCONF */ #endif /* IKSD */ printf("\n"); break; } #endif /* NOCMDL */ case SHCD: { extern char * myhome; s = getenv("CDPATH"); if (!s) s = "(none)"; printf("\n current directory: %s\n", zgtdir()); printf(" previous directory: %s\n", prevdir ? prevdir : "(none)"); printf(" cd home: %s\n", homepath()); printf(" cd path: %s\n", ckcdpath ? ckcdpath : s); printf(" cd message: %s\n", showoff(srvcdmsg & 2)); printf(" server cd-message: %s\n", showoff(srvcdmsg & 1)); printf(" cd message file: %s\n\n",cdmsgstr ? cdmsgstr : "(none)"); break; } #ifndef NOCSETS case SHASSOC: (VOID) showassoc(); break; #endif /* NOCSETS */ #ifdef CKLOGDIAL case SHCONNX: #ifdef NEWFTP if (ftpisconnected()) { extern char cxlogbuf[]; dologshow(W_FTP | 1); if (cxlogbuf[0]) dologshow(1); } else { #endif /* NEWFTP */ dologshow(1); #ifdef NEWFTP } #endif /* NEWFTP */ break; #endif /* CKLOGDIAL */ case SHOPTS: optlines = 0; #ifndef NOFRILLS (VOID) showdelopts(); #endif /* NOFRILLS */ #ifdef DOMYDIR (VOID) showdiropts(); #endif /* DOMYDIR */ #ifdef CKPURGE (VOID) showpurgopts(); #endif /* CKPURGE */ (VOID) showtypopts(); break; #ifndef NOLOCAL case SHOFLO: (VOID) shoflow(); break; #endif /* NOLOCAL */ #ifndef NOXFER case SHOXFER: (VOID) shoxfer(); break; #endif /* NOXFER */ #ifdef CK_RECALL case SHHISTORY: (VOID) cmhistory(); break; #endif /* CK_RECALL */ #ifndef NOSEXP #ifndef NOSPL case SHSEXP: (VOID) shosexp(); break; #endif /* NOSPL */ #endif /* NOSEXP */ #ifdef ANYSSH case SHOSSH: (VOID) shossh(); break; #endif /* ANYSSH */ #ifdef KUI case SHOGUI: (VOID) shogui(); break; #endif /* KUI */ #ifndef NOFRILLS #ifndef NORENAME case SHOREN: (VOID) shorename(); break; #endif /* NORENAME */ #endif /* NOFRILLS */ case SHOLOC: { #ifdef HAVE_LOCALE char *s; extern int nolocale; printf("\n"); printf("Locale %s:\n", nolocale ? "disabled" : "enabled"); #ifdef COMMENT s = setlocale(LC_ALL, NULL); if (!s) s = ""; printf("LC_ALL=%s\n",s); #endif /* COMMENT */ s = setlocale(LC_COLLATE, NULL); if (!s) s = ""; printf(" LC_COLLATE=\"%s\"\n",s); s = setlocale(LC_CTYPE, NULL); if (!s) s = ""; printf(" LC_CTYPE=\"%s\"\n",s); s = setlocale(LC_MONETARY, NULL); if (!s) s = ""; printf(" LC_MONETARY=\"%s\"\n",s); s = setlocale(LC_MESSAGES, NULL); if (!s) s = ""; printf(" LC_MESSAGES=\"%s\"\n",s); s = setlocale(LC_NUMERIC, NULL); if (!s) s = ""; printf(" LC_NUMERIC=\"%s\"\n",s); s = setlocale(LC_TIME, NULL); if (!s) s = ""; printf(" LC_TIME=\"%s\"\n",s); printf(" LANG=\"%s\"\n",getenv("LANG")); printf("\n"); #else printf("\n"); printf(" Locale support is not included in this version of Kermit\n"); printf("\n"); #endif /* HAVE_LOCALE */ break; } default: printf("\nNothing to show...\n"); return(-2); } return(success = 1); } #ifndef NOXFER int shoatt() { printf("Attributes: %s\n", showoff(atcapr)); if (!atcapr) return(0); printf(" Blocksize: %s\n", showoff(atblki)); printf(" Date: %s\n", showoff(atdati)); printf(" Disposition: %s\n", showoff(atdisi)); printf(" Encoding (Character Set): %s\n", showoff(atenci)); printf(" Length: %s\n", showoff(atleni)); printf(" Type (text/binary): %s\n", showoff(attypi)); printf(" System ID: %s\n", showoff(atsidi)); printf(" System Info: %s\n", showoff(atsysi)); #ifdef CK_PERMS printf(" Permissions In: %s\n", showoff(atlpri)); printf(" Permissions Out: %s\n", showoff(atlpro)); #endif /* CK_PERMS */ #ifdef STRATUS printf(" Format: %s\n", showoff(atfrmi)); printf(" Creator: %s\n", showoff(atcrei)); printf(" Account: %s\n", showoff(atacti)); #endif /* STRATUS */ return(0); } #endif /* NOXFER */ #ifndef NOSPL int /* SHOW MACROS */ shomac(s1, s2) char *s1, *s2; { int x, n, pp; pp = 0; /* Parenthesis counter */ debug(F110,"shomac s1",s1,0); debug(F110,"shomac s2",s2,0); #ifdef IKSD if ( inserver && #ifdef IKSDCONF iksdcf #else /* IKSDCONF */ 1 #endif /* IKSDCONF */ ) { if (!ckstrcmp("on_exit",s1,-1,0) || !ckstrcmp("on_logout",s1,-1,0)) return(0); } #endif /* IKSD */ if (!s1) return(0); else printf("%s = ",s1); /* Print blank line and macro name */ n = (int)strlen(s1) + 4; /* Width of current line */ if (!s2) s2 = "(not defined)"; while ((x = *s2++)) { /* Loop thru definition */ if (x == '(') pp++; /* Treat commas within parens */ if (x == ')') pp--; /* as ordinary text */ if (pp < 0) pp = 0; /* Outside parens, */ if (x == ',' && pp == 0) { /* comma becomes comma-dash-NL. */ putchar(','); putchar('-'); x = '\n'; } if (inserver && (x == '\n')) /* Send CR before LF */ putchar(CR); putchar((CHAR)x); /* Output the character */ if (x == '\n') { /* If it was a newline */ #ifdef UNIX #ifdef NOSETBUF fflush(stdout); #endif /* NOSETBUF */ #endif /* UNIX */ putchar(' '); /* Indent the next line 1 space */ while(*s2 == ' ') s2++; /* skip past leading blanks */ n = 2; /* restart the character counter */ slc++; /* and increment the line counter. */ } else if (++n > (cmd_cols - 1)) { /* If line is too wide */ putchar('-'); /* output a dash */ if (inserver) putchar(CR); /* and a carriage return */ putchar(NL); /* and a newline */ #ifdef UNIX #ifdef NOSETBUF fflush(stdout); #endif /* NOSETBUF */ #endif /* UNIX */ n = 1; /* and restart the char counter */ slc++; /* and increment the line counter */ } if (n < 3 && slc > (cmd_rows - 3)) { /* If new line and screen full */ if (!askmore()) return(-1); /* ask if they want more. */ n = 1; /* They do, start a new line */ slc = 0; /* and restart line counter */ } } if (inserver) putchar(CR); putchar(NL); /* End of definition */ if (++slc > (cmd_rows - 3)) { if (!askmore()) return(-1); slc = 0; } return(0); } #endif /* NOSPL */ #endif /* NOSHOW */ int x_ifnum = 0; /* Flag for IF NUMERIC active */ #ifndef NOSPL /* Evaluate an arithmetic expression. */ /* Code adapted from ev, by Howie Kaye of Columbia U & others. */ static int xerror = 0; int divbyzero = 0; static char *cp; static CK_OFF_T tokval; static char curtok; static CK_OFF_T expval; #define LONGBITS (8*sizeof (CK_OFF_T)) #define NUMBER 'N' #define N_EOT 'E' /* Replacement for strchr() and index(), neither of which seem to be universal. */ static char * #ifdef CK_ANSIC windex(char * s, char c) #else windex(s,c) char *s, c; #endif /* CK_ANSIC */ /* windex */ { while (*s != NUL && *s != c) s++; if (*s == c) return(s); else return(NULL); } /* g e t t o k Returns the next token. If token is a NUMBER, sets tokval appropriately. */ static char gettok() { char tbuf[80] /* ,*tp */ ; /* Buffer to accumulate number */ while (isspace(*cp)) /* Skip past leading spaces */ cp++; debug(F110,"GETTOK",cp,0); switch (*cp) { case '$': /* ??? */ case '+': /* Add */ case '-': /* Subtract or Negate */ case '@': /* Greatest Common Divisor */ case '*': /* Multiply */ case '/': /* Divide */ case '%': /* Modulus */ case '<': /* Left shift */ case '>': /* Right shift */ case '&': /* And */ case '|': /* Or */ case '#': /* Exclusive Or */ case '~': /* Not */ case '^': /* Exponent */ case '!': /* Factorial */ case '(': /* Parens for grouping */ case ')': return(*cp++); /* operator, just return it */ case '\n': case '\0': return(N_EOT); /* End of line, return that */ } #ifdef COMMENT /* This is the original code, which allows only integer numbers. */ if (isxdigit(*cp)) { /* Digit, must be a number */ int radix = 10; /* Default radix */ for (tp = tbuf; isxdigit(*cp); cp++) *tp++ = (char) (isupper(*cp) ? tolower(*cp) : *cp); *tp = '\0'; /* End number */ switch(isupper(*cp) ? tolower(*cp) : *cp) { /* Examine break char */ case 'h': case 'x': radix = 16; cp++; break; /* if radix signifier... */ case 'o': case 'q': radix = 8; cp++; break; case 't': radix = 2; cp++; break; } for (tp = tbuf, tokval = 0; *tp != '\0'; tp++) { int dig; dig = *tp - '0'; /* Convert number */ if (dig > 10) dig -= 'a'-'0'-10; if (dig >= radix) { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("?Invalid digit '%c' in number\n",*tp); xerror = 1; return(NUMBER); } tokval = radix*tokval + dig; } return(NUMBER); } if (cmdlvl == 0 && !x_ifnum && !xerror) printf("Invalid character '%c' in input\n",*cp); xerror = 1; cp++; return(gettok()); #else /* This code allows non-numbers to be treated as macro names */ { int i, x; char * s, * cp1; cp1 = cp; tp = tbuf; for (i = 0; i < 80; i++) { /* Look ahead to next break character */ /* pretty much anything that is not in the switch() above. */ if (isalpha(*cp) || isdigit(*cp) || *cp == '_' || *cp == ':' || *cp == '.' || *cp == '[' || *cp == ']' || *cp == '{' || *cp == '}' ) tbuf[i] = *cp++; else break; } if (i >= 80) { printf("Too long - \"%s\"\n", cp1); xerror = 1; cp++; return(gettok()); } if (xerror) return(NUMBER); tbuf[i] = NUL; s = tbuf; if (!isdigit(tbuf[0])) { char * s2 = NULL; x = mxlook(mactab,tbuf,nmac); debug(F111,"gettok mxlook",tbuf,x); if (x < 0) { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("Bad number - \"%s\"\n",tbuf); xerror = 1; cp++; return(gettok()); } s2 = mactab[x].mval; if (!s2) s2 = ""; if (*s2) s = s2; } #ifdef CKFLOAT x = isfloat(s,0); #else x = chknum(s); #endif /* CKFLOAT */ if (x > 0) { tokval = ckatofs(s); } else { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("Bad number - \"%s\"\n",tbuf); xerror = 1; cp++; return(gettok()); } return(NUMBER); } #endif /* COMMENT */ } static CK_OFF_T #ifdef CK_ANSIC expon(CK_OFF_T x, CK_OFF_T y) #else expon(x,y) CK_OFF_T x,y; #endif /* CK_ANSIC */ /* expon */ { CK_OFF_T result = 1; int sign = 1; if (y < 0) return(0); if (x < 0) { x = -x; if (y & 1) sign = -1; } while (y != 0) { if (y & 1) result *= x; y >>= 1; if (y != 0) x *= x; } return(result * sign); } /* * factor ::= simple | simple ^ factor * */ static VOID factor() { CK_OFF_T oldval; simple(); if (curtok == '^') { oldval = expval; curtok = gettok(); factor(); expval = expon(oldval,expval); } } /* * termp ::= NULL | {*,/,%,&} factor termp * */ static VOID termp() { while (curtok == '*' || curtok == '/' || curtok == '%' || curtok == '&') { CK_OFF_T oldval; char op; op = curtok; curtok = gettok(); /* skip past operator */ oldval = expval; factor(); switch(op) { case '*': expval = oldval * expval; break; case '/': case '%': if (expval == 0) { if (!x_ifnum) printf("?Divide by zero\n"); xerror = 1; divbyzero = 1; expval = -1; } else expval = (op == '/') ? (oldval / expval) : (oldval % expval); break; case '&': expval = oldval & expval; break; } } } static CK_OFF_T #ifdef CK_ANSIC fact(CK_OFF_T x) #else fact(x) CK_OFF_T x; #endif /* CK_ANSIC */ /* fact */ { /* factorial */ CK_OFF_T result = 1; while (x > 1) result *= x--; return(result); } /* * term ::= factor termp * */ static VOID term() { factor(); termp(); } static CK_OFF_T #ifdef CK_ANSIC gcd(CK_OFF_T x, CK_OFF_T y) #else gcd(x,y) CK_OFF_T x,y; #endif /* CK_ANSIC */ /* gcd */ { /* Greatest Common Divisor */ int nshift = 0; if (x < 0) x = -x; if (y < 0) y = -y; /* validate arguments */ if (x == 0 || y == 0) return(x + y); /* this is bogus */ while (!((x & 1) | (y & 1))) { /* get rid of powers of 2 */ nshift++; x >>= 1; y >>= 1; } while (x != 1 && y != 1 && x != 0 && y != 0) { while (!(x & 1)) x >>= 1; /* eliminate unnecessary */ while (!(y & 1)) y >>= 1; /* powers of 2 */ if (x < y) { /* force x to be larger */ CK_OFF_T t; t = x; x = y; y = t; } x -= y; } if (x == 0 || y == 0) return((x + y) << nshift); /* gcd is non-zero one */ else return((CK_OFF_T) 1 << nshift); /* else gcd is 1 */ } /* * exprp ::= NULL | {+,-,|,...} term exprp * */ static VOID exprp() { while (windex("+-|<>#@",curtok) != NULL) { CK_OFF_T oldval; char op; op = curtok; curtok = gettok(); /* skip past operator */ oldval = expval; term(); switch(op) { case '+' : expval = oldval + expval; break; case '-' : expval = oldval - expval; break; case '|' : expval = oldval | expval; break; case '#' : expval = oldval ^ expval; break; case '@' : expval = gcd(oldval,expval); break; case '<' : expval = oldval << expval; break; case '>' : expval = oldval >> expval; break; } } } /* * expr ::= term exprp * */ static VOID expr() { term(); exprp(); } static CK_OFF_T xparse() { curtok = gettok(); expr(); #ifdef COMMENT if (curtok == '$') { curtok = gettok(); if (curtok != NUMBER) { if (cmdlvl == 0 && !x_ifnum) printf("?Illegal radix\n"); xerror = 1; return(0); } curtok = gettok(); } #endif /* COMMENT */ if (curtok != N_EOT) { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("?Extra characters after expression\n"); xerror = 1; } return(expval); } char * /* Silent front end for evala() */ evalx(s) char *s; { char * p; int t; t = x_ifnum; x_ifnum = 1; p = evala(s); x_ifnum = t; return(p); } char * evala(s) char *s; { CK_OFF_T v; /* Numeric value */ if (!s) return(""); xerror = 0; /* Start out with no error */ divbyzero = 0; cp = s; /* Make the argument global */ v = xparse(); /* Parse the string */ return(xerror ? "" : ckfstoa(v)); /* Return empty string on error */ } /* * simplest ::= NUMBER | ( expr ) * */ static VOID simplest() { char * p; p = cp; if (curtok == NUMBER) expval = tokval; else if (curtok == '(') { curtok = gettok(); /* skip over paren */ expr(); if (curtok != ')') { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("?Missing right parenthesis\n"); xerror = 1; } debug(F110,"GETTOK SIMPLEST ()",p,0); } else { if (cmdlvl == 0 && !x_ifnum && !xerror) printf("?Operator unexpected\n"); xerror = 1; } curtok = gettok(); } /* * simpler ::= simplest | simplest ! * */ static VOID simpler() { simplest(); if (curtok == '!') { curtok = gettok(); expval = fact(expval); } } /* * simple ::= {-,~,!} simpler | simpler * */ static VOID simple() { if (curtok == '-' || curtok == '~' || curtok == '!' || curtok == '+') { int op = curtok; curtok = gettok(); /* skip over - sign */ simpler(); /* parse the factor again */ if (op != '+') expval = (op == '-') ? -expval : ((op == '!') ? !expval : ~expval); } else simpler(); } /* D C L A R R A Y -- Declare an array */ /* Call with: char a = single character designator for the array, e.g. "a". int n = size of array. -1 means to undeclare the array. Returns: 0 or greater on success, having created the requested array with with n+1 elements, 0..n. If an array of the same name existed previously, it is destroyed. The new array has all its elements initialized to NULL pointers. When an array is successfully created, the return value is its index (0 = 'a', 1 = 'b', and so on.) -1 on failure (because 'a' out of range or malloc failure). */ int #ifdef CK_ANSIC dclarray(char a, int n) #else dclarray(a,n) char a; int n; #endif /* CK_ANSIC */ /* dclarray */ { char c, **p; int i, n2, rc; if (a > 63 && a < 91) a += 32; /* Convert letters to lowercase */ if (a < ARRAYBASE || a > 122) /* Verify name */ return(-1); if (n < 0) /* Check arg */ return(-1); if (n+1 < 0) /* MAXINT+1 wraps around */ return(-1); c = a; a -= ARRAYBASE; /* Convert name to number */ rc = a; /* Array index will be return code */ if ((p = a_ptr[a]) != NULL) { /* Delete old array of same name */ if (a_link[a] > -1) { /* Is it a link? */ if (n == 0) { /* If we're just deleting it */ a_ptr[a] = (char **) NULL; /* clear all the info. */ a_dim[a] = 0; a_link[a] = -1; return(0); } /* Not deleting */ a = a_link[a]; /* Switch to linked-to array */ } n2 = a_dim[a]; /* Real array */ for (i = 0; i <= n2; i++) { /* First delete its elements */ if (p[i]) { free(p[i]); p[i] = NULL; } } free((char *)a_ptr[a]); /* Then the element list */ if (n == 0) { /* If undeclaring this array... */ for (i = 0; i < 122 - ARRAYBASE; i++) { /* Any linked arrays? */ if (i != a && a_link[i] == a) { /* Find them */ a_ptr[i] = (char **) NULL; /* and remove them */ a_dim[i] = 0; a_link[i] = -1; } } } a_ptr[a] = (char **) NULL; /* Remove pointer to element list */ a_dim[a] = 0; /* Set dimension at zero. */ a_link[a] = -1; /* Unset link word */ } if (n < 0) /* If only undeclaring, */ return(0); /* we're done. */ p = (char **) malloc((n+1) * sizeof(char **)); /* Allocate for new array */ if (p == NULL) return(-1); /* Check */ a_ptr[a] = p; /* Save pointer to member list */ a_dim[a] = n; /* Save dimension */ for (i = 0; i <= n; i++) /* Initialize members to null */ p[i] = NULL; for (i = 0; i < (int) 'z' - ARRAYBASE; i++) { /* Any linked arrays? */ if (i != a && a_link[i] == a) { /* Find and update them */ a_ptr[i] = p; a_dim[i] = n; } } return(rc); } /* X A R R A Y -- Convert array name to array index */ int xarray(s) char * s; { char buf[8]; int x; char c; if (!s) s = ""; debug(F110,"xarray",s,0); if (!*s) return(-1); x = strlen(s); buf[0] = NUL; buf[1] = NUL; buf[2] = s[0]; buf[3] = (x > 0) ? s[1] : NUL; buf[4] = (x > 1) ? s[2] : NUL; buf[5] = (x > 2) ? s[3] : NUL; buf[6] = NUL; debug(F110,"xarray buf[3]",&buf[3],0); s = buf+2; if (*s == '&') { buf[1] = CMDQ; s--; } else if (*s != CMDQ) { buf[0] = CMDQ; buf[1] = '&'; s = buf; } debug(F110,"xarray s",s,0); c = *(s+2); if (isupper(c)) c = tolower(c); if (c == '@') c = 96; x = (int)c - ARRAYBASE; if (*(s+3) == '[') *(s+3) = NUL; if (x < 0) { return(-1); } if (x > ('z' - ARRAYBASE)) { debug(F101,"xarray x out of range","",x); return(-1); } if (*(s+3)) { debug(F110,"xarray syntax",s,0); return(-1); } return(x); } /* boundspair() -- parses blah[n:m] For use with array segment specifiers and compact substring notation. Ignores the "blah" part, gets the values of n and m, which can be numbers, variables, or arithmetic expressions; anything that resolves to a number. Call with: s - string to parse sep - array of permissible bounds separator chars lo - pointer to low-bound result (or -1) hi - pointer to hi-bound result (or -1) zz - pointer to separator char that was encountered (or NUL) Returns: -1 on failure 0 on success */ int #ifdef CK_ANSIC boundspair(char *s, char *sep, int *lo, int *hi, char *zz) #else boundspair(s,sep,lo,hi,zz) char *s, *sep, *zz; int *lo, *hi; #endif /* CK_ANSIC */ { int i, x, y, range[2], bc = 0; char c = NUL, *s2 = NULL, buf[256], *p, *q, *r, *e[2], *tmp = NULL; debug(F110,"boundspair s",s,0); debug(F110,"boundspair sep",sep,0); *lo = -1; /* Default bounds */ *hi = -1; *zz = 0; /* Default bounds separator */ range[0] = -1; /* It's OK -- get contents */ range[1] = -1; /* of subscript brackets */ if (!s) s = ""; if (!*s) return(-1); makestr(&tmp,s); /* Make a pokeable copy */ p = tmp; q = NULL; r = NULL; for (p = s; *p; p++) { /* Get the two elements */ if (*p == '[') { bc++; /* Bracket counter */ if (bc == 1 && !q) q = p+1; } else if (*p == ']') { bc--; if (bc == 0 && q) *p = NUL; } else if (bc == 1) { /* If within brackers */ s2 = ckstrchr(sep,*p); /* Check for separator */ if (s2) { debug(F000,"boundspair *s2","",*s2); if (c) { debug(F000,"boundspair","Too many separators",*s2); makestr(&tmp,NULL); return(-1); } c = *s2; /* Separator character */ *p = NUL; r = p+1; } } } if (bc == 0 && !q) { /* This allows such constructions as "show array a" */ debug(F110,"boundspair","no brackets",0); makestr(&tmp,NULL); return(0); } if (bc != 0 || !q) { debug(F110,"boundspair","unbalanced or missing brackets",0); makestr(&tmp,NULL); return(-1); } if (!q) q = ""; if (!*q) q = "-1"; if (!r) r = ""; if (!*r) r = "-1"; e[0] = q; e[1] = r; debug(F000,"boundspair c","",c); debug(F110,"boundspair q",q,0); debug(F110,"boundspair r",r,0); for (i = 0; i < 2 && e[i]; i++) { y = 255; /* Expand variables, etc. */ s = buf; zzstring(e[i],&s,&y); s = evalx(buf); /* Evaluate it arithmetically */ if (s) if (*s) ckstrncpy(buf,s,256); if (!chknum(buf)) { /* Did we get a number? */ debug(F110,"boundspair element not numeric",buf,0); makestr(&tmp,NULL); /* No, fail. */ return(-1); } range[i] = atoi(buf); } makestr(&tmp,NULL); /* Free temporary poked string */ *lo = range[0]; /* Return what we got */ *hi = range[1]; *zz = c; debug(F101,"boundspair lo","",*lo); debug(F101,"boundspair hi","",*hi); return(0); } /* A R R A Y B O U N D S -- Parse array segment notation \&a[n:m] */ /* Call with s = array reference, plus two pointers to ints. Returns -1 on error, or array index, with the two ints set as follows: \&a[] -1, -1 \&a[3] 3, -1 \&a[3:17] 3, 17 The array need not be declared -- this routine is just for parsing. */ int arraybounds(s,lo,hi) char * s; int * lo, * hi; { int i, x, y, range[2]; char zz, buf[256], * p, * q; char * tmp = NULL; *lo = -1; /* Default bounds */ *hi = -1; if (!s) s = ""; /* Defense de null args */ if (!*s) return(-1); x = xarray(s); /* Check basic structure */ debug(F111,"arraybounds xarray",s,x); if (x < 0) /* Not OK, fail. */ return(-1); y = boundspair(s,":",lo,hi,&zz); debug(F111,"arraybounds boundspair",s,y); debug(F101,"arraybounds lo","",*lo); debug(F101,"arraybounds hi","",*hi); if (y < 0) /* Get bounds */ return(-1); return(x); } /* A R R A Y N A M -- Parse an array name */ /* Call with pointer to string that starts with the array reference. String may begin with either \& or just &. On success, Returns letter ID (always lowercase) in argument c, which can also be accent grave (` = 96; '@' is converted to grave); Dimension or subscript in argument n; IMPORTANT: These arguments must be provided by the caller as addresses of ints (not chars), for example: char *s; int x, y; arraynam(s,&x,&y); On failure, returns a negative number, with args n and c set to zero. */ int arraynam(ss,c,n) char *ss; int *c; int *n; { int i, y, pp, len; char x; char *s, *p, *sx, *vnp; /* On stack to allow for recursive calls... */ char vnbuf[ARRAYREFLEN+1]; /* Entire array reference */ char ssbuf[ARRAYREFLEN+1]; /* Subscript in "plain text" */ char sxbuf[16]; /* Evaluated subscript */ *c = *n = 0; /* Initialize return values */ len = strlen(ss); for (pp = 0,i = 0; i < len; i++) { /* Check length */ if (ss[i] == '[') { pp++; } else if (ss[i] == ']') { if (--pp == 0) break; } } if (i > ARRAYREFLEN) { printf("?Array reference too long - %s\n",ss); return(-9); } ckstrncpy(vnbuf,ss,ARRAYREFLEN); vnp = vnbuf; if (vnbuf[0] == CMDQ && vnbuf[1] == '&') vnp++; if (*vnp != '&') { printf("?Not an array - %s\n",vnbuf); return(-9); } x = *(vnp + 1); /* Fold case of array name */ /* We don't use isupper & tolower here on purpose because these */ /* would produce undesired effects with accented letters. */ if (x > 63 && x < 91) x = *(vnp + 1) = (char) (x + 32); if ((x < ARRAYBASE) || (x > 122) || (*(vnp+2) != '[')) { if (msgflg) { printf("?Invalid format for array name - %s\n",vnbuf); return(-9); } else return(-2); } *c = x; /* Return the array name */ s = vnp+3; /* Get dimension */ p = ssbuf; pp = 1; /* Bracket counter */ for (i = 0; i < ARRAYREFLEN && *s != NUL; i++) { /* Copy up to ] */ if (*s == '[') pp++; if (*s == ']' && --pp == 0) break; *p++ = *s++; } if (*s != ']') { printf("?No closing bracket on array dimension - %s\n",vnbuf); return(-9); } p--; /* Trim whitespace from end */ while (*p == SP || *p == HT) p--; p++; *p = NUL; /* Terminate subscript with null */ p = ssbuf; /* Point to beginning of subscript */ while (*p == SP || *p == HT) /* Trim whitespace from beginning */ p++; sx = sxbuf; /* Where to put expanded subscript */ y = 16; { /* Even if VARIABLE-EVALUATION SIMPLE use RECURSIVE for subscripts */ /* NOTE: This is vulnerable to SIGINT and whatnot... */ int tmp = vareval; /* Save VARIABLE-EVALUATION setting */ vareval = 1; /* Force it to RECURSIVE */ zzstring(p,&sx,&y); /* Convert variables, etc. */ vareval = tmp; /* Restore VARIABLE-EVALUATION */ } sx = sxbuf; while (*sx == SP) sx++; /* debug(F110,"arraynam sx","",sx); */ if (!*sx) { /* Empty brackets... */ *n = -17; /* (Secret code :-) */ return(-2); } p = evala(sx); /* Run it thru \fneval()... */ if (p) if (*p) ckstrncpy(sxbuf,p,16); /* We know it has to be a number. */ if (!chknum(sxbuf)) { /* Make sure it's all digits */ if (msgflg) { printf("?Array dimension or subscript missing or not numeric\n"); return(-9); } else return(-2); } if ((y = atoi(sxbuf)) < 0) { if (cmflgs == 0) printf("\n"); if (msgflg) { printf("?Array dimension or subscript not positive or zero\n"); return(-9); } else return(-2); } *n = y; /* Return the subscript or dimension */ return(0); } /* chkarray returns 0 or greater if array exists, negative otherwise */ int chkarray(a,i) int a, i; { /* Check if array is declared */ int x; /* and if subscript is in range */ if (a == 64) a = 96; /* Convert atsign to grave accent */ x = a - ARRAYBASE; /* Values must be in range 95-122 */ #ifdef COMMENT if (x == 0 && maclvl < 0) /* Macro arg vector but no macro */ return(0); #endif /* COMMENT */ if (x < 0 || x > 'z' - ARRAYBASE) /* Not in range */ return(-2); if (a_ptr[x] == NULL) return(-1); /* Not declared */ if (i > a_dim[x]) return(-2); /* Declared but out of range. */ return(a_dim[x]); /* All ok, return dimension */ } #ifdef COMMENT /* This isn't used. */ char * arrayval(a,i) int a, i; { /* Return value of \&a[i] */ int x; char **p; /* (possibly NULL) */ if (a == 64) a = 96; /* Convert atsign to grave accent */ x = a - ARRAYBASE; /* Values must be in range 95-122 */ if (x < 0 || x > 27) return(NULL); /* Not in range */ if ((x > 0) && (p = a_ptr[x]) == NULL) /* Array not declared */ return(NULL); if (i > a_dim[x]) /* Subscript out of range. */ return(NULL); return(p[i]); /* All ok, return pointer to value. */ } #endif /* COMMENT */ /* pusharray() is called when an array name is included in a LOCAL statement. It moves the pointers from the global definition to the stack, and removes the global definition. Later, if the same array is declared in the local context, it occupies the global definition in the normal way. But when popclvl() is called, it replaces the global definition with the one saved here. The "secret code" is used to indicate to popclv() that it should remove the global array when popping through this level -- otherwise if a local array were declared that had no counterpart at any higher level, it would never be deleted. This allows Algol-like inheritance to work both on the way down and on the way back up. */ int pusharray(x,z) int x, z; { int y; debug(F000,"pusharray x","",x); debug(F101,"pusharray z","",z); y = chkarray(x,z); debug(F101,"pusharray y","",y); x -= ARRAYBASE; /* Convert name letter to index. */ if (x < 0 || x > 27) return(-1); if (y < 0) { aa_ptr[cmdlvl][x] = (char **) NULL; aa_dim[cmdlvl][x] = -23; /* Secret code (see popclvl()) */ } else { aa_ptr[cmdlvl][x] = a_ptr[x]; aa_dim[cmdlvl][x] = y; } a_ptr[x] = (char **) NULL; a_dim[x] = 0; return(0); } /* P A R S E V A R -- Parse a variable name or array reference. */ /* Call with: s = pointer to candidate variable name or array reference. *c = address of integer in which to return variable ID. *i = address of integer in which to return array subscript. Returns: -2: syntax error in variable name or array reference. 1: successful parse of a simple variable, with ID in c. 2: successful parse of an array reference, w/ID in c and subscript in i. */ int parsevar(s,c,i) char *s; int *c, *i; { char *p; int x,y,z; p = s; if (*s == CMDQ) s++; /* Point after backslash */ if (*s != '%' && *s != '&') { /* Make sure it's % or & */ printf("?Not a variable name - %s\n",p); return(-9); } if ((int)strlen(s) < 2) { printf("?Incomplete variable name - %s\n",p); return(-9); } if (*s == '%' && *(s+2) != '\0') { printf("?Only one character after '%%' in variable name, please\n"); return(-9); } if (*s == '&' && *(s+2) != '[') { printf("?Array subscript expected - %s\n",p); return(-9); } if (*s == '%') { /* Simple variable. */ y = *(s+1); /* Get variable ID letter/char */ if (isupper(y)) y -= ('a'-'A'); /* Convert upper to lower case */ *c = y; /* Set the return values. */ *i = -1; /* No array subscript. */ return(1); /* Return 1 = simple variable */ } if (*s == '&') { /* Array reference. */ y = arraynam(s,&x,&z); /* Go parse it. */ debug(F101,"parsevar arraynam","",y); if ((y) < 0) { if (y == -2) return(pusharray(x,z)); if (y != -9) printf("?Invalid array reference - %s\n",p); return(-9); } if (chkarray(x,z) < 0) { /* Check if declared, etc. */ printf("?Array not declared or subscript out of range\n"); return(-9); } *c = x; /* Return array letter */ *i = z; /* and subscript. */ return(2); } return(-2); /* None of the above. */ } #define VALN 32 /* Get the numeric value of a variable */ /* Call with pointer to variable name, pointer to int for return value. Returns: 0 on success with second arg containing the value. -1 on failure (bad variable syntax, variable not defined or not numeric). */ int varval(s,v) char *s; CK_OFF_T *v; { char valbuf[VALN+1]; /* s is pointer to variable name */ char name[256]; char *p; int y; if (*s != CMDQ) { /* Handle macro names too */ ckmakmsg(name,256,"\\m(",s,")",NULL); s = name; } p = valbuf; /* Expand variable into valbuf. */ y = VALN; if (zzstring(s,&p,&y) < 0) return(-1); p = valbuf; /* Make sure value is numeric */ if (!*p) { /* Be nice -- let an undefined */ valbuf[0] = '0'; /* variable be treated as 0. */ valbuf[1] = NUL; } if (chknum(p)) { /* Convert numeric string to int */ *v = ckatofs(p); /* OK */ } else { /* Not OK */ p = evala(p); /* Maybe it's an expression */ if (!chknum(p)) /* Did it evaluate? */ return(-1); /* No, failure. */ else /* Yes, */ *v = ckatofs(p); /* success */ } return(0); } /* Increment or decrement a variable */ /* Returns -1 on failure, 0 on success */ int incvar(s,x,z) char *s; CK_OFF_T x; int z; { /* Increment a numeric variable */ CK_OFF_T n; /* s is pointer to variable name */ /* x is amount to increment by */ /* z != 0 means add */ /* z = 0 means subtract */ if (varval(s,&n) < 0) /* Convert numeric string to int */ return(-1); if (z) /* Increment it by the given amount */ n += x; else /* or decrement as requested. */ n -= x; addmac(s,ckfstoa(n)); /* Replace old variable */ return(0); } /* D O D O -- Do a macro */ /* Call with x = macro table index, s = pointer to arguments. Returns 0 on failure, 1 on success. */ int dodo(x,s,flags) int x; char *s; int flags; { int y; extern int tra_asg, tra_cmd; int tra_tmp; /* For TRACE */ #ifndef NOLOCAL #ifdef OS2 extern int term_io; int term_io_sav = term_io; #endif /* OS2 */ #endif /* NOLOCAL */ if (x < 0) /* It can happen! */ return(-1); tra_tmp = tra_asg; if (++maclvl >= MACLEVEL) { /* Make sure we have storage */ debug(F101,"dodo maclvl too deep","",maclvl); --maclvl; printf("Macros nested too deeply\n"); return(0); } macp[maclvl] = mactab[x].mval; /* Point to the macro body */ macx[maclvl] = mactab[x].mval; /* Remember where the beginning is */ #ifdef COMMENT makestr(&(m_line[maclvl]),s); /* Entire arg string for "\%*" */ #endif /* COMMENT */ cmdlvl++; /* Entering a new command level */ if (cmdlvl >= CMDSTKL) { /* Too many macros + TAKE files? */ debug(F101,"dodo cmdlvl too deep","",cmdlvl); cmdlvl--; printf("?TAKE files and DO commands nested too deeply\n"); return(0); } #ifdef DEBUG if (deblog) { debug(F111,"CMD +M",mactab[x].kwd,cmdlvl); debug(F010,"CMD ->",s,0); } #endif /* DEBUG */ #ifdef VMS conres(); /* So Ctrl-C, etc, will work. */ #endif /* VMS */ #ifndef NOLOCAL #ifdef OS2 term_io = 0; /* Disable terminal emulator I/O */ #endif /* OS2 */ #endif /* NOLOCAL */ ifcmd[cmdlvl] = 0; iftest[cmdlvl] = 0; count[cmdlvl] = count[cmdlvl-1]; /* Inherit COUNT from previous level */ intime[cmdlvl] = intime[cmdlvl-1]; /* Inherit previous INPUT TIMEOUT */ inpcas[cmdlvl] = inpcas[cmdlvl-1]; /* and INPUT CASE */ takerr[cmdlvl] = takerr[cmdlvl-1]; /* and TAKE ERROR */ merror[cmdlvl] = merror[cmdlvl-1]; /* and MACRO ERROR */ xquiet[cmdlvl] = quiet; xvarev[cmdlvl] = vareval; xcmdsrc = CMD_MD; cmdstk[cmdlvl].src = CMD_MD; /* Say we're in a macro */ cmdstk[cmdlvl].lvl = maclvl; /* and remember the macro level */ cmdstk[cmdlvl].ccflgs = flags & ~CF_IMAC; /* Set flags */ /* Initialize return value except in FOR, WHILE, IF, and SWITCH macros */ if (!(flags & CF_IMAC) && mrval[maclvl]) { free(mrval[maclvl]); mrval[maclvl] = NULL; } /* Clear old %0..%9 arguments */ addmac("%0",mactab[x].kwd); /* Define %0 = name of macro */ makestr(&(m_xarg[maclvl][0]),mactab[x].kwd); varnam[0] = '%'; varnam[2] = '\0'; tra_asg = 0; for (y = 1; y < 10; y++) { /* Clear args %1..%9 */ if (m_arg[maclvl][y]) { /* Don't call delmac() unless */ varnam[1] = (char) (y + '0'); /* we have to... */ delmac(varnam,0); } } tra_asg = tra_tmp; /* Break the big "s" string up into macro arguments */ xwords(s,MAXARGLIST,NULL,0); #ifndef NOLOCAL #ifdef OS2 term_io = term_io_sav; #endif /* OS2 */ #endif /* NOLOCAL */ if (tra_cmd) printf("[%d] +M: \"%s\"\n",cmdlvl,mactab[x].kwd); return(1); } /* Insert "literal" quote around each comma-separated command to prevent */ /* its premature expansion. Only do this if object command is surrounded */ /* by braces. */ static char* flit = "\\flit("; int litcmd(src,dest,n) char **src, **dest; int n; { int bc = 0, pp = 0; char c, *s, *lp, *ss; s = *src; lp = *dest; debug(F010,"litcmd",s,0); while (*s == SP) s++; /* Strip extra leading spaces */ if (*s == '{') { /* Starts with brace */ pp = 0; /* Paren counter */ bc = 1; /* Count leading brace */ *lp++ = *s++; /* Copy it */ if (--n < 1) return(-1); /* Check space */ while (*s == SP) s++; /* Strip interior leading spaces */ ss = flit; /* Point to "\flit(" */ while ((*lp++ = *ss++)) /* Copy it */ if (--n < 1) /* and check space */ return(-1); lp--; /* Back up over null */ while (*s) { /* Go thru rest of text */ c = *s; if (c == '{') bc++; /* Count brackets */ if (c == '(') pp++; /* and parens */ if (c == ')') { /* Right parenthesis. */ pp--; /* Count it. */ if (pp < 0) { /* An unbalanced right paren... */ #ifdef COMMENT /* The problem here is that "\{" appears to be a quoted brace and therefore isn't counted; then the "}" matches an earlier opening brace, causing (e.g.) truncation of macros by getncm(). */ if (n < 5) /* Out of space in dest buffer? */ return(-1); /* If so, give up. */ *lp++ = CMDQ; /* Must be quoted to prevent */ *lp++ = '}'; /* premature termination of */ *lp++ = '4'; /* \flit(...) */ *lp++ = '1'; *lp++ = '}'; n -= 5; #else /* Here we rely on the fact the \nnn never takes more than 3 digits */ if (n < 4) /* Out of space in dest buffer? */ return(-1); /* If so, give up. */ *lp++ = CMDQ; /* Must be quoted to prevent */ *lp++ = '0'; /* premature termination of */ *lp++ = '4'; /* \flit(...) */ *lp++ = '1'; n -= 4; #endif /* COMMENT */ pp++; /* Uncount it. */ s++; continue; } } if (c == '}') { /* Closing brace. */ if (--bc == 0) { /* Final one? */ *lp++ = ')'; /* Add closing paren for "\flit()" */ if (--n < 1) return(-1); *lp++ = c; if (--n < 1) return(-1); s++; break; } } *lp++ = c; /* General case */ if (--n < 1) return(-1); s++; } *lp = NUL; } else { /* No brackets around, */ while ((*lp++ = *s++)) /* just copy. */ if (--n < 1) return(-1); lp--; } *src = s; /* Return updated source */ *dest = lp; /* and destination pointers */ if (bc) /* Fail if braces unbalanced */ return(-1); else /* Otherwise succeed. */ return(0); } #endif /* NOSPL */ /* Functions moved here from ckuusr.c to even out the module sizes... */ /* Breaks up string s -- IN PLACE! -- into a list of up to max words. Pointers to each word go into the array list[]. max is the maximum number of words (pointers). If list is NULL, then they are added to the macro table. flag = 0 means the last field is to be one word, like all the other fields, so anything after it is discarded. flag = 1 means the last field extends to the end of the string, even if there are lots of words left, so the last field contains the remainder of the string. */ VOID xwords(s,max,list,flag) char *s; int max; char *list[]; int flag; { char *p; int b, i, k, q, y, z; int macro = 0; if (!list) { debug(F100," xwords list is NULL","",0); macro = 1; } else { debug(F100," xwords LIST is defined","",0); } debug(F100,"xwords ENTRY","",0); #ifndef NOSPL /* debug(F110," xwords macro",(char *)m_xarg[maclvl][0],0); */ debug(F101," xwords maclvl","",maclvl); debug(F101," xwords max","",max); debug(F101," xwords flag","",flag); debug(F110," xwords string",s,0); debug(F101," xwords macro","",macro); #endif /* NOSPL */ p = s; /* Pointer to beginning of string */ q = 0; /* Flag for doublequote removal */ b = 0; /* Flag for outer brace removal */ k = 0; /* Flag for in-word */ y = 0; /* Brace nesting level */ z = 0; /* "Word" counter, 0 thru max */ if (!s) s = ""; /* Nothing to do */ if (!*s) return; if (list) for (i = 0; i <= max; i++) /* Initialize pointers */ list[i] = NULL; if (flag) max--; #ifndef NOSPL /* Macro arguments at this point are a single string... must split it up. As of C-Kermit 9.0.304 Dev.22, 24 April 2017, we use cksplit() for this instead of tons of messy code in xwords() written decades ago to do what cksplit() does better. */ if (macro) { struct stringarray * q = NULL; char **pp = NULL; int n; if (maclvl < 0) { debug(F101," xwords maclvl < 0","",maclvl); newerrmsg("Internal error: maclvl < 0"); } debug(F101," xwords splitting macro arguments.. maclvl","",maclvl); /* Space is the only separator; grouping is with "" or {} */ q = cksplit(1,0,p," ","ALL",1+2,0,0,1); z = q->a_size; /* Number of "words" in string */ if (z <= 0) return; pp = q->a_head; if (pp) { /* In C-Kermit 9.0.304 Dev.22, April 2017, we have to get the macro arguments from the previous macro level (prev). Up to now, the macro arguments were evaluated when the DO command was parsed, before dodo() or xwords() were ever called. Now we're evaluating them after already entering the new macro stack level: evalmacroarg() is just a front end for zzstring(), which is at the heart of all variable-substitution operations. To evaluate a \%1-9 variable, zzstring() looks in the CURRENT macro stack frame. Rather than mess with zzstring(), I set maclvl back before calling evalmacroarg() and restore it immediately afterward. It's the only safe way to do this, Because zzstring() has no way of knowing whether (say) \%1 is on the DO command line or in some other context. */ debug(F101," xwords macro cksplit items","",z); if (z > max) z = max; for (i = 1; i <= z; i++) { /* Loop through macro arguments. */ p = pp[i]; debug(F111," xwords arg i",p,i); maclvl--; /* Get argument from previous level */ evalmacroarg(&p); /* Evaluate it */ maclvl++; /* Use its value on currentlevel */ debug(F111," xwords arg i evaluated",p,i); makestr(&(m_xarg[maclvl][i]),p); if (i < 10) { varnam[1] = (char) (i + '0'); /* Assign last arg */ addmac(varnam,p); debug(F111," xwords arg name",varnam,maclvl); debug(F111," xwords def def ",p,maclvl); } } /* Handle argc and the dimension of the \&_[] arg vector array */ if (maclvl < 0) { /* (How can this be?) */ a_dim[0] = z; /* Array dimension is one less */ topargc = z + 1; /* than \v(argc) */ debug(F111," xwords a_dim[0]","IMPOSSIBLE",a_dim[0]); } else { macargc[maclvl] = z + 1; /* Set \v(argc) variable */ n_xarg[maclvl] = z + 1; /* This is the actual number */ a_ptr[0] = m_xarg[maclvl]; /* Point \&_[] at the args */ a_dim[0] = z; /* And give it this dimension */ debug(F111," xwords a_dim[0]","E",a_dim[0]); } } return; } #endif /* NOSPL */ /* Not macro args, some other kind of list. This whole mess could be a cksplit() call... */ while (1) { /* Go thru word list */ if (!s || (*s == '\0')) { /* No more characters? */ if (k != 0) { /* Was I in a word? */ if (z == max) break; /* Yes, only go up to max. */ z++; /* Count this word. */ list[z] = p; /* Assign pointer. */ debug(F111," xwords list item p z",p,z); } break; /* And get out. */ } if (k == 0 && (*s == SP || *s == HT)) { /* Eat leading blanks */ s++; continue; } else if (q == 0 && *s == '{') { /* An opening brace */ if (k == 0 && y == 0) { /* If leading brace */ p = s+1; /* point past it */ b = 1; /* and flag that we did this */ } k = 1; /* Flag that we're in a word */ y++; /* Count the brace. */ } else if (q == 0 && *s == '}') { /* A closing brace. */ y--; /* Count it. */ if (y <= 0 && b != 0) { /* If it matches the leading brace */ char c; c = *(s+1); if (!c || c == SP || c == HT) { /* at EOL or followed by SP */ *s = SP; /* change it to a space */ b = 0; /* and we're not in braces any more */ } } #ifdef DOUBLEQUOTING /* Opening doublequote */ } else if (k == 0 && b == 0 && *s == '"' && dblquo) { y++; p = s+1; /* point past it */ q = 1; /* and flag that we did this */ k = 1; /* Flag that we're in a word */ /* Closing double quote */ } else if (q > 0 && k > 0 && b == 0 && *s == '"' && dblquo) { char c; c = *(s+1); if (!c || c == SP || c == HT) { /* at EOL or followed by SP */ y--; *s = SP; /* change it to a space */ q = 0; /* and we're not in quotes any more */ } #endif /* DOUBLEQUOTING */ } else if (*s != SP && *s != HT) { /* Nonspace means we're in a word */ if (k == 0) { /* If we weren't in a word before, */ p = s; /* Mark the beginning */ if (flag && z == max) { /* Want last word to be remainder? */ z++; list[z] = p; /* Yes, point to it */ break; /* and quit */ } k = 1; /* Set in-word flag */ } } /* If we're not inside a braced quantity, and we are in a word, and */ /* we have hit whitespace, then we have a word. */ if ((y < 1) && (k != 0) && (*s == SP || *s == HT) && !b) { if (!flag || z < max) /* if we don't want to keep rest */ *s = '\0'; /* terminate the arg with null */ k = 0; /* say we're not in a word any more */ y = 0; /* start braces off clean again */ if (z == max) break; /* Only go up to max. */ z++; /* count this arg */ list[z] = p; p = s+1; } s++; /* Point past this character */ } if ((z == 0) && (y > 1)) { /* Extra closing brace(s) at end */ z++; list[z] = p; } return; } #ifndef NOSPL /* D O S H I F T -- Do the SHIFT Command; shift macro args left by n */ /* Note: at some point let's consolidate m_arg[][] and m_xarg[][]. */ int doshift(n) int n; { /* n = shift count */ int i, top, level; char /* *s, *m, */ buf[6]; /* Buffer to build scalar names */ char * sx = tmpbuf; int nx = TMPBUFSIZ; debug(F101,"SHIFT count","",n); debug(F101,"SHIFT topargc","",topargc); if (n < 1) /* Stay in range */ return(n == 0 ? 1 : 0); level = maclvl; top = (level < 0) ? topargc : macargc[level]; if (n >= top) n = top - 1; #ifdef DEBUG if (deblog) { debug(F101,"SHIFT count 2","",n); debug(F101,"SHIFT level","",level); if (level > -1) debug(F101,"SHIFT macargc[level]","",macargc[level]); } #endif /* DEBUG */ buf[0] = '\\'; /* Initialize name template */ buf[1] = '%'; buf[2] = NUL; buf[3] = NUL; for (i = 1; i <= n; i++) { /* Free shifted-over args */ if (level < 0) { makestr(&(toparg[i]),NULL); } else { makestr(&(m_xarg[level][i]),NULL); } if (i < 10) { /* Is this necessary? */ buf[2] = (char)(i+'0'); delmac(buf,0); } } for (i = 1; i <= top-n; i++) { /* Shift remaining args */ if (level < 0) { #ifdef COMMENT toparg[i] = toparg[i+n]; /* Full vector */ #else makestr(&(toparg[i]),toparg[i+n]); /* Full vector */ #endif /* COMMENT */ if (i < 10) /* Scalars... */ makestr(&(g_var[i+'0']),toparg[i+n]); } else { #ifdef COMMENT m_xarg[level][i] = m_xarg[level][i+n]; #else makestr(&(m_xarg[level][i]),m_xarg[level][i+n]); #endif /* COMMENT */ if (i < 10) { buf[2] = (char)(i+'0'); debug(F010,"SHIFT buf",buf,0); addmac(buf,m_xarg[level][i+n]); } } } for (i = top-n; i <= top; i++) { /* Clear n args from the end */ if (level < 0) { #ifdef COMMENT toparg[i] = NULL; #else makestr(&(toparg[i]),NULL); #endif /* COMMENt */ if (i < 10) makestr(&(g_var[i+'0']),NULL); } else { #ifdef COMMENT m_xarg[level][i] = NULL; #else makestr(&(m_xarg[level][i]),NULL); #endif /* COMMENt */ if (i < 10) { buf[2] = (char)(i+'0'); delmac(buf,0); } } } if (level > -1) { /* Macro args */ macargc[level] -= n; /* Adjust count */ n_xarg[maclvl] = macargc[level]; /* Here too */ a_dim[0] = macargc[level] - 1; /* Adjust array dimension */ debug(F111,"a_dim[0]","F",a_dim[0]); zzstring("\\fjoin(&_[],{ },1)",&sx,&nx); /* Handle \%* */ #ifdef COMMENT makestr(&(m_line[level]),tmpbuf); #endif /* COMMENT */ } else { /* Ditto for top level */ topargc -= n; a_dim[0] = topargc - 1; debug(F111,"a_dim[0]","G",a_dim[0]); zzstring("\\fjoin(&_[],{ },1)",&sx,&nx); #ifdef COMMENT makestr(&topline,tmpbuf); #endif /* COMMENT */ } return(1); } #endif /* NOSPL */ int docd(cx) int cx; { /* Do the CD command */ int x; extern int server, srvcdmsg, cdactive; extern char * cdmsgfile[], * ckcdpath; char *s, *p; #ifdef MAC char temp[34]; #endif /* MAC */ #ifdef IKSDCONF extern int iksdcf; #endif /* IKSDCONF */ #ifndef NOFRILLS if (cx == XXBACK) { if ((x = cmcfm()) < 0) cwdf = 1; if (prevdir) { s = zgtdir(); if (!zchdir(prevdir)) { cwdf = 0; perror(s); } else { makestr(&prevdir,s); } } return(cwdf); } #endif /* NOFRILLS */ if (cx == XXCDUP) { #ifdef VMS s = "[-]"; #else #ifdef datageneral s = "^"; #else s = ".."; #endif /* datageneral */ #endif /* VMS */ ckstrncpy(line,s,LINBUFSIZ); goto gocd; } #ifndef NOSPL if (cx == XXKCD) { /* Symbolic (Kermit) CD */ char * p; int n, k; x = cmkey(kcdtab,nkcdtab,"Symbolic directory name","home",xxstring); if (x < 0) return(x); x = lookup(kcdtab,atmbuf,nkcdtab,&k); /* Get complete keyword */ if (x < 0) { printf("?Lookup error\n"); /* shouldn't happen */ return(-9); } if ((x = cmcfm()) < 0) return(x); if (k == VN_HOME) { /* HOME: allow SET HOME to override */ ckstrncpy(line,homepath(),LINBUFSIZ); } else { /* Other symbolic name */ /* Convert to variable syntax */ ckmakmsg(tmpbuf,TMPBUFSIZ,"\\v(",kcdtab[k].kwd,")",NULL); p = line; /* Expand the variable */ n = LINBUFSIZ; zzstring(tmpbuf,&p,&n); if (!line[0]) { /* Fail if variable not defined */ printf("?%s - not defined\n",tmpbuf); return(success = 0); } } s = line; /* All OK, go try to CD... */ goto gocd; } #endif /* NOSPL */ cdactive = 1; #ifdef GEMDOS if ((x = cmdir("Name of local directory, or carriage return", homepath(), &s, NULL ) ) < 0 ) return(x); #else #ifdef OS2 if ((x = cmdirp("Name of PC disk and/or directory,\n\ or press the Enter key for the default", homepath(), &s, ckcdpath ? ckcdpath : getenv("CDPATH"), xxstring ) ) < 0 ) return(x); #else #ifdef MAC x = ckstrncpy(temp,homepath(),32); if (x > 0) if (temp[x-1] != ':') { temp[x] = ':'; temp[x+1] = NUL; } if ((x = cmtxt("Name of Macintosh volume and/or folder,\n\ or press the Return key for the desktop on the boot disk", temp,&s, xxstring)) < 0 ) return(x); #else if ((x = cmdirp("Carriage return for home directory,\n\ or name of directory on this computer", #ifdef VMS "SYS$LOGIN", /* With no colon */ #else homepath(), /* In VMS this is "SYS$LOGIN:" */ #endif /* VMS */ &s, ckcdpath ? ckcdpath : getenv("CDPATH"), xxstring )) < 0) return(x); #endif /* MAC */ #endif /* OS2 */ #endif /* GEMDOS */ ckstrncpy(line,s,LINBUFSIZ); /* Make a safe copy */ s = line; #ifdef VMS if (ckmatch("*.DIR;1$",s,0,0)) if (cvtdir(s,tmpbuf,TMPBUFSIZ) > 0) s = tmpbuf; #endif /* VMS */ debug(F110,"docd",s,0); #ifndef MAC if ((x = cmcfm()) < 0) /* Get confirmation */ return(x); #endif /* MAC */ gocd: #ifdef datageneral x = strlen(line); /* homdir ends in colon, */ if (x > 1 && line[x-1] == ':') /* and "dir" doesn't like that... */ line[x-1] = NUL; #endif /* datageneral */ #ifdef MAC cwdf = 1; if (!zchdir(s)) { cwdf = 0; if (*s != ':') { /* If it failed, */ char *p; /* supply leading colon */ int len = (int)strlen(s) + 2; p = malloc(len); /* and try again... */ if (p) { strcpy(p,":"); /* safe */ strcat(p,s); /* safe */ if (zchdir(p)) cwdf = 1; free(p); p = NULL; } } } if (!cwdf) perror(s); #else p = zgtdir(); if (!zchdir(s)) { cwdf = 0; #ifdef CKROOT if (ckrooterr) printf("?Off limits: \"%s\"\n",s); else #endif /* CKROOT */ perror(s); } else cwdf = 1; #endif /* MAC */ x = 0; if (cwdf) { makestr(&prevdir,p); debug(F111,"docd","srvcdmsg",srvcdmsg); if (srvcdmsg #ifdef IKSDCONF && !(inserver && !iksdcf) #endif /* IKSDCONF */ ) { int i; for (i = 0; i < 8; i++) { debug(F111,"docd cdmsgfile[i]",cdmsgfile[i],i); if (zchki(cdmsgfile[i]) > -1) { x = 1; dotype(cdmsgfile[i],xaskmore,0,0,NULL,0,NULL,0,0,NULL,0); break; } } } } /* xdocd: */ if (!x && srvcdmsg && !server #ifdef IKSDCONF && !(inserver && !iksdcf) #endif /* IKSDCONF */ && !quiet && !xcmdsrc) printf("%s\n", zgtdir()); return(cwdf); } static int on_ctrlc = 0; VOID fixcmd() { /* Fix command parser after interruption */ #ifndef NOSPL #ifndef NOONCTRLC if (nmac) { /* Any macros defined? */ int k; /* Yes */ char * s = "on_ctrlc"; /* Name of Ctrl-C handling macro */ k = mlook(mactab,s,nmac); /* Look it up. */ if (k >= 0) { /* If found, */ if (on_ctrlc++ == 0) { /* if not already executing, */ if (dodo(k,"",0) > -1) /* set it up, */ parser(1); /* execute it, */ } delmac(s,1); /* and undefine it. */ } } on_ctrlc = 0; #endif /* NOONCTRLC */ #endif /* NOSPL */ dostop(); /* Back to top level (also calls conint()). */ bgchk(); /* Check background status */ if (*psave) { /* If old prompt saved, */ cmsetp(psave); /* restore it. */ *psave = NUL; } success = 0; /* Tell parser last command failed */ } #ifndef NOSHOW /* SHOW FEATURES */ /* Note, presently optlist[] index overflow is not checked. There is plenty of room (less than 360 entries for 1000 slots). When space starts to get tight, check for noptlist >= NOPTLIST every time noptlist is incremented. */ #define NOPTLIST 1024 static int noptlist = 0; static char * optlist[NOPTLIST+1]; static int hpos = 0; int prtopt(lines,s) int * lines; char *s; { /* Print an option */ int y, i; /* Does word wrap. */ if (!s) s = ""; i = *lines; if (!*s) { /* Empty argument */ if (hpos > 0) { /* means to end this line. */ printf("\n"); /* Not needed if already at */ if (++i > (cmd_rows - 3)) { /* beginning of new line. */ if (!askmore()) return(0); else i = 0; } } printf("\n"); /* And then make a blank line */ if (++i > (cmd_rows - 3)) { if (!askmore()) return(0); else i = 0; } hpos = 0; *lines = i; return(1); } y = (int)strlen(s) + 1; hpos += y; debug(F101,"prtopt hpos","",hpos); debug(F101,"prtopt cmd_cols","",cmd_cols); if ( #ifdef OS2 hpos > ((cmd_cols > 40) ? (cmd_cols - 1) : 79) #else /* OS2 */ hpos > ((tt_cols > 40) ? (tt_cols - 1) : 79) #endif /* OS2 */ ) { printf("\n"); if (++i > (cmd_rows - 3)) { if (!askmore()) return(0); else i = 0; } printf(" %s",s); hpos = y; } else printf(" %s",s); *lines = i; return(1); } static VOID initoptlist() { int i; if (noptlist > 0) return; for (i = 0; i < NOPTLIST; i++) optlist[i] = NULL; #ifdef MAC #ifdef MPW makestr(&(optlist[noptlist++]),"MPW"); #endif /* MPW */ #endif /* MAC */ #ifdef MAC #ifdef THINK_C makestr(&(optlist[noptlist++]),"THINK_C"); #endif /* THINK_C */ #endif /* MAC */ #ifdef __386__ makestr(&(optlist[noptlist++]),"__386__"); #endif /* __386__ */ /* Memory models... */ #ifdef __FLAT__ makestr(&(optlist[noptlist++]),"__FLAT__"); #endif /* __FLAT__ */ #ifdef __SMALL__ makestr(&(optlist[noptlist++]),"__SMALL__"); #endif /* __SMALL__ */ #ifdef __MEDIUM__ makestr(&(optlist[noptlist++]),"__MEDIUM__"); #endif /* __MEDIUM__ */ #ifdef __COMPACT__ makestr(&(optlist[noptlist++]),"__COMPACT__"); #endif /* __COMPACT__ */ #ifdef __LARGE__ makestr(&(optlist[noptlist++]),"__LARGE__"); #endif /* __LARGE__ */ #ifdef DEBUG #ifdef IFDEBUG makestr(&(optlist[noptlist++]),"IFDEBUG"); #else makestr(&(optlist[noptlist++]),"DEBUG"); #endif /* IFDEBUG */ #endif /* DEBUG */ #ifdef TLOG makestr(&(optlist[noptlist++]),"TLOG"); #endif /* TLOG */ #ifdef BIGBUFOK makestr(&(optlist[noptlist++]),"BIGBUFOK"); #endif /* BIGBUFOK */ #ifdef INPBUFSIZ sprintf(line,"INPBUFSIZ=%d",INPBUFSIZ); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* INPBUFSIZE */ #ifdef LINBUFSIZ sprintf(line,"LINBUFSIZ=%d",LINBUFSIZ); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* LINBUFSIZE */ #ifdef INBUFSIZE sprintf(line,"INBUFSIZE=%d",INBUFSIZE); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* INBUFSIZE */ #ifdef OBUFSIZE sprintf(line,"OBUFSIZE=%d",OBUFSIZE); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* OBUFSIZE */ #ifdef FD_SETSIZE sprintf(line,"FD_SETSIZE=%d",FD_SETSIZE); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* FD_SETSIZE */ #ifdef XFRCAN makestr(&(optlist[noptlist++]),"XFRCAN"); #endif /* XFRCAN */ #ifdef XPRINT makestr(&(optlist[noptlist++]),"XPRINT"); #endif /* XPRINT */ #ifdef PIPESEND makestr(&(optlist[noptlist++]),"PIPESEND"); #endif /* PIPESEND */ #ifdef CK_SPEED makestr(&(optlist[noptlist++]),"CK_SPEED"); #endif /* CK_SPEED */ #ifdef CK_FAST makestr(&(optlist[noptlist++]),"CK_FAST"); #endif /* CK_FAST */ #ifdef CK_APC makestr(&(optlist[noptlist++]),"CK_APC"); #endif /* CK_APC */ #ifdef CK_AUTODL makestr(&(optlist[noptlist++]),"CK_AUTODL"); #endif /* CK_AUTODL */ #ifdef CK_MKDIR makestr(&(optlist[noptlist++]),"CK_MKDIR"); #endif /* CK_MKDIR */ #ifdef HAVE_LOCALE makestr(&(optlist[noptlist++]),"HAVE_LOCALE"); #endif /* HAVE_LOCALE */ #ifdef HAVE_SNPRINTF makestr(&(optlist[noptlist++]),"HAVE_SNPRINTF"); #endif /* HAVE_SNPRINTF */ #ifdef NOMKDIR makestr(&(optlist[noptlist++]),"NOMKDIR"); #endif /* NOMKDIR */ #ifdef CK_LABELED makestr(&(optlist[noptlist++]),"CK_LABELED"); #endif /* CK_LABELED */ #ifdef NODIAL makestr(&(optlist[noptlist++]),"NODIAL"); #endif /* NODIAL */ #ifdef MINIDIAL makestr(&(optlist[noptlist++]),"MINIDIAL"); #endif /* MINIDIAL */ #ifdef WHATAMI makestr(&(optlist[noptlist++]),"WHATAMI"); #endif /* WHATAMI */ #ifdef DYNAMIC makestr(&(optlist[noptlist++]),"DYNAMIC"); #endif /* DYNAMIC */ #ifndef NOSPL sprintf(line,"CMDDEP=%d",CMDDEP); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* NOSPL */ #ifdef MAXPATHLEN sprintf(line,"MAXPATHLEN=%d",MAXPATHLEN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXPATHLEN */ #ifdef DEVNAMLEN sprintf(line,"DEVNAMLEN=%d",DEVNAMLEN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* DEVNAMLEN */ #ifdef NO_PARAM_H makestr(&(optlist[noptlist++]),"NO_PARAM_H"); #endif /* NO_PARAM_H */ #ifdef INCL_PARAM_H makestr(&(optlist[noptlist++]),"INCL_PARAM_H"); #endif /* INCL_PARAM_H */ #ifdef CKMAXPATH sprintf(line,"CKMAXPATH=%d",CKMAXPATH); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* CKMAXPATH */ sprintf(line,"CKMAXOPEN=%d",CKMAXOPEN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #ifndef UNIX /* These aren't actually used... In Unix we get maximum number of open files from sysconf() at runtime. */ sprintf(line,"Z_MAXCHAN=%d",Z_MAXCHAN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #ifdef OPEN_MAX sprintf(line,"OPEN_MAX=%d",OPEN_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* OPEN_MAX */ #ifdef _POSIX_OPEN_MAX sprintf(line,"_POSIX_OPEN_MAX=%d",_POSIX_OPEN_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* _POSIX_OPEN_MAX */ #endif /* UNIX */ #ifdef CKCHANNELIO { extern int z_maxchan; #ifdef UNIX extern int ckmaxfiles; sprintf(line,"ckmaxfiles=%d",ckmaxfiles); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* UNIX */ sprintf(line,"z_maxchan=%d",z_maxchan); /* SAFE */ makestr(&(optlist[noptlist++]),line); } #endif /* CKCHANNELIO */ #ifdef FOPEN_MAX sprintf(line,"FOPEN_MAX=%d",FOPEN_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* FOPEN_MAX */ #ifdef MAXGETPATH sprintf(line,"MAXGETPATH=%d",MAXGETPATH); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXGETPATH */ #ifdef CMDBL sprintf(line,"CMDBL=%d",CMDBL); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* CMDBL */ #ifdef VNAML sprintf(line,"VNAML=%d",VNAML); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* VNAML */ #ifdef ARRAYREFLEN sprintf(line,"ARRAYREFLEN=%d",ARRAYREFLEN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* ARRAYREFLEN */ #ifdef UIDBUFLEN sprintf(line,"UIDBUFLEN=%d",UIDBUFLEN); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* UIDBUFLEN */ #ifdef FORDEPTH sprintf(line,"FORDEPTH=%d",FORDEPTH); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* FORDEPTH */ #ifdef MAXTAKE sprintf(line,"MAXTAKE=%d",MAXTAKE); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXTAKE */ #ifdef MACLEVEL sprintf(line,"MACLEVEL=%d",MACLEVEL); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MACLEVEL */ #ifdef MAC_MAX sprintf(line,"MAC_MAX=%d",MAC_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAC_MAX */ #ifdef _LARGEFILE_SOURCE makestr(&(optlist[noptlist++]),"_LARGEFILE_SOURCE"); #endif /* _LARGEFILE_SOURCE */ #ifdef _FILE_OFFSET_BITS sprintf(line,"_FILE_OFFSET_BITS=%d",_FILE_OFFSET_BITS); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* _FILE_OFFSET_BITS */ #ifdef __USE_FILE_OFFSET64 makestr(&(optlist[noptlist++]),"__USE_FILE_OFFSET64"); #endif /* __USE_FILE_OFFSET64 */ #ifdef __USE_LARGEFILE64 makestr(&(optlist[noptlist++]),"__USE_LARGEFILE64"); #endif /* __USE_LARGEFILE64 */ #ifdef COMMENT #ifdef CHAR_MAX sprintf(line,"CHAR_MAX=%llx",CHAR_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* CHAR_MAX */ #ifdef UCHAR_MAX sprintf(line,"UCHAR_MAX=%llx",UCHAR_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* UCHAR_MAX */ #ifdef SHRT_MAX sprintf(line,"SHRT_MAX=%llx",SHRT_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* SHRT_MAX */ #ifdef USHRT_MAX sprintf(line,"USHRT_MAX=%llx",USHRT_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* USHRT_MAX */ #ifdef INT_MAX sprintf(line,"INT_MAX=%llx",INT_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* INT_MAX */ #ifdef UINT_MAX sprintf(line,"UINT_MAX=%llx",UINT_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* UINT_MAX */ #ifdef MAX_LONG sprintf(line,"MAX_LONG=%llx",MAX_LONG); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAX_LONG */ #ifdef LONG_MAX sprintf(line,"LONG_MAX=%llx",LONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* LONG_MAX */ #ifdef ULONG_MAX sprintf(line,"ULONG_MAX=%llx",ULONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* ULONG_MAX */ #ifdef MAXINT sprintf(line,"MAXINT=%llx",MAXINT); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXINT */ #ifdef MAXLONG sprintf(line,"MAXLONG=%llx",MAXLONG); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXLONG */ #ifdef NT #ifdef LLONG_MAX sprintf(line,"LLONG_MAX=%I64x",LLONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* LLONG_MAX */ #ifdef ULLONG_MAX sprintf(line,"ULLONG_MAX=%I64x",ULLONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* ULLONG_MAX */ #ifdef MAXLONGLONG sprintf(line,"MAXLONGLONG=%I64x",MAXLONGLONG); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXLONGLONG */ #else #ifdef LLONG_MAX sprintf(line,"LLONG_MAX=%llx",LLONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* LLONG_MAX */ #ifdef ULLONG_MAX sprintf(line,"ULLONG_MAX=%llx",ULLONG_MAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* ULLONG_MAX */ #ifdef MAXLONGLONG sprintf(line,"MAXLONGLONG=%llx",MAXLONGLONG); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXLONGLONG */ #endif #ifdef _INTEGRAL_MAX_BITS sprintf(line,"_INTEGRAL_MAX_BITS=%d",_INTEGRAL_MAX_BITS); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* _INTEGRAL_MAX_BITS */ #endif /* COMMENT */ #ifdef MINPUTMAX sprintf(line,"MINPUTMAX=%d",MINPUTMAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MINPUTMAX */ #ifdef MAXWLD sprintf(line,"MAXWLD=%d",MAXWLD); /* SAFE */ makestr(&(optlist[noptlist++]),line); #else #ifdef OS2 makestr(&(optlist[noptlist++]),"MAXWLD=unlimited"); #endif /* OS2 */ #endif /* MAXWLD */ #ifdef MSENDMAX sprintf(line,"MSENDMAX=%d",MSENDMAX); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MSENDMAX */ #ifdef MAXDDIR sprintf(line,"MAXDDIR=%d",MAXDDIR); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXDDIR */ #ifdef MAXDNUMS sprintf(line,"MAXDNUMS=%d",MAXDNUMS); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* MAXDNUMS */ #ifdef UNIX makestr(&(optlist[noptlist++]),"UNIX"); #endif /* UNIX */ #ifdef VMS makestr(&(optlist[noptlist++]),"VMS"); #ifdef __VMS_VER sprintf(line,"__VMS_VER=%d",__VMS_VER); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* __VMS_VER */ #ifdef VMSV70 makestr(&(optlist[noptlist++]),"VMSV70"); #endif /* VMSV70 */ #ifdef OLD_VMS makestr(&(optlist[noptlist++]),"OLD_VMS"); #endif /* OLD_VMS */ #ifdef vms makestr(&(optlist[noptlist++]),"vms"); #endif /* vms */ #ifdef VMSV60 makestr(&(optlist[noptlist++]),"VMSV60"); #endif /* VMSV60 */ #ifdef VMSV80 makestr(&(optlist[noptlist++]),"VMSV80"); #endif /* VMSV80 */ #ifdef VMSSHARE makestr(&(optlist[noptlist++]),"VMSSHARE"); #endif /* VMSSHARE */ #ifdef NOVMSSHARE makestr(&(optlist[noptlist++]),"NOVMSSHARE"); #endif /* NOVMSSHARE */ #endif /* VMS */ #ifdef datageneral makestr(&(optlist[noptlist++]),"datageneral"); #endif /* datageneral */ #ifdef apollo makestr(&(optlist[noptlist++]),"apollo"); #endif /* apollo */ #ifdef aegis makestr(&(optlist[noptlist++]),"aegis"); #endif /* aegis */ #ifdef A986 makestr(&(optlist[noptlist++]),"A986"); #endif /* A986 */ #ifdef AMIGA makestr(&(optlist[noptlist++]),"AMIGA"); #endif /* AMIGA */ #ifdef CONVEX9 makestr(&(optlist[noptlist++]),"CONVEX9"); #endif /* CONVEX9 */ #ifdef CONVEX10 makestr(&(optlist[noptlist++]),"CONVEX10"); #endif /* CONVEX9 */ #ifdef MAC makestr(&(optlist[noptlist++]),"MAC"); #endif /* MAC */ #ifdef AUX makestr(&(optlist[noptlist++]),"AUX"); #endif /* AUX */ #ifdef OS2 makestr(&(optlist[noptlist++]),"OS2"); #ifdef NT makestr(&(optlist[noptlist++]),"NT"); #endif /* NT */ #endif /* OS2 */ #ifdef OSK makestr(&(optlist[noptlist++]),"OS9"); #endif /* OSK */ #ifdef MSDOS makestr(&(optlist[noptlist++]),"MSDOS"); #endif /* MSDOS */ #ifdef DIRENT makestr(&(optlist[noptlist++]),"DIRENT"); #endif /* DIRENT */ #ifdef SDIRENT makestr(&(optlist[noptlist++]),"SDIRENT"); #endif /* SDIRENT */ #ifdef NDIR makestr(&(optlist[noptlist++]),"NDIR"); #endif /* NDIR */ #ifdef XNDIR makestr(&(optlist[noptlist++]),"XNDIR"); #endif /* XNDIR */ #ifdef SAVEDUID makestr(&(optlist[noptlist++]),"SAVEDUID"); #endif /* SAVEDUID */ #ifdef RENAME makestr(&(optlist[noptlist++]),"RENAME"); #endif /* RENAME */ #ifdef CK_TMPDIR makestr(&(optlist[noptlist++]),"CK_TMPDIR"); #endif /* CK_TMPDIR */ #ifdef NOCCTRAP makestr(&(optlist[noptlist++]),"NOCCTRAP"); #endif /* NOCCTRAP */ #ifdef NOCOTFMC makestr(&(optlist[noptlist++]),"NOCOTFMC"); #endif /* NOCOTFMC */ #ifdef NOFRILLS makestr(&(optlist[noptlist++]),"NOFRILLS"); #endif /* NOFRILLS */ #ifdef PARSENSE makestr(&(optlist[noptlist++]),"PARSENSE"); #endif /* PARSENSE */ #ifdef TIMEH makestr(&(optlist[noptlist++]),"TIMEH"); #endif /* TIMEH */ #ifdef NOTIMEH makestr(&(optlist[noptlist++]),"TIMEH"); #endif /* NOTIMEH */ #ifdef SYSTIMEH makestr(&(optlist[noptlist++]),"SYSTIMEH"); #endif /* SYSTIMEH */ #ifdef NOSYSTIMEH makestr(&(optlist[noptlist++]),"SYSTIMEH"); #endif /* NOSYSTIMEH */ #ifdef SYSTIMEBH makestr(&(optlist[noptlist++]),"SYSTIMEBH"); #endif /* SYSTIMEBH */ #ifdef NOSYSTIMEBH makestr(&(optlist[noptlist++]),"SYSTIMEBH"); #endif /* NOSYSTIMEBH */ #ifdef UTIMEH makestr(&(optlist[noptlist++]),"UTIMEH"); #endif /* UTIMEH */ #ifdef SYSUTIMEH makestr(&(optlist[noptlist++]),"SYSUTIMEH"); #endif /* SYSUTIMEH */ #ifdef CK_NEED_SIG makestr(&(optlist[noptlist++]),"CK_NEED_SIG"); #endif /* CK_NEED_SIG */ #ifdef CK_TTYFD makestr(&(optlist[noptlist++]),"CK_TTYFD"); #endif /* CK_TTYFD */ #ifdef NETCONN makestr(&(optlist[noptlist++]),"NETCONN"); #endif /* NETCONN */ #ifdef TCPSOCKET makestr(&(optlist[noptlist++]),"TCPSOCKET"); #ifdef NOTCPOPTS makestr(&(optlist[noptlist++]),"NOTCPOPTS"); #endif /* NOTCPOPTS */ #ifdef CK_DNS_SRV makestr(&(optlist[noptlist++]),"CK_DNS_SRV"); #endif /* CK_DNS_SRV */ #ifdef NO_DNS_SRV makestr(&(optlist[noptlist++]),"NO_DNS_SRV"); #endif /* NO_DNS_SRV */ #ifdef CKGHNLHOST makestr(&(optlist[noptlist++]),"CKGHNLHOST"); #endif /* CKGHNLHOST */ #ifdef NOLISTEN makestr(&(optlist[noptlist++]),"NOLISTEN"); #endif /* NOLISTEN */ #ifdef SOL_SOCKET makestr(&(optlist[noptlist++]),"SOL_SOCKET"); #endif /* SOL_SOCKET */ #ifdef SO_OOBINLINE makestr(&(optlist[noptlist++]),"SO_OOBINLINE"); #endif /* SO_OOBINLNE */ #ifdef SO_DONTROUTE makestr(&(optlist[noptlist++]),"SO_DONTROUTE"); #endif /* SO_DONTROUTE */ #ifdef SO_KEEPALIVE makestr(&(optlist[noptlist++]),"SO_KEEPALIVE"); #endif /* SO_KEEPALIVE */ #ifdef SO_LINGER makestr(&(optlist[noptlist++]),"SO_LINGER"); #endif /* SO_LINGER */ #ifdef TCP_NODELAY makestr(&(optlist[noptlist++]),"TCP_NODELAY"); #endif /* TCP_NODELAY */ #ifdef SO_SNDBUF makestr(&(optlist[noptlist++]),"SO_SNDBUF"); #endif /* SO_SNDBUF */ #ifdef SO_RCVBUF makestr(&(optlist[noptlist++]),"SO_RCVBUF"); #endif /* SO_RCVBUF */ #ifdef h_addr makestr(&(optlist[noptlist++]),"h_addr"); #endif /* h_addr */ #ifdef HADDRLIST makestr(&(optlist[noptlist++]),"HADDRLIST"); #endif /* HADDRLIST */ #ifdef CK_SOCKS makestr(&(optlist[noptlist++]),"CK_SOCKS"); #ifdef CK_SOCKS5 makestr(&(optlist[noptlist++]),"CK_SOCKS5"); #endif /* CK_SOCKS5 */ #ifdef CK_SOCKS_NS makestr(&(optlist[noptlist++]),"CK_SOCKS_NS"); #endif /* CK_SOCKS_NS */ #endif /* CK_SOCKS */ #ifdef RLOGCODE makestr(&(optlist[noptlist++]),"RLOGCODE"); #endif /* RLOGCODE */ #ifdef NETCMD makestr(&(optlist[noptlist++]),"NETCMD"); #endif /* NETCMD */ #ifdef NONETCMD makestr(&(optlist[noptlist++]),"NONETCMD"); #endif /* NONETCMD */ #ifdef NETPTY makestr(&(optlist[noptlist++]),"NETPTY"); #endif /* NETPTY */ #ifdef CK_ENVIRONMENT makestr(&(optlist[noptlist++]),"CK_ENVIRONMENT"); #endif /* CK_ENVIRONMENT */ #endif /* TCPSOCKET */ #ifdef TNCODE makestr(&(optlist[noptlist++]),"TNCODE"); #endif /* TNCODE */ #ifdef CK_FORWARD_X makestr(&(optlist[noptlist++]),"CK_FORWARD_X"); #endif /* CK_FORWARD_X */ #ifdef TN_COMPORT makestr(&(optlist[noptlist++]),"TN_COMPORT"); #endif /* TN_COMPORT */ #ifdef MULTINET makestr(&(optlist[noptlist++]),"MULTINET"); #endif /* MULTINET */ #ifdef DEC_TCPIP makestr(&(optlist[noptlist++]),"DEC_TCPIP"); #endif /* DEC_TCPIP */ #ifdef TCPWARE makestr(&(optlist[noptlist++]),"TCPWARE"); #endif /* TCPWARE */ #ifdef UCX50 makestr(&(optlist[noptlist++]),"UCX50"); #endif /* UCX50 */ #ifdef CMU_TCPIP makestr(&(optlist[noptlist++]),"CMU_TCPIP"); #endif /* CMU_TCPIP */ #ifdef TTLEBUF makestr(&(optlist[noptlist++]),"TTLEBUF"); #endif /* TTLEBUF */ #ifdef NETLEBUF makestr(&(optlist[noptlist++]),"NETLEBUF"); #endif /* NETLEBUF */ #ifdef IKS_OPTION makestr(&(optlist[noptlist++]),"IKS_OPTION"); #endif /* IKS_OPTION */ #ifdef IKSDB makestr(&(optlist[noptlist++]),"IKSDB"); #endif /* IKSDB */ #ifdef IKSDCONF makestr(&(optlist[noptlist++]),"IKSDCONF"); #endif /* IKSDCONF */ #ifdef CK_LOGIN makestr(&(optlist[noptlist++]),"CK_LOGIN"); #endif /* CK_LOGIN */ #ifdef CK_PAM makestr(&(optlist[noptlist++]),"CK_PAM"); #endif /* CK_PAM */ #ifdef CK_SHADOW makestr(&(optlist[noptlist++]),"CK_SHADOW"); #endif /* CK_SHADOW */ #ifdef CONGSPD makestr(&(optlist[noptlist++]),"CONGSPD"); #endif /* CONGSPD */ #ifdef SUNX25 makestr(&(optlist[noptlist++]),"SUNX25"); #endif /* SUNX25 */ #ifdef IBMX25 makestr(&(optlist[noptlist++]),"IBMX25"); #endif /* IBMX25 */ #ifdef HPX25 makestr(&(optlist[noptlist++]),"HPX25"); #endif /* HPX25 */ #ifdef DECNET makestr(&(optlist[noptlist++]),"DECNET"); #endif /* DECNET */ #ifdef SUPERLAT makestr(&(optlist[noptlist++]),"SUPERLAT"); #endif /* SUPERLAT */ #ifdef NPIPE makestr(&(optlist[noptlist++]),"NPIPE"); #endif /* NPIPE */ #ifdef CK_NETBIOS makestr(&(optlist[noptlist++]),"CK_NETBIOS"); #endif /* CK_NETBIOS */ #ifdef ATT7300 makestr(&(optlist[noptlist++]),"ATT7300"); #endif /* ATT7300 */ #ifdef ATT6300 makestr(&(optlist[noptlist++]),"ATT6300"); #endif /* ATT6300 */ #ifdef HDBUUCP makestr(&(optlist[noptlist++]),"HDBUUCP"); #endif /* HDBUUCP */ #ifdef USETTYLOCK makestr(&(optlist[noptlist++]),"USETTYLOCK"); #endif /* USETTYLOCK */ #ifdef USE_UU_LOCK makestr(&(optlist[noptlist++]),"USE_UU_LOCK"); #endif /* USE_UU_LOCK */ #ifdef HAVE_LOCKDEV makestr(&(optlist[noptlist++]),"HAVE_LOCKDEV"); #endif /* HAVE_LOCKDEV */ #ifdef HAVE_BAUDBOY makestr(&(optlist[noptlist++]),"HAVE_BAUDBOY"); #endif /* HAVE_BAUDBOY */ #ifdef HAVE_OPENPTY makestr(&(optlist[noptlist++]),"HAVE_OPENPTY"); #endif /* HAVE_OPENPTY */ #ifdef TTPTYCMD makestr(&(optlist[noptlist++]),"TTPTYCMD"); #endif /* TTPTYCMD */ #ifdef NOUUCP makestr(&(optlist[noptlist++]),"NOUUCP"); #endif /* NOUUCP */ #ifdef LONGFN makestr(&(optlist[noptlist++]),"LONGFN"); #endif /* LONGFN */ #ifdef RDCHK makestr(&(optlist[noptlist++]),"RDCHK"); #endif /* RDCHK */ #ifdef SELECT makestr(&(optlist[noptlist++]),"SELECT"); #endif /* SELECT */ #ifdef USLEEP makestr(&(optlist[noptlist++]),"USLEEP"); #endif /* USLEEP */ #ifdef NAP makestr(&(optlist[noptlist++]),"NAP"); #endif /* NAP */ #ifdef NAPHACK makestr(&(optlist[noptlist++]),"NAPHACK"); #endif /* NAPHACK */ #ifdef CK_POLL makestr(&(optlist[noptlist++]),"CK_POLL"); #endif /* CK_POLL */ #ifdef NOIEXTEN makestr(&(optlist[noptlist++]),"NOIEXTEN"); #endif /* NOIEXTEN */ #ifdef EXCELAN makestr(&(optlist[noptlist++]),"EXCELAN"); #endif /* EXCELAN */ #ifdef INTERLAN makestr(&(optlist[noptlist++]),"INTERLAN"); #endif /* INTERLAN */ #ifdef NOFILEH makestr(&(optlist[noptlist++]),"NOFILEH"); #endif /* NOFILEH */ #ifdef NOSYSIOCTLH makestr(&(optlist[noptlist++]),"NOSYSIOCTLH"); #endif /* NOSYSIOCTLH */ #ifdef DCLPOPEN makestr(&(optlist[noptlist++]),"DCLPOPEN"); #endif /* DCLPOPEN */ #ifdef NOSETBUF makestr(&(optlist[noptlist++]),"NOSETBUF"); #endif /* NOSETBUF */ #ifdef NOXFER makestr(&(optlist[noptlist++]),"NOXFER"); #endif /* NOXFER */ #ifdef NOCURSES makestr(&(optlist[noptlist++]),"NOCURSES"); #endif /* NOCURSES */ #ifdef NOSERVER makestr(&(optlist[noptlist++]),"NOSERVER"); #endif /* NOSERVER */ #ifdef NOPATTERNS makestr(&(optlist[noptlist++]),"NOPATTERNS"); #else #ifdef PATTERNS makestr(&(optlist[noptlist++]),"PATTERNS"); #endif /* PATTERNS */ #endif /* NOPATTERNS */ #ifdef NOCKEXEC makestr(&(optlist[noptlist++]),"NOCKEXEC"); #else #ifdef CKEXEC makestr(&(optlist[noptlist++]),"CKEXEC"); #endif /* CKEXEC */ #endif /* NOCKEXEC */ #ifdef NOAUTODL makestr(&(optlist[noptlist++]),"NOAUTODL"); #endif /* NOAUTODL */ #ifdef NOMSEND makestr(&(optlist[noptlist++]),"NOMSEND"); #endif /* NOMSEND */ #ifdef NOFDZERO makestr(&(optlist[noptlist++]),"NOFDZERO"); #endif /* NOFDZERO */ #ifdef NOPOPEN makestr(&(optlist[noptlist++]),"NOPOPEN"); #endif /* NOPOPEN */ #ifdef NOPARTIAL makestr(&(optlist[noptlist++]),"NOPARTIAL"); #endif /* NOPARTIAL */ #ifdef NOKVERBS makestr(&(optlist[noptlist++]),"NOKVERBS"); #endif /* NOKVERBS */ #ifdef NOSETREU makestr(&(optlist[noptlist++]),"NOSETREU"); #endif /* NOSETREU */ #ifdef LCKDIR makestr(&(optlist[noptlist++]),"LCKDIR"); #endif /* LCKDIR */ #ifdef ACUCNTRL makestr(&(optlist[noptlist++]),"ACUCNTRL"); #endif /* ACUCNTRL */ #ifdef BSD4 makestr(&(optlist[noptlist++]),"BSD4"); #endif /* BSD4 */ #ifdef BSD44 makestr(&(optlist[noptlist++]),"BSD44"); #endif /* BSD44 */ #ifdef BSD41 makestr(&(optlist[noptlist++]),"BSD41"); #endif /* BSD41 */ #ifdef BSD43 makestr(&(optlist[noptlist++]),"BSD43"); #endif /* BSD43 */ #ifdef BSD29 makestr(&(optlist[noptlist++]),"BSD29"); #endif /* BSD29 */ #ifdef BSDI makestr(&(optlist[noptlist++]),"BSDI"); #endif /* BSDI */ #ifdef __bsdi__ makestr(&(optlist[noptlist++]),"__bsdi__"); #endif /* __bsdi__ */ #ifdef __NetBSD__ makestr(&(optlist[noptlist++]),"__NetBSD__"); #endif /* __NetBSD__ */ #ifdef __OpenBSD__ makestr(&(optlist[noptlist++]),"__OpenBSD__"); #endif /* __OpenBSD__ */ #ifdef __FreeBSD__ makestr(&(optlist[noptlist++]),"__FreeBSD__"); #endif /* __FreeBSD__ */ #ifdef FREEBSD4 makestr(&(optlist[noptlist++]),"FREEBSD4"); #endif /* FREEBSD4 */ #ifdef FREEBSD8 makestr(&(optlist[noptlist++]),"FREEBSD8"); #endif /* FREEBSD8 */ #ifdef FREEBSD9 makestr(&(optlist[noptlist++]),"FREEBSD9"); #endif /* FREEBSD9 */ #ifdef __linux__ makestr(&(optlist[noptlist++]),"__linux__"); #endif /* __linux__ */ #ifdef LINUX_HI_SPD makestr(&(optlist[noptlist++]),"LINUX_HI_SPD"); #endif /* LINUX_HI_SPD */ #ifdef LYNXOS makestr(&(optlist[noptlist++]),"LYNXOS"); #endif /* LYNXOS */ #ifdef V7 makestr(&(optlist[noptlist++]),"V7"); #endif /* V7 */ #ifdef AIX370 makestr(&(optlist[noptlist++]),"AIX370"); #endif /* AIX370 */ #ifdef RTAIX makestr(&(optlist[noptlist++]),"RTAIX"); #endif /* RTAIX */ #ifdef HPUX makestr(&(optlist[noptlist++]),"HPUX"); #endif /* HPUX */ #ifdef HPUX9 makestr(&(optlist[noptlist++]),"HPUX9"); #endif /* HPUX9 */ #ifdef HPUX10 makestr(&(optlist[noptlist++]),"HPUX10"); #endif /* HPUX10 */ #ifdef HPUX1000 makestr(&(optlist[noptlist++]),"HPUX1000"); #endif /* HPUX1000 */ #ifdef HPUX1100 makestr(&(optlist[noptlist++]),"HPUX1100"); #endif /* HPUX1100 */ #ifdef HPUXPRE65 makestr(&(optlist[noptlist++]),"HPUXPRE65"); #endif /* HPUXPRE65 */ #ifdef DGUX makestr(&(optlist[noptlist++]),"DGUX"); #endif /* DGUX */ #ifdef DGUX430 makestr(&(optlist[noptlist++]),"DGUX430"); #endif /* DGUX430 */ #ifdef DGUX540 makestr(&(optlist[noptlist++]),"DGUX540"); #endif /* DGUX540 */ #ifdef DGUX543 makestr(&(optlist[noptlist++]),"DGUX543"); #endif /* DGUX543 */ #ifdef DGUX54410 makestr(&(optlist[noptlist++]),"DGUX54410"); #endif /* DGUX54410 */ #ifdef DGUX54411 makestr(&(optlist[noptlist++]),"DGUX54411"); #endif /* DGUX54411 */ #ifdef sony_news makestr(&(optlist[noptlist++]),"sony_news"); #endif /* sony_news */ #ifdef CIE makestr(&(optlist[noptlist++]),"CIE"); #endif /* CIE */ #ifdef XENIX makestr(&(optlist[noptlist++]),"XENIX"); #endif /* XENIX */ #ifdef SCO_XENIX makestr(&(optlist[noptlist++]),"SCO_XENIX"); #endif /* SCO_XENIX */ #ifdef ISIII makestr(&(optlist[noptlist++]),"ISIII"); #endif /* ISIII */ #ifdef I386IX makestr(&(optlist[noptlist++]),"I386IX"); #endif /* I386IX */ #ifdef RTU makestr(&(optlist[noptlist++]),"RTU"); #endif /* RTU */ #ifdef PROVX1 makestr(&(optlist[noptlist++]),"PROVX1"); #endif /* PROVX1 */ #ifdef PYRAMID makestr(&(optlist[noptlist++]),"PYRAMID"); #endif /* PYRAMID */ #ifdef TOWER1 makestr(&(optlist[noptlist++]),"TOWER1"); #endif /* TOWER1 */ #ifdef UTEK makestr(&(optlist[noptlist++]),"UTEK"); #endif /* UTEK */ #ifdef ZILOG makestr(&(optlist[noptlist++]),"ZILOG"); #endif /* ZILOG */ #ifdef TRS16 makestr(&(optlist[noptlist++]),"TRS16"); #endif /* TRS16 */ #ifdef MINIX makestr(&(optlist[noptlist++]),"MINIX"); #endif /* MINIX */ #ifdef MINIX2 makestr(&(optlist[noptlist++]),"MINIX2"); #endif /* MINIX2 */ #ifdef MINIX3 makestr(&(optlist[noptlist++]),"MINIX3"); #endif /* MINIX3 */ #ifdef MINIX315 makestr(&(optlist[noptlist++]),"MINIX315"); #endif /* MINIX315 */ #ifdef C70 makestr(&(optlist[noptlist++]),"C70"); #endif /* C70 */ #ifdef AIXPS2 makestr(&(optlist[noptlist++]),"AIXPS2"); #endif /* AIXPS2 */ #ifdef AIXRS makestr(&(optlist[noptlist++]),"AIXRS"); #endif /* AIXRS */ #ifdef UTSV makestr(&(optlist[noptlist++]),"UTSV"); #endif /* UTSV */ #ifdef ATTSV makestr(&(optlist[noptlist++]),"ATTSV"); #endif /* ATTSV */ #ifdef SVR3 makestr(&(optlist[noptlist++]),"SVR3"); #endif /* SVR3 */ #ifdef SVR4 makestr(&(optlist[noptlist++]),"SVR4"); #endif /* SVR4 */ #ifdef DELL_SVR4 makestr(&(optlist[noptlist++]),"DELL_SVR4"); #endif /* DELL_SVR4 */ #ifdef ICL_SVR4 makestr(&(optlist[noptlist++]),"ICL_SVR4"); #endif /* ICL_SVR4 */ #ifdef OSF makestr(&(optlist[noptlist++]),"OSF"); #endif /* OSF */ #ifdef OSF1 makestr(&(optlist[noptlist++]),"OSF1"); #endif /* OSF1 */ #ifdef __OSF makestr(&(optlist[noptlist++]),"__OSF"); #endif /* __OSF */ #ifdef __OSF__ makestr(&(optlist[noptlist++]),"__OSF__"); #endif /* __OSF__ */ #ifdef __osf__ makestr(&(optlist[noptlist++]),"__osf__"); #endif /* __osf__ */ #ifdef __OSF1 makestr(&(optlist[noptlist++]),"__OSF1"); #endif /* __OSF1 */ #ifdef __OSF1__ makestr(&(optlist[noptlist++]),"__OSF1__"); #endif /* __OSF1__ */ #ifdef PTX makestr(&(optlist[noptlist++]),"PTX"); #endif /* PTX */ #ifdef POSIX makestr(&(optlist[noptlist++]),"POSIX"); #endif /* POSIX */ #ifdef BSD44ORPOSIX makestr(&(optlist[noptlist++]),"BSD44ORPOSIX"); #endif /* BSD44ORPOSIX */ #ifdef SVORPOSIX makestr(&(optlist[noptlist++]),"SVORPOSIX"); #endif /* SVORPOSIX */ #ifdef SVR4ORPOSIX makestr(&(optlist[noptlist++]),"SVR4ORPOSIX"); #endif /* SVR4ORPOSIX */ #ifdef OS2ORVMS makestr(&(optlist[noptlist++]),"OS2ORVMS"); #endif /* OS2ORVMS */ #ifdef OS2ORUNIX makestr(&(optlist[noptlist++]),"OS2ORUNIX"); #endif /* OS2ORUNIX */ #ifdef VMSORUNIX makestr(&(optlist[noptlist++]),"VMSORUNIX"); #endif /* VMSORUNIX */ #ifdef VMS64BIT makestr(&(optlist[noptlist++]),"VMS64BIT"); /* VMS on Alpha or IA64 */ #endif /* VMS64BIT */ #ifdef VMSI64 makestr(&(optlist[noptlist++]),"VMSI64"); /* VMS on IA64 */ #endif /* VMSI64 */ #ifdef _POSIX_SOURCE makestr(&(optlist[noptlist++]),"_POSIX_SOURCE"); #endif /* _POSIX_SOURCE */ #ifdef _XOPEN_SOURCE makestr(&(optlist[noptlist++]),"_XOPEN_SOURCE"); #endif #ifdef _ALL_SOURCE makestr(&(optlist[noptlist++]),"_ALL_SOURCE"); #endif #ifdef _SVID3 makestr(&(optlist[noptlist++]),"_SVID3"); #endif /* _SVID3 */ #ifdef Plan9 makestr(&(optlist[noptlist++]),"Plan9"); #endif /* Plan9 */ #ifdef SOLARIS makestr(&(optlist[noptlist++]),"SOLARIS"); #ifdef SOLARIS24 makestr(&(optlist[noptlist++]),"SOLARIS24"); #endif /* SOLARIS24 */ #ifdef SOLARIS25 makestr(&(optlist[noptlist++]),"SOLARIS25"); #endif /* SOLARIS25 */ #ifdef SOLARIS26 makestr(&(optlist[noptlist++]),"SOLARIS26"); #endif /* SOLARIS26 */ #ifdef SOLARIS7 makestr(&(optlist[noptlist++]),"SOLARIS7"); #endif /* SOLARIS7 */ #ifdef SOLARIS8 makestr(&(optlist[noptlist++]),"SOLARIS8"); #endif /* SOLARIS8 */ #ifdef SOLARIS9 makestr(&(optlist[noptlist++]),"SOLARIS9"); #endif /* SOLARIS9 */ #ifdef SOLARIS10 makestr(&(optlist[noptlist++]),"SOLARIS10"); #endif /* SOLARIS10 */ #endif /* SOLARIS */ #ifdef SUNOS4 makestr(&(optlist[noptlist++]),"SUNOS4"); #endif /* SUNOS4 */ #ifdef SUN4S5 makestr(&(optlist[noptlist++]),"SUN4S5"); #endif /* SUN4S5 */ #ifdef IRIX makestr(&(optlist[noptlist++]),"IRIX"); #endif /* IRIX */ #ifdef ENCORE makestr(&(optlist[noptlist++]),"ENCORE"); #endif /* ENCORE */ #ifdef ultrix makestr(&(optlist[noptlist++]),"ultrix"); #endif #ifdef sxaE50 makestr(&(optlist[noptlist++]),"sxaE50"); #endif #ifdef mips makestr(&(optlist[noptlist++]),"mips"); #endif #ifdef MIPS makestr(&(optlist[noptlist++]),"MIPS"); #endif #ifdef vax makestr(&(optlist[noptlist++]),"vax"); #endif #ifdef VAX makestr(&(optlist[noptlist++]),"VAX"); #endif #ifdef alpha makestr(&(optlist[noptlist++]),"alpha"); #endif #ifdef ALPHA makestr(&(optlist[noptlist++]),"ALPHA"); #endif #ifdef __ALPHA makestr(&(optlist[noptlist++]),"__ALPHA"); #endif #ifdef __alpha makestr(&(optlist[noptlist++]),"__alpha"); #endif #ifdef __AXP makestr(&(optlist[noptlist++]),"__AXP"); #endif #ifdef AXP makestr(&(optlist[noptlist++]),"AXP"); #endif #ifdef axp makestr(&(optlist[noptlist++]),"axp"); #endif #ifdef __ALPHA__ makestr(&(optlist[noptlist++]),"__ALPHA__"); #endif #ifdef __alpha__ makestr(&(optlist[noptlist++]),"__alpha__"); #endif #ifdef sun makestr(&(optlist[noptlist++]),"sun"); #endif #ifdef sun3 makestr(&(optlist[noptlist++]),"sun3"); #endif #ifdef sun386 makestr(&(optlist[noptlist++]),"sun386"); #endif #ifdef _SUN makestr(&(optlist[noptlist++]),"_SUN"); #endif #ifdef sun4 makestr(&(optlist[noptlist++]),"sun4"); #endif #ifdef sparc makestr(&(optlist[noptlist++]),"sparc"); #endif #ifdef _CRAY makestr(&(optlist[noptlist++]),"_CRAY"); #endif /* _CRAY */ #ifdef NEXT33 makestr(&(optlist[noptlist++]),"NEXT33"); #endif #ifdef NEXT makestr(&(optlist[noptlist++]),"NEXT"); #endif #ifdef NeXT makestr(&(optlist[noptlist++]),"NeXT"); #endif #ifdef MACH makestr(&(optlist[noptlist++]),"MACH"); #endif #ifdef MACOSX makestr(&(optlist[noptlist++]),"MACOSX"); #endif #ifdef MACOSX10 makestr(&(optlist[noptlist++]),"MACOSX10"); #endif #ifdef MACOSX103 makestr(&(optlist[noptlist++]),"MACOSX10e"); #endif #ifdef COMMENT /* not used */ #ifdef MACOSX103 makestr(&(optlist[noptlist++]),"MACOSX103"); #endif #endif /* COMMENT */ #ifdef sgi makestr(&(optlist[noptlist++]),"sgi"); #endif #ifdef M_SYS5 makestr(&(optlist[noptlist++]),"M_SYS5"); #endif #ifdef __SYSTEM_FIVE makestr(&(optlist[noptlist++]),"__SYSTEM_FIVE"); #endif #ifdef sysV makestr(&(optlist[noptlist++]),"sysV"); #endif #ifdef M_XENIX /* SCO Xenix V and UNIX/386 */ makestr(&(optlist[noptlist++]),"M_XENIX"); #endif #ifdef M_UNIX /* SCO UNIX */ makestr(&(optlist[noptlist++]),"M_UNIX"); #endif #ifdef _M_UNIX /* SCO UNIX 3.2v4 = ODT 2.0 */ makestr(&(optlist[noptlist++]),"_M_UNIX"); #endif #ifdef CK_SCOV5 makestr(&(optlist[noptlist++]),"CK_SCOV5"); #endif #ifdef SCO_OSR504 makestr(&(optlist[noptlist++]),"SCO_OSR504"); #endif #ifdef M_IA64 makestr(&(optlist[noptlist++]),"M_IA64"); #endif #ifdef _M_IA64 makestr(&(optlist[noptlist++]),"_M_IA64"); #endif #ifdef ia64 makestr(&(optlist[noptlist++]),"ia64"); #endif #ifdef _ia64 makestr(&(optlist[noptlist++]),"_ia64"); #endif #ifdef _ia64_ makestr(&(optlist[noptlist++]),"_ia64_"); #endif #ifdef __ia64 makestr(&(optlist[noptlist++]),"__ia64"); #endif #ifdef M_I686 makestr(&(optlist[noptlist++]),"M_I686"); #endif #ifdef _M_I686 makestr(&(optlist[noptlist++]),"_M_I686"); #endif #ifdef i686 makestr(&(optlist[noptlist++]),"i686"); #endif #ifdef M_I586 makestr(&(optlist[noptlist++]),"M_I586"); #endif #ifdef _M_I586 makestr(&(optlist[noptlist++]),"_M_I586"); #endif #ifdef i586 makestr(&(optlist[noptlist++]),"i586"); #endif #ifdef M_I486 makestr(&(optlist[noptlist++]),"M_I486"); #endif #ifdef _M_I486 makestr(&(optlist[noptlist++]),"_M_I486"); #endif #ifdef i486 makestr(&(optlist[noptlist++]),"i486"); #endif #ifdef M_I386 makestr(&(optlist[noptlist++]),"M_I386"); #endif #ifdef _M_I386 makestr(&(optlist[noptlist++]),"_M_I386"); #endif #ifdef i386 makestr(&(optlist[noptlist++]),"i386"); #endif #ifdef __i386 makestr(&(optlist[noptlist++]),"__i386"); #endif #ifdef __x86 makestr(&(optlist[noptlist++]),"__x86"); #endif #ifdef __x86_64 makestr(&(optlist[noptlist++]),"__x86_64"); #endif #ifdef __amd64 makestr(&(optlist[noptlist++]),"__amd64"); #endif #ifdef _ILP32 makestr(&(optlist[noptlist++]),"_ILP32"); #endif #ifdef _ILP64 makestr(&(optlist[noptlist++]),"_ILP64"); #endif #ifdef _LP32 makestr(&(optlist[noptlist++]),"_LP32"); #endif #ifdef _LP64 makestr(&(optlist[noptlist++]),"_LP64"); #endif #ifdef __LP32__ makestr(&(optlist[noptlist++]),"__LP32__"); #endif #ifdef __LP64__ makestr(&(optlist[noptlist++]),"__LP64__"); #endif #ifdef _XGP4_2 makestr(&(optlist[noptlist++]),"_XGP4_2"); #endif #ifdef __ppc__ makestr(&(optlist[noptlist++]),"__ppc__"); #endif #ifdef __ppc32__ makestr(&(optlist[noptlist++]),"__ppc32__"); #endif #ifdef __ppc64__ makestr(&(optlist[noptlist++]),"__ppc64__"); #endif #ifdef CK_64BIT makestr(&(optlist[noptlist++]),"CK_64BIT"); #endif #ifdef i286 makestr(&(optlist[noptlist++]),"i286"); #endif #ifdef M_I286 makestr(&(optlist[noptlist++]),"M_I286"); #endif #ifdef __sparc makestr(&(optlist[noptlist++]),"__sparc"); #endif #ifdef __sparcv8 makestr(&(optlist[noptlist++]),"__sparcv8"); #endif #ifdef __sparcv9 makestr(&(optlist[noptlist++]),"__sparcv9"); #endif #ifdef mc68000 makestr(&(optlist[noptlist++]),"mc68000"); #endif #ifdef mc68010 makestr(&(optlist[noptlist++]),"mc68010"); #endif #ifdef mc68020 makestr(&(optlist[noptlist++]),"mc68020"); #endif #ifdef mc68030 makestr(&(optlist[noptlist++]),"mc68030"); #endif #ifdef mc68040 makestr(&(optlist[noptlist++]),"mc68040"); #endif #ifdef M_68000 makestr(&(optlist[noptlist++]),"M_68000"); #endif #ifdef M_68010 makestr(&(optlist[noptlist++]),"M_68010"); #endif #ifdef M_68020 makestr(&(optlist[noptlist++]),"M_68020"); #endif #ifdef M_68030 makestr(&(optlist[noptlist++]),"M_68030"); #endif #ifdef M_68040 makestr(&(optlist[noptlist++]),"M_68040"); #endif #ifdef m68k makestr(&(optlist[noptlist++]),"m68k"); #endif #ifdef m88k makestr(&(optlist[noptlist++]),"m88k"); #endif #ifdef pdp11 makestr(&(optlist[noptlist++]),"pdp11"); #endif #ifdef iAPX makestr(&(optlist[noptlist++]),"iAPX"); #endif #ifdef hpux makestr(&(optlist[noptlist++]),"hpux"); #endif #ifdef __hpux makestr(&(optlist[noptlist++]),"__hpux"); #endif #ifdef __hp9000s800 makestr(&(optlist[noptlist++]),"__hp9000s800"); #endif #ifdef __hp9000s700 makestr(&(optlist[noptlist++]),"__hp9000s700"); #endif #ifdef __hp9000s500 makestr(&(optlist[noptlist++]),"__hp9000s500"); #endif #ifdef __hp9000s300 makestr(&(optlist[noptlist++]),"__hp9000s300"); #endif #ifdef __hp9000s200 makestr(&(optlist[noptlist++]),"__hp9000s200"); #endif #ifdef AIX makestr(&(optlist[noptlist++]),"AIX"); #endif #ifdef _AIXFS makestr(&(optlist[noptlist++]),"_AIXFS"); #endif #ifdef u370 makestr(&(optlist[noptlist++]),"u370"); #endif #ifdef u3b makestr(&(optlist[noptlist++]),"u3b"); #endif #ifdef u3b2 makestr(&(optlist[noptlist++]),"u3b2"); #endif #ifdef multimax makestr(&(optlist[noptlist++]),"multimax"); #endif #ifdef balance makestr(&(optlist[noptlist++]),"balance"); #endif #ifdef ibmrt makestr(&(optlist[noptlist++]),"ibmrt"); #endif #ifdef _IBMRT makestr(&(optlist[noptlist++]),"_IBMRT"); #endif #ifdef ibmrs6000 makestr(&(optlist[noptlist++]),"ibmrs6000"); #endif #ifdef _AIX makestr(&(optlist[noptlist++]),"_AIX"); #endif /* _AIX */ #ifdef _IBMR2 makestr(&(optlist[noptlist++]),"_IBMR2"); #endif #ifdef UNIXWARE makestr(&(optlist[noptlist++]),"UNIXWARE"); #endif #ifdef QNX makestr(&(optlist[noptlist++]),"QNX"); #ifdef __QNX__ makestr(&(optlist[noptlist++]),"__QNX__"); #ifdef __16BIT__ makestr(&(optlist[noptlist++]),"__16BIT__"); #endif #ifdef CK_QNX16 makestr(&(optlist[noptlist++]),"CK_QNX16"); #endif #ifdef __32BIT__ makestr(&(optlist[noptlist++]),"__32BIT__"); #endif #ifdef CK_QNX32 makestr(&(optlist[noptlist++]),"CK_QNX32"); #endif #endif /* __QNX__ */ #endif /* QNX */ #ifdef QNX6 makestr(&(optlist[noptlist++]),"QNX6"); #endif /* QNX6 */ #ifdef NEUTRINO makestr(&(optlist[noptlist++]),"NEUTRINO"); #endif /* NEUTRINO */ #ifdef __STRICT_BSD__ makestr(&(optlist[noptlist++]),"__STRICT_BSD__"); #endif #ifdef __STRICT_ANSI__ makestr(&(optlist[noptlist++]),"__STRICT_ANSI__"); #endif #ifdef _ANSI_C_SOURCE makestr(&(optlist[noptlist++]),"_ANSI_C_SOURCE"); #endif #ifdef __STDC__ makestr(&(optlist[noptlist++]),"__STDC__"); #endif #ifdef cplusplus makestr(&(optlist[noptlist++]),"cplusplus"); #endif #ifdef __DECC makestr(&(optlist[noptlist++]),"__DECC"); #ifdef __DECC_VER sprintf(line,"__DECC_VER=%d",__DECC_VER); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* __DECC_VER */ #endif /* __DECC */ #ifdef __CRTL_VER sprintf(line,"__CRTL_VER=%d",__CRTL_VER); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* __CRTL_VER */ #ifdef __GNUC__ /* gcc in ansi mode */ makestr(&(optlist[noptlist++]),"__GNUC__"); #endif #ifdef GNUC /* gcc in traditional mode */ makestr(&(optlist[noptlist++]),"GNUC"); #endif #ifdef __EGCS__ /* egcs in ansi mode */ makestr(&(optlist[noptlist++]),"__EGCS__"); #endif #ifdef __egcs__ /* egcs in ansi mode */ makestr(&(optlist[noptlist++]),"__egcs__"); #endif #ifdef __WATCOMC__ makestr(&(optlist[noptlist++]),"__WATCOMC__"); #endif #ifdef CK_ANSIC makestr(&(optlist[noptlist++]),"CK_ANSIC"); #endif #ifdef CK_ANSILIBS makestr(&(optlist[noptlist++]),"CK_ANSILIBS"); #endif #ifdef CKCONINTB4CB makestr(&(optlist[noptlist++]),"CKCONINTB4CB"); #endif /* CKCONINTB4CB */ #ifdef NOTERMCAP makestr(&(optlist[noptlist++]),"NOTERMCAP"); #endif /* NOTERMCAP */ #ifdef __GLIBC__ makestr(&(optlist[noptlist++]),"__GLIBC__"); #endif #ifdef _SC_JOB_CONTROL makestr(&(optlist[noptlist++]),"_SC_JOB_CONTROL"); #endif #ifdef _POSIX_JOB_CONTROL makestr(&(optlist[noptlist++]),"_POSIX_JOB_CONTROL"); #endif #ifdef SIG_I makestr(&(optlist[noptlist++]),"SIG_I"); #endif /* SIG_I */ #ifdef SIG_V makestr(&(optlist[noptlist++]),"SIG_V"); #endif /* SIG_V */ #ifdef CK_POSIX_SIG makestr(&(optlist[noptlist++]),"CK_POSIX_SIG"); #endif #ifdef SVR3JC makestr(&(optlist[noptlist++]),"SVR3JC"); #endif #ifdef _386BSD makestr(&(optlist[noptlist++]),"_386BSD"); #endif #ifdef _BSD makestr(&(optlist[noptlist++]),"_BSD"); #endif #ifdef USE_MEMCPY makestr(&(optlist[noptlist++]),"USE_MEMCPY"); #endif /* USE_MEMCPY */ #ifdef USE_LSTAT makestr(&(optlist[noptlist++]),"USE_LSTAT"); #endif /* USE_LSTAT */ #ifdef TERMIOX makestr(&(optlist[noptlist++]),"TERMIOX"); #endif /* TERMIOX */ #ifdef STERMIOX makestr(&(optlist[noptlist++]),"STERMIOX"); #endif /* STERMIOX */ #ifdef CK_CURSES makestr(&(optlist[noptlist++]),"CK_CURSES"); #endif /* CK_CURSES */ #ifdef CK_NEWTERM makestr(&(optlist[noptlist++]),"CK_NEWTERM"); #endif /* CK_NEWTERM */ #ifdef CK_WREFRESH makestr(&(optlist[noptlist++]),"CK_WREFRESH"); #endif /* CK_WREFRESH */ #ifdef CK_PCT_BAR makestr(&(optlist[noptlist++]),"CK_PCT_BAR"); #endif /* CK_PCT_BAR */ #ifdef CK_DTRCD makestr(&(optlist[noptlist++]),"CK_DTRCD"); #endif /* CK_DTRCD */ #ifdef CK_DTRCTS makestr(&(optlist[noptlist++]),"CK_DTRCTS"); #endif /* CK_DTRCTS */ #ifdef CK_RTSCTS makestr(&(optlist[noptlist++]),"CK_RTSCTS"); #endif /* CK_RTSCTS */ #ifdef POSIX_CRTSCTS makestr(&(optlist[noptlist++]),"POSIX_CRTSCTS"); #endif /* POSIX_CRTSCTS */ #ifdef FIXCRTSCTS makestr(&(optlist[noptlist++]),"FIXCRTSCTS"); #endif /* FIXCRTSCTS */ #ifdef HWPARITY makestr(&(optlist[noptlist++]),"HWPARITY"); #endif /* HWPARITY */ #ifdef CK_SYSINI #ifdef CK_INI_A makestr(&(optlist[noptlist++]),"CK_INI_A"); ckmakmsg(line,LINBUFSIZ,"CK_SYSINI=\"",CK_SYSINI,"\"",NULL); makestr(&(optlist[noptlist++]),line); #else #ifdef CK_INI_B makestr(&(optlist[noptlist++]),"CK_INI_B"); ckmakmsg(line,LINBUFSIZ,"CK_SYSINI=\"",CK_SYSINI,"\"",NULL); makestr(&(optlist[noptlist++]),line); #else makestr(&(optlist[noptlist++]),"CK_SYSINI"); #endif /* CK_INI_B */ #endif /* CK_INI_A */ #endif /* CK_DSYSINI */ #ifdef CK_DSYSINI makestr(&(optlist[noptlist++]),"CK_DSYSINI"); #endif /* CK_DSYSINI */ #ifdef CK_TTGWSIZ makestr(&(optlist[noptlist++]),"CK_TTGWSIZ"); #endif /* CK_TTGWSIZ */ #ifdef CK_NAWS makestr(&(optlist[noptlist++]),"CK_NAWS"); #endif /* CK_NAWS */ #ifdef MDMHUP makestr(&(optlist[noptlist++]),"MDMHUP"); #endif /* MDMHUP */ #ifdef HUP_CLOSE_POSIX makestr(&(optlist[noptlist++]),"HUP_CLOSE_POSIX"); #endif /* HUP_CLOSE_POSIX */ #ifdef NO_HUP_CLOSE_POSIX makestr(&(optlist[noptlist++]),"NO_HUP_CLOSE_POSIX"); #endif /* NO_HUP_CLOSE_POSIX */ #ifdef DCMDBUF makestr(&(optlist[noptlist++]),"DCMDBUF"); #endif /* DCMDBUF */ #ifdef CK_RECALL makestr(&(optlist[noptlist++]),"CK_RECALL"); #endif /* CK_RECALL */ #ifdef BROWSER makestr(&(optlist[noptlist++]),"BROWSER"); #endif /* BROWSER */ #ifdef CLSOPN makestr(&(optlist[noptlist++]),"CLSOPN"); #endif /* CLSOPN */ #ifdef STRATUS makestr(&(optlist[noptlist++]),"STRATUS"); #endif /* STRATUS */ #ifdef __VOS__ makestr(&(optlist[noptlist++]),"__VOS__"); #endif /* __VOS__ */ #ifdef STRATUSX25 makestr(&(optlist[noptlist++]),"STRATUSX25"); #endif /* STRATUSX25 */ #ifdef OS2MOUSE makestr(&(optlist[noptlist++]),"OS2MOUSE"); #endif /* OS2MOUSE */ #ifdef CK_REXX makestr(&(optlist[noptlist++]),"CK_REXX"); #endif /* CK_REXX */ #ifdef CK_TIMERS makestr(&(optlist[noptlist++]),"CK_TIMERS"); #endif /* CK_TIMERS */ #ifdef TTSPDLIST makestr(&(optlist[noptlist++]),"TTSPDLIST"); #endif /* TTSPDLIST */ #ifdef CK_PERMS makestr(&(optlist[noptlist++]),"CK_PERMS"); #endif /* CK_PERMS */ #ifdef CKTUNING makestr(&(optlist[noptlist++]),"CKTUNING"); #endif /* CKTUNING */ #ifdef NEWFTP makestr(&(optlist[noptlist++]),"NEWFTP"); #endif /* NEWFTP */ #ifdef SYSFTP makestr(&(optlist[noptlist++]),"SYSFTP"); #endif /* SYSFTP */ #ifdef NOFTP makestr(&(optlist[noptlist++]),"NOFTP"); #endif /* NOFTP */ #ifdef CKHTTP makestr(&(optlist[noptlist++]),"CKHTTP"); #endif /* CKHTTP */ #ifdef NOHTTP makestr(&(optlist[noptlist++]),"NOHTTP"); #endif /* NOHTTP */ #ifdef CKROOT makestr(&(optlist[noptlist++]),"CKROOT"); #endif /* CKROOT */ #ifdef CKREALPATH makestr(&(optlist[noptlist++]),"CKREALPATH"); #endif /* CKREALPATH */ #ifdef STREAMING makestr(&(optlist[noptlist++]),"STREAMING"); #endif /* STREAMING */ #ifdef UNPREFIXZERO makestr(&(optlist[noptlist++]),"UNPREFIXZERO"); #endif /* UNPREFIXZERO */ #ifdef CKREGEX makestr(&(optlist[noptlist++]),"CKREGEX"); #endif /* CKREGEX */ #ifdef ZXREWIND makestr(&(optlist[noptlist++]),"ZXREWIND"); #endif /* ZXREWIND */ #ifdef CKSYSLOG makestr(&(optlist[noptlist++]),"CKSYSLOG"); #endif /* CKSYSLOG */ #ifdef SYSLOGLEVEL sprintf(line,"SYSLOGLEVEL=%d",SYSLOGLEVEL); /* SAFE */ makestr(&(optlist[noptlist++]),line); #endif /* SYSLOGLEVEL */ #ifdef NOSEXP makestr(&(optlist[noptlist++]),"NOSEXP"); #endif /* NOSEXP */ #ifdef CKLEARN makestr(&(optlist[noptlist++]),"CKLEARN"); #else #ifdef NOLOEARN makestr(&(optlist[noptlist++]),"NOLOEARN"); #endif /* NOLOEARN */ #endif /* CKLEARN */ #ifdef BETATEST makestr(&(optlist[noptlist++]),"BETATEST"); #endif /* BETATEST */ #ifdef NOFLOAT makestr(&(optlist[noptlist++]),"NOFLOAT"); #else #ifdef FNFLOAT makestr(&(optlist[noptlist++]),"FNFLOAT"); #endif /* FNFLOAT */ #ifdef CKFLOAT #ifdef GFTIMER makestr(&(optlist[noptlist++]),"GFTIMER"); #endif /* GFTIMER */ #ifdef CKFLOAT_S ckmakmsg(line,LINBUFSIZ,"CKFLOAT=",CKFLOAT_S,NULL,NULL); makestr(&(optlist[noptlist++]),line); #else makestr(&(optlist[noptlist++]),"CKFLOAT"); #endif /* CKFLOAT_S */ #endif /* CKFLOAT */ #endif /* NOFLOAT */ #ifdef SSH makestr(&(optlist[noptlist++]),"SSH"); #endif /* SSH */ #ifdef NETDLL makestr(&(optlist[noptlist++]),"NETDLL"); #endif /* NETDLL */ #ifdef NETFILE makestr(&(optlist[noptlist++]),"NETFILE"); #endif /* NETFILE */ #ifdef CK_TAPI makestr(&(optlist[noptlist++]),"CK_TAPI"); #endif /* CK_TAPI */ #ifdef CK_SSL makestr(&(optlist[noptlist++]),"CK_SSL"); #ifdef OPENSSL_VERSION_TEXT ckmakmsg(line,LINBUFSIZ, "OPENSSL_VERSION_TEXT=","\"",OPENSSL_VERSION_TEXT,"\""); makestr(&(optlist[noptlist++]),line); #endif /* OPENSSL_VERSION_TEXT */ #endif /* CK_SSL */ debug(F101,"initoptlist noptlist","",noptlist); sh_sort(optlist,NULL,noptlist,0,0,0); } int shofea() { int i; int flag = 0; int lines = 1; #ifdef FNFLOAT extern int fp_digits, fp_rounding; #endif /* FNFLOAT */ extern int byteorder; printf("%s\n",versio); if (inserver) return(1); debug(F101,"shofea NOPTLIST","",NOPTLIST); initoptlist(); debug(F101,"shofea noptlist","",noptlist); #ifdef OS2 #ifdef NT #ifdef _M_ALPHA printf("Microsoft Windows Operating Systems for Alpha CPUs.\n"); #else /* _M_ALPHA */ #ifdef _M_PPC printf("Microsoft Windows Operating Systems for PowerPC CPUs.\n"); #else /* _M_PPC */ #ifdef _M_MRX000 printf("Microsoft Windows Operating Systems for MIPS CPUs.\n"); #else /* _M_MRX000 */ #ifdef _M_IX86 printf("Microsoft Windows Operating Systems for 32-bit Intel CPUs.\n"); #else /* _M_IX86 */ UNKNOWN WINDOWS PLATFORM #endif /* _M_IX86 */ #endif /* _M_MRX000 */ #endif /* _M_PPC */ #endif /* _M_ALPHA */ #else /* NT */ #ifdef M_I286 printf("IBM OS/2 16-bit.\n"); #else printf("IBM OS/2 32-bit.\n"); #endif /* M_I286 */ #endif /* NT */ lines++; #endif /* OS2 */ printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf("Major optional features included:\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } if (sizeof(CK_OFF_T) == 8) { printf(" Large files and large integers (64 bits)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } } #ifdef NETCONN printf(" Network support (type SHOW NET for further info)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #ifdef IKS_OPTION printf(" Telnet Kermit Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* IKS_OPTION */ #ifdef CK_AUTHENTICATION printf(" Telnet Authentication Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #ifdef CK_KERBEROS #ifdef KRB4 #ifdef KRB5 printf(" Kerberos(TM) IV and Kerberos V authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #else /* KRB5 */ printf(" Kerberos(TM) IV authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* KRB5 */ #else /* KRB4 */ #ifdef KRB5 printf(" Kerberos(TM) V authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* KRB5 */ #endif /* KRB4 */ #endif /* CK_KERBEROS */ #ifdef CK_SRP printf(" SRP(TM) (Secure Remote Password) authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_SRP */ #ifdef CK_SSL printf(" Secure Sockets Layer (SSL)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" Transport Layer Security (TLS)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_SSL */ #ifdef SSHBUILTIN printf(" Secure Shell (SSH) [internal]\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* SSHBUILTIN */ #ifdef SSHCMD printf(" Secure Shell (SSH) [external]\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* SSHCMD */ #ifdef CK_ENCRYPTION printf(" Telnet Encryption Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #ifdef CK_DES printf(" Telnet DES Encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_DES */ #ifdef CK_CAST printf(" Telnet CAST Encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_CAST */ #ifdef CK_KERBEROS #ifdef KRB5 #ifdef ALLOW_KRB_3DES_ENCRYPT printf(" Kerberos 3DES/AES Telnet Encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* ALLOW_KRB_3DES_ENCRYPT */ #endif /* KRB5 */ #endif /* CK_KERBEROS */ #endif /* CK_ENCRYPTION */ #endif /* CK_AUTHENTICATION */ #ifdef CK_FORWARD_X printf(" X Windows forwarding\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_FORWARD_X */ #ifdef TN_COMPORT printf(" Telnet Remote Com Port Control Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* TN_COMPORT */ #ifdef CK_SOCKS #ifdef CK_SOCKS5 printf(" SOCKS 5\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #else /* CK_SOCKS5 */ printf(" SOCKS 4\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_SOCKS5 */ #endif /* CK_SOCKS */ #ifdef NEWFTP printf(" Built-in FTP client\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* NEWFTP */ #ifdef CKHTTP printf(" Built-in HTTP client\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CKHTTP */ #endif /* NETCONN */ #ifdef CK_RTSCTS printf(" Hardware flow control\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_RTSCTS */ #ifdef CK_XYZ #ifdef XYZ_INTERNAL printf(" Built-in XYZMODEM protocols\n"); #else printf(" External XYZMODEM protocol support\n"); #endif /* XYZ_INTERNAL */ if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_XYZ */ #ifndef NOCSETS printf(" Latin-1 (West European) character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #ifdef LATIN2 printf(" Latin-2 (East European) character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* LATIN2 */ #ifdef CYRILLIC printf(" Cyrillic (Russian, Ukrainian, etc) character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CYRILLIC */ #ifdef GREEK printf(" Greek character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* GREEK */ #ifdef HEBREW printf(" Hebrew character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* HEBREW */ #ifdef KANJI printf(" Japanese character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* KANJI */ #ifdef UNICODE printf(" Unicode character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* UNICODE */ #ifdef CKOUNI if (ck_isunicode()) printf(" Unicode support for ISO-2022 Terminal Emulation\n"); else printf(" Unicode translation for Terminal Character-Sets\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CKOUNI */ #endif /* NOCSETS */ #ifdef NETPTY printf(" Pseudoterminal control\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* NETPTY */ #ifdef CK_REDIR printf(" REDIRECT command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_REDIR */ #ifdef CK_RESEND printf(" RESEND command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_RESEND */ #ifndef NOXFER #ifdef CK_CURSES printf(" Fullscreen file transfer display\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_CURSES */ #endif /* NOXFER */ #ifdef CK_SPEED printf(" Control-character unprefixing\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_SPEED */ #ifdef STREAMING printf(" Streaming\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* STREAMING */ #ifdef CK_AUTODL printf(" Autodownload\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_AUTODL */ #ifdef OS2MOUSE printf(" Mouse support\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* OS2MOUSE */ #ifdef CK_REXX printf(" REXX script language interface\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_REXX */ #ifdef IKSD #ifdef CK_LOGIN printf(" Internet Kermit Service with user login support\n"); #else /* CK_LOGIN */ printf(" Internet Kermit Service without user login support\n"); #endif /* CK_LOGIN */ if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* IKSD */ printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf("Major optional features not included:\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } if (sizeof(CK_OFF_T) <= 4) { printf(" No large files or large integers\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } } #ifdef NOXFER printf(" No file-transfer protocols\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else #ifndef CK_CURSES #ifndef MAC printf(" No fullscreen file transfer display\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* MAC */ #endif /* CK_CURSES */ #ifdef NOSERVER printf(" No server mode\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOSERVER */ #ifndef CK_SPEED printf(" No control-character unprefixing\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_SPEED */ #ifndef STREAMING printf(" No streaming\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* STREAMING */ #ifndef CK_AUTODL printf(" No autodownload\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_AUTODL */ #ifndef CK_XYZ printf(" No built-in XYZMODEM protocols\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_XYZ */ #ifdef NOFLOAT printf(" No floating-point arithmetic\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; printf(" No S-Expressions (LISP interpreter)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else #ifdef NOSEXP printf(" No S-Expressions (LISP interpreter)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOSEXP */ #endif /* NOFLOAT */ #ifdef NOTLOG printf(" No transaction log\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOTLOG */ #endif /* NOXFER */ #ifdef NODEBUG printf(" No debugging\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NODEBUG */ #ifdef NOHELP printf(" No built-in help\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOHELP */ #ifdef NOLOCAL printf(" No making connections\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else #ifndef NETCONN printf(" No network support\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else /* NETCONN */ #ifndef IKS_OPTION printf(" No Telnet Kermit Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* IKS_OPTION */ #endif /* NETCONN */ #ifdef NOSSH printf(" No Secure Shell (SSH)\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* NOSSH */ #ifndef CK_AUTHENTICATION printf(" No Kerberos(TM) authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" No SRP(TM) (Secure Remote Password) protocol\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" No Secure Sockets Layer (SSL) protocol\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" No Transport Layer Security (TLS) protocol\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" No encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else /* CK_AUTHENTICATION */ #ifndef CK_KERBEROS printf(" No Kerberos(TM) authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else /* CK_KERBEROS */ #ifndef KRB4 printf(" No Kerberos(TM) IV authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* KRB4 */ #ifndef KRB5 printf(" No Kerberos(TM) V authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* KRB5 */ #endif /* CK_KERBEROS */ #ifndef CK_SRP printf(" No SRP(TM) (Secure Remote Password) authentication\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_SRP */ #ifndef CK_SSL printf(" No Secure Sockets Layer (SSL) protocol\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" No Transport Layer Security (TLS) protocol\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_SSL */ #ifndef CK_ENCRYPTION printf(" No Telnet Encryption Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else /* CK_ENCRYPTION */ #ifndef OS2 #ifndef CK_DES printf(" No Telnet DES encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_DES */ #ifndef CK_CAST printf(" No Telnet CAST encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_CAST */ #ifdef COMMENT #ifdef CK_KERBEROS #ifdef KRB5 #ifndef ALLOW_KRB_3DES_ENCRYPT printf(" No Kerberos 3DES/AES Telnet Encryption\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* ALLOW_KRB_3DES_ENCRYPT */ #endif /* KRB5 */ #endif /* CK_KERBEROS */ #endif /* COMMENT */ #endif /* OS2 */ #endif /* CK_ENCRYPTION */ #endif /* CK_AUTHENTICATION */ #ifndef CK_FORWARD_X printf(" No X Windows forwarding\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_FORWARD_X */ #ifndef TN_COMPORT printf(" No Telnet Remote Com Port Control Option\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* TN_COMPORT */ #ifndef CK_SOCKS printf(" No SOCKS\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_SOCKS */ #ifndef NEWFTP printf(" No built-in FTP client\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* NEWFTP */ #ifdef NOHTTP printf(" No built-in HTTP client\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* NOHTTP */ #ifdef NODIAL printf(" No DIAL command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else #ifdef MINIDIAL printf(" Support for most modem types excluded\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* MINIDIAL */ #endif /* NODIAL */ #endif /* NOLOCAL */ #ifndef CK_RTSCTS #ifndef MAC printf(" No hardware flow control\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* MAC */ #endif /* CK_RTSCTS */ #ifdef NOXMIT printf(" No TRANSMIT command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOXMIT */ #ifdef NOSCRIPT printf(" No SCRIPT command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOSCRIPT */ #ifdef NOSPL printf(" No script programming features\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOSPL */ #ifdef NOCSETS printf(" No character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #else #ifndef LATIN2 printf(" No Latin-2 character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* LATIN2 */ #ifdef NOGREEK printf(" No Greek character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOGREEK */ #ifdef NOHEBREW printf(" No Hebrew character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOHEBREW */ #ifdef NOUNICODE printf(" No Unicode character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOUNICODE */ #ifdef NOCYRIL printf(" No Cyrillic character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOCYRIL */ #ifndef KANJI printf(" No Kanji character-set translation\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* KANJI */ #endif /* NOCSETS */ #ifdef NOCMDL printf(" No command-line arguments\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOCMDL */ #ifdef NOPUSH printf(" No escape to system\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOPUSH */ #ifdef NOJC #ifdef UNIX printf(" No UNIX job control\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* UNIX */ #endif /* NOJC */ #ifdef NOSETKEY printf(" No SET KEY command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NOSETKEY */ #ifndef CK_REDIR printf(" No REDIRECT or PIPE command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_REDIR */ #ifdef UNIX #ifndef NETPTY printf(" No pseudoterminal control\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* NETPTY */ #endif /* UNIX */ #ifndef CK_RESEND printf(" No RESEND command\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_RESEND */ #ifdef OS2 #ifdef __32BIT__ #ifndef OS2MOUSE printf(" No Mouse support\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* __32BIT__ */ #endif /* OS2 */ #endif /* OS2MOUSE */ #ifdef OS2 #ifndef NT #ifndef CK_REXX printf(" No REXX script language interface\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* CK_REXX */ #endif /* NT */ #endif /* OS2 */ #ifndef IKSD printf(" No Internet Kermit Service\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } flag = 1; #endif /* IKSD */ if (flag == 0) { printf(" None\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } } printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #ifdef CK_UTSNAME if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf("Host info:\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" Machine: %s\n",unm_mch[0] ? unm_mch : "(unknown)"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" Model: %s\n",unm_mod[0] ? unm_mod : "(unknown)"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" OS: %s\n",unm_nam[0] ? unm_nam : "(unknown)"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" OS Release: %s\n",unm_rel[0] ? unm_rel : "(unknown)"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf(" OS Version: %s\n",unm_ver[0] ? unm_ver : "(unknown)"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* CK_UTSNAME */ /* Print compile-time (-D) options, as well as C preprocessor predefined symbols that might affect us... */ #ifdef KTARGET { char * s; /* Makefile target */ s = KTARGET; if (!s) s = ""; if (!*s) s = "(unknown)"; printf("\n"); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } printf("Target: %s\n", s); if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } } #endif /* KTARGET */ #ifdef __VERSION__ #ifdef __GNUC__ printf("GCC version: %s\n", __VERSION__); #else printf("Compiler version: %s\n", __VERSION__); #endif /* __GNUC__ */ if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } #endif /* __VERSION__ */ #ifdef __DATE__ /* GNU and other ANSI */ #ifdef __TIME__ printf("Compiled %s %s, options:\n", __DATE__, __TIME__); #else printf("Compiled %s, options:\n", __DATE__); #endif /* __TIME__ */ #else /* !__DATE__ */ printf("Compiler options:\n"); #endif /* __DATE__ */ if (++lines > cmd_rows - 3) { if (!askmore()) return(1); else lines = 0; } for (i = 0; i < noptlist; i++) /* Print sorted option list */ if (!prtopt(&lines,optlist[i])) return(0); if (!prtopt(&lines,"")) return(0); /* Start a new section */ /* Sizes of data types */ ckmakmsg(line, LINBUFSIZ, "byte order: ", byteorder ? "little" : "big", " endian", NULL ); { /* Whether to use %d or %ld with sizeof is a portability issue, so... */ int size = 0; if (!prtopt(&lines,line)) return(0); if (!prtopt(&lines,"")) return(0); /* Start a new section */ size = (int)sizeof(int); sprintf(line,"sizeofs: int=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); size = (int)sizeof(long); sprintf(line,"long=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); #ifndef OS2 /* Windows doesn't have off_t */ size = (int)sizeof(off_t); sprintf(line,"off_t=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); #endif /* OS2 */ size = (int)sizeof(CK_OFF_T); sprintf(line,"CK_OFF_T=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); #ifdef BIGBUFOK size = (int)sizeof(size_t); sprintf(line,"size_t=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); #endif /* BIGBUFOK */ size = (int)sizeof(short); sprintf(line,"short=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); size = (int)sizeof(char); sprintf(line,"char=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); size = (int)sizeof(char *); sprintf(line,"char*=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); size = (int)sizeof(float); sprintf(line,"float=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); size = (int)sizeof(double); sprintf(line,"double=%d",size); /* SAFE */ if (!prtopt(&lines,line)) return(0); } #ifdef FNFLOAT if (!prtopt(&lines,"")) return(0); /* Start a new section */ if (!prtopt(&lines,"floating-point:")) return(0); sprintf(line,"precision=%d",fp_digits); /* SAFE */ if (!prtopt(&lines,line)) return(0); sprintf(line,"rounding=%d",fp_rounding); /* SAFE */ if (!prtopt(&lines,line)) return(0); #endif /* FNFLOAT */ prtopt(&lines,""); return(0); } #endif /* NOSHOW */ #endif /* NOICP */
806522.c
/***************************************************** Title : NMEA Service Author : kingyo File : NMEA_Service.c DATE : 2020/07/05 ******************************************************/ #include "NMEA_Service.h" #include "uart.h" volatile static char rxData[256]; volatile static char gNMEA[17]; volatile static char gUTC_Date[17]; volatile static uint8_t gUART_pass; /***************************** * UART 受信割り込み *****************************/ static void UartRxCallBack(void) { static uint8_t cnt = 0; uint8_t rxByte = UDR0; uint8_t i; // スルーさせる if (gUART_pass) { UDR0 = rxByte; return; } rxData[cnt] = rxByte; if (rxByte != '\n') { cnt++; return; } // 一行受信完了 cnt = 0; // $GPGGA if (rxData[0] == '$' && rxData[1] == 'G' && rxData[2] == 'P' && rxData[3] == 'G' && rxData[4] == 'G' && rxData[5] == 'A') { for (i = 0; i < 255; i++) { if(rxData[i] == ',') break; } // UTC時刻 gNMEA[0] = rxData[i+1]; gNMEA[1] = rxData[i+2]; gNMEA[2] = ':'; gNMEA[3] = rxData[i+3]; gNMEA[4] = rxData[i+4]; gNMEA[5] = ':'; gNMEA[6] = rxData[i+5]; gNMEA[7] = rxData[i+6]; gNMEA[8] = ' '; for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 緯度 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 北緯 or 南緯 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 経度 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 東経 or 西経 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 位置特定品質 gNMEA[9] = rxData[i+1]; gNMEA[10] = ' '; for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 使用衛星数 gNMEA[11] = rxData[i+1]; gNMEA[12] = rxData[i+2]; // 以下未使用 gNMEA[13] = ' '; gNMEA[14] = ' '; gNMEA[15] = ' '; gNMEA[16] = '\0'; } else // $GPRMC if (rxData[0] == '$' && rxData[1] == 'G' && rxData[2] == 'P' && rxData[3] == 'R' && rxData[4] == 'M' && rxData[5] == 'C') { for (i = 0; i < 255; i++) { if(rxData[i] == ',') break; } // UTC時刻 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // ステータス // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 緯度 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 北緯 or 南緯 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 経度 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 東経 or 西経 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 地表における移動の速度 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // 地表における移動の真方位 // 未使用 for (i++; i < 255; i++) { if(rxData[i] == ',') break; } // UTC日付 gUTC_Date[0] = '2'; gUTC_Date[1] = '0'; gUTC_Date[2] = rxData[i+5]; gUTC_Date[3] = rxData[i+6]; gUTC_Date[4] = '/'; gUTC_Date[5] = rxData[i+3]; gUTC_Date[6] = rxData[i+4]; gUTC_Date[7] = '/'; gUTC_Date[8] = rxData[i+1]; gUTC_Date[9] = rxData[i+2]; gUTC_Date[10] = ' '; gUTC_Date[11] = ' '; gUTC_Date[12] = ' '; gUTC_Date[13] = ' '; gUTC_Date[14] = ' '; gUTC_Date[15] = ' '; gUTC_Date[16] = '\0'; } } /***************************** * 初期化 *****************************/ void NMEA_Init(void) { UART_SetRxCallBackFunc(UartRxCallBack); gUART_pass = 0; } /***************************** * NMEAデータコピー *****************************/ uint8_t NMEA_GetNMEA(uint8_t stIndex, char *buf, uint8_t fillNullChar) { uint8_t i, j = stIndex; for (i = 0; i < 14; i++) { *(buf + j++) = gNMEA[i]; } if (fillNullChar) { for (i = 0; i < 2; i++) { *(buf + j++) = ' '; } *(buf + j++) = '\0'; } return j; } /***************************** * UTC日付コピー *****************************/ uint8_t NMEA_GetUTCDate(uint8_t stIndex, char *buf, uint8_t fillNullChar) { uint8_t i, j = stIndex; for (i = 0, j = 0; i < 11; i++) { *(buf + j++) = gUTC_Date[i]; } if (fillNullChar) { for (i = 0; i < 5; i++) { *(buf + j++) = ' '; } *(buf + j++) = '\0'; } return j; } /***************************** * アラーム情報を返す *****************************/ uint8_t NMEA_GetAramStatus(void) { return (gNMEA[9] == '0'); } /***************************** * UARTスルー設定 *****************************/ void NMEA_SetUartThrough(uint8_t throughEn) { gUART_pass = throughEn ? 1 : 0; }
572794.c
/******************************************************************************* * File Name: main.c * * Version: 1.1 * * Description: * This project demonstrates simultaneous usage of the BLE GAP Peripheral and * Broadcaster roles. The device would connect to a peer device, while also * broadcasting (non-connectable advertising) at the same time. * * Hardware Dependency: * YABP-00102-A : Cypress EZ-BLE PRoC Bluetooth Evaluation Board * YP-01: USB to TTL * ******************************************************************************** * Copyright (2016), YABTRONIX TECHNOLOGIES INC. ****************************************************************************** * By : Yvan Bourassa * Date: March 21, 2016 *******************************************************************************/ /******************************************************************************* * Included headers *******************************************************************************/ #include <project.h> #include <stdio.h> #include <common.h> /*************************************** * Function Prototypes ***************************************/ void StackEventHandler(uint32 event, void* eventParam); /******************************************************************************* * Function Name: StackEventHandler ******************************************************************************** * * Summary: * This is an event callback function to receive events from the CYBLE Component. * * Parameters: * uint8 event: Event from the CYBLE component. * void* eventParams: A structure instance for corresponding event type. The * list of event structure is described in the component * datasheet. * * Return: * None * *******************************************************************************/ void StackEventHandler(uint32 event, void* eventParam) { /*local variables*/ CYBLE_GAPC_ADV_REPORT_T advReport; uint8 i; switch(event) { case CYBLE_EVT_STACK_ON: /*BLE stack ON*/ //printf("Bluetooth ON:\r\n"); /*Start Scanning*/ if(CYBLE_ERROR_OK==CyBle_GapcStartScan(CYBLE_SCANNING_SLOW)) { //printf("Sarted to Scan\r\n"); } break; case CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT: /* scan progress result event occurs * when it receives any advertisiment packet * or scan response packet from peer device*/ advReport=*(CYBLE_GAPC_ADV_REPORT_T *)eventParam; //printf("CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT:\r\n"); /* Print the Advertising Event details of peer device:*/ //printf("eventType:"); //************************************************ /* REPLACE THIS BY JSON FORMAT */ //************************************************ switch(advReport.eventType) { case CYBLE_GAPC_CONN_UNDIRECTED_ADV: //printf("Connectable undirected advertising\r\n"); break; case CYBLE_GAPC_CONN_DIRECTED_ADV: //printf("Connectable directed advertising\r\n"); break; case CYBLE_GAPC_SCAN_UNDIRECTED_ADV: //printf("Scannable undirected advertising\r\n"); break; case CYBLE_GAPC_NON_CONN_UNDIRECTED_ADV: //printf("Non connectable undirected advertising\r\n"); break; case CYBLE_GAPC_SCAN_RSP: //printf("SCAN_RSP\r\n"); break; } /* PEER addr type */ //printf(" peerAddrType: "); if(advReport.peerAddrType==CYBLE_GAP_ADDR_TYPE_PUBLIC) { //printf("PUBLIC\r\n"); } else if(advReport.peerAddrType==CYBLE_GAP_ADDR_TYPE_RANDOM) { //printf("RANDOM \r\n"); } /* PEER Device address type */ printf("%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x,", advReport.peerBdAddr[5u], advReport.peerBdAddr[4u], advReport.peerBdAddr[3u], advReport.peerBdAddr[2u], advReport.peerBdAddr[1u], advReport.peerBdAddr[0u]); /* Advertising or scan response data */ //printf(" Peer device adveritsing/scan response data Length: %x \r\n", advReport.dataLen); //printf(" advertising/scan response data of peer device: "); if(advReport.dataLen!=0) { for(i = 0u; i < (advReport.dataLen); i++) { printf("%02x,", advReport.data[i]); } } /* RSSI of the received packet from peer Device */ printf("%i", (advReport.rssi)); printf("\n"); /* Stop GAP for next scan */ CyBle_GapcStopScan(); break; case CYBLE_EVT_GAPC_SCAN_START_STOP: if(CyBle_GetState()==CYBLE_STATE_DISCONNECTED) { /*Restart scanning if time out happens*/ CyBle_GapcStartScan(CYBLE_SCANNING_SLOW); } break; default: break; } } /******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * Main function. * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { /* Variable declarations */ //CYBLE_LP_MODE_T lpMode; //CYBLE_BLESS_STATE_T blessState; //uint8 InterruptsStatus; /* Start communication component */ UART_Start(); /* Enable global interrupts */ CyGlobalIntEnable; /* Internal low power oscillator is stopped as it is not used in this project */ CySysClkIloStop(); /* Set the divider for ECO, ECO will be used as source when IMO is switched off to save power, ** to drive the HFCLK */ CySysClkWriteEcoDiv(CY_SYS_CLK_ECO_DIV8); CyBle_Start(StackEventHandler); /*Infinite Loop*/ for(;;) { CyBle_ProcessEvents(); } } /* [] END OF FILE */
928211.c
/* Copyright (C) 1997,1998,2000,2002-2004,2005 Free Software Foundation, Inc. This file is part of the GNU C Library. 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; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <signal.h> #define __need_NULL #include <stddef.h> #include <string.h> #include <sysdep-cancel.h> #include <sys/syscall.h> #include <bp-checks.h> #ifdef __NR_rt_sigtimedwait /* Return any pending signal or wait for one for the given time. */ static int do_sigwait (const sigset_t *set, int *sig) { int ret; #ifdef SIGCANCEL sigset_t tmpset; if (set != NULL && (__builtin_expect (__sigismember (set, SIGCANCEL), 0) # ifdef SIGSETXID || __builtin_expect (__sigismember (set, SIGSETXID), 0) # endif )) { /* Create a temporary mask without the bit for SIGCANCEL set. */ // We are not copying more than we have to. memcpy (&tmpset, set, _NSIG / 8); __sigdelset (&tmpset, SIGCANCEL); # ifdef SIGSETXID __sigdelset (&tmpset, SIGSETXID); # endif set = &tmpset; } #endif /* XXX The size argument hopefully will have to be changed to the real size of the user-level sigset_t. */ #ifdef INTERNAL_SYSCALL INTERNAL_SYSCALL_DECL (err); do ret = INTERNAL_SYSCALL (rt_sigtimedwait, err, 4, CHECK_SIGSET (set), NULL, NULL, _NSIG / 8); while (INTERNAL_SYSCALL_ERROR_P (ret, err) && INTERNAL_SYSCALL_ERRNO (ret, err) == EINTR); if (! INTERNAL_SYSCALL_ERROR_P (ret, err)) { *sig = ret; ret = 0; } else ret = INTERNAL_SYSCALL_ERRNO (ret, err); #else do ret = INLINE_SYSCALL (rt_sigtimedwait, 4, CHECK_SIGSET (set), NULL, NULL, _NSIG / 8); while (ret == -1 && errno == EINTR); if (ret != -1) { *sig = ret; ret = 0; } else ret = errno; #endif return ret; } int __sigwait (set, sig) const sigset_t *set; int *sig; { if (SINGLE_THREAD_P) return do_sigwait (set, sig); int oldtype = LIBC_CANCEL_ASYNC (); int result = do_sigwait (set, sig); LIBC_CANCEL_RESET (oldtype); return result; } libc_hidden_def (__sigwait) weak_alias (__sigwait, sigwait) #else # include <sysdeps/posix/sigwait.c> #endif strong_alias (__sigwait, __libc_sigwait)
395624.c
/* vi: set sw=4 ts=4: */ /* * vconfig implementation for busybox * * Copyright (C) 2001 Manuel Novoa III <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* BB_AUDIT SUSv3 N/A */ #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <net/if.h> #include <string.h> #include <limits.h> #include "busybox.h" /* Stuff from linux/if_vlan.h, kernel version 2.4.23 */ enum vlan_ioctl_cmds { ADD_VLAN_CMD, DEL_VLAN_CMD, SET_VLAN_INGRESS_PRIORITY_CMD, SET_VLAN_EGRESS_PRIORITY_CMD, GET_VLAN_INGRESS_PRIORITY_CMD, GET_VLAN_EGRESS_PRIORITY_CMD, SET_VLAN_NAME_TYPE_CMD, SET_VLAN_FLAG_CMD }; enum vlan_name_types { VLAN_NAME_TYPE_PLUS_VID, /* Name will look like: vlan0005 */ VLAN_NAME_TYPE_RAW_PLUS_VID, /* name will look like: eth1.0005 */ VLAN_NAME_TYPE_PLUS_VID_NO_PAD, /* Name will look like: vlan5 */ VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD, /* Name will look like: eth0.5 */ VLAN_NAME_TYPE_HIGHEST }; struct vlan_ioctl_args { int cmd; /* Should be one of the vlan_ioctl_cmds enum above. */ char device1[24]; union { char device2[24]; int VID; unsigned int skb_priority; unsigned int name_type; unsigned int bind_type; unsigned int flag; /* Matches vlan_dev_info flags */ } u; short vlan_qos; }; #define VLAN_GROUP_ARRAY_LEN 4096 #define SIOCSIFVLAN 0x8983 /* Set 802.1Q VLAN options */ /* On entry, table points to the length of the current string plus * nul terminator plus data length for the subsequent entry. The * return value is the last data entry for the matching string. */ static const char *xfind_str(const char *table, const char *str) { while (strcasecmp(str, table+1) != 0) { if (!*(table += table[0])) { bb_show_usage(); } } return table - 1; } static const char cmds[] = { 4, ADD_VLAN_CMD, 7, 'a', 'd', 'd', 0, 3, DEL_VLAN_CMD, 7, 'r', 'e', 'm', 0, 3, SET_VLAN_NAME_TYPE_CMD, 17, 's', 'e', 't', '_', 'n', 'a', 'm', 'e', '_', 't', 'y', 'p', 'e', 0, 4, SET_VLAN_FLAG_CMD, 12, 's', 'e', 't', '_', 'f', 'l', 'a', 'g', 0, 5, SET_VLAN_EGRESS_PRIORITY_CMD, 18, 's', 'e', 't', '_', 'e', 'g', 'r', 'e', 's', 's', '_', 'm', 'a', 'p', 0, 5, SET_VLAN_INGRESS_PRIORITY_CMD, 16, 's', 'e', 't', '_', 'i', 'n', 'g', 'r', 'e', 's', 's', '_', 'm', 'a', 'p', 0, }; static const char name_types[] = { VLAN_NAME_TYPE_PLUS_VID, 16, 'V', 'L', 'A', 'N', '_', 'P', 'L', 'U', 'S', '_', 'V', 'I', 'D', 0, VLAN_NAME_TYPE_PLUS_VID_NO_PAD, 22, 'V', 'L', 'A', 'N', '_', 'P', 'L', 'U', 'S', '_', 'V', 'I', 'D', '_', 'N', 'O', '_', 'P', 'A', 'D', 0, VLAN_NAME_TYPE_RAW_PLUS_VID, 15, 'D', 'E', 'V', '_', 'P', 'L', 'U', 'S', '_', 'V', 'I', 'D', 0, VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD, 20, 'D', 'E', 'V', '_', 'P', 'L', 'U', 'S', '_', 'V', 'I', 'D', '_', 'N', 'O', '_', 'P', 'A', 'D', 0, }; static const char conf_file_name[] = "/proc/net/vlan/config"; int vconfig_main(int argc, char **argv) { struct vlan_ioctl_args ifr; const char *p; int fd; if (argc < 3) { bb_show_usage(); } /* Don't bother closing the filedes. It will be closed on cleanup. */ if (open(conf_file_name, O_RDONLY) < 0) { /* Is 802.1q is present? */ bb_perror_msg_and_die("open %s", conf_file_name); } memset(&ifr, 0, sizeof(struct vlan_ioctl_args)); ++argv; p = xfind_str(cmds+2, *argv); ifr.cmd = *p; if (argc != p[-1]) { bb_show_usage(); } if (ifr.cmd == SET_VLAN_NAME_TYPE_CMD) { /* set_name_type */ ifr.u.name_type = *xfind_str(name_types+1, argv[1]); } else { if (strlen(argv[1]) >= IF_NAMESIZE) { bb_error_msg_and_die("if_name >= %d chars\n", IF_NAMESIZE); } strcpy(ifr.device1, argv[1]); p = argv[2]; /* I suppose one could try to combine some of the function calls below, * since ifr.u.flag, ifr.u.VID, and ifr.u.skb_priority are all same-sized * (unsigned) int members of a unions. But because of the range checking, * doing so wouldn't save that much space and would also make maintainence * more of a pain. */ if (ifr.cmd == SET_VLAN_FLAG_CMD) { /* set_flag */ ifr.u.flag = bb_xgetularg10_bnd(p, 0, 1); } else if (ifr.cmd == ADD_VLAN_CMD) { /* add */ ifr.u.VID = bb_xgetularg10_bnd(p, 0, VLAN_GROUP_ARRAY_LEN-1); } else if (ifr.cmd != DEL_VLAN_CMD) { /* set_{egress|ingress}_map */ ifr.u.skb_priority = bb_xgetularg10_bnd(p, 0, ULONG_MAX); ifr.vlan_qos = bb_xgetularg10_bnd(argv[3], 0, 7); } } if (((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) || (ioctl(fd, SIOCSIFVLAN, &ifr) < 0) ) { bb_perror_msg_and_die("socket or ioctl error for %s", *argv); } return 0; }
849826.c
#include <stdio.h> #include "IRTrans.h" SOCKET irt_server; main () { int res; NETWORKSTATUS *stat; res = ConnectIRTransServer ("194.139.118.68",&irt_server); if (res) { printf ("Connect Result: %d\n",res); return -1; } stat = SendCCFCommandLong (irt_server,"0000 007D 00A4 0000 00A7 0048 000C 003C 000C 0018 000C 0018 000C 0018 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 0018 000C 003C 000C 003C 000C 0018 000C 003C 000C 003C 000C 003C 000C 003C 000C 003C 000C 0018 000C 0018 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 003C 000C 003C 000C 003C 000C 003C 000C 0018 000C 003C 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 003C 000C 003C 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000D 03D4 00A7 0048 000C 003C 000C 0018 000D 0017 000C 0018 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 0018 000C 003C 000C 003C 000C 0018 000C 003C 000C 003C 000C 003C 000C 003C 000C 003C 000D 0017 000C 0018 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 003C 000C 0018 000C 0018 000C 003C 000C 0018 000C 003C 000D 003B 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 003C 000C 0018 000D 0017 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000D 0017 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000D 0017 000C 0018 000C 003C 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000C 0018 000D 0017 000C 003C 000C 0018 000C 0018 000C 0018 000C 0018 000C 003C 000C 0018 000C 0018 000C 0018 000C 003C 000C 003C 000C 003C 000C 0018 000C 0000",0,0,0,0); if (stat) { printf ("Error: %s\n",stat->message); } DisconnectIRTransServer (irt_server); return 0; }
714108.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2018, The University of Texas at Austin Copyright (C) 2016 - 2018, Advanced Micro Devices, Inc. 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(s) of the copyright holder(s) 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 "immintrin.h" #include "blis.h" /* Union data structure to access AVX registers One 256-bit AVX register holds 8 SP elements. */ typedef union { __m256 v; float f[8] __attribute__((aligned(64))); } v8sf_t; /* Union data structure to access AVX registers * One 256-bit AVX register holds 4 DP elements. */ typedef union { __m256d v; double d[4] __attribute__((aligned(64))); } v4df_t; // ----------------------------------------------------------------------------- void bli_sdotxf_zen_int_8 ( conj_t conjat, conj_t conjx, dim_t m, dim_t b_n, float* restrict alpha, float* restrict a, inc_t inca, inc_t lda, float* restrict x, inc_t incx, float* restrict beta, float* restrict y, inc_t incy, cntx_t* cntx ) { const dim_t fuse_fac = 8; const dim_t n_elem_per_reg = 8; // If the b_n dimension is zero, y is empty and there is no computation. if ( bli_zero_dim1( b_n ) ) return; // If the m dimension is zero, or if alpha is zero, the computation // simplifies to updating y. if ( bli_zero_dim1( m ) || PASTEMAC(s,eq0)( *alpha ) ) { sscalv_ker_ft f = bli_cntx_get_ukr_dt( BLIS_FLOAT, BLIS_SCALV_KER, cntx ); f ( BLIS_NO_CONJUGATE, b_n, beta, y, incy, cntx ); return; } // If b_n is not equal to the fusing factor, then perform the entire // operation as a loop over dotxv. if ( b_n != fuse_fac ) { sdotxv_ker_ft f = bli_cntx_get_ukr_dt( BLIS_FLOAT, BLIS_DOTXV_KER, cntx ); for ( dim_t i = 0; i < b_n; ++i ) { float* a1 = a + (0 )*inca + (i )*lda; float* x1 = x + (0 )*incx; float* psi1 = y + (i )*incy; f ( conjat, conjx, m, alpha, a1, inca, x1, incx, beta, psi1, cntx ); } return; } // At this point, we know that b_n is exactly equal to the fusing factor. // However, m may not be a multiple of the number of elements per vector. // Going forward, we handle two possible storage formats of A explicitly: // (1) A is stored by columns, or (2) A is stored by rows. Either case is // further split into two subproblems along the m dimension: // (a) a vectorized part, starting at m = 0 and ending at any 0 <= m' <= m. // (b) a scalar part, starting at m' and ending at m. If no vectorization // is possible then m' == 0 and thus the scalar part is the entire // problem. If 0 < m', then the a and x pointers and m variable will // be adjusted accordingly for the second subproblem. // Note: since parts (b) for both (1) and (2) are so similar, they are // factored out into one code block after the following conditional, which // distinguishes between (1) and (2). // Intermediate variables to hold the completed dot products float rho0 = 0, rho1 = 0, rho2 = 0, rho3 = 0, rho4 = 0, rho5 = 0, rho6 = 0, rho7 = 0; if ( inca == 1 && incx == 1 ) { const dim_t n_iter_unroll = 1; // Use the unrolling factor and the number of elements per register // to compute the number of vectorized and leftover iterations. dim_t m_viter = ( m ) / ( n_elem_per_reg * n_iter_unroll ); // Set up pointers for x and the b_n columns of A (rows of A^T). float* restrict x0 = x; float* restrict a0 = a + 0*lda; float* restrict a1 = a + 1*lda; float* restrict a2 = a + 2*lda; float* restrict a3 = a + 3*lda; float* restrict a4 = a + 4*lda; float* restrict a5 = a + 5*lda; float* restrict a6 = a + 6*lda; float* restrict a7 = a + 7*lda; // Initialize b_n rho vector accumulators to zero. v8sf_t rho0v; rho0v.v = _mm256_setzero_ps(); v8sf_t rho1v; rho1v.v = _mm256_setzero_ps(); v8sf_t rho2v; rho2v.v = _mm256_setzero_ps(); v8sf_t rho3v; rho3v.v = _mm256_setzero_ps(); v8sf_t rho4v; rho4v.v = _mm256_setzero_ps(); v8sf_t rho5v; rho5v.v = _mm256_setzero_ps(); v8sf_t rho6v; rho6v.v = _mm256_setzero_ps(); v8sf_t rho7v; rho7v.v = _mm256_setzero_ps(); v8sf_t x0v; v8sf_t a0v, a1v, a2v, a3v, a4v, a5v, a6v, a7v; // If there are vectorized iterations, perform them with vector // instructions. for ( dim_t i = 0; i < m_viter; ++i ) { // Load the input values. x0v.v = _mm256_loadu_ps( x0 + 0*n_elem_per_reg ); a0v.v = _mm256_loadu_ps( a0 + 0*n_elem_per_reg ); a1v.v = _mm256_loadu_ps( a1 + 0*n_elem_per_reg ); a2v.v = _mm256_loadu_ps( a2 + 0*n_elem_per_reg ); a3v.v = _mm256_loadu_ps( a3 + 0*n_elem_per_reg ); a4v.v = _mm256_loadu_ps( a4 + 0*n_elem_per_reg ); a5v.v = _mm256_loadu_ps( a5 + 0*n_elem_per_reg ); a6v.v = _mm256_loadu_ps( a6 + 0*n_elem_per_reg ); a7v.v = _mm256_loadu_ps( a7 + 0*n_elem_per_reg ); // perform: rho?v += a?v * x0v; rho0v.v = _mm256_fmadd_ps( a0v.v, x0v.v, rho0v.v ); rho1v.v = _mm256_fmadd_ps( a1v.v, x0v.v, rho1v.v ); rho2v.v = _mm256_fmadd_ps( a2v.v, x0v.v, rho2v.v ); rho3v.v = _mm256_fmadd_ps( a3v.v, x0v.v, rho3v.v ); rho4v.v = _mm256_fmadd_ps( a4v.v, x0v.v, rho4v.v ); rho5v.v = _mm256_fmadd_ps( a5v.v, x0v.v, rho5v.v ); rho6v.v = _mm256_fmadd_ps( a6v.v, x0v.v, rho6v.v ); rho7v.v = _mm256_fmadd_ps( a7v.v, x0v.v, rho7v.v ); x0 += n_elem_per_reg * n_iter_unroll; a0 += n_elem_per_reg * n_iter_unroll; a1 += n_elem_per_reg * n_iter_unroll; a2 += n_elem_per_reg * n_iter_unroll; a3 += n_elem_per_reg * n_iter_unroll; a4 += n_elem_per_reg * n_iter_unroll; a5 += n_elem_per_reg * n_iter_unroll; a6 += n_elem_per_reg * n_iter_unroll; a7 += n_elem_per_reg * n_iter_unroll; } #if 0 rho0 += rho0v.f[0] + rho0v.f[1] + rho0v.f[2] + rho0v.f[3] + rho0v.f[4] + rho0v.f[5] + rho0v.f[6] + rho0v.f[7]; rho1 += rho1v.f[0] + rho1v.f[1] + rho1v.f[2] + rho1v.f[3] + rho1v.f[4] + rho1v.f[5] + rho1v.f[6] + rho1v.f[7]; rho2 += rho2v.f[0] + rho2v.f[1] + rho2v.f[2] + rho2v.f[3] + rho2v.f[4] + rho2v.f[5] + rho2v.f[6] + rho2v.f[7]; rho3 += rho3v.f[0] + rho3v.f[1] + rho3v.f[2] + rho3v.f[3] + rho3v.f[4] + rho3v.f[5] + rho3v.f[6] + rho3v.f[7]; rho4 += rho4v.f[0] + rho4v.f[1] + rho4v.f[2] + rho4v.f[3] + rho4v.f[4] + rho4v.f[5] + rho4v.f[6] + rho4v.f[7]; rho5 += rho5v.f[0] + rho5v.f[1] + rho5v.f[2] + rho5v.f[3] + rho5v.f[4] + rho5v.f[5] + rho5v.f[6] + rho5v.f[7]; rho6 += rho6v.f[0] + rho6v.f[1] + rho6v.f[2] + rho6v.f[3] + rho6v.f[4] + rho6v.f[5] + rho6v.f[6] + rho6v.f[7]; rho7 += rho7v.f[0] + rho7v.f[1] + rho7v.f[2] + rho7v.f[3] + rho7v.f[4] + rho7v.f[5] + rho7v.f[6] + rho7v.f[7]; #else // Now we need to sum the elements within each vector. v8sf_t onev; onev.v = _mm256_set1_ps( 1.0f ); // Sum the elements of a given rho?v by dotting it with 1. The '1' in // '0xf1' stores the sum of the upper four and lower four values to // the low elements of each lane: elements 4 and 0, respectively. (The // 'f' in '0xf1' means include all four elements of each lane in the // summation.) rho0v.v = _mm256_dp_ps( rho0v.v, onev.v, 0xf1 ); rho1v.v = _mm256_dp_ps( rho1v.v, onev.v, 0xf1 ); rho2v.v = _mm256_dp_ps( rho2v.v, onev.v, 0xf1 ); rho3v.v = _mm256_dp_ps( rho3v.v, onev.v, 0xf1 ); rho4v.v = _mm256_dp_ps( rho4v.v, onev.v, 0xf1 ); rho5v.v = _mm256_dp_ps( rho5v.v, onev.v, 0xf1 ); rho6v.v = _mm256_dp_ps( rho6v.v, onev.v, 0xf1 ); rho7v.v = _mm256_dp_ps( rho7v.v, onev.v, 0xf1 ); // Manually add the results from above to finish the sum. rho0 = rho0v.f[0] + rho0v.f[4]; rho1 = rho1v.f[0] + rho1v.f[4]; rho2 = rho2v.f[0] + rho2v.f[4]; rho3 = rho3v.f[0] + rho3v.f[4]; rho4 = rho4v.f[0] + rho4v.f[4]; rho5 = rho5v.f[0] + rho5v.f[4]; rho6 = rho6v.f[0] + rho6v.f[4]; rho7 = rho7v.f[0] + rho7v.f[4]; #endif // Adjust for scalar subproblem. m -= n_elem_per_reg * n_iter_unroll * m_viter; a += n_elem_per_reg * n_iter_unroll * m_viter /* * inca */; x += n_elem_per_reg * n_iter_unroll * m_viter /* * incx */; } else if ( lda == 1 ) { const dim_t n_iter_unroll = 4; // Use the unrolling factor and the number of elements per register // to compute the number of vectorized and leftover iterations. dim_t m_viter = ( m ) / ( n_iter_unroll ); // Initialize pointers for x and A. float* restrict x0 = x; float* restrict a0 = a; // Initialize rho vector accumulators to zero. v8sf_t rho0v; rho0v.v = _mm256_setzero_ps(); v8sf_t rho1v; rho1v.v = _mm256_setzero_ps(); v8sf_t rho2v; rho2v.v = _mm256_setzero_ps(); v8sf_t rho3v; rho3v.v = _mm256_setzero_ps(); v8sf_t x0v, x1v, x2v, x3v; v8sf_t a0v, a1v, a2v, a3v; for ( dim_t i = 0; i < m_viter; ++i ) { // Load the input values. a0v.v = _mm256_loadu_ps( a0 + 0*inca ); a1v.v = _mm256_loadu_ps( a0 + 1*inca ); a2v.v = _mm256_loadu_ps( a0 + 2*inca ); a3v.v = _mm256_loadu_ps( a0 + 3*inca ); x0v.v = _mm256_broadcast_ss( x0 + 0*incx ); x1v.v = _mm256_broadcast_ss( x0 + 1*incx ); x2v.v = _mm256_broadcast_ss( x0 + 2*incx ); x3v.v = _mm256_broadcast_ss( x0 + 3*incx ); // perform : rho?v += a?v * x?v; rho0v.v = _mm256_fmadd_ps( a0v.v, x0v.v, rho0v.v ); rho1v.v = _mm256_fmadd_ps( a1v.v, x1v.v, rho1v.v ); rho2v.v = _mm256_fmadd_ps( a2v.v, x2v.v, rho2v.v ); rho3v.v = _mm256_fmadd_ps( a3v.v, x3v.v, rho3v.v ); x0 += incx * n_iter_unroll; a0 += inca * n_iter_unroll; } // Combine the 8 accumulators into one vector register. rho0v.v = _mm256_add_ps( rho0v.v, rho1v.v ); rho2v.v = _mm256_add_ps( rho2v.v, rho3v.v ); rho0v.v = _mm256_add_ps( rho0v.v, rho2v.v ); // Write vector components to scalar values. rho0 = rho0v.f[0]; rho1 = rho0v.f[1]; rho2 = rho0v.f[2]; rho3 = rho0v.f[3]; rho4 = rho0v.f[4]; rho5 = rho0v.f[5]; rho6 = rho0v.f[6]; rho7 = rho0v.f[7]; // Adjust for scalar subproblem. m -= n_iter_unroll * m_viter; a += n_iter_unroll * m_viter * inca; x += n_iter_unroll * m_viter * incx; } else { // No vectorization possible; use scalar iterations for the entire // problem. } // Scalar edge case. { // Initialize pointers for x and the b_n columns of A (rows of A^T). float* restrict x0 = x; float* restrict a0 = a + 0*lda; float* restrict a1 = a + 1*lda; float* restrict a2 = a + 2*lda; float* restrict a3 = a + 3*lda; float* restrict a4 = a + 4*lda; float* restrict a5 = a + 5*lda; float* restrict a6 = a + 6*lda; float* restrict a7 = a + 7*lda; // If there are leftover iterations, perform them with scalar code. for ( dim_t i = 0; i < m ; ++i ) { const float x0c = *x0; const float a0c = *a0; const float a1c = *a1; const float a2c = *a2; const float a3c = *a3; const float a4c = *a4; const float a5c = *a5; const float a6c = *a6; const float a7c = *a7; rho0 += a0c * x0c; rho1 += a1c * x0c; rho2 += a2c * x0c; rho3 += a3c * x0c; rho4 += a4c * x0c; rho5 += a5c * x0c; rho6 += a6c * x0c; rho7 += a7c * x0c; x0 += incx; a0 += inca; a1 += inca; a2 += inca; a3 += inca; a4 += inca; a5 += inca; a6 += inca; a7 += inca; } } // Now prepare the final rho values to output/accumulate back into // the y vector. v8sf_t rho0v, y0v; // Insert the scalar rho values into a single vector. rho0v.f[0] = rho0; rho0v.f[1] = rho1; rho0v.f[2] = rho2; rho0v.f[3] = rho3; rho0v.f[4] = rho4; rho0v.f[5] = rho5; rho0v.f[6] = rho6; rho0v.f[7] = rho7; // Broadcast the alpha scalar. v8sf_t alphav; alphav.v = _mm256_broadcast_ss( alpha ); // We know at this point that alpha is nonzero; however, beta may still // be zero. If beta is indeed zero, we must overwrite y rather than scale // by beta (in case y contains NaN or Inf). if ( PASTEMAC(s,eq0)( *beta ) ) { // Apply alpha to the accumulated dot product in rho: // y := alpha * rho y0v.v = _mm256_mul_ps( alphav.v, rho0v.v ); } else { // Broadcast the beta scalar. v8sf_t betav; betav.v = _mm256_broadcast_ss( beta ); // Load y. if ( incy == 1 ) { y0v.v = _mm256_loadu_ps( y + 0*n_elem_per_reg ); } else { y0v.f[0] = *(y + 0*incy); y0v.f[1] = *(y + 1*incy); y0v.f[2] = *(y + 2*incy); y0v.f[3] = *(y + 3*incy); y0v.f[4] = *(y + 4*incy); y0v.f[5] = *(y + 5*incy); y0v.f[6] = *(y + 6*incy); y0v.f[7] = *(y + 7*incy); } // Apply beta to y and alpha to the accumulated dot product in rho: // y := beta * y + alpha * rho y0v.v = _mm256_mul_ps( betav.v, y0v.v ); y0v.v = _mm256_fmadd_ps( alphav.v, rho0v.v, y0v.v ); } // Store the output. if ( incy == 1 ) { _mm256_storeu_ps( (y + 0*n_elem_per_reg), y0v.v ); } else { *(y + 0*incy) = y0v.f[0]; *(y + 1*incy) = y0v.f[1]; *(y + 2*incy) = y0v.f[2]; *(y + 3*incy) = y0v.f[3]; *(y + 4*incy) = y0v.f[4]; *(y + 5*incy) = y0v.f[5]; *(y + 6*incy) = y0v.f[6]; *(y + 7*incy) = y0v.f[7]; } } // ----------------------------------------------------------------------------- void bli_ddotxf_zen_int_8 ( conj_t conjat, conj_t conjx, dim_t m, dim_t b_n, double* restrict alpha, double* restrict a, inc_t inca, inc_t lda, double* restrict x, inc_t incx, double* restrict beta, double* restrict y, inc_t incy, cntx_t* cntx ) { const dim_t fuse_fac = 8; const dim_t n_elem_per_reg = 4; // If the b_n dimension is zero, y is empty and there is no computation. if ( bli_zero_dim1( b_n ) ) return; // If the m dimension is zero, or if alpha is zero, the computation // simplifies to updating y. if ( bli_zero_dim1( m ) || PASTEMAC(d,eq0)( *alpha ) ) { dscalv_ker_ft f = bli_cntx_get_ukr_dt( BLIS_DOUBLE, BLIS_SCALV_KER, cntx ); f ( BLIS_NO_CONJUGATE, b_n, beta, y, incy, cntx ); return; } // If b_n is not equal to the fusing factor, then perform the entire // operation as a loop over dotxv. if ( b_n != fuse_fac ) { ddotxv_ker_ft f = bli_cntx_get_ukr_dt( BLIS_DOUBLE, BLIS_DOTXV_KER, cntx ); for ( dim_t i = 0; i < b_n; ++i ) { double* a1 = a + (0 )*inca + (i )*lda; double* x1 = x + (0 )*incx; double* psi1 = y + (i )*incy; f ( conjat, conjx, m, alpha, a1, inca, x1, incx, beta, psi1, cntx ); } return; } // At this point, we know that b_n is exactly equal to the fusing factor. // However, m may not be a multiple of the number of elements per vector. // Going forward, we handle two possible storage formats of A explicitly: // (1) A is stored by columns, or (2) A is stored by rows. Either case is // further split into two subproblems along the m dimension: // (a) a vectorized part, starting at m = 0 and ending at any 0 <= m' <= m. // (b) a scalar part, starting at m' and ending at m. If no vectorization // is possible then m' == 0 and thus the scalar part is the entire // problem. If 0 < m', then the a and x pointers and m variable will // be adjusted accordingly for the second subproblem. // Note: since parts (b) for both (1) and (2) are so similar, they are // factored out into one code block after the following conditional, which // distinguishes between (1) and (2). // Intermediate variables to hold the completed dot products double rho0 = 0, rho1 = 0, rho2 = 0, rho3 = 0, rho4 = 0, rho5 = 0, rho6 = 0, rho7 = 0; if ( inca == 1 && incx == 1 ) { const dim_t n_iter_unroll = 1; // Use the unrolling factor and the number of elements per register // to compute the number of vectorized and leftover iterations. dim_t m_viter = ( m ) / ( n_elem_per_reg * n_iter_unroll ); // Set up pointers for x and the b_n columns of A (rows of A^T). double* restrict x0 = x; double* restrict a0 = a + 0*lda; double* restrict a1 = a + 1*lda; double* restrict a2 = a + 2*lda; double* restrict a3 = a + 3*lda; double* restrict a4 = a + 4*lda; double* restrict a5 = a + 5*lda; double* restrict a6 = a + 6*lda; double* restrict a7 = a + 7*lda; // Initialize b_n rho vector accumulators to zero. v4df_t rho0v; rho0v.v = _mm256_setzero_pd(); v4df_t rho1v; rho1v.v = _mm256_setzero_pd(); v4df_t rho2v; rho2v.v = _mm256_setzero_pd(); v4df_t rho3v; rho3v.v = _mm256_setzero_pd(); v4df_t rho4v; rho4v.v = _mm256_setzero_pd(); v4df_t rho5v; rho5v.v = _mm256_setzero_pd(); v4df_t rho6v; rho6v.v = _mm256_setzero_pd(); v4df_t rho7v; rho7v.v = _mm256_setzero_pd(); v4df_t x0v; v4df_t a0v, a1v, a2v, a3v, a4v, a5v, a6v, a7v; // If there are vectorized iterations, perform them with vector // instructions. for ( dim_t i = 0; i < m_viter; ++i ) { // Load the input values. x0v.v = _mm256_loadu_pd( x0 + 0*n_elem_per_reg ); a0v.v = _mm256_loadu_pd( a0 + 0*n_elem_per_reg ); a1v.v = _mm256_loadu_pd( a1 + 0*n_elem_per_reg ); a2v.v = _mm256_loadu_pd( a2 + 0*n_elem_per_reg ); a3v.v = _mm256_loadu_pd( a3 + 0*n_elem_per_reg ); a4v.v = _mm256_loadu_pd( a4 + 0*n_elem_per_reg ); a5v.v = _mm256_loadu_pd( a5 + 0*n_elem_per_reg ); a6v.v = _mm256_loadu_pd( a6 + 0*n_elem_per_reg ); a7v.v = _mm256_loadu_pd( a7 + 0*n_elem_per_reg ); // perform: rho?v += a?v * x0v; rho0v.v = _mm256_fmadd_pd( a0v.v, x0v.v, rho0v.v ); rho1v.v = _mm256_fmadd_pd( a1v.v, x0v.v, rho1v.v ); rho2v.v = _mm256_fmadd_pd( a2v.v, x0v.v, rho2v.v ); rho3v.v = _mm256_fmadd_pd( a3v.v, x0v.v, rho3v.v ); rho4v.v = _mm256_fmadd_pd( a4v.v, x0v.v, rho4v.v ); rho5v.v = _mm256_fmadd_pd( a5v.v, x0v.v, rho5v.v ); rho6v.v = _mm256_fmadd_pd( a6v.v, x0v.v, rho6v.v ); rho7v.v = _mm256_fmadd_pd( a7v.v, x0v.v, rho7v.v ); x0 += n_elem_per_reg * n_iter_unroll; a0 += n_elem_per_reg * n_iter_unroll; a1 += n_elem_per_reg * n_iter_unroll; a2 += n_elem_per_reg * n_iter_unroll; a3 += n_elem_per_reg * n_iter_unroll; a4 += n_elem_per_reg * n_iter_unroll; a5 += n_elem_per_reg * n_iter_unroll; a6 += n_elem_per_reg * n_iter_unroll; a7 += n_elem_per_reg * n_iter_unroll; } #if 0 rho0 += rho0v.d[0] + rho0v.d[1] + rho0v.d[2] + rho0v.d[3]; rho1 += rho1v.d[0] + rho1v.d[1] + rho1v.d[2] + rho1v.d[3]; rho2 += rho2v.d[0] + rho2v.d[1] + rho2v.d[2] + rho2v.d[3]; rho3 += rho3v.d[0] + rho3v.d[1] + rho3v.d[2] + rho3v.d[3]; rho4 += rho4v.d[0] + rho4v.d[1] + rho4v.d[2] + rho4v.d[3]; rho5 += rho5v.d[0] + rho5v.d[1] + rho5v.d[2] + rho5v.d[3]; rho6 += rho6v.d[0] + rho6v.d[1] + rho6v.d[2] + rho6v.d[3]; rho7 += rho7v.d[0] + rho7v.d[1] + rho7v.d[2] + rho7v.d[3]; #else // Sum the elements of a given rho?v. This computes the sum of // elements within lanes and stores the sum to both elements. rho0v.v = _mm256_hadd_pd( rho0v.v, rho0v.v ); rho1v.v = _mm256_hadd_pd( rho1v.v, rho1v.v ); rho2v.v = _mm256_hadd_pd( rho2v.v, rho2v.v ); rho3v.v = _mm256_hadd_pd( rho3v.v, rho3v.v ); rho4v.v = _mm256_hadd_pd( rho4v.v, rho4v.v ); rho5v.v = _mm256_hadd_pd( rho5v.v, rho5v.v ); rho6v.v = _mm256_hadd_pd( rho6v.v, rho6v.v ); rho7v.v = _mm256_hadd_pd( rho7v.v, rho7v.v ); // Manually add the results from above to finish the sum. rho0 = rho0v.d[0] + rho0v.d[2]; rho1 = rho1v.d[0] + rho1v.d[2]; rho2 = rho2v.d[0] + rho2v.d[2]; rho3 = rho3v.d[0] + rho3v.d[2]; rho4 = rho4v.d[0] + rho4v.d[2]; rho5 = rho5v.d[0] + rho5v.d[2]; rho6 = rho6v.d[0] + rho6v.d[2]; rho7 = rho7v.d[0] + rho7v.d[2]; #endif // Adjust for scalar subproblem. m -= n_elem_per_reg * n_iter_unroll * m_viter; a += n_elem_per_reg * n_iter_unroll * m_viter /* * inca */; x += n_elem_per_reg * n_iter_unroll * m_viter /* * incx */; } else if ( lda == 1 ) { const dim_t n_iter_unroll = 3; const dim_t n_reg_per_row = 2; // fuse_fac / n_elem_per_reg; // Use the unrolling factor and the number of elements per register // to compute the number of vectorized and leftover iterations. dim_t m_viter = ( m ) / ( n_reg_per_row * n_iter_unroll ); // Initialize pointers for x and A. double* restrict x0 = x; double* restrict a0 = a; // Initialize rho vector accumulators to zero. v4df_t rho0v; rho0v.v = _mm256_setzero_pd(); v4df_t rho1v; rho1v.v = _mm256_setzero_pd(); v4df_t rho2v; rho2v.v = _mm256_setzero_pd(); v4df_t rho3v; rho3v.v = _mm256_setzero_pd(); v4df_t rho4v; rho4v.v = _mm256_setzero_pd(); v4df_t rho5v; rho5v.v = _mm256_setzero_pd(); v4df_t x0v, x1v, x2v; v4df_t a0v, a1v, a2v, a3v, a4v, a5v; for ( dim_t i = 0; i < m_viter; ++i ) { // Load the input values. a0v.v = _mm256_loadu_pd( a0 + 0*inca + 0*n_elem_per_reg ); a1v.v = _mm256_loadu_pd( a0 + 0*inca + 1*n_elem_per_reg ); a2v.v = _mm256_loadu_pd( a0 + 1*inca + 0*n_elem_per_reg ); a3v.v = _mm256_loadu_pd( a0 + 1*inca + 1*n_elem_per_reg ); a4v.v = _mm256_loadu_pd( a0 + 2*inca + 0*n_elem_per_reg ); a5v.v = _mm256_loadu_pd( a0 + 2*inca + 1*n_elem_per_reg ); x0v.v = _mm256_broadcast_sd( x0 + 0*incx ); x1v.v = _mm256_broadcast_sd( x0 + 1*incx ); x2v.v = _mm256_broadcast_sd( x0 + 2*incx ); // perform : rho?v += a?v * x?v; rho0v.v = _mm256_fmadd_pd( a0v.v, x0v.v, rho0v.v ); rho1v.v = _mm256_fmadd_pd( a1v.v, x0v.v, rho1v.v ); rho2v.v = _mm256_fmadd_pd( a2v.v, x1v.v, rho2v.v ); rho3v.v = _mm256_fmadd_pd( a3v.v, x1v.v, rho3v.v ); rho4v.v = _mm256_fmadd_pd( a4v.v, x2v.v, rho4v.v ); rho5v.v = _mm256_fmadd_pd( a5v.v, x2v.v, rho5v.v ); x0 += incx * n_iter_unroll; a0 += inca * n_iter_unroll; } // Combine the 8 accumulators into one vector register. rho0v.v = _mm256_add_pd( rho0v.v, rho2v.v ); rho0v.v = _mm256_add_pd( rho0v.v, rho4v.v ); rho1v.v = _mm256_add_pd( rho1v.v, rho3v.v ); rho1v.v = _mm256_add_pd( rho1v.v, rho5v.v ); // Write vector components to scalar values. rho0 = rho0v.d[0]; rho1 = rho0v.d[1]; rho2 = rho0v.d[2]; rho3 = rho0v.d[3]; rho4 = rho1v.d[0]; rho5 = rho1v.d[1]; rho6 = rho1v.d[2]; rho7 = rho1v.d[3]; // Adjust for scalar subproblem. m -= n_iter_unroll * m_viter; a += n_iter_unroll * m_viter * inca; x += n_iter_unroll * m_viter * incx; } else { // No vectorization possible; use scalar iterations for the entire // problem. } // Scalar edge case. { // Initialize pointers for x and the b_n columns of A (rows of A^T). double* restrict x0 = x; double* restrict a0 = a + 0*lda; double* restrict a1 = a + 1*lda; double* restrict a2 = a + 2*lda; double* restrict a3 = a + 3*lda; double* restrict a4 = a + 4*lda; double* restrict a5 = a + 5*lda; double* restrict a6 = a + 6*lda; double* restrict a7 = a + 7*lda; // If there are leftover iterations, perform them with scalar code. for ( dim_t i = 0; i < m ; ++i ) { const double x0c = *x0; const double a0c = *a0; const double a1c = *a1; const double a2c = *a2; const double a3c = *a3; const double a4c = *a4; const double a5c = *a5; const double a6c = *a6; const double a7c = *a7; rho0 += a0c * x0c; rho1 += a1c * x0c; rho2 += a2c * x0c; rho3 += a3c * x0c; rho4 += a4c * x0c; rho5 += a5c * x0c; rho6 += a6c * x0c; rho7 += a7c * x0c; x0 += incx; a0 += inca; a1 += inca; a2 += inca; a3 += inca; a4 += inca; a5 += inca; a6 += inca; a7 += inca; } } // Now prepare the final rho values to output/accumulate back into // the y vector. v4df_t rho0v, rho1v, y0v, y1v; // Insert the scalar rho values into a single vector. rho0v.d[0] = rho0; rho0v.d[1] = rho1; rho0v.d[2] = rho2; rho0v.d[3] = rho3; rho1v.d[0] = rho4; rho1v.d[1] = rho5; rho1v.d[2] = rho6; rho1v.d[3] = rho7; // Broadcast the alpha scalar. v4df_t alphav; alphav.v = _mm256_broadcast_sd( alpha ); // We know at this point that alpha is nonzero; however, beta may still // be zero. If beta is indeed zero, we must overwrite y rather than scale // by beta (in case y contains NaN or Inf). if ( PASTEMAC(d,eq0)( *beta ) ) { // Apply alpha to the accumulated dot product in rho: // y := alpha * rho y0v.v = _mm256_mul_pd( alphav.v, rho0v.v ); y1v.v = _mm256_mul_pd( alphav.v, rho1v.v ); } else { // Broadcast the beta scalar. v4df_t betav; betav.v = _mm256_broadcast_sd( beta ); // Load y. if ( incy == 1 ) { y0v.v = _mm256_loadu_pd( y + 0*n_elem_per_reg ); y1v.v = _mm256_loadu_pd( y + 1*n_elem_per_reg ); } else { y0v.d[0] = *(y + 0*incy); y0v.d[1] = *(y + 1*incy); y0v.d[2] = *(y + 2*incy); y0v.d[3] = *(y + 3*incy); y1v.d[0] = *(y + 4*incy); y1v.d[1] = *(y + 5*incy); y1v.d[2] = *(y + 6*incy); y1v.d[3] = *(y + 7*incy); } // Apply beta to y and alpha to the accumulated dot product in rho: // y := beta * y + alpha * rho y0v.v = _mm256_mul_pd( betav.v, y0v.v ); y1v.v = _mm256_mul_pd( betav.v, y1v.v ); y0v.v = _mm256_fmadd_pd( alphav.v, rho0v.v, y0v.v ); y1v.v = _mm256_fmadd_pd( alphav.v, rho1v.v, y1v.v ); } if ( incy == 1 ) { // Store the output. _mm256_storeu_pd( (y + 0*n_elem_per_reg), y0v.v ); _mm256_storeu_pd( (y + 1*n_elem_per_reg), y1v.v ); } else { *(y + 0*incy) = y0v.d[0]; *(y + 1*incy) = y0v.d[1]; *(y + 2*incy) = y0v.d[2]; *(y + 3*incy) = y0v.d[3]; *(y + 4*incy) = y1v.d[0]; *(y + 5*incy) = y1v.d[1]; *(y + 6*incy) = y1v.d[2]; *(y + 7*incy) = y1v.d[3]; } }
135130.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__malloc_char_memcpy_54c.c Label Definition File: CWE126_Buffer_Overread__malloc.label.xml Template File: sources-sink-54c.tmpl.c */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sink: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void CWE126_Buffer_Overread__malloc_char_memcpy_54d_badSink(char * data); void CWE126_Buffer_Overread__malloc_char_memcpy_54c_badSink(char * data) { CWE126_Buffer_Overread__malloc_char_memcpy_54d_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declaration */ void CWE126_Buffer_Overread__malloc_char_memcpy_54d_goodG2BSink(char * data); /* goodG2B uses the GoodSource with the BadSink */ void CWE126_Buffer_Overread__malloc_char_memcpy_54c_goodG2BSink(char * data) { CWE126_Buffer_Overread__malloc_char_memcpy_54d_goodG2BSink(data); } #endif /* OMITGOOD */
929199.c
#include <math.h> #include <stdlib.h> #include <stdio.h> #include "xxhash.h" #include "ida_search_core.h" #include "ida_search_777.h" // ============================================================================ // step20 - stage LR oblique edges // ============================================================================ unsigned int oblique_edges_777[NUM_OBLIQUE_EDGES_777] = { 10, 11, 12, 16, 20, 23, 27, 30, 34, 38, 39, 40, // Upper 59, 60, 61, 65, 69, 72, 76, 79, 83, 87, 88, 89, // Left 108, 109, 110, 114, 118, 121, 125, 128, 132, 136, 137, 138, // Front 157, 158, 159, 163, 167, 170, 174, 177, 181, 185, 186, 187, // Right 206, 207, 208, 212, 216, 219, 223, 226, 230, 234, 235, 236, // Back 255, 256, 257, 261, 265, 268, 272, 275, 279, 283, 284, 285, // Down }; unsigned int left_oblique_edges_777[NUM_LEFT_OBLIQUE_EDGES_777] = { 10, 30, 20, 40, // Upper 59, 79, 69, 89, // Left 108, 128, 118, 138, // Front 157, 177, 167, 187, // Right 206, 226, 216, 236, // Back 255, 275, 265, 285, // Down }; unsigned int middle_oblique_edges_777[NUM_MIDDLE_OBLIQUE_EDGES_777] = { 11, 23, 27, 39, // Upper 60, 72, 76, 88, // Left 109, 121, 125, 137, // Front 158, 170, 174, 186, // Right 207, 219, 223, 235, // Back 256, 268, 272, 284, // Down }; unsigned int right_oblique_edges_777[NUM_RIGHT_OBLIQUE_EDGES_777] = { 12, 16, 34, 38, // Upper 61, 65, 83, 87, // Left 110, 114, 132, 136, // Front 159, 163, 181, 185, // Right 208, 212, 230, 234, // Back 257, 261, 279, 283, // Down }; unsigned char get_unpaired_left_obliques_count_777 (char *cube) { unsigned char left_unpaired_obliques = 8; unsigned int left_cube_index = 0; unsigned int middle_cube_index = 0; for (unsigned char i = 0; i < NUM_MIDDLE_OBLIQUE_EDGES_777; i++) { left_cube_index = left_oblique_edges_777[i]; middle_cube_index = middle_oblique_edges_777[i]; if (cube[left_cube_index] == '1' && cube[middle_cube_index] == '1') { left_unpaired_obliques -= 1; } } return left_unpaired_obliques; } unsigned char get_unpaired_right_obliques_count_777 (char *cube) { unsigned char right_unpaired_obliques = 8; unsigned int middle_cube_index = 0; unsigned int right_cube_index = 0; for (unsigned char i = 0; i < NUM_MIDDLE_OBLIQUE_EDGES_777; i++) { middle_cube_index = middle_oblique_edges_777[i]; right_cube_index = right_oblique_edges_777[i]; if (cube[right_cube_index] == '1' && cube[middle_cube_index] == '1') { if (right_unpaired_obliques == 0) { printf("ERROR: right_unpaired_obliques is already 0, i %d, middle_cube_index %d, right_cube_index %d", i, middle_cube_index, right_cube_index); print_cube(cube, 7); exit(1); } right_unpaired_obliques -= 1; } } return right_unpaired_obliques; } unsigned char get_unpaired_obliques_count_777 (char *cube) { unsigned char left_paired_obliques = 0; unsigned char left_unpaired_obliques = 8; unsigned char right_paired_obliques = 0; unsigned char right_unpaired_obliques = 8; unsigned int left_cube_index = 0; unsigned int middle_cube_index = 0; unsigned int right_cube_index = 0; for (unsigned char i = 0; i < NUM_LEFT_OBLIQUE_EDGES_777; i++) { left_cube_index = left_oblique_edges_777[i]; middle_cube_index = middle_oblique_edges_777[i]; right_cube_index = right_oblique_edges_777[i]; if (cube[left_cube_index] == '1' && cube[middle_cube_index] == '1') { left_paired_obliques += 1; } if (cube[right_cube_index] == '1' && cube[middle_cube_index] == '1') { right_paired_obliques += 1; } } left_unpaired_obliques -= left_paired_obliques; right_unpaired_obliques -= right_paired_obliques; return (left_unpaired_obliques + right_unpaired_obliques); } struct ida_heuristic_result ida_heuristic_LR_oblique_edges_stage_777 ( char *cube, unsigned int max_cost_to_goal) { int unpaired_count = get_unpaired_obliques_count_777(cube); struct ida_heuristic_result result; unsigned long long state = 0; // Get the state of the oblique edges for (int i = 0; i < NUM_OBLIQUE_EDGES_777; i++) { if (cube[oblique_edges_777[i]] == '1') { state |= 0x1; } state <<= 1; } // state takes 18 chars in hex state >>= 1; sprintf(result.lt_state, "%018llx", state); // inadmissable heuristic but fast...kudos to xyzzy for this formula if (unpaired_count > 8) { result.cost_to_goal = 4 + (unpaired_count >> 1); } else { result.cost_to_goal = unpaired_count; } return result; } int ida_search_complete_LR_oblique_edges_stage_777 (char *cube) { if (get_unpaired_obliques_count_777(cube) == 0) { return 1; } else { return 0; } } // ============================================================================ // step30 - stage UD oblique edges // ============================================================================ unsigned int UFBD_oblique_edges_777[NUM_OBLIQUE_EDGES_777] = { 10, 11, 12, 16, 20, 23, 27, 30, 34, 38, 39, 40, // Upper 108, 109, 110, 114, 118, 121, 125, 128, 132, 136, 137, 138, // Front 206, 207, 208, 212, 216, 219, 223, 226, 230, 234, 235, 236, // Back 255, 256, 257, 261, 265, 268, 272, 275, 279, 283, 284, 285, // Down }; unsigned int UFBD_left_oblique_edges_777[NUM_LEFT_OBLIQUE_EDGES_777] = { 10, 30, 20, 40, // Upper 108, 128, 118, 138, // Front 206, 226, 216, 236, // Back 255, 275, 265, 285, // Down }; unsigned int UFBD_middle_oblique_edges_777[NUM_MIDDLE_OBLIQUE_EDGES_777] = { 11, 23, 27, 39, // Upper 109, 121, 125, 137, // Front 207, 219, 223, 235, // Back 256, 268, 272, 284, // Down }; unsigned int UFBD_right_oblique_edges_777[NUM_RIGHT_OBLIQUE_EDGES_777] = { 12, 16, 34, 38, // Upper 110, 114, 132, 136, // Front 208, 212, 230, 234, // Back 257, 261, 279, 283, // Down }; unsigned int get_UFBD_unpaired_obliques_count_777 (char *cube) { int left_paired_obliques = 0; int left_unpaired_obliques = 8; int right_paired_obliques = 0; int right_unpaired_obliques = 8; int left_cube_index = 0; int middle_cube_index = 0; int right_cube_index = 0; for (int i = 0; i < UFBD_NUM_LEFT_OBLIQUE_EDGES_777; i++) { left_cube_index = UFBD_left_oblique_edges_777[i]; middle_cube_index = UFBD_middle_oblique_edges_777[i]; right_cube_index = UFBD_right_oblique_edges_777[i]; if (cube[left_cube_index] == '1' && cube[middle_cube_index] == '1') { left_paired_obliques += 1; } if (cube[right_cube_index] == '1' && cube[middle_cube_index] == '1') { right_paired_obliques += 1; } } left_unpaired_obliques -= left_paired_obliques; right_unpaired_obliques -= right_paired_obliques; return (left_unpaired_obliques + right_unpaired_obliques); } struct ida_heuristic_result ida_heuristic_UD_oblique_edges_stage_777 ( char *cube, unsigned int max_cost_to_goal) { struct ida_heuristic_result result; unsigned long long state = 0; // Get the state of the oblique edges for (int i = 0; i < UFBD_NUM_OBLIQUE_EDGES_777; i++) { if (cube[UFBD_oblique_edges_777[i]] == '1') { state |= 0x1; } state <<= 1; } // state takes 12 chars in hex state >>= 1; sprintf(result.lt_state, "%012llx", state); // inadmissable heuristic but fast...kudos to xyzzy for this formula int unpaired_count = get_unpaired_obliques_count_777(cube); if (unpaired_count > 8) { result.cost_to_goal = 4 + (unpaired_count >> 1); } else { result.cost_to_goal = unpaired_count; } // Not used...I was experimenting with using the left_oblique count and // right oblique count seperately. Will leave this hear for a rainy day. /* unsigned char unpaired_left_count = get_unpaired_left_obliques_count_777(cube); unsigned char unpaired_right_count = get_unpaired_right_obliques_count_777(cube); unsigned char unpaired_count = 0; if (unpaired_left_count >= unpaired_right_count) { unpaired_count = unpaired_left_count; } else { unpaired_count = unpaired_right_count; } if (unpaired_count > 8) { print_cube(cube, 7); printf("unpaired_left_count %d\n", unpaired_left_count); printf("unpaired_right_count %d\n", unpaired_right_count); printf("ERROR: invalid unpaired_count %d\n", unpaired_count); exit(1); } // There are at most 8 unpaired left obliques or 8 unpaired right obliques. // Optimally solve a bunch and get some stats that show what total cost is // when considering left and right obliques? // The most we can pair at a time is 2 so divide by 2 for an admissable heuristic if (unpaired_count) { // result.cost_to_goal = ceil(unpaired_count / 2); result.cost_to_goal = ceil(unpaired_count / 1.1); } else { result.cost_to_goal = 0; } */ return result; } int ida_search_complete_UD_oblique_edges_stage_777 (char *cube) { if (get_UFBD_unpaired_obliques_count_777(cube) == 0) { return 1; } else { return 0; } }
112676.c
/*------------------------------------------------------------------------- * * varsup.c * postgres OID & XID variables support routines * * Copyright (c) 2000-2017, PostgreSQL Global Development Group * * IDENTIFICATION * src/backend/access/transam/varsup.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/clog.h" #include "access/commit_ts.h" #include "access/subtrans.h" #include "access/transam.h" #include "access/xact.h" #include "access/xlog.h" #include "commands/dbcommands.h" #include "miscadmin.h" #include "postmaster/autovacuum.h" #include "storage/pmsignal.h" #include "storage/proc.h" #include "utils/syscache.h" /* Number of OIDs to prefetch (preallocate) per XLOG write */ #define VAR_OID_PREFETCH 8192 /* pointer to "variable cache" in shared memory (set up by shmem.c) */ VariableCache ShmemVariableCache = NULL; /* * Allocate the next XID for a new transaction or subtransaction. * * The new XID is also stored into MyPgXact before returning. * * Note: when this is called, we are actually already inside a valid * transaction, since XIDs are now not allocated until the transaction * does something. So it is safe to do a database lookup if we want to * issue a warning about XID wrap. */ TransactionId GetNewTransactionId(bool isSubXact) { TransactionId xid; /* * Workers synchronize transaction state at the beginning of each parallel * operation, so we can't account for new XIDs after that point. */ if (IsInParallelMode()) elog(ERROR, "cannot assign TransactionIds during a parallel operation"); /* * During bootstrap initialization, we return the special bootstrap * transaction id. */ if (IsBootstrapProcessingMode()) { Assert(!isSubXact); MyPgXact->xid = BootstrapTransactionId; return BootstrapTransactionId; } /* safety check, we should never get this far in a HS slave */ if (RecoveryInProgress()) elog(ERROR, "cannot assign TransactionIds during recovery"); LWLockAcquire(XidGenLock, LW_EXCLUSIVE); xid = ShmemVariableCache->nextXid; /*---------- * Check to see if it's safe to assign another XID. This protects against * catastrophic data loss due to XID wraparound. The basic rules are: * * If we're past xidVacLimit, start trying to force autovacuum cycles. * If we're past xidWarnLimit, start issuing warnings. * If we're past xidStopLimit, refuse to execute transactions, unless * we are running in single-user mode (which gives an escape hatch * to the DBA who somehow got past the earlier defenses). * * Note that this coding also appears in GetNewMultiXactId. *---------- */ if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit)) { /* * For safety's sake, we release XidGenLock while sending signals, * warnings, etc. This is not so much because we care about * preserving concurrency in this situation, as to avoid any * possibility of deadlock while doing get_database_name(). First, * copy all the shared values we'll need in this path. */ TransactionId xidWarnLimit = ShmemVariableCache->xidWarnLimit; TransactionId xidStopLimit = ShmemVariableCache->xidStopLimit; TransactionId xidWrapLimit = ShmemVariableCache->xidWrapLimit; Oid oldest_datoid = ShmemVariableCache->oldestXidDB; LWLockRelease(XidGenLock); /* * To avoid swamping the postmaster with signals, we issue the autovac * request only once per 64K transaction starts. This still gives * plenty of chances before we get into real trouble. */ if (IsUnderPostmaster && (xid % 65536) == 0) SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER); if (IsUnderPostmaster && TransactionIdFollowsOrEquals(xid, xidStopLimit)) { char *oldest_datname = get_database_name(oldest_datoid); /* complain even if that DB has disappeared */ if (oldest_datname) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"", oldest_datname), errhint("Stop the postmaster and vacuum that database in single-user mode.\n" "You might also need to commit or roll back old prepared transactions."))); else ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("database is not accepting commands to avoid wraparound data loss in database with OID %u", oldest_datoid), errhint("Stop the postmaster and vacuum that database in single-user mode.\n" "You might also need to commit or roll back old prepared transactions."))); } else if (TransactionIdFollowsOrEquals(xid, xidWarnLimit)) { char *oldest_datname = get_database_name(oldest_datoid); /* complain even if that DB has disappeared */ if (oldest_datname) ereport(WARNING, (errmsg("database \"%s\" must be vacuumed within %u transactions", oldest_datname, xidWrapLimit - xid), errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n" "You might also need to commit or roll back old prepared transactions."))); else ereport(WARNING, (errmsg("database with OID %u must be vacuumed within %u transactions", oldest_datoid, xidWrapLimit - xid), errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n" "You might also need to commit or roll back old prepared transactions."))); } /* Re-acquire lock and start over */ LWLockAcquire(XidGenLock, LW_EXCLUSIVE); xid = ShmemVariableCache->nextXid; } /* * If we are allocating the first XID of a new page of the commit log, * zero out that commit-log page before returning. We must do this while * holding XidGenLock, else another xact could acquire and commit a later * XID before we zero the page. Fortunately, a page of the commit log * holds 32K or more transactions, so we don't have to do this very often. * * Extend pg_subtrans and pg_commit_ts too. */ ExtendCLOG(xid); ExtendCommitTs(xid); ExtendSUBTRANS(xid); /* * Now advance the nextXid counter. This must not happen until after we * have successfully completed ExtendCLOG() --- if that routine fails, we * want the next incoming transaction to try it again. We cannot assign * more XIDs until there is CLOG space for them. */ TransactionIdAdvance(ShmemVariableCache->nextXid); /* * We must store the new XID into the shared ProcArray before releasing * XidGenLock. This ensures that every active XID older than * latestCompletedXid is present in the ProcArray, which is essential for * correct OldestXmin tracking; see src/backend/access/transam/README. * * XXX by storing xid into MyPgXact without acquiring ProcArrayLock, we * are relying on fetch/store of an xid to be atomic, else other backends * might see a partially-set xid here. But holding both locks at once * would be a nasty concurrency hit. So for now, assume atomicity. * * Note that readers of PGXACT xid fields should be careful to fetch the * value only once, rather than assume they can read a value multiple * times and get the same answer each time. * * The same comments apply to the subxact xid count and overflow fields. * * A solution to the atomic-store problem would be to give each PGXACT its * own spinlock used only for fetching/storing that PGXACT's xid and * related fields. * * If there's no room to fit a subtransaction XID into PGPROC, set the * cache-overflowed flag instead. This forces readers to look in * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a * race-condition window, in that the new XID will not appear as running * until its parent link has been placed into pg_subtrans. However, that * will happen before anyone could possibly have a reason to inquire about * the status of the XID, so it seems OK. (Snapshots taken during this * window *will* include the parent XID, so they will deliver the correct * answer later on when someone does have a reason to inquire.) */ { /* * Use volatile pointer to prevent code rearrangement; other backends * could be examining my subxids info concurrently, and we don't want * them to see an invalid intermediate state, such as incrementing * nxids before filling the array entry. Note we are assuming that * TransactionId and int fetch/store are atomic. */ volatile PGPROC *myproc = MyProc; volatile PGXACT *mypgxact = MyPgXact; if (!isSubXact) mypgxact->xid = xid; else { int nxids = mypgxact->nxids; if (nxids < PGPROC_MAX_CACHED_SUBXIDS) { myproc->subxids.xids[nxids] = xid; mypgxact->nxids = nxids + 1; } else mypgxact->overflowed = true; } } LWLockRelease(XidGenLock); return xid; } /* * Read nextXid but don't allocate it. */ TransactionId ReadNewTransactionId(void) { TransactionId xid; LWLockAcquire(XidGenLock, LW_SHARED); xid = ShmemVariableCache->nextXid; LWLockRelease(XidGenLock); return xid; } /* * Determine the last safe XID to allocate given the currently oldest * datfrozenxid (ie, the oldest XID that might exist in any database * of our cluster), and the OID of the (or a) database with that value. */ void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid) { TransactionId xidVacLimit; TransactionId xidWarnLimit; TransactionId xidStopLimit; TransactionId xidWrapLimit; TransactionId curXid; Assert(TransactionIdIsNormal(oldest_datfrozenxid)); /* * The place where we actually get into deep trouble is halfway around * from the oldest potentially-existing XID. (This calculation is * probably off by one or two counts, because the special XIDs reduce the * size of the loop a little bit. But we throw in plenty of slop below, * so it doesn't matter.) */ xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1); if (xidWrapLimit < FirstNormalTransactionId) xidWrapLimit += FirstNormalTransactionId; /* * We'll refuse to continue assigning XIDs in interactive mode once we get * within 1M transactions of data loss. This leaves lots of room for the * DBA to fool around fixing things in a standalone backend, while not * being significant compared to total XID space. (Note that since * vacuuming requires one transaction per table cleaned, we had better be * sure there's lots of XIDs left...) */ xidStopLimit = xidWrapLimit - 1000000; if (xidStopLimit < FirstNormalTransactionId) xidStopLimit -= FirstNormalTransactionId; /* * We'll start complaining loudly when we get within 10M transactions of * the stop point. This is kind of arbitrary, but if you let your gas * gauge get down to 1% of full, would you be looking for the next gas * station? We need to be fairly liberal about this number because there * are lots of scenarios where most transactions are done by automatic * clients that won't pay attention to warnings. (No, we're not gonna make * this configurable. If you know enough to configure it, you know enough * to not get in this kind of trouble in the first place.) */ xidWarnLimit = xidStopLimit - 10000000; if (xidWarnLimit < FirstNormalTransactionId) xidWarnLimit -= FirstNormalTransactionId; /* * We'll start trying to force autovacuums when oldest_datfrozenxid gets * to be more than autovacuum_freeze_max_age transactions old. * * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range, * so that xidVacLimit will be well before xidWarnLimit. * * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that * we don't have to worry about dealing with on-the-fly changes in its * value. It doesn't look practical to update shared state from a GUC * assign hook (too many processes would try to execute the hook, * resulting in race conditions as well as crashes of those not connected * to shared memory). Perhaps this can be improved someday. See also * SetMultiXactIdLimit. */ xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age; if (xidVacLimit < FirstNormalTransactionId) xidVacLimit += FirstNormalTransactionId; /* Grab lock for just long enough to set the new limit values */ LWLockAcquire(XidGenLock, LW_EXCLUSIVE); ShmemVariableCache->oldestXid = oldest_datfrozenxid; ShmemVariableCache->xidVacLimit = xidVacLimit; ShmemVariableCache->xidWarnLimit = xidWarnLimit; ShmemVariableCache->xidStopLimit = xidStopLimit; ShmemVariableCache->xidWrapLimit = xidWrapLimit; ShmemVariableCache->oldestXidDB = oldest_datoid; curXid = ShmemVariableCache->nextXid; LWLockRelease(XidGenLock); /* Log the info */ ereport(DEBUG1, (errmsg("transaction ID wrap limit is %u, limited by database with OID %u", xidWrapLimit, oldest_datoid))); /* * If past the autovacuum force point, immediately signal an autovac * request. The reason for this is that autovac only processes one * database per invocation. Once it's finished cleaning up the oldest * database, it'll call here, and we'll signal the postmaster to start * another iteration immediately if there are still any old databases. */ if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) && IsUnderPostmaster && !InRecovery) SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER); /* Give an immediate warning if past the wrap warn point */ if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit) && !InRecovery) { char *oldest_datname; /* * We can be called when not inside a transaction, for example during * StartupXLOG(). In such a case we cannot do database access, so we * must just report the oldest DB's OID. * * Note: it's also possible that get_database_name fails and returns * NULL, for example because the database just got dropped. We'll * still warn, even though the warning might now be unnecessary. */ if (IsTransactionState()) oldest_datname = get_database_name(oldest_datoid); else oldest_datname = NULL; if (oldest_datname) ereport(WARNING, (errmsg("database \"%s\" must be vacuumed within %u transactions", oldest_datname, xidWrapLimit - curXid), errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n" "You might also need to commit or roll back old prepared transactions."))); else ereport(WARNING, (errmsg("database with OID %u must be vacuumed within %u transactions", oldest_datoid, xidWrapLimit - curXid), errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n" "You might also need to commit or roll back old prepared transactions."))); } } /* * ForceTransactionIdLimitUpdate -- does the XID wrap-limit data need updating? * * We primarily check whether oldestXidDB is valid. The cases we have in * mind are that that database was dropped, or the field was reset to zero * by pg_resetxlog. In either case we should force recalculation of the * wrap limit. Also do it if oldestXid is old enough to be forcing * autovacuums or other actions; this ensures we update our state as soon * as possible once extra overhead is being incurred. */ bool ForceTransactionIdLimitUpdate(void) { TransactionId nextXid; TransactionId xidVacLimit; TransactionId oldestXid; Oid oldestXidDB; /* Locking is probably not really necessary, but let's be careful */ LWLockAcquire(XidGenLock, LW_SHARED); nextXid = ShmemVariableCache->nextXid; xidVacLimit = ShmemVariableCache->xidVacLimit; oldestXid = ShmemVariableCache->oldestXid; oldestXidDB = ShmemVariableCache->oldestXidDB; LWLockRelease(XidGenLock); if (!TransactionIdIsNormal(oldestXid)) return true; /* shouldn't happen, but just in case */ if (!TransactionIdIsValid(xidVacLimit)) return true; /* this shouldn't happen anymore either */ if (TransactionIdFollowsOrEquals(nextXid, xidVacLimit)) return true; /* past VacLimit, don't delay updating */ if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(oldestXidDB))) return true; /* could happen, per comments above */ return false; } /* * GetNewObjectId -- allocate a new OID * * OIDs are generated by a cluster-wide counter. Since they are only 32 bits * wide, counter wraparound will occur eventually, and therefore it is unwise * to assume they are unique unless precautions are taken to make them so. * Hence, this routine should generally not be used directly. The only * direct callers should be GetNewOid() and GetNewRelFileNode() in * catalog/catalog.c. */ Oid GetNewObjectId(void) { Oid result; /* safety check, we should never get this far in a HS slave */ if (RecoveryInProgress()) elog(ERROR, "cannot assign OIDs during recovery"); LWLockAcquire(OidGenLock, LW_EXCLUSIVE); /* * Check for wraparound of the OID counter. We *must* not return 0 * (InvalidOid); and as long as we have to check that, it seems a good * idea to skip over everything below FirstNormalObjectId too. (This * basically just avoids lots of collisions with bootstrap-assigned OIDs * right after a wrap occurs, so as to avoid a possibly large number of * iterations in GetNewOid.) Note we are relying on unsigned comparison. * * During initdb, we start the OID generator at FirstBootstrapObjectId, so * we only wrap if before that point when in bootstrap or standalone mode. * The first time through this routine after normal postmaster start, the * counter will be forced up to FirstNormalObjectId. This mechanism * leaves the OIDs between FirstBootstrapObjectId and FirstNormalObjectId * available for automatic assignment during initdb, while ensuring they * will never conflict with user-assigned OIDs. */ if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId)) { if (IsPostmasterEnvironment) { /* wraparound, or first post-initdb assignment, in normal mode */ ShmemVariableCache->nextOid = FirstNormalObjectId; ShmemVariableCache->oidCount = 0; } else { /* we may be bootstrapping, so don't enforce the full range */ if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId)) { /* wraparound in standalone mode (unlikely but possible) */ ShmemVariableCache->nextOid = FirstNormalObjectId; ShmemVariableCache->oidCount = 0; } } } /* If we run out of logged for use oids then we must log more */ if (ShmemVariableCache->oidCount == 0) { XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH); ShmemVariableCache->oidCount = VAR_OID_PREFETCH; } result = ShmemVariableCache->nextOid; (ShmemVariableCache->nextOid)++; (ShmemVariableCache->oidCount)--; LWLockRelease(OidGenLock); return result; }
352424.c
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct Tree Tree; int size = 0; struct Tree { int key; int height; Tree* left; Tree* right; }; int max(int a, int b) { return (a > b) ? a : b; } int getHeight(Tree* tree) { return tree ? tree->height : 0; } int balanceFactor(Tree* tree) { return tree ? getHeight(tree->right) - getHeight(tree->left) : 0; } void fixHeight(Tree* tree) { if (tree) tree->height = max(getHeight(tree->left), getHeight(tree->right)) + 1; } Tree* rotateRight(Tree* tree) { Tree* newTree = tree->left; tree->left = newTree->right; newTree->right = tree; fixHeight(tree); fixHeight(newTree); return newTree; } Tree* rotateLeft(Tree* tree) { Tree* newTree = tree->right; tree->right = newTree->left; newTree->left = tree; fixHeight(tree); fixHeight(newTree); return newTree; } Tree* balance(Tree* tree) { fixHeight(tree); if (balanceFactor(tree) == 2) { if (balanceFactor(tree->right) < 0) tree->right = rotateRight(tree->right); return rotateLeft(tree); } if (balanceFactor(tree) == -2) { if (balanceFactor(tree->left) > 0) tree->left = rotateLeft(tree->left); return rotateRight(tree); } return tree; } Tree* createTree(int key) { Tree* tree = malloc(sizeof(Tree)); tree->left = NULL; tree->right = NULL; tree->height = 1; tree->key = key; return tree; } void deleteTree(Tree* tree) { if (!tree) return; if (tree->left) deleteTree(tree->left); if (tree->right) deleteTree(tree->right); free(tree); } Tree* put(Tree* tree, int key) { if (key >= tree->key) { if (!tree->right) tree->right = createTree(key); else tree->right = put(tree->right, key); } else { if (!tree->left) tree->left = createTree(key); else tree->left = put(tree->left, key); } return balance(tree); } int main() { // при добавлении случайных чисел усредним полученные значения максимумов double sum = 0; for (int k = 0; k < 100; ++k) { size = 1; Tree* root = createTree(rand()); double max1 = 0; for (int i = 0; i < 1000; i++) { root = put(root, rand()); size++; if (i > 100) { double d = getHeight(root) / log2(size); max1 = (d > max1) ? d : max1; } } sum += max1; deleteTree(root); } printf("%lf\n", sum / 100); size = 1; Tree* root = createTree(0); double max2 = 0; for (int i = 0; i < 1000; ++i) { root = put(root, i + 1); size++; if (i > 100) { double d = getHeight(root) / log2(size); max2 = (d > max2) ? d : max2; } } printf("%lf", max2); deleteTree(root); return 0; }
940853.c
/******************************************************************************* * * HAL_PMM.c * Power Management Module Library for MSP430F5xx/6xx family * * * Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/ * * * 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 Texas Instruments Incorporated 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 "msp430.h" #include "HAL_PMM.h" /******************************************************************************* * \brief Increase Vcore by one level * * \param level Level to which Vcore needs to be increased * \return status Success/failure ******************************************************************************/ static uint16_t SetVCoreUp(uint8_t level) { uint16_t PMMRIE_backup, SVSMHCTL_backup, SVSMLCTL_backup; // The code flow for increasing the Vcore has been altered to work around // the erratum FLASH37. // Please refer to the Errata sheet to know if a specific device is affected // DO NOT ALTER THIS FUNCTION // Open PMM registers for write access PMMCTL0_H = 0xA5; // Disable dedicated Interrupts // Backup all registers PMMRIE_backup = PMMRIE; PMMRIE &= ~(SVMHVLRPE | SVSHPE | SVMLVLRPE | SVSLPE | SVMHVLRIE | SVMHIE | SVSMHDLYIE | SVMLVLRIE | SVMLIE | SVSMLDLYIE); SVSMHCTL_backup = SVSMHCTL; SVSMLCTL_backup = SVSMLCTL; // Clear flags PMMIFG = 0; // Set SVM highside to new level and check if a VCore increase is possible SVSMHCTL = SVMHE | SVSHE | (SVSMHRRL0 * level); // Wait until SVM highside is settled while ((PMMIFG & SVSMHDLYIFG) == 0) ; // Clear flag PMMIFG &= ~SVSMHDLYIFG; // Check if a VCore increase is possible if ((PMMIFG & SVMHIFG) == SVMHIFG){ // -> Vcc is too low for a Vcore increase // recover the previous settings PMMIFG &= ~SVSMHDLYIFG; SVSMHCTL = SVSMHCTL_backup; // Wait until SVM highside is settled while ((PMMIFG & SVSMHDLYIFG) == 0) ; // Clear all Flags PMMIFG &= ~(SVMHVLRIFG | SVMHIFG | SVSMHDLYIFG | SVMLVLRIFG | SVMLIFG | SVSMLDLYIFG); PMMRIE = PMMRIE_backup; // Restore PMM interrupt enable register PMMCTL0_H = 0x00; // Lock PMM registers for write access return PMM_STATUS_ERROR; // return: voltage not set } // Set also SVS highside to new level // Vcc is high enough for a Vcore increase SVSMHCTL |= (SVSHRVL0 * level); // Wait until SVM highside is settled while ((PMMIFG & SVSMHDLYIFG) == 0) ; // Clear flag PMMIFG &= ~SVSMHDLYIFG; // Set VCore to new level PMMCTL0_L = PMMCOREV0 * level; // Set SVM, SVS low side to new level SVSMLCTL = SVMLE | (SVSMLRRL0 * level) | SVSLE | (SVSLRVL0 * level); // Wait until SVM, SVS low side is settled while ((PMMIFG & SVSMLDLYIFG) == 0) ; // Clear flag PMMIFG &= ~SVSMLDLYIFG; // SVS, SVM core and high side are now set to protect for the new core level // Restore Low side settings // Clear all other bits _except_ level settings SVSMLCTL &= (SVSLRVL0 + SVSLRVL1 + SVSMLRRL0 + SVSMLRRL1 + SVSMLRRL2); // Clear level settings in the backup register,keep all other bits SVSMLCTL_backup &= ~(SVSLRVL0 + SVSLRVL1 + SVSMLRRL0 + SVSMLRRL1 + SVSMLRRL2); // Restore low-side SVS monitor settings SVSMLCTL |= SVSMLCTL_backup; // Restore High side settings // Clear all other bits except level settings SVSMHCTL &= (SVSHRVL0 + SVSHRVL1 + SVSMHRRL0 + SVSMHRRL1 + SVSMHRRL2); // Clear level settings in the backup register,keep all other bits SVSMHCTL_backup &= ~(SVSHRVL0 + SVSHRVL1 + SVSMHRRL0 + SVSMHRRL1 + SVSMHRRL2); // Restore backup SVSMHCTL |= SVSMHCTL_backup; // Wait until high side, low side settled while (((PMMIFG & SVSMLDLYIFG) == 0) && ((PMMIFG & SVSMHDLYIFG) == 0)) ; // Clear all Flags PMMIFG &= ~(SVMHVLRIFG | SVMHIFG | SVSMHDLYIFG | SVMLVLRIFG | SVMLIFG | SVSMLDLYIFG); PMMRIE = PMMRIE_backup; // Restore PMM interrupt enable register PMMCTL0_H = 0x00; // Lock PMM registers for write access return PMM_STATUS_OK; } /******************************************************************************* * \brief Decrease Vcore by one level * * \param level Level to which Vcore needs to be decreased * \return status Success/failure ******************************************************************************/ static uint16_t SetVCoreDown(uint8_t level) { uint16_t PMMRIE_backup, SVSMHCTL_backup, SVSMLCTL_backup; // The code flow for decreasing the Vcore has been altered to work around // the erratum FLASH37. // Please refer to the Errata sheet to know if a specific device is affected // DO NOT ALTER THIS FUNCTION // Open PMM registers for write access PMMCTL0_H = 0xA5; // Disable dedicated Interrupts // Backup all registers PMMRIE_backup = PMMRIE; PMMRIE &= ~(SVMHVLRPE | SVSHPE | SVMLVLRPE | SVSLPE | SVMHVLRIE | SVMHIE | SVSMHDLYIE | SVMLVLRIE | SVMLIE | SVSMLDLYIE); SVSMHCTL_backup = SVSMHCTL; SVSMLCTL_backup = SVSMLCTL; // Clear flags PMMIFG &= ~(SVMHIFG | SVSMHDLYIFG | SVMLIFG | SVSMLDLYIFG); // Set SVM, SVS high & low side to new settings in normal mode SVSMHCTL = SVMHE | (SVSMHRRL0 * level) | SVSHE | (SVSHRVL0 * level); SVSMLCTL = SVMLE | (SVSMLRRL0 * level) | SVSLE | (SVSLRVL0 * level); // Wait until SVM high side and SVM low side is settled while ((PMMIFG & SVSMHDLYIFG) == 0 || (PMMIFG & SVSMLDLYIFG) == 0) ; // Clear flags PMMIFG &= ~(SVSMHDLYIFG + SVSMLDLYIFG); // SVS, SVM core and high side are now set to protect for the new core level // Set VCore to new level PMMCTL0_L = PMMCOREV0 * level; // Restore Low side settings // Clear all other bits _except_ level settings SVSMLCTL &= (SVSLRVL0 + SVSLRVL1 + SVSMLRRL0 + SVSMLRRL1 + SVSMLRRL2); // Clear level settings in the backup register,keep all other bits SVSMLCTL_backup &= ~(SVSLRVL0 + SVSLRVL1 + SVSMLRRL0 + SVSMLRRL1 + SVSMLRRL2); // Restore low-side SVS monitor settings SVSMLCTL |= SVSMLCTL_backup; // Restore High side settings // Clear all other bits except level settings SVSMHCTL &= (SVSHRVL0 + SVSHRVL1 + SVSMHRRL0 + SVSMHRRL1 + SVSMHRRL2); // Clear level settings in the backup register, keep all other bits SVSMHCTL_backup &= ~(SVSHRVL0 + SVSHRVL1 + SVSMHRRL0 + SVSMHRRL1 + SVSMHRRL2); // Restore backup SVSMHCTL |= SVSMHCTL_backup; // Wait until high side, low side settled while (((PMMIFG & SVSMLDLYIFG) == 0) && ((PMMIFG & SVSMHDLYIFG) == 0)) ; // Clear all Flags PMMIFG &= ~(SVMHVLRIFG | SVMHIFG | SVSMHDLYIFG | SVMLVLRIFG | SVMLIFG | SVSMLDLYIFG); PMMRIE = PMMRIE_backup; // Restore PMM interrupt enable register PMMCTL0_H = 0x00; // Lock PMM registers for write access return PMM_STATUS_OK; // Return: OK } uint16_t SetVCore(uint8_t level) { uint16_t actlevel; uint16_t status = 0; level &= PMMCOREV_3; // Set Mask for Max. level actlevel = (PMMCTL0 & PMMCOREV_3); // Get actual VCore // step by step increase or decrease while ((level != actlevel) && (status == 0)) { if (level > actlevel){ status = SetVCoreUp(++actlevel); } else { status = SetVCoreDown(--actlevel); } } return status; }
375362.c
#include <stdio.h> int arraySum( int array[], const int n) { int sum = 0, *ptr; int *const arrayEnd = array + n; for (ptr = array; ptr < arrayEnd; ++ptr) sum += *ptr; return sum; } int main(int argc, char const *argv[]) { int arraySum( int array[], const int n); int values[10] = {3,7,-9,3,6,-1,7,9,1,-5}; printf("The sum is %i\n", arraySum(values, 10)); return 0; }
985700.c
/* * Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2020 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2006 University of Houston. All rights reserved. * Copyright (c) 2006-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include <stdio.h> #include "ompi/mpi/c/bindings.h" #include "ompi/runtime/params.h" #include "ompi/group/group.h" #include "ompi/errhandler/errhandler.h" #include "ompi/communicator/communicator.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_Group_range_incl = PMPI_Group_range_incl #endif #define MPI_Group_range_incl PMPI_Group_range_incl #endif static const char FUNC_NAME[] = "MPI_Group_range_incl"; int MPI_Group_range_incl(MPI_Group group, int n_triplets, int ranges[][3], MPI_Group *new_group) { int err, i,indx; int group_size; int * elements_int_list; /* can't act on NULL group */ if( MPI_PARAM_CHECK ) { OMPI_ERR_INIT_FINALIZE(FUNC_NAME); if ( (MPI_GROUP_NULL == group) || (NULL == group) || (NULL == new_group) ) { return OMPI_ERRHANDLER_NOHANDLE_INVOKE(MPI_ERR_GROUP, FUNC_NAME); } group_size = ompi_group_size ( group); elements_int_list = (int *) malloc(sizeof(int) * (group_size+1)); if (NULL == elements_int_list) { return OMPI_ERRHANDLER_NOHANDLE_INVOKE(MPI_ERR_OTHER, FUNC_NAME); } for (i = 0; i < group_size; i++) { elements_int_list[i] = -1; } for ( i=0; i < n_triplets; i++) { if ((0 > ranges[i][0]) || (ranges[i][0] > group_size)) { goto error_rank; } if ((0 > ranges[i][1]) || (ranges[i][1] > group_size)) { goto error_rank; } if (ranges[i][2] == 0) { goto error_rank; } if ((ranges[i][0] < ranges[i][1])) { if (ranges[i][2] < 0) { goto error_rank; } /* positive stride */ for (indx = ranges[i][0]; indx <= ranges[i][1]; indx += ranges[i][2]) { /* make sure rank has not already been selected */ if (elements_int_list[indx] != -1) { goto error_rank; } elements_int_list[indx] = i; } } else if (ranges[i][0] > ranges[i][1]) { if (ranges[i][2] > 0) { goto error_rank; } /* negative stride */ for (indx = ranges[i][0]; indx >= ranges[i][1]; indx += ranges[i][2]) { /* make sure rank has not already been selected */ if (elements_int_list[indx] != -1) { goto error_rank; } elements_int_list[indx] = i; } } else { /* first_rank == last_rank */ indx = ranges[i][0]; if (elements_int_list[indx] != -1) { goto error_rank; } elements_int_list[indx] = i; } } free ( elements_int_list); } err = ompi_group_range_incl ( group, n_triplets, ranges, new_group ); OMPI_ERRHANDLER_NOHANDLE_RETURN(err, err, FUNC_NAME ); error_rank: free(elements_int_list); return OMPI_ERRHANDLER_NOHANDLE_INVOKE(MPI_ERR_RANK, FUNC_NAME); }
410378.c
/**************************************************************************** * drivers/wireless/cc3000.c * * Copyright (C) 2013-2016 Gregory Nutt. All rights reserved. * Authors: Gregory Nutt <[email protected]> * David_s5 <[email protected]> * * References: * CC30000 from Texas Instruments http://processors.wiki.ti.com/index.php/CC3000 * * See also: * http://processors.wiki.ti.com/index.php/CC3000_Host_Driver_Porting_Guide * http://processors.wiki.ti.com/index.php/CC3000_Host_Programming_Guide * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <sys/time.h> #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <pthread.h> #include <semaphore.h> #include <poll.h> #include <errno.h> #include <assert.h> #include <debug.h> #include <arpa/inet.h> #include <nuttx/irq.h> #include <nuttx/kmalloc.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <nuttx/semaphore.h> #include <nuttx/fs/fs.h> #include <nuttx/spi/spi.h> #include <nuttx/wireless/ioctl.h> #include <nuttx/wireless/cc3000.h> #include <nuttx/wireless/cc3000/include/cc3000_upif.h> #include <nuttx/wireless/cc3000/cc3000_common.h> #include <nuttx/wireless/cc3000/hci.h> #include "cc3000_socket.h" #include "cc3000.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #ifndef CCASSERT #define CCASSERT(predicate) _x_CCASSERT_LINE(predicate, __LINE__) #define _x_CCASSERT_LINE(predicate, line) typedef char constraint_violated_on_line_##line[2*((predicate)!=0)-1]; #endif CCASSERT(sizeof(cc3000_buffer_desc) <= CONFIG_MQ_MAXMSGSIZE); #ifndef CONFIG_CC3000_WORKER_THREAD_PRIORITY # define CONFIG_CC3000_WORKER_THREAD_PRIORITY (SCHED_PRIORITY_MAX) #endif #ifndef CONFIG_CC3000_WORKER_STACKSIZE # define CONFIG_CC3000_WORKER_STACKSIZE 240 #endif #ifndef CONFIG_CC3000_SELECT_THREAD_PRIORITY # define CONFIG_CC3000_SELECT_THREAD_PRIORITY (SCHED_PRIORITY_DEFAULT-1) #endif #ifndef CONFIG_CC3000_SELECT_STACKSIZE # define CONFIG_CC3000_SELECT_STACKSIZE 368 #endif #ifndef ARRAY_SIZE # define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif #define NUMBER_OF_MSGS 1 #define FREE_SLOT -1 #define CLOSE_SLOT -2 #if defined(CONFIG_DEBUG_FEATURES) && defined(CONFIG_CC3000_PROBES) # define CC3000_GUARD (0xc35aa53c) # define INIT_GUARD(p) p->guard = CC3000_GUARD # define CHECK_GUARD(p) DEBUGASSERT(p->guard == CC3000_GUARD) # define PROBE(pin,state) priv->config->probe(priv->config,pin, state) #else # define INIT_GUARD(p) # define CHECK_GUARD(p) # define PROBE(pin,state) #endif #define waiterr(x,...) // _err #define waitinfo(x,...) // _info /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Low-level SPI helpers */ static void cc3000_lock_and_select(FAR struct spi_dev_s *spi); static void cc3000_deselect_and_unlock(FAR struct spi_dev_s *spi); /* Interrupts and data sampling */ static void cc3000_notify(FAR struct cc3000_dev_s *priv); static void *cc3000_worker(FAR void *arg); static int cc3000_interrupt(int irq, FAR void *context, FAR void *arg); /* Character driver methods */ static int cc3000_open(FAR struct file *filep); static int cc3000_close(FAR struct file *filep); static ssize_t cc3000_read(FAR struct file *filep, FAR char *buffer, size_t len); static ssize_t cc3000_write(FAR struct file *filep, FAR const char *buffer, size_t len); static int cc3000_ioctl(FAR struct file *filep, int cmd, unsigned long arg); #ifndef CONFIG_DISABLE_POLL static int cc3000_poll(FAR struct file *filep, struct pollfd *fds, bool setup); #endif static int cc3000_wait_data(FAR struct cc3000_dev_s *priv, int sockfd); static int cc3000_accept_socket(FAR struct cc3000_dev_s *priv, int sd, FAR struct sockaddr *addr, socklen_t *addrlen); static int cc3000_add_socket(FAR struct cc3000_dev_s *priv, int sd); static int cc3000_remove_socket(FAR struct cc3000_dev_s *priv, int sd); static int cc3000_remote_closed_socket(FAR struct cc3000_dev_s *priv, int sd); /**************************************************************************** * Private Data ****************************************************************************/ /* This the vtable that supports the character driver interface */ static const struct file_operations cc3000_fops = { cc3000_open, /* open */ cc3000_close, /* close */ cc3000_read, /* read */ cc3000_write, /* write */ 0, /* seek */ cc3000_ioctl, /* ioctl */ #ifndef CONFIG_DISABLE_POLL cc3000_poll /* poll */ #endif }; /* If only a single CC3000 device is supported, then the driver state * structure may as well be pre-allocated. */ #ifndef CONFIG_CC3000_MULTIPLE static struct cc3000_dev_s g_cc3000; /* Otherwise, we will need to maintain allocated driver instances in a list */ #else static struct cc3000_dev_s *g_cc3000list; #endif uint8_t spi_readCommand[] = READ_COMMAND; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: cc3000_devtake() and cc3000_devgive() * * Description: * Used to get exclusive access to a CC3000 driver. * ****************************************************************************/ static inline void cc3000_devtake(FAR struct cc3000_dev_s *priv) { /* Take the semaphore (perhaps waiting) */ while (sem_wait(&priv->devsem) < 0) { /* The only case that an error should occur here is if the wait was * awakened by a signal. */ DEBUGASSERT(errno == EINTR); } } static inline void cc3000_devgive(FAR struct cc3000_dev_s *priv) { (void)sem_post(&priv->devsem); } /**************************************************************************** * Name: cc3000_configspi * * Description: * Configure the SPI for use with the CC3000. This function should be * called to configure the SPI * bus. * * Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static inline void cc3000_configspi(FAR struct spi_dev_s *spi) { ninfo("Mode: %d Bits: 8 Frequency: %d\n", CONFIG_CC3000_SPI_MODE, CONFIG_CC3000_SPI_FREQUENCY); SPI_SETMODE(spi, CONFIG_CC3000_SPI_MODE); SPI_SETBITS(spi, 8); (void)SPI_HWFEATURES(spi, 0); (void)SPI_SETFREQUENCY(spi, CONFIG_CC3000_SPI_FREQUENCY); } /**************************************************************************** * Name: cc3000_lock * * Description: * Lock the SPI bus and re-configure as necessary. This function must be * to assure: (1) exclusive access to the SPI bus, and (2) to assure that * the shared bus is properly configured for the cc3000 module. * * Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void cc3000_lock_and_select(FAR struct spi_dev_s *spi) { /* Lock the SPI bus so that we have exclusive access */ (void)SPI_LOCK(spi, true); /* We have the lock. Now make sure that the SPI bus is configured for the * CC3000 (it might have gotten configured for a different device while * unlocked) */ cc3000_configspi(spi); SPI_SELECT(spi, SPIDEV_WIRELESS(0), true); } /**************************************************************************** * Name: cc3000_unlock * * Description: * Un-lock the SPI bus after each transfer, possibly losing the current * configuration if we are sharing the SPI bus with other devices. * * Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void cc3000_deselect_and_unlock(FAR struct spi_dev_s *spi) { /* De select */ SPI_SELECT(spi, SPIDEV_WIRELESS(0), false); /* Relinquish the SPI bus. */ (void)SPI_LOCK(spi, false); } /**************************************************************************** * Name: cc3000_wait * * Description: * Helper function to wait on the semaphore signaled by the * * Parameters: * priv - Reference to the CC3000 driver structure * priv - * * Returned Value: * 0 - Semaphore signaled and devsem retaken * < 0 - Some Error occurred * Assumptions: * Own the devsem on entry * ****************************************************************************/ static int cc3000_wait(FAR struct cc3000_dev_s *priv, sem_t *psem) { int ret; /* Give up */ sched_lock(); cc3000_devgive(priv); /* Wait on first psem to become signaled */ ret = sem_wait(psem); if (ret < 0) { return -errno; } /* Then retake the mutual exclusion semaphore */ cc3000_devtake(priv); sched_unlock(); return OK; } /**************************************************************************** * Name: cc3000_wait_irq * * Description: * Helper function to wait on the irqsem signaled by the interrupt * * Parameters: * priv - Reference to the CC3000 driver structure * * Returned Value: * 0 - Semaphore signaled and devsem retaken * < 0 - Some Error occurred * Assumptions: * Own the devsem on entry * ****************************************************************************/ static inline int cc3000_wait_irq(FAR struct cc3000_dev_s *priv) { return cc3000_wait(priv, &priv->irqsem); } /**************************************************************************** * Name: cc3000_wait_ready * * Description: * Helper function to wait on the readysem signaled by the interrupt * * Parameters: * priv - Reference to the CC3000 driver structure * * Returned Value: * 0 - Semaphore signaled and devsem retaken * < 0 - Some Error occurred * Assumptions: * Own the devsem on entry * ****************************************************************************/ static inline int cc3000_wait_ready(FAR struct cc3000_dev_s *priv) { return cc3000_wait(priv, &priv->readysem); } /**************************************************************************** * Name: cc3000_pollnotify ****************************************************************************/ #ifndef CONFIG_DISABLE_POLL static void cc3000_pollnotify(FAR struct cc3000_dev_s *priv, uint32_t type) { int i; for (i = 0; i < CONFIG_CC3000_NPOLLWAITERS; i++) { struct pollfd *fds = priv->fds[i]; if (fds) { fds->revents |= type; ninfo("Report events: %02x\n", fds->revents); sem_post(fds->sem); } } } #endif /**************************************************************************** * Name: cc3000_notify ****************************************************************************/ static void cc3000_notify(FAR struct cc3000_dev_s *priv) { /* If there are threads waiting for read data, then signal one of them * that the read data is available. */ if (priv->nwaiters > 0) { /* After posting this semaphore, we need to exit because the CC3000 * is no longer available. */ sem_post(&priv->waitsem); } /* If there are threads waiting on poll() for CC3000 data to become available, * then wake them up now. NOTE: we wake up all waiting threads because we * do not know that they are going to do. If they all try to read the data, * then some make end up blocking after all. */ #ifndef CONFIG_DISABLE_POLL cc3000_pollnotify(priv, POLLIN); #endif } /**************************************************************************** * Name: cc3000_worker ****************************************************************************/ static void *select_thread_func(FAR void *arg) { FAR struct cc3000_dev_s *priv = (FAR struct cc3000_dev_s *)arg; struct timeval timeout; TICC3000fd_set readsds; TICC3000fd_set exceptsds; int ret = 0; int maxFD = 0; int s = 0; memset(&timeout, 0, sizeof(struct timeval)); timeout.tv_sec = 0; timeout.tv_usec = (500000); /* 500 msecs */ while (1) { sem_wait(&priv->selectsem); CHECK_GUARD(priv); /* Increase the count back by one to be decreased by the original caller */ sem_post(&priv->selectsem); maxFD = -1; CC3000_FD_ZERO(&readsds); CC3000_FD_ZERO(&exceptsds); /* Ping correct socket descriptor param for select */ for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if (priv->sockets[s].sd != FREE_SLOT) { if (priv->sockets[s].sd == CLOSE_SLOT) { priv->sockets[s].sd = FREE_SLOT; waitinfo("Close\n"); int count; do { sem_getvalue(&priv->sockets[s].semwait, &count); if (count < 0) { /* Release the waiting threads */ waitinfo("Closed Signaled %d\n", count); sem_post(&priv->sockets[s].semwait); } } while (count < 0); continue; } CC3000_FD_SET(priv->sockets[s].sd, &readsds); CC3000_FD_SET(priv->sockets[s].sd, &exceptsds); if (maxFD <= priv->sockets[s].sd) { maxFD = priv->sockets[s].sd + 1; } } } if (maxFD < 0) { /* Handled only socket close. */ continue; } /* Polling instead of blocking here to process "accept" below */ ret = cc3000_select(maxFD, (fd_set *) &readsds, NULL, (fd_set *) &exceptsds, &timeout); if (priv->selecttid == -1) { /* driver close will terminate the thread and by that all sync * objects owned by it will be released */ return OK; } for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if ((priv->sockets[s].sd != FREE_SLOT || priv->sockets[s].sd != CLOSE_SLOT) && /* Check that the socket is valid */ priv->sockets[s].sd != priv->accepting_socket.acc.sd) /* Verify this is not an accept socket */ { if (ret > 0 && CC3000_FD_ISSET(priv->sockets[s].sd, &readsds)) /* and has pending data */ { waitinfo("Signaled %d\n", priv->sockets[s].sd); sem_post(&priv->sockets[s].semwait); /* release the waiting thread */ } else if (ret > 0 && CC3000_FD_ISSET(priv->sockets[s].sd, &exceptsds)) /* or has pending exception */ { waitinfo("Signaled %d (exception)\n", priv->sockets[s].sd); sem_post(&priv->sockets[s].semwait); /* release the waiting thread */ } else if (priv->sockets[s].received_closed_event) /* or remote has closed connection and we have now read all of HW buffer. */ { waitinfo("Signaled %d (closed & empty)\n", priv->sockets[s].sd); priv->sockets[s].emptied_and_remotely_closed = true; sem_post(&priv->sockets[s].semwait); /* release the waiting thread */ } } } if (priv->accepting_socket.acc.sd != FREE_SLOT) /* If accept polling in needed */ { if (priv->accepting_socket.acc.sd == CLOSE_SLOT) { ret = CC3000_SOC_ERROR; } else { ret = cc3000_do_accept(priv->accepting_socket.acc.sd, /* Send the select command on non blocking */ &priv->accepting_socket.addr, /* Set up in ioctl */ &priv->accepting_socket.addrlen); } if (ret != CC3000_SOC_IN_PROGRESS) /* Not waiting => error or accepted */ { priv->accepting_socket.acc.sd = FREE_SLOT; priv->accepting_socket.acc.status = ret; sem_post(&priv->accepting_socket.acc.semwait); /* Release the waiting thread */ } } } return OK; } /**************************************************************************** * Name: cc3000_worker ****************************************************************************/ static void *cc3000_worker(FAR void *arg) { FAR struct cc3000_dev_s *priv = (FAR struct cc3000_dev_s *)arg; int ret; ASSERT(priv != NULL && priv->config != NULL); /* We have started, release our creator */ sem_post(&priv->readysem); while (1) { PROBE(0, 1); CHECK_GUARD(priv); cc3000_devtake(priv); /* Done ? */ if ((cc3000_wait_irq(priv) != -EINTR) && (priv->workertid != -1)) { PROBE(0, 0); ninfo("State%d\n", priv->state); switch (priv->state) { case eSPI_STATE_POWERUP: /* Signal the device has interrupted after power up */ priv->state = eSPI_STATE_INITIALIZED; sem_post(&priv->readysem); break; case eSPI_STATE_WRITE_WAIT_IRQ: /* Signal the device has interrupted after Chip Select During a write operation */ priv->state = eSPI_STATE_WRITE_PROCEED; sem_post(&priv->readysem); break; case eSPI_STATE_WRITE_DONE: /* IRQ post a write => Solicited */ case eSPI_STATE_IDLE: /* IRQ when Idel => cc3000 has data for the hosts Unsolicited */ { uint16_t data_to_recv; priv->state = eSPI_STATE_READ_IRQ; /* Issue the read command */ cc3000_lock_and_select(priv->spi); /* Assert CS */ priv->state = eSPI_STATE_READ_PROCEED; SPI_EXCHANGE(priv->spi, spi_readCommand, priv->rx_buffer.pbuffer, ARRAY_SIZE(spi_readCommand)); /* Extract Length bytes from Rx Buffer. Here we need to convert * unaligned data in network order (big endian, MS byte first) to * host order. We cannot use ntohs here because the data is not * aligned. */ data_to_recv = (uint16_t)priv->rx_buffer.pbuffer[READ_OFFSET_TO_LENGTH] << 8 | (uint16_t)priv->rx_buffer.pbuffer[READ_OFFSET_TO_LENGTH + 1]; if (data_to_recv) { /* We will read ARRAY_SIZE(spi_readCommand) + data_to_recv. is it odd? */ if ((data_to_recv + ARRAY_SIZE(spi_readCommand)) & 1) { /* Odd so make it even */ data_to_recv++; } /* Read the whole payload in at the beginning of the buffer * Will it fit? */ if (data_to_recv >= priv->rx_buffer_max_len) { ninfo("data_to_recv %d", data_to_recv); } DEBUGASSERT(data_to_recv < priv->rx_buffer_max_len); SPI_RECVBLOCK(priv->spi, priv->rx_buffer.pbuffer, data_to_recv); } cc3000_deselect_and_unlock(priv->spi); /* De assert CS */ /* Disable more messages as the wl code will resume via CC3000IOC_COMPLETE */ if (data_to_recv) { int count; priv->state = eSPI_STATE_READ_READY; priv->rx_buffer.len = data_to_recv; ret = mq_send(priv->queue, (FAR const char *)&priv->rx_buffer, sizeof(priv->rx_buffer), 1); DEBUGASSERT(ret >= 0); UNUSED(ret); /* Notify any waiters that new CC3000 data is available */ cc3000_notify(priv); /* Give up driver */ cc3000_devgive(priv); ninfo("Wait On Completion\n"); sem_wait(priv->wrkwaitsem); ninfo("Completed S:%d irq :%d\n", priv->state, priv->config->irq_read(priv->config)); sem_getvalue(&priv->irqsem, &count); if (priv->config->irq_read(priv->config) && count == 0) { sem_post(&priv->irqsem); } if (priv->state == eSPI_STATE_READ_READY) { priv->state = eSPI_STATE_IDLE; } continue; } } break; default: ninfo("default: State%d\n", priv->state); break; } } cc3000_devgive(priv); } return OK; } /**************************************************************************** * Name: cc3000_interrupt ****************************************************************************/ static int cc3000_interrupt(int irq, FAR void *context, FAR void *arg) { FAR struct cc3000_dev_s *priv = (FAR struct cc3000_dev_s *)arg; DEBUGASSERT(priv != NULL); /* Run the worker thread */ PROBE(1, 0); sem_post(&priv->irqsem); PROBE(1, 1); /* Clear any pending interrupts and return success */ priv->config->irq_clear(priv->config); return OK; } /**************************************************************************** * Name: cc3000_open ****************************************************************************/ static int cc3000_open(FAR struct file *filep) { FAR struct inode *inode; struct mq_attr attr; pthread_attr_t tattr; pthread_t threadid; struct sched_param param; char queuename[QUEUE_NAMELEN]; FAR struct cc3000_dev_s *priv; uint8_t tmp; int ret; #ifdef CONFIG_CC3000_MT int s; #endif DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); ninfo("crefs: %d\n", priv->crefs); /* Get exclusive access to the driver data structure */ cc3000_devtake(priv); /* Increment the reference count */ tmp = priv->crefs + 1; if (tmp == 0) { /* More than 255 opens; uint8_t overflows to zero */ ret = -EMFILE; goto out_with_sem; } /* When the reference increments to 1, this is the first open event * on the driver.. and an opportunity to do any one-time initialization. */ if (tmp == 1) { /* Initialize semaphores */ sem_init(&priv->waitsem, 0, 0); /* Initialize event wait semaphore */ sem_init(&priv->irqsem, 0, 0); /* Initialize IRQ Ready semaphore */ sem_init(&priv->readysem, 0, 0); /* Initialize Device Ready semaphore */ /* These semaphores are all used for signaling and, hence, should * not have priority inheritance enabled. */ sem_setprotocol(&priv->waitsem, SEM_PRIO_NONE); sem_setprotocol(&priv->irqsem, SEM_PRIO_NONE); sem_setprotocol(&priv->readysem, SEM_PRIO_NONE); #ifdef CONFIG_CC3000_MT priv->accepting_socket.acc.sd = FREE_SLOT; sem_init(&priv->accepting_socket.acc.semwait, 0, 0); sem_setprotocol(&priv->accepting_socket.acc.semwait, SEM_PRIO_NONE); for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { priv->sockets[s].sd = FREE_SLOT; priv->sockets[s].received_closed_event = false; priv->sockets[s].emptied_and_remotely_closed = false; sem_init(&priv->sockets[s].semwait, 0, 0); sem_setprotocol(&priv->sockets[s].semwait, SEM_PRIO_NONE); } #endif /* Ensure the power is off so we get the falling edge of IRQ */ priv->config->power_enable(priv->config, false); attr.mq_maxmsg = NUMBER_OF_MSGS; attr.mq_msgsize = sizeof(cc3000_buffer_desc); attr.mq_flags = 0; /* Set the flags for the open of the queue. * Make it a blocking open on the queue, meaning it will block if * this process tries to send to the queue and the queue is full. * * O_CREAT - the queue will get created if it does not already exist. * O_WRONLY - we are only planning to write to the queue. * * Open the queue, and create it if the receiving process hasn't * already created it. */ snprintf(queuename, QUEUE_NAMELEN, QUEUE_FORMAT, priv->minor); priv->queue = mq_open(queuename, O_WRONLY | O_CREAT, 0666, &attr); if (priv->queue < 0) { ret = -errno; goto errout_sem_destroy; } pthread_attr_init(&tattr); tattr.stacksize = CONFIG_CC3000_WORKER_STACKSIZE; param.sched_priority = CONFIG_CC3000_WORKER_THREAD_PRIORITY; pthread_attr_setschedparam(&tattr, &param); ret = pthread_create(&priv->workertid, &tattr, cc3000_worker, (pthread_addr_t)priv); if (ret != 0) { ret = -ret; /* pthread_create does not modify errno. */ goto errout_mq_close; } pthread_attr_init(&tattr); tattr.stacksize = CONFIG_CC3000_SELECT_STACKSIZE; param.sched_priority = CONFIG_CC3000_SELECT_THREAD_PRIORITY; pthread_attr_setschedparam(&tattr, &param); sem_init(&priv->selectsem, 0, 0); sem_setprotocol(&priv->selectsem, SEM_PRIO_NONE); ret = pthread_create(&priv->selecttid, &tattr, select_thread_func, (pthread_addr_t)priv); if (ret != 0) { ret = -ret; /* pthread_create does not modify errno. */ goto errout_worker_cancel; } /* Do late allocation with hopes of realloc not fragmenting */ priv->rx_buffer.pbuffer = kmm_malloc(priv->rx_buffer_max_len); DEBUGASSERT(priv->rx_buffer.pbuffer); if (!priv->rx_buffer.pbuffer) { ret = -errno; goto errout_select_cancel; } priv->state = eSPI_STATE_POWERUP; priv->config->irq_clear(priv->config); /* Bring the device Online A) on http://processors.wiki.ti.com/index.php/File:CC3000_Master_SPI_Write_Sequence_After_Power_Up.png */ priv->config->irq_enable(priv->config, true); /* Wait on child thread */ cc3000_wait_ready(priv); priv->config->power_enable(priv->config, true); } /* Save the new open count on success */ priv->crefs = tmp; ret = OK; goto out_with_sem; errout_select_cancel: threadid = priv->selecttid; priv->selecttid = -1; pthread_cancel(threadid); pthread_join(threadid, NULL); sem_destroy(&priv->selectsem); errout_worker_cancel: threadid = priv->workertid; priv->workertid = -1; pthread_cancel(threadid); pthread_join(threadid, NULL); errout_mq_close: mq_close(priv->queue); priv->queue = 0; errout_sem_destroy: #ifdef CONFIG_CC3000_MT sem_destroy(&priv->accepting_socket.acc.semwait); for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { priv->sockets[s].sd = FREE_SLOT; sem_destroy(&priv->sockets[s].semwait); } #endif sem_destroy(&priv->waitsem); sem_destroy(&priv->irqsem); sem_destroy(&priv->readysem); out_with_sem: cc3000_devgive(priv); return ret; } /**************************************************************************** * Name: cc3000_close ****************************************************************************/ static int cc3000_close(FAR struct file *filep) { FAR struct inode *inode; FAR struct cc3000_dev_s *priv; #ifdef CONFIG_CC3000_MT int s; #endif DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); ninfo("crefs: %d\n", priv->crefs); /* Get exclusive access to the driver data structure */ cc3000_devtake(priv); /* Decrement the reference count unless it would decrement a negative * value. When the count decrements to zero, there are no further * open references to the driver. */ int tmp = priv->crefs; if (priv->crefs >= 1) { priv->crefs--; } if (tmp == 1) { pthread_t id = priv->selecttid; priv->selecttid = -1; pthread_cancel(id); pthread_join(id, NULL); sem_destroy(&priv->selectsem); priv->config->irq_enable(priv->config, false); priv->config->irq_clear(priv->config); priv->config->power_enable(priv->config, false); id = priv->workertid; priv->workertid = -1; pthread_cancel(id); pthread_join(id, NULL); mq_close(priv->queue); priv->queue = 0; kmm_free(priv->rx_buffer.pbuffer); priv->rx_buffer.pbuffer = 0; #ifdef CONFIG_CC3000_MT sem_destroy(&priv->accepting_socket.acc.semwait); for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { priv->sockets[s].sd = FREE_SLOT; sem_destroy(&priv->sockets[s].semwait); } #endif sem_destroy(&priv->waitsem); sem_destroy(&priv->irqsem); sem_destroy(&priv->readysem); } cc3000_devgive(priv); return OK; } /**************************************************************************** * Name: cc3000_read ****************************************************************************/ static ssize_t cc3000_read(FAR struct file *filep, FAR char *buffer, size_t len) { FAR struct inode *inode; FAR struct cc3000_dev_s *priv; int ret; ssize_t nread; ninfo("buffer:%p len:%d\n", buffer, len); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); /* Get exclusive access to the driver data structure */ cc3000_devtake(priv); /* Verify that the caller has provided a buffer large enough to receive * the maximum data. */ if (len < priv->rx_buffer_max_len) { nerr("ERROR: Unsupported read size: %d\n", len); nread = -ENOSYS; goto errout_with_sem; } for (nread = priv->rx_buffer.len; nread == 0; nread = priv->rx_buffer.len) { if (nread > 0) { /* Yes.. break out to return what we have. */ break; } /* data is not available now. We would have to wait to get * receive sample data. If the user has specified the O_NONBLOCK * option, then just return an error. */ ninfo("CC3000 data is not available\n"); if (filep->f_oflags & O_NONBLOCK) { nread = -EAGAIN; break; } /* Otherwise, wait for something to be written to the * buffer. Increment the number of waiters so that the notify * will know that it needs to post the semaphore to wake us up. */ sched_lock(); priv->nwaiters++; cc3000_devgive(priv); /* We may now be pre-empted! But that should be okay because we * have already incremented nwaiters. Pre-emptions is disabled * but will be re-enabled while we are waiting. */ ninfo("Waiting..\n"); ret = sem_wait(&priv->waitsem); priv->nwaiters--; sched_unlock(); /* Did we successfully get the waitsem? */ if (ret >= 0) { /* Yes... then retake the mutual exclusion semaphore */ cc3000_devtake(priv); } /* Was the semaphore wait successful? Did we successful re-take the * mutual exclusion semaphore? */ if (ret < 0) { /* No.. One of the two sem_wait's failed. */ int errval = errno; /* Were we awakened by a signal? Did we read anything before * we received the signal? */ if (errval != EINTR || nread >= 0) { /* Yes.. return the error. */ nread = -errval; } /* Break out to return what we have. Note, we can't exactly * "break" out because whichever error occurred, we do not hold * the exclusion semaphore. */ goto errout_without_sem; } } if (nread > 0) { memcpy(buffer, priv->rx_buffer.pbuffer, priv->rx_buffer.len); priv->rx_buffer.len = 0; } errout_with_sem: cc3000_devgive(priv); errout_without_sem: ninfo("Returning: %d\n", nread); #ifndef CONFIG_DISABLE_POLL if (nread > 0) { cc3000_pollnotify(priv, POLLOUT); } #endif return nread; } /**************************************************************************** * Name:cc3000_write * * Bit of non standard buffer management ahead * The buffer is memory allocated in the user space with space for the spi * header * ****************************************************************************/ static ssize_t cc3000_write(FAR struct file *filep, FAR const char *usrbuffer, size_t len) { FAR struct inode *inode; FAR struct cc3000_dev_s *priv; FAR char *buffer = (FAR char *) usrbuffer; ssize_t nwritten = 0; int ret; /* Set the padding if count(buffer) is even ( as it will be come odd with header) */ size_t tx_len = (len & 1) ? len : len +1; ninfo("buffer:%p len:%d tx_len:%d\n", buffer, len, tx_len); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); /* Get exclusive access to the driver data structure */ cc3000_devtake(priv); /* Figure out the total length of the packet in order to figure out if there is padding or not */ buffer[0] = WRITE; buffer[1] = HI(tx_len); buffer[2] = LO(tx_len); buffer[3] = 0; buffer[4] = 0; tx_len += SPI_HEADER_SIZE; /* The first write transaction to occur after release of the shutdown has * slightly different timing than the others. The normal Master SPI * write sequence is nCS low, followed by IRQ low (CC3000 host), * indicating that the CC3000 core device is ready to accept data. * However, after power up the sequence is slightly different, as shown * in the following Figure: * * http://processors.wiki.ti.com/index.php/File:CC3000_Master_SPI_Write_Sequence_After_Power_Up.png * * The following is a sequence of operations: * - The master detects the IRQ line low: in this case the detection of * IRQ low does not indicate the intention of the CC3000 device to * communicate with the master but rather CC3000 readiness after power * up. * - The master asserts nCS. * - The master introduces a delay of at least 50 μs before starting * actual transmission of data. * - The master transmits the first 4 bytes of the SPI header. * - The master introduces a delay of at least an additional 50 μs. * - The master transmits the rest of the packet. */ if (priv->state == eSPI_STATE_POWERUP) { ret = cc3000_wait_ready(priv); if (ret < 0) { nwritten = ret; goto errout_without_sem; } } if (priv->state == eSPI_STATE_INITIALIZED) { cc3000_lock_and_select(priv->spi); /* Assert CS */ usleep(55); SPI_SNDBLOCK(priv->spi, buffer, 4); usleep(55); SPI_SNDBLOCK(priv->spi, buffer+4, tx_len-4); } else { ninfo("Assert CS\n"); priv->state = eSPI_STATE_WRITE_WAIT_IRQ; cc3000_lock_and_select(priv->spi); /* Assert CS */ ninfo("Wait on IRQ Active\n"); ret = cc3000_wait_ready(priv); ninfo("IRQ Signaled\n"); if (ret < 0) { /* This should only happen if the wait was canceled by an signal */ cc3000_deselect_and_unlock(priv->spi); ninfo("sem_wait: %d\n", errno); DEBUGASSERT(errno == EINTR); nwritten = ret; goto errout_without_sem; } SPI_SNDBLOCK(priv->spi, buffer, tx_len); } priv->state = eSPI_STATE_WRITE_DONE; ninfo("Deassert CS S:eSPI_STATE_WRITE_DONE\n"); cc3000_deselect_and_unlock(priv->spi); nwritten = tx_len; cc3000_devgive(priv); errout_without_sem: ninfo("Returning: %d\n", ret); return nwritten; } /**************************************************************************** * Name:cc3000_ioctl ****************************************************************************/ static int cc3000_ioctl(FAR struct file *filep, int cmd, unsigned long arg) { FAR struct inode *inode; FAR struct cc3000_dev_s *priv; int ret; ninfo("cmd: %d arg: %ld\n", cmd, arg); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); /* Get exclusive access to the driver data structure */ cc3000_devtake(priv); /* Process the IOCTL by command */ ret = OK; switch (cmd) { case CC3000IOC_GETQUESEMID: { FAR int *pminor = (FAR int *)(arg); DEBUGASSERT(pminor != NULL); *pminor = priv->minor; break; } case CC3000IOC_ADDSOCKET: { FAR int *pfd = (FAR int *)(arg); DEBUGASSERT(pfd != NULL); *pfd = cc3000_add_socket(priv, *pfd); break; } case CC3000IOC_REMOVESOCKET: { FAR int *pfd = (FAR int *)(arg); DEBUGASSERT(pfd != NULL); *pfd = cc3000_remove_socket(priv, *pfd); break; } case CC3000IOC_REMOTECLOSEDSOCKET: { FAR int *pfd = (FAR int *)(arg); DEBUGASSERT(pfd != NULL); *pfd = cc3000_remote_closed_socket(priv, *pfd); break; } case CC3000IOC_SELECTDATA: { FAR int *pfd = (FAR int *)(arg); DEBUGASSERT(pfd != NULL); *pfd = cc3000_wait_data(priv, *pfd); break; } case CC3000IOC_SELECTACCEPT: { FAR cc3000_acceptcfg *pcfg = (FAR cc3000_acceptcfg *)(arg); DEBUGASSERT(pcfg != NULL); pcfg->sockfd = cc3000_accept_socket(priv, pcfg->sockfd, pcfg->addr, pcfg->addrlen); break; } case CC3000IOC_SETRX_SIZE: { irqstate_t flags; FAR int *psize = (FAR int *)(arg); int rv; DEBUGASSERT(psize != NULL); rv = priv->rx_buffer_max_len; flags = enter_critical_section(); priv->rx_buffer_max_len = *psize; priv->rx_buffer.pbuffer = kmm_realloc(priv->rx_buffer.pbuffer, *psize); leave_critical_section(flags); DEBUGASSERT(priv->rx_buffer.pbuffer); *psize = rv; break; } default: ret = -ENOTTY; break; } cc3000_devgive(priv); return ret; } /**************************************************************************** * Name: cc3000_poll ****************************************************************************/ #ifndef CONFIG_DISABLE_POLL static int cc3000_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup) { FAR struct inode *inode; FAR struct cc3000_dev_s *priv; int ret = OK; int i; ninfo("setup: %d\n", (int)setup); DEBUGASSERT(filep && fds); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); priv = (FAR struct cc3000_dev_s *)inode->i_private; CHECK_GUARD(priv); /* Are we setting up the poll? Or tearing it down? */ cc3000_devtake(priv); if (setup) { /* Ignore waits that do not include POLLIN */ if ((fds->events & POLLIN) == 0) { ret = -EDEADLK; goto errout; } /* This is a request to set up the poll. Find an available * slot for the poll structure reference */ for (i = 0; i < CONFIG_CC3000_NPOLLWAITERS; i++) { /* Find an available slot */ if (!priv->fds[i]) { /* Bind the poll structure and this slot */ priv->fds[i] = fds; fds->priv = &priv->fds[i]; break; } } if (i >= CONFIG_CC3000_NPOLLWAITERS) { fds->priv = NULL; ret = -EBUSY; goto errout; } /* Should we immediately notify on any of the requested events? */ if (priv->rx_buffer.len) { cc3000_notify(priv); } } else if (fds->priv) { /* This is a request to tear down the poll. */ struct pollfd **slot = (struct pollfd **)fds->priv; DEBUGASSERT(slot != NULL); /* Remove all memory of the poll setup */ *slot = NULL; fds->priv = NULL; } errout: cc3000_devgive(priv); return ret; } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: cc3000_register * * Description: * Configure the CC3000 to use the provided SPI device instance. This * will register the driver as /dev/inputN where N is the minor device * number * * Input Parameters: * dev - An SPI driver instance * config - Persistent board configuration data * minor - The input device minor number * * Returned Value: * Zero is returned on success. Otherwise, a negated errno value is * returned to indicate the nature of the failure. * ****************************************************************************/ int cc3000_register(FAR struct spi_dev_s *spi, FAR struct cc3000_config_s *config, int minor) { FAR struct cc3000_dev_s *priv; char drvname[DEV_NAMELEN]; char semname[SEM_NAMELEN]; #ifdef CONFIG_CC3000_MULTIPLE irqstate_t flags; #endif int ret; ninfo("spi: %p minor: %d\n", spi, minor); /* Debug-only sanity checks */ DEBUGASSERT(spi != NULL && config != NULL && minor >= 0 && minor < 100); /* Create and initialize a CC3000 device driver instance */ #ifndef CONFIG_CC3000_MULTIPLE priv = &g_cc3000; #else priv = (FAR struct cc3000_dev_s *)kmm_malloc(sizeof(struct cc3000_dev_s)); if (!priv) { nerr("ERROR: kmm_malloc(%d) failed\n", sizeof(struct cc3000_dev_s)); return -ENOMEM; } #endif /* Initialize the CC3000 device driver instance */ memset(priv, 0, sizeof(struct cc3000_dev_s)); INIT_GUARD(priv); priv->minor = minor; /* Save the minor number */ priv->spi = spi; /* Save the SPI device handle */ priv->config = config; /* Save the board configuration */ priv->rx_buffer_max_len = config->max_rx_size; sem_init(&priv->devsem, 0, 1); /* Initialize device structure semaphore */ (void)snprintf(semname, SEM_NAMELEN, SEM_FORMAT, minor); priv->wrkwaitsem = sem_open(semname, O_CREAT, 0, 0); /* Initialize Worker Wait semaphore */ #ifdef CONFIG_CC3000_MT pthread_mutex_init(&g_cc3000_mut, NULL); #endif /* Make sure that interrupts are disabled */ config->irq_clear(config); config->irq_enable(config, false); /* Attach the interrupt handler */ ret = config->irq_attach(config, cc3000_interrupt, priv); if (ret < 0) { nerr("ERROR: Failed to attach interrupt\n"); goto errout_with_priv; } /* Register the device as an input device */ (void)snprintf(drvname, DEV_NAMELEN, DEV_FORMAT, minor); ninfo("Registering %s\n", drvname); ret = register_driver(drvname, &cc3000_fops, 0666, priv); if (ret < 0) { nerr("ERROR: register_driver() failed: %d\n", ret); goto errout_with_priv; } /* If multiple CC3000 devices are supported, then we will need to add * this new instance to a list of device instances so that it can be * found by the interrupt handler based on the recieved IRQ number. */ #ifdef CONFIG_CC3000_MULTIPLE priv->flink = g_cc3000list; g_cc3000list = priv; leave_critical_section(flags); #endif /* And return success (?) */ return OK; errout_with_priv: sem_destroy(&priv->devsem); sem_close(priv->wrkwaitsem); sem_unlink(semname); #ifdef CONFIG_CC3000_MT pthread_mutex_destroy(&g_cc3000_mut); #endif #ifdef CONFIG_CC3000_MULTIPLE kmm_free(priv); #endif return ret; } /**************************************************************************** * Name: cc3000_wait_data * * Description: * Adds this socket for monitoring for the data available * * Input Parameters: * priv - The device cc3000_dev_s instance * sockfd cc3000 socket handle * * Returned Value: * Zero is returned on success. Otherwise, a -1 value is * returned to indicate socket not found or shut down occured. * ****************************************************************************/ static int cc3000_wait_data(FAR struct cc3000_dev_s *priv, int sockfd) { int s; for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if (priv->sockets[s].sd == sockfd) { sched_lock(); cc3000_devgive(priv); sem_post(&priv->selectsem); /* Wake select thread if need be */ sem_wait(&priv->sockets[s].semwait); /* Wait caller on select to finish */ sem_wait(&priv->selectsem); /* Sleep select thread */ cc3000_devtake(priv); sched_unlock(); if (priv->sockets[s].sd != sockfd) { return -1; } if (priv->sockets[s].emptied_and_remotely_closed) { return -ECONNABORTED; } return OK; } } return (s >= CONFIG_WL_MAX_SOCKETS || priv->selecttid == -1) ? -1 : OK; } /**************************************************************************** * Name: cc3000_accept_socket * * Description: * Adds this socket for monitoring for the accept operation * * Input Parameters: * priv - The device cc3000_dev_s instance * sockfd - cc3000 socket handle to monitor * * Returned Value: * Zero is returned on success. Otherwise, a negative value is * returned to indicate an error. * ****************************************************************************/ static int cc3000_accept_socket(FAR struct cc3000_dev_s *priv, int sd, struct sockaddr *addr, socklen_t *addrlen) { priv->accepting_socket.acc.status = CC3000_SOC_ERROR; priv->accepting_socket.acc.sd = sd; sched_lock(); cc3000_devgive(priv); sem_post(&priv->selectsem); /* Wake select thread if need be */ sem_wait(&priv->accepting_socket.acc.semwait); /* Wait caller on select to finish */ sem_wait(&priv->selectsem); /* Sleep the Thread */ cc3000_devtake(priv); sched_unlock(); if (priv->accepting_socket.acc.status != CC3000_SOC_ERROR) { *addr = priv->accepting_socket.addr; *addrlen = priv->accepting_socket.addrlen; cc3000_add_socket(priv, priv->accepting_socket.acc.status); } return priv->accepting_socket.acc.status; } /**************************************************************************** * Name: cc3000_add_socket * * Description: * Adds a socket to the list for monitoring for long operation * * Input Parameters: * sd cc3000 socket handle * minor - The input device minor number * * Returned Value: * Zero is returned on success. Otherwise, a -1 value is * returned to indicate socket not found. * ****************************************************************************/ static int cc3000_add_socket(FAR struct cc3000_dev_s *priv, int sd) { irqstate_t flags; int s; if (sd < 0) { return sd; } flags = enter_critical_section(); for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if (priv->sockets[s].sd == FREE_SLOT) { priv->sockets[s].received_closed_event = false; priv->sockets[s].emptied_and_remotely_closed = false; priv->sockets[s].sd = sd; break; } } leave_critical_section(flags); return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK; } /**************************************************************************** * Name: cc3000_remove_socket * * Description: * Removes a socket from the list of monitoring for long operation * * Input Parameters: * sd cc3000 socket handle * minor - The input device minor number * * Returned Value: * Zero is returned on success. Otherwise, a -1 value is * returned to indicate socket not found. * ****************************************************************************/ static int cc3000_remove_socket(FAR struct cc3000_dev_s *priv, int sd) { irqstate_t flags; int s; sem_t *ps = 0; if (sd < 0) { return sd; } flags = enter_critical_section(); if (priv->accepting_socket.acc.sd == sd) { priv->accepting_socket.acc.sd = CLOSE_SLOT; ps = &priv->accepting_socket.acc.semwait; } for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if (priv->sockets[s].sd == sd) { priv->sockets[s].received_closed_event = false; priv->sockets[s].emptied_and_remotely_closed = false; priv->sockets[s].sd = CLOSE_SLOT; ps = &priv->sockets[s].semwait; break; } } leave_critical_section(flags); if (ps) { sched_lock(); cc3000_devgive(priv); sem_post(&priv->selectsem); /* Wake select thread if need be */ sem_wait(ps); sem_wait(&priv->selectsem); /* Sleep the Thread */ cc3000_devtake(priv); sched_unlock(); } return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK; } /**************************************************************************** * Name: cc3000_remote_closed_socket * * Description: * Mark socket as closed by remote host * * Input Parameters: * sd cc3000 socket handle * * Returned Value: * Zero is returned on success. Otherwise, a -1 value is * returned to indicate socket not found. * ****************************************************************************/ static int cc3000_remote_closed_socket(FAR struct cc3000_dev_s *priv, int sd) { irqstate_t flags; int s; if (sd < 0) { return sd; } flags = enter_critical_section(); for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++) { if (priv->sockets[s].sd == sd) { priv->sockets[s].received_closed_event = true; } } leave_critical_section(flags); return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK; }
338335.c
/* * Copyright (C) 2009-2012 the libgit2 contributors * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "protocol.h" #include "pkt.h" #include "buffer.h" int git_protocol_store_refs(git_protocol *p, const char *data, size_t len) { git_buf *buf = &p->buf; git_vector *refs = p->refs; int error; const char *line_end, *ptr; if (len == 0) { /* EOF */ if (buf->size != 0) return p->error = git__throw(GIT_ERROR, "EOF and unprocessed data"); else return 0; } git_buf_put(buf, data, len); ptr = buf->ptr; while (1) { git_pkt *pkt; if (buf->size == 0) return 0; error = git_pkt_parse_line(&pkt, ptr, &line_end, buf->size); if (error == GIT_ESHORTBUFFER) return 0; /* Ask for more */ if (error < GIT_SUCCESS) return p->error = git__rethrow(error, "Failed to parse pkt-line"); git_buf_consume(buf, line_end); error = git_vector_insert(refs, pkt); if (error < GIT_SUCCESS) return p->error = git__rethrow(error, "Failed to add pkt to list"); if (pkt->type == GIT_PKT_FLUSH) p->flush = 1; } return error; }
943688.c
/* ** Copyright 2005-2018 Solarflare Communications Inc. ** 7505 Irvine Center Drive, Irvine, CA 92618, USA ** Copyright 2002-2005 Level 5 Networks Inc. ** ** This program is free software; you can redistribute it and/or modify it ** under the terms of version 2 of the GNU General Public License as ** published by the Free Software Foundation. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. */ /**************************************************************************\ *//*! \file ** <L5_PRIVATE L5_SOURCE> ** \author kjm ** \brief onload_set_stackname() extension. ** \date 2010/12/11 ** \cop (c) Solarflare Communications Inc. ** </L5_PRIVATE> *//* \**************************************************************************/ #include "internal.h" ci_inline int prepare_thread_specific_opts(ci_netif_config_opts** opts_out) { struct oo_per_thread* pt = oo_per_thread_get(); if( pt->thread_local_netif_opts == NULL ) { ci_netif_config_opts* default_opts; pt->thread_local_netif_opts = malloc(sizeof(*pt->thread_local_netif_opts)); if( ! pt->thread_local_netif_opts) return -ENOMEM; default_opts = &ci_cfg_opts.netif_opts; memcpy(pt->thread_local_netif_opts, default_opts, sizeof(*default_opts)); } *opts_out = pt->thread_local_netif_opts; return 0; } int onload_stack_opt_get_int(const char* opt_env, int64_t* opt_val) { struct oo_per_thread* pt; ci_netif_config_opts* opts; pt = oo_per_thread_get(); opts = pt->thread_local_netif_opts; if( opts == NULL) { opts = &ci_cfg_opts.netif_opts; } #undef CI_CFG_OPT #undef CI_CFG_STR_OPT #define CI_CFG_STR_OPT(...) #define CI_CFG_OPT(env, name, p3, p4, p5, p6, p7, p8, p9, p10) \ { \ if( ! strcmp(env, opt_env) ) { \ *opt_val = opts->name; \ return 0; \ } \ } #include <ci/internal/opts_netif_def.h> LOG_E(ci_log("%s: Requested option %s not found", __FUNCTION__, opt_env)); return -EINVAL; } extern int onload_stack_opt_get_str(const char* opt_env, char* val_out, size_t* val_out_len) { struct oo_per_thread* pt; ci_netif_config_opts* opts; pt = oo_per_thread_get(); opts = pt->thread_local_netif_opts; if( opts == NULL) { opts = &ci_cfg_opts.netif_opts; } #undef CI_CFG_OPT #undef CI_CFG_STR_OPT #define CI_CFG_OPT(...) #define CI_CFG_STR_OPT(env, name, p3, p4, p5, p6, p7, p8, p9, p10) \ { \ if( ! strcmp(env, opt_env) ) { \ size_t buf_len = *val_out_len; \ *val_out_len = strlen(opts->name) + 1; \ if( buf_len < *val_out_len ) \ return -ENOSPC; \ strcpy(val_out, opts->name); \ return 0; \ } \ } #include <ci/internal/opts_netif_def.h> LOG_E(ci_log("%s: Requested option %s not found", __FUNCTION__, opt_env)); return -EINVAL; } /* This API provides per thread ability to modify ci_netif_config_opts * for future stacks. If not present, this makes a thread local copy * of the default ci_netif_config_opts and updates it as requested. * Any future stacks will use the thread local copy of config_opts and * if absent, use the default copy. */ int onload_stack_opt_set_int(const char* opt_env, int64_t opt_val) { ci_netif_config_opts* opts; int rc = prepare_thread_specific_opts(&opts); if( rc != 0 ) return rc; #define ci_uint32_fmt "%u" #define ci_uint16_fmt "%u" #define ci_uint8_fmt "%u" #define ci_int32_fmt "%d" #define ci_int16_fmt "%d" #define ci_int8_fmt "%d" #define ci_iptime_t_fmt "%u" #define _CI_CFG_BITVAL _optbits #define _CI_CFG_BITVAL1 1 #define _CI_CFG_BITVAL2 2 #define _CI_CFG_BITVAL3 3 #define _CI_CFG_BITVAL4 4 #define _CI_CFG_BITVAL8 8 #define _CI_CFG_BITVAL12 12 #define _CI_CFG_BITVAL16 16 #define _CI_CFG_BITVALA8 _CI_CFG_BITVAL #undef CI_CFG_OPTFILE_VERSION #undef CI_CFG_OPT #undef CI_CFG_STR_OPT #undef CI_CFG_OPTGROUP #undef MIN #undef MAX #undef SMIN #undef SMAX #define CI_CFG_OPTFILE_VERSION(version) #define CI_CFG_OPTGROUP(group, category, expertise) #define MIN 0 #define MAX (((1ull<<(_bitwidth-1))<<1) - 1ull) #define SMAX (MAX >> 1) #define SMIN (-SMAX-1) #define CI_CFG_STR_OPT(...) #define CI_CFG_OPT(env, name, type, doc, bits, group, default, min, max, presentation) \ { \ type _max; \ type _min; \ int _optbits = sizeof(type) * 8; \ int _bitwidth = _CI_CFG_BITVAL##bits; \ (void)_bitwidth; \ (void)_optbits; \ _max = (type)(max); \ _min = (type)(min); \ if( ! strcmp(env, opt_env) ) { \ if( opt_val < _min || opt_val > _max ) { \ LOG_E(ci_log("%s: %"PRId64" outside of range ("type##_fmt":" \ type##_fmt") for %s", \ __FUNCTION__, opt_val, _min, _max, opt_env)); \ return -EINVAL; \ } \ opts->name = opt_val; \ return 0; \ } \ } #include <ci/internal/opts_netif_def.h> LOG_E(ci_log("%s: Requested option %s not found", __FUNCTION__, opt_env)); return -EINVAL; } int onload_stack_opt_set_str(const char* opt_env, const char* opt_val) { ci_netif_config_opts* opts; int rc = prepare_thread_specific_opts(&opts); if( rc != 0 ) return rc; #undef CI_CFG_OPTFILE_VERSION #undef CI_CFG_OPT #undef CI_CFG_STR_OPT #undef CI_CFG_OPTGROUP #define CI_CFG_OPTFILE_VERSION(version) #define CI_CFG_OPTGROUP(group, category, expertise) #define CI_CFG_OPT(...) #define CI_CFG_STR_OPT(env, name, type, doc, bits, group, default, min, max, presentation) \ { \ if( ! strcmp(env, opt_env) ) { \ if( strlen(opt_val) >= sizeof(type) ) { \ LOG_E(ci_log("%s: value string too long for %s", \ __FUNCTION__, opt_env)); \ return -EINVAL; \ } \ strcpy(opts->name, opt_val); \ return 0; \ } \ } #include <ci/internal/opts_netif_def.h> LOG_E(ci_log("%s: Requested option %s not found", __FUNCTION__, opt_env)); return -EINVAL; } /* Simply delete the thread local copy of config_opts to revert to * using the netif's config_opts. */ int onload_stack_opt_reset(void) { struct oo_per_thread* pt; pt = oo_per_thread_get(); if( pt->thread_local_netif_opts != NULL ) { free(pt->thread_local_netif_opts); pt->thread_local_netif_opts = NULL; } return 0; }
178167.c
#include <ccan/array_size/array_size.h> #include <ccan/time/time.h> #include <common/status.h> #undef status_trace #define status_trace(...) #define main unused_main int main(int argc, char *argv[]); #include "../onchaind.c" #undef main /* AUTOGENERATED MOCKS START */ /* Generated stub for commit_number_obscurer */ u64 commit_number_obscurer(const struct pubkey *opener_payment_basepoint UNNEEDED, const struct pubkey *accepter_payment_basepoint UNNEEDED) { fprintf(stderr, "commit_number_obscurer called!\n"); abort(); } /* Generated stub for daemon_shutdown */ void daemon_shutdown(void) { fprintf(stderr, "daemon_shutdown called!\n"); abort(); } /* Generated stub for derive_keyset */ bool derive_keyset(const struct pubkey *per_commitment_point UNNEEDED, const struct basepoints *self UNNEEDED, const struct basepoints *other UNNEEDED, struct keyset *keyset UNNEEDED) { fprintf(stderr, "derive_keyset called!\n"); abort(); } /* Generated stub for fromwire_hsm_get_per_commitment_point_reply */ bool fromwire_hsm_get_per_commitment_point_reply(const tal_t *ctx UNNEEDED, const void *p UNNEEDED, struct pubkey *per_commitment_point UNNEEDED, struct secret **old_commitment_secret UNNEEDED) { fprintf(stderr, "fromwire_hsm_get_per_commitment_point_reply called!\n"); abort(); } /* Generated stub for fromwire_hsm_sign_tx_reply */ bool fromwire_hsm_sign_tx_reply(const void *p UNNEEDED, struct bitcoin_signature *sig UNNEEDED) { fprintf(stderr, "fromwire_hsm_sign_tx_reply called!\n"); abort(); } /* Generated stub for fromwire_onchain_depth */ bool fromwire_onchain_depth(const void *p UNNEEDED, struct bitcoin_txid *txid UNNEEDED, u32 *depth UNNEEDED) { fprintf(stderr, "fromwire_onchain_depth called!\n"); abort(); } /* Generated stub for fromwire_onchain_dev_memleak */ bool fromwire_onchain_dev_memleak(const void *p UNNEEDED) { fprintf(stderr, "fromwire_onchain_dev_memleak called!\n"); abort(); } /* Generated stub for fromwire_onchain_htlc */ bool fromwire_onchain_htlc(const void *p UNNEEDED, struct htlc_stub *htlc UNNEEDED, bool *tell_if_missing UNNEEDED, bool *tell_immediately UNNEEDED) { fprintf(stderr, "fromwire_onchain_htlc called!\n"); abort(); } /* Generated stub for fromwire_onchain_init */ bool fromwire_onchain_init(const tal_t *ctx UNNEEDED, const void *p UNNEEDED, struct shachain *shachain UNNEEDED, u64 *funding_amount_satoshi UNNEEDED, struct pubkey *old_remote_per_commitment_point UNNEEDED, struct pubkey *remote_per_commitment_point UNNEEDED, u32 *local_to_self_delay UNNEEDED, u32 *remote_to_self_delay UNNEEDED, u32 *feerate_per_kw UNNEEDED, u64 *local_dust_limit_satoshi UNNEEDED, struct bitcoin_txid *our_broadcast_txid UNNEEDED, u8 **local_scriptpubkey UNNEEDED, u8 **remote_scriptpubkey UNNEEDED, struct pubkey *ourwallet_pubkey UNNEEDED, enum side *funder UNNEEDED, struct basepoints *local_basepoints UNNEEDED, struct basepoints *remote_basepoints UNNEEDED, struct bitcoin_tx **tx UNNEEDED, u32 *tx_blockheight UNNEEDED, u32 *reasonable_depth UNNEEDED, secp256k1_ecdsa_signature **htlc_signature UNNEEDED, u64 *num_htlcs UNNEEDED, u32 *min_possible_feerate UNNEEDED, u32 *max_possible_feerate UNNEEDED, struct pubkey **possible_remote_per_commit_point UNNEEDED) { fprintf(stderr, "fromwire_onchain_init called!\n"); abort(); } /* Generated stub for fromwire_onchain_known_preimage */ bool fromwire_onchain_known_preimage(const void *p UNNEEDED, struct preimage *preimage UNNEEDED) { fprintf(stderr, "fromwire_onchain_known_preimage called!\n"); abort(); } /* Generated stub for fromwire_onchain_spent */ bool fromwire_onchain_spent(const tal_t *ctx UNNEEDED, const void *p UNNEEDED, struct bitcoin_tx **tx UNNEEDED, u32 *input_num UNNEEDED, u32 *blockheight UNNEEDED) { fprintf(stderr, "fromwire_onchain_spent called!\n"); abort(); } /* Generated stub for htlc_offered_wscript */ u8 *htlc_offered_wscript(const tal_t *ctx UNNEEDED, const struct ripemd160 *ripemd UNNEEDED, const struct keyset *keyset UNNEEDED) { fprintf(stderr, "htlc_offered_wscript called!\n"); abort(); } /* Generated stub for htlc_received_wscript */ u8 *htlc_received_wscript(const tal_t *ctx UNNEEDED, const struct ripemd160 *ripemd UNNEEDED, const struct abs_locktime *expiry UNNEEDED, const struct keyset *keyset UNNEEDED) { fprintf(stderr, "htlc_received_wscript called!\n"); abort(); } /* Generated stub for htlc_success_tx */ struct bitcoin_tx *htlc_success_tx(const tal_t *ctx UNNEEDED, const struct bitcoin_txid *commit_txid UNNEEDED, unsigned int commit_output_number UNNEEDED, u64 htlc_msatoshi UNNEEDED, u16 to_self_delay UNNEEDED, u32 feerate_per_kw UNNEEDED, const struct keyset *keyset UNNEEDED) { fprintf(stderr, "htlc_success_tx called!\n"); abort(); } /* Generated stub for htlc_timeout_tx */ struct bitcoin_tx *htlc_timeout_tx(const tal_t *ctx UNNEEDED, const struct bitcoin_txid *commit_txid UNNEEDED, unsigned int commit_output_number UNNEEDED, u64 htlc_msatoshi UNNEEDED, u32 cltv_expiry UNNEEDED, u16 to_self_delay UNNEEDED, u32 feerate_per_kw UNNEEDED, const struct keyset *keyset UNNEEDED) { fprintf(stderr, "htlc_timeout_tx called!\n"); abort(); } /* Generated stub for master_badmsg */ void master_badmsg(u32 type_expected UNNEEDED, const u8 *msg) { fprintf(stderr, "master_badmsg called!\n"); abort(); } /* Generated stub for peer_billboard */ void peer_billboard(bool perm UNNEEDED, const char *fmt UNNEEDED, ...) { fprintf(stderr, "peer_billboard called!\n"); abort(); } /* Generated stub for shachain_get_secret */ bool shachain_get_secret(const struct shachain *shachain UNNEEDED, u64 commit_num UNNEEDED, struct secret *preimage UNNEEDED) { fprintf(stderr, "shachain_get_secret called!\n"); abort(); } /* Generated stub for status_failed */ void status_failed(enum status_failreason code UNNEEDED, const char *fmt UNNEEDED, ...) { fprintf(stderr, "status_failed called!\n"); abort(); } /* Generated stub for status_fmt */ void status_fmt(enum log_level level UNNEEDED, const char *fmt UNNEEDED, ...) { fprintf(stderr, "status_fmt called!\n"); abort(); } /* Generated stub for status_setup_sync */ void status_setup_sync(int fd UNNEEDED) { fprintf(stderr, "status_setup_sync called!\n"); abort(); } /* Generated stub for subdaemon_setup */ void subdaemon_setup(int argc UNNEEDED, char *argv[]) { fprintf(stderr, "subdaemon_setup called!\n"); abort(); } /* Generated stub for to_self_wscript */ u8 *to_self_wscript(const tal_t *ctx UNNEEDED, u16 to_self_delay UNNEEDED, const struct keyset *keyset UNNEEDED) { fprintf(stderr, "to_self_wscript called!\n"); abort(); } /* Generated stub for towire_hsm_get_per_commitment_point */ u8 *towire_hsm_get_per_commitment_point(const tal_t *ctx UNNEEDED, u64 n UNNEEDED) { fprintf(stderr, "towire_hsm_get_per_commitment_point called!\n"); abort(); } /* Generated stub for towire_hsm_sign_delayed_payment_to_us */ u8 *towire_hsm_sign_delayed_payment_to_us(const tal_t *ctx UNNEEDED, u64 commit_num UNNEEDED, const struct bitcoin_tx *tx UNNEEDED, const u8 *wscript UNNEEDED, u64 input_amount UNNEEDED) { fprintf(stderr, "towire_hsm_sign_delayed_payment_to_us called!\n"); abort(); } /* Generated stub for towire_hsm_sign_local_htlc_tx */ u8 *towire_hsm_sign_local_htlc_tx(const tal_t *ctx UNNEEDED, u64 commit_num UNNEEDED, const struct bitcoin_tx *tx UNNEEDED, const u8 *wscript UNNEEDED, u64 input_amount UNNEEDED) { fprintf(stderr, "towire_hsm_sign_local_htlc_tx called!\n"); abort(); } /* Generated stub for towire_hsm_sign_penalty_to_us */ u8 *towire_hsm_sign_penalty_to_us(const tal_t *ctx UNNEEDED, const struct secret *revocation_secret UNNEEDED, const struct bitcoin_tx *tx UNNEEDED, const u8 *wscript UNNEEDED, u64 input_amount UNNEEDED) { fprintf(stderr, "towire_hsm_sign_penalty_to_us called!\n"); abort(); } /* Generated stub for towire_hsm_sign_remote_htlc_to_us */ u8 *towire_hsm_sign_remote_htlc_to_us(const tal_t *ctx UNNEEDED, const struct pubkey *remote_per_commitment_point UNNEEDED, const struct bitcoin_tx *tx UNNEEDED, const u8 *wscript UNNEEDED, u64 input_amount UNNEEDED) { fprintf(stderr, "towire_hsm_sign_remote_htlc_to_us called!\n"); abort(); } /* Generated stub for towire_onchain_add_utxo */ u8 *towire_onchain_add_utxo(const tal_t *ctx UNNEEDED, const struct bitcoin_txid *prev_out_tx UNNEEDED, u32 prev_out_index UNNEEDED, const struct pubkey *per_commit_point UNNEEDED, u64 value UNNEEDED, u32 blockheight UNNEEDED) { fprintf(stderr, "towire_onchain_add_utxo called!\n"); abort(); } /* Generated stub for towire_onchain_all_irrevocably_resolved */ u8 *towire_onchain_all_irrevocably_resolved(const tal_t *ctx UNNEEDED) { fprintf(stderr, "towire_onchain_all_irrevocably_resolved called!\n"); abort(); } /* Generated stub for towire_onchain_broadcast_tx */ u8 *towire_onchain_broadcast_tx(const tal_t *ctx UNNEEDED, const struct bitcoin_tx *tx UNNEEDED) { fprintf(stderr, "towire_onchain_broadcast_tx called!\n"); abort(); } /* Generated stub for towire_onchain_dev_memleak_reply */ u8 *towire_onchain_dev_memleak_reply(const tal_t *ctx UNNEEDED, bool leak UNNEEDED) { fprintf(stderr, "towire_onchain_dev_memleak_reply called!\n"); abort(); } /* Generated stub for towire_onchain_extracted_preimage */ u8 *towire_onchain_extracted_preimage(const tal_t *ctx UNNEEDED, const struct preimage *preimage UNNEEDED) { fprintf(stderr, "towire_onchain_extracted_preimage called!\n"); abort(); } /* Generated stub for towire_onchain_htlc_timeout */ u8 *towire_onchain_htlc_timeout(const tal_t *ctx UNNEEDED, const struct htlc_stub *htlc UNNEEDED) { fprintf(stderr, "towire_onchain_htlc_timeout called!\n"); abort(); } /* Generated stub for towire_onchain_init_reply */ u8 *towire_onchain_init_reply(const tal_t *ctx UNNEEDED) { fprintf(stderr, "towire_onchain_init_reply called!\n"); abort(); } /* Generated stub for towire_onchain_missing_htlc_output */ u8 *towire_onchain_missing_htlc_output(const tal_t *ctx UNNEEDED, const struct htlc_stub *htlc UNNEEDED) { fprintf(stderr, "towire_onchain_missing_htlc_output called!\n"); abort(); } /* Generated stub for towire_onchain_unwatch_tx */ u8 *towire_onchain_unwatch_tx(const tal_t *ctx UNNEEDED, const struct bitcoin_txid *txid UNNEEDED) { fprintf(stderr, "towire_onchain_unwatch_tx called!\n"); abort(); } /* Generated stub for wire_sync_read */ u8 *wire_sync_read(const tal_t *ctx UNNEEDED, int fd UNNEEDED) { fprintf(stderr, "wire_sync_read called!\n"); abort(); } /* Generated stub for wire_sync_write */ bool wire_sync_write(int fd UNNEEDED, const void *msg TAKES UNNEEDED) { fprintf(stderr, "wire_sync_write called!\n"); abort(); } /* AUTOGENERATED MOCKS END */ #if DEVELOPER /* Generated stub for dump_memleak */ bool dump_memleak(struct htable *memtable UNNEEDED) { fprintf(stderr, "dump_memleak called!\n"); abort(); } /* Generated stub for memleak_enter_allocations */ struct htable *memleak_enter_allocations(const tal_t *ctx UNNEEDED, const void *exclude1 UNNEEDED, const void *exclude2 UNNEEDED) { fprintf(stderr, "memleak_enter_allocations called!\n"); abort(); } /* Generated stub for memleak_remove_referenced */ void memleak_remove_referenced(struct htable *memtable UNNEEDED, const void *root UNNEEDED) { fprintf(stderr, "memleak_remove_referenced called!\n"); abort(); } /* Generated stub for memleak_scan_region */ void memleak_scan_region(struct htable *memtable UNNEEDED, const void *p UNNEEDED, size_t bytelen UNNEEDED) { fprintf(stderr, "memleak_scan_region called!\n"); abort(); } /* Generated stub for notleak_ */ void *notleak_(const void *ptr UNNEEDED, bool plus_children UNNEEDED) { fprintf(stderr, "notleak_ called!\n"); abort(); } #endif int main(int argc, char *argv[]) { setup_locale(); struct bitcoin_tx *tx; struct bitcoin_signature sig; u8 *der, *wscript; u64 fee; struct pubkey htlc_key; struct keyset *keys; struct timeabs start, end; int iterations = 1000; secp256k1_ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN); setup_tmpctx(); tx = bitcoin_tx_from_hex(tmpctx, "0200000001e1ebca08cf1c301ac563580a1126d5c8fcb0e5e2043230b852c726553caf1e1d0000000000000000000160ae0a000000000022002082e03c5a9cb79c82cd5a0572dc175290bc044609aabe9cc852d61927436041796d000000", strlen("0200000001e1ebca08cf1c301ac563580a1126d5c8fcb0e5e2043230b852c726553caf1e1d0000000000000000000160ae0a000000000022002082e03c5a9cb79c82cd5a0572dc175290bc044609aabe9cc852d61927436041796d000000")); tx->input[0].amount = tal(tx, u64); *tx->input[0].amount = 700000; der = tal_hexdata(tmpctx, "30450221009b2e0eef267b94c3899fb0dc7375012e2cee4c10348a068fe78d1b82b4b14036022077c3fad3adac2ddf33f415e45f0daf6658b7a0b09647de4443938ae2dbafe2b9" "01", strlen("30450221009b2e0eef267b94c3899fb0dc7375012e2cee4c10348a068fe78d1b82b4b14036022077c3fad3adac2ddf33f415e45f0daf6658b7a0b09647de4443938ae2dbafe2b9" "01")); if (!signature_from_der(der, tal_count(der), &sig)) abort(); wscript = tal_hexdata(tmpctx, "76a914a8c40c334351dbe8e5908544f1c98fbcfb8719fc8763ac6721038ffd2621647812011960152bfb79c5a2787dfe6c4f37e2222547de054432eb7f7c820120876475527c2103cf8e2f193a6aed60db80af75f3c8d59c2de735b299b7c7083527be9bd23b77a852ae67a914b8bcd51efa35be1e50ae2d5f72f4500acb005c9c88ac6868", strlen("76a914a8c40c334351dbe8e5908544f1c98fbcfb8719fc8763ac6721038ffd2621647812011960152bfb79c5a2787dfe6c4f37e2222547de054432eb7f7c820120876475527c2103cf8e2f193a6aed60db80af75f3c8d59c2de735b299b7c7083527be9bd23b77a852ae67a914b8bcd51efa35be1e50ae2d5f72f4500acb005c9c88ac6868")); if (!pubkey_from_hexstr("038ffd2621647812011960152bfb79c5a2787dfe6c4f37e2222547de054432eb7f", strlen("038ffd2621647812011960152bfb79c5a2787dfe6c4f37e2222547de054432eb7f"), &htlc_key)) abort(); /* Dance around a little because keyset is const */ keys = tal(tmpctx, struct keyset); keys->other_htlc_key = htlc_key; keyset = keys; if (argc > 1) iterations = atoi(argv[1]); max_possible_feerate = 250000; min_possible_feerate = max_possible_feerate + 1 - iterations; start = time_now(); fee = grind_htlc_tx_fee(tx, &sig, wscript, 663); end = time_now(); assert(fee == 165750); printf("%u iterations in %"PRIu64" msec = %"PRIu64" nsec each\n", iterations, time_to_msec(time_between(end, start)), time_to_nsec(time_divide(time_between(end, start), iterations))); tal_free(tmpctx); secp256k1_context_destroy(secp256k1_ctx); return 0; }
216406.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <time.h> #define VERSION_H \ "#ifndef %s_VERSION_H\n" \ "#define %s_VERSION_H\n" \ "\n" \ "#define %s_VERSION_MAJOR %d\n" \ "#define %s_VERSION_MINOR %d\n" \ "#define %s_VERSION_PATCH %d\n" \ "#define %s_VERSION_BUILD %d\n" \ "#define %s_VERSION_META \"%s\"\n" \ "#define %s_VERSION \"%d.%d.%d.%d%s\"\n" \ "#define %s_COMPILE_DATE \"%s\"\n" \ "#define %s_COMPILE_TIME \"%s\"\n" \ "\n" \ "#endif /* %s_VERSION_H */\n" #define USAGE \ "Usage: %s [-hMmpbaPDTiB]\n" \ "\n" \ "Options:\n" \ " -h, --help Print this menu and exit.\n" \ " -M, --major Major number.\n" \ " -m, --minor Minor number.\n" \ " -p, --patch Patch number.\n" \ " -b, --build Build number.\n" \ " -a, --meta Meta information.\n" \ " -P, --prefix The macro prefix [default: \"%s\"]\n" \ " -D, --date Date format [default: \"%s\"]\n" \ " -T, --time Time format [default: \"%s\"]\n" \ " -i, --auto-build Auto increment build number.\n" \ " -F, --build-file The file containing the build number.\n" \ "\n" int main(int argc, char** argv) { struct option long_options[] = { {"help", required_argument, NULL, 'h'}, {"major", required_argument, NULL, 'M'}, {"minor", required_argument, NULL, 'm'}, {"patch", required_argument, NULL, 'p'}, {"build", required_argument, NULL, 'b'}, {"meta", required_argument, NULL, 'a'}, {"prefix", required_argument, NULL, 'P'}, {"date", required_argument, NULL, 'D'}, {"time", required_argument, NULL, 'T'}, {"auto-build", no_argument, NULL, 'i'}, {"build-file", required_argument, NULL, 'F'}, }; int major, minor, patch, build, c, auto_inc_build; char *meta, *prefix, *datefmt, *timefmt, *buildfile; time_t timer; struct tm* tm_info; char datestr[32]; char timestr[32]; memset(datestr, 0, sizeof(datestr)); memset(timestr, 0, sizeof(timestr)); major = minor = patch = build = auto_inc_build = 0; meta = ""; prefix = "EXAMPLE"; datefmt = "%Y-%m-%d"; timefmt = "%H:%M:%S"; buildfile = NULL; while ((c = getopt_long(argc, argv, "hM:m:p:b:a:P:D:T:iF:", long_options, 0)) != -1) { switch (c) { case 'h': printf(USAGE, argv[0], prefix, datefmt, timefmt); return 0; case 'M': major = atoi(optarg); break; case 'm': minor = atoi(optarg); break; case 'p': patch = atoi(optarg); break; case 'b': build = atoi(optarg); break; case 'a': meta = optarg; break; case 'P': prefix = optarg; break; case 'D': datefmt = optarg; break; case 'T': timefmt = optarg; break; case 'i': auto_inc_build = 1; break; case 'F': buildfile = optarg; break; case '?': exit(1); } } if (auto_inc_build) { if (buildfile) { /* 65535 builds should be plenty (plus null-terminator) */ char line[17]; FILE* fp = fopen(buildfile, "r"); if (fp == NULL) { /* Don't overwrite build number if we can't * open file; keep the existing value. */ build = build != 0 ? build : 0; } else { fread(line, sizeof(line), 1, fp); build = atoi(line); fclose(fp); } build++; /* Reopen to write new value; Truncate file. */ fp = fopen(buildfile, "w+"); if (fp == NULL) { fprintf(stderr, "%s: %s\n", buildfile, strerror(errno)); exit(1); } /* Overwrite existing build value. */ snprintf(line, sizeof(line), "%d", build); fprintf(fp, "%d", build); fclose(fp); } } time(&timer); tm_info = localtime(&timer); strftime(datestr, sizeof(datestr), datefmt, tm_info); strftime(timestr, sizeof(timestr), timefmt, tm_info); printf(VERSION_H, prefix, prefix, prefix, major, prefix, minor, prefix, patch, prefix, build, prefix, meta, prefix, major, minor, patch, build, meta, prefix, datestr, prefix, timestr, prefix); return 0; }
804871.c
/** ****************************************************************************** * @file main.c * @brief Example main file * contains the main code for blinking an LED @verbatim ============================================================================== ##### Title of the project ##### ============================================================================== @endverbatim ****************************************************************************** * @attention * * LICENSE * * The MIT License (MIT) * * Copyright (c) 2020 Rohit Gujarathi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "utilities.h" #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "stm32f4xx_hal.h" #include "simple_module.h" void SystemClock_Config(void); static GPIO_InitTypeDef GPIO_InitStruct; /** @brief LED pin */ #define LED1_PIN GPIO_PIN_13 /** @brief LED port */ #define LED1_PORT GPIOG /** * @brief Task for blinking an LED every second * * @param pvParameters void pointer to task parameters * * @retval void */ void LedBlinky_Task(void *pvParameters) { while (1) { HAL_GPIO_TogglePin(LED1_PORT, LED1_PIN); vTaskDelay(1000/portTICK_PERIOD_MS); } } int main ( void ) { #if SEMIHOSTING initialise_monitor_handles(); setbuf(stdout, NULL); //~ setvbuf(stdout, NULL, _IONBF, 0); INFO("Main program start"); #endif HAL_Init(); SystemClock_Config(); __HAL_RCC_GPIOG_CLK_ENABLE(); GPIO_InitStruct.Pin = LED1_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(LED1_PORT, &GPIO_InitStruct); // calling something from the modules SomethingSimple(2, 7); xTaskCreate( LedBlinky_Task, /* The function that implements the task. */ "LedBlinky", /* The text name assigned to the task - for debug only as it is not used by the kernel. */ configMINIMAL_STACK_SIZE, /* The size of the stack to allocate to the task. */ NULL, /* The parameter passed to the task - just to check the functionality. */ 3, /* The priority assigned to the task. */ NULL ); /* The task handle is not required, so NULL is passed. */ vTaskStartScheduler(); while (1) { } return 0; } /** * @brief Setup the system clock * * @note This function is taken from STM32CubeMX * * @retval void */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); /** Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 8; RCC_OscInitStruct.PLL.PLLN = 128; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 4; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV4; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } }
231340.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_char_fixed_square_01.c Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-01.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fixed Fixed value * GoodSource: Small, non-zero * Sinks: square * GoodSink: Ensure there is no overflow before performing the squaring operation * BadSink : Square data * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" #include <math.h> #ifndef OMITBAD void CWE190_Integer_Overflow__unsigned_char_fixed_square_01_bad() { unsigned char data; data = ' '; /* FLAW: Use the maximum size of the data type */ data = UCHAR_MAX; { /* POTENTIAL FLAW: Squaring data could cause an overflow */ unsigned char result = data * data; printHexUnsignedCharLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { unsigned char data; data = ' '; /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 5; { /* POTENTIAL FLAW: Squaring data could cause an overflow */ unsigned char result = data * data; printHexUnsignedCharLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { unsigned char data; data = ' '; /* FLAW: Use the maximum size of the data type */ data = UCHAR_MAX; { unsigned char result = -1; /* FIX: Add a check to prevent an overflow from occurring */ if (data <= (unsigned char)sqrt((unsigned char)UCHAR_MAX)) { result = data * data; printHexUnsignedCharLine(result); } else { printLine("Input value is too large to perform arithmetic safely."); } } } void CWE190_Integer_Overflow__unsigned_char_fixed_square_01_good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE190_Integer_Overflow__unsigned_char_fixed_square_01_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__unsigned_char_fixed_square_01_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
730895.c
/********************************************************** * Copyright 2009-2011 VMware, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ********************************************************* * Authors: * Zack Rusin <zackr-at-vmware-dot-com> * Thomas Hellstrom <thellstrom-at-vmware-dot-com> */ #include "xa_context.h" #include "xa_priv.h" #include "util/u_inlines.h" #include "util/u_sampler.h" #include "util/u_surface.h" #include "cso_cache/cso_context.h" static void xa_yuv_bind_blend_state(struct xa_context *r) { struct pipe_blend_state blend; memset(&blend, 0, sizeof(struct pipe_blend_state)); blend.rt[0].blend_enable = 0; blend.rt[0].colormask = PIPE_MASK_RGBA; /* porter&duff src */ blend.rt[0].rgb_src_factor = PIPE_BLENDFACTOR_ONE; blend.rt[0].alpha_src_factor = PIPE_BLENDFACTOR_ONE; blend.rt[0].rgb_dst_factor = PIPE_BLENDFACTOR_ZERO; blend.rt[0].alpha_dst_factor = PIPE_BLENDFACTOR_ZERO; cso_set_blend(r->cso, &blend); } static void xa_yuv_bind_shaders(struct xa_context *r) { unsigned vs_traits = 0, fs_traits = 0; struct xa_shader shader; vs_traits |= VS_YUV; fs_traits |= FS_YUV; shader = xa_shaders_get(r->shaders, vs_traits, fs_traits); cso_set_vertex_shader_handle(r->cso, shader.vs); cso_set_fragment_shader_handle(r->cso, shader.fs); } static void xa_yuv_bind_samplers(struct xa_context *r, struct xa_surface *yuv[]) { struct pipe_sampler_state *samplers[3]; struct pipe_sampler_state sampler; struct pipe_sampler_view view_templ; unsigned int i; memset(&sampler, 0, sizeof(struct pipe_sampler_state)); sampler.wrap_s = PIPE_TEX_WRAP_CLAMP; sampler.wrap_t = PIPE_TEX_WRAP_CLAMP; sampler.min_img_filter = PIPE_TEX_FILTER_LINEAR; sampler.mag_img_filter = PIPE_TEX_FILTER_LINEAR; sampler.min_mip_filter = PIPE_TEX_MIPFILTER_NEAREST; sampler.normalized_coords = 1; for (i = 0; i < 3; ++i) { samplers[i] = &sampler; u_sampler_view_default_template(&view_templ, yuv[i]->tex, yuv[i]->tex->format); r->bound_sampler_views[i] = r->pipe->create_sampler_view(r->pipe, yuv[i]->tex, &view_templ); } r->num_bound_samplers = 3; cso_set_samplers(r->cso, PIPE_SHADER_FRAGMENT, 3, (const struct pipe_sampler_state **)samplers); cso_set_sampler_views(r->cso, PIPE_SHADER_FRAGMENT, 3, r->bound_sampler_views); } static void xa_yuv_fs_constants(struct xa_context *r, const float conversion_matrix[]) { const int param_bytes = 16 * sizeof(float); renderer_set_constants(r, PIPE_SHADER_FRAGMENT, conversion_matrix, param_bytes); } XA_EXPORT int xa_yuv_planar_blit(struct xa_context *r, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int dst_w, int dst_h, struct xa_box *box, unsigned int num_boxes, const float conversion_matrix[], struct xa_surface *dst, struct xa_surface *yuv[]) { float scale_x; float scale_y; int ret; if (dst_w == 0 || dst_h == 0) return XA_ERR_NONE; ret = xa_ctx_srf_create(r, dst); if (ret != XA_ERR_NONE) return -XA_ERR_NORES; renderer_bind_destination(r, r->srf); xa_yuv_bind_blend_state(r); xa_yuv_bind_shaders(r); xa_yuv_bind_samplers(r, yuv); xa_yuv_fs_constants(r, conversion_matrix); scale_x = (float)src_w / (float)dst_w; scale_y = (float)src_h / (float)dst_h; while (num_boxes--) { int x = box->x1; int y = box->y1; int w = box->x2 - box->x1; int h = box->y2 - box->y1; xa_scissor_update(r, x, y, box->x2, box->y2); renderer_draw_yuv(r, (float)src_x + scale_x * (x - dst_x), (float)src_y + scale_y * (y - dst_y), scale_x * w, scale_y * h, x, y, w, h, yuv); box++; } xa_context_flush(r); xa_ctx_sampler_views_destroy(r); xa_ctx_srf_destroy(r); return XA_ERR_NONE; }
350977.c
/* * TYPE 0x11: (Washington) * Aztech MMPRO16AB, * Aztech Sound Galaxy Pro 16 AB * Aztech Sound Galaxy Washington 16 * Packard Bell Sound 16A * ...and other OEM names * FCC ID I38-MMSN824 and others * * TYPE 0x0C: (Clinton) * Aztech Sound Galaxy Nova 16 Extra * Aztech Sound Galaxy Clinton 16 * Packard Bell Forte 16 * ...and other OEM names * * Also works more or less for drivers of other models with the same chipsets. * * Copyright (c) 2020 Eluan Costa Miranda <[email protected]> All rights reserved. * * 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/>. * * ============================================================================= * * The CS4248 DSP used is pin and software compatible with the AD1848. * I also have one of these cards with a CS4231. The driver talks to the * emulated card as if it was a CS4231 and I still don't know how to tell the * drivers to see the CS4248. The CS4231 more advanced features are NOT used, * just the new input/output channels. Apparently some drivers are hardcoded * for one or the other, so there is an option for this. * * There is lots more to be learned form the Win95 drivers. The Linux driver is * very straightforward and doesn't do much. * * Recording and voice modes in the windows mixer still do nothing in PCem, so * this is missing. * * There is a jumper to load the startup configuration from an EEPROM. This is * implemented, so any software-configured parameters will be saved. * * The CD-ROM interface commands are just ignored, along with gameport. * The MPU401 is always enabled. * The OPL3 is always active in some (all?) drivers/cards, so there is no * configuration for this. * * Tested with DOS (driver installation, tools, diagnostics), Win3.1 (driver * installation, tools), Win95 (driver auto-detection), Win NT 3.1 (driver * installation), lots of games. * * I consider type 0x11 (Washington) to be very well tested. Type 0x0C (Clinton) * wasn't fully tested, but works well for WSS/Windows. BEWARE that there are * *too many* driver types and OEM versions for each card. Maybe yours isn't * emulated or you have the wrong driver. Some features of each card may work * when using wrong drivers. CODEC selection is also important. * * Any updates to the WSS and SBPROV2 sound cards should be synced here when * appropriate. The WSS was completely cloned here, while the SBPROV2 tends * to call the original functions, except for initialization. * * TODO/Notes: * -Some stuff still not understood on I/O addresses 0x624 and 0x530-0x533. * -Is the CS42xx dither mode used anywhere? Implement. * -What are the voice commands mode in Win95 mixer again? * -Configuration options not present on Aztech's CONFIG.EXE have been commented * out or deleted. Other types of cards with this chipset may need them. * -Sfademo on the Descent CD fails under Win95, works under DOS, see if it * happens on real hardware (and OPL3 stops working after the failure) * -There appears to be some differences in sound volumes bertween MIDI, * SBPROV2, WSS and OPL3? Also check relationship between the SBPROV2 mixer and * the WSS mixer! Are they independent? Current mode selects which mixer? Are * they entangled? * -Check real hardware to see if advanced, mic boost, etc appear in the mixer? * -CD-ROM driver shipped with the card (SGIDECD.SYS) checks for model strings. * I have implemented mine (AZtech CDA 468-02I 4x) in PCem. * -Descent 2 W95 version can't start cd music. Happens on real hardware. * Explanation further below. * -DOSQuake and Descent 2 DOS cd music do not work under Win95. The mode * selects get truncated and send all zeros for output channel selection and * volume, Descent 2 also has excess zeros! This is a PCem bug, happens on all * sound cards. CD audio works in Winquake and Descent 2 DOS setup program. * -DOSQuake CD audio works under DOS with VIDE-CDD.SYS and SGIDECD.SYS. * Descent 2 DOS is still mute but volume selection appears to be working. * Descent 2 fails to launch with SGIDECD.SYS with "Device failed to request * command". SGIDECD.SYS is the CD-ROM driver included with the sound card * drivers. My real CD-ROM drive can't read anything so I can't check the * real behavior of this driver. * -Some cards just have regular IDE ports while other have proprietary ports. * The regular IDE ports just have a option to enable an almost-generic CD-ROM * driver in CONFIG.SYS/AUTOEXEC.BAT (like SGIDECD.SYS) and the onboard port * is enabled/disabled by jumpers. The proprietary ones also have * address/dma/irq settings. Since the configuration options are ignored here, * this behaves like a card with a regular interface disabled by jumper and * the configuration just adds/removes the drivers (which will see other IDE * interfaces present) from the boot process. * -Continue reverse engineering to see if the AZT1605 shares the SB DMA with * WSS or if it is set separately by the TSR loaded on boot. Currently it is * only set by PCem config and then saved to EEPROM (which would make it fixed * if loading from EEPROM too). * -Related to the previous note, part of the SBPROV2 emulation on the CLINTON * family appears to be implemented with a TSR. It's better to remove the TSR * for now. I need to investigate this. Mixer is also weird under DOS (and * wants to save to EEPROM? I don't think the WASHINGTON does this). * -VOLSET.EXE /S:S is supposed to be a no-op on the MMP16AB? * -Search for TODO in this file. :-) * * Misc things I use to test for regressions: Windows sounds, Descent under * dos/windows, Descent 2 dos/windows (+ cd music option), Descent 2 W95 + cd * music, Age of Empires (CD + Midi), cd-audio under Windows + volume, * cd-audio under dos + volume, Aztech diagnose.exe, Aztech volset /M:3 then * volset /D, Aztech setmode, mixer (volume + balance) under dos and windows, * DOSQuake under dos and windows (+ cd music and volumes, + Winquake). * * Reason for Descent 2 Win95 CD-Audio not working: * The game calls auxGetNumDevs() to check if any of the AUX devices has * caps.wTechnology == AUXCAPS_CDAUDIO, but this fails because the Aztech * Win95 driver only returns a "Line-In" device. I'm not aware of any other * game that does this and this is completely unnecessary. Other games that * play cd audio correctly have the exact *same* initialization code, minus * this check that only Descent 2 Win95 does. It would work if it just skipped * this check and progressed with calling mciSendCommand() with * mciOpenParms.lpstrDeviceType = "cdaudio", like other games do. There are * some sound cards listed as incompatible in the game's README.TXT file that * are probably due to this. */ #include <math.h> #include <stdlib.h> #include "ibm.h" #include "device.h" #include "dma.h" #include "io.h" #include "nvr.h" #include "pic.h" #include "sound.h" #include "sound_ad1848.h" #include "sound_azt2316a.h" #include "sound_opl.h" #include "sound_sb.h" #include "sound_sb_dsp.h" /*530, 11, 3 - 530=23*/ /*530, 11, 1 - 530=22*/ /*530, 11, 0 - 530=21*/ /*530, 10, 1 - 530=1a*/ /*530, 10, 0 - 530=19*/ /*530, 9, 1 - 530=12*/ /*530, 7, 1 - 530=0a*/ /*604, 11, 1 - 530=22*/ /*e80, 11, 1 - 530=22*/ /*f40, 11, 1 - 530=22*/ static int azt2316a_wss_dma[4] = {0, 0, 1, 3}; static int azt2316a_wss_irq[8] = {5, 7, 9, 10, 11, 12, 14, 15}; /* W95 only uses 7-10, others may be wrong */ //static uint16_t azt2316a_wss_addr[4] = {0x530, 0x604, 0xe80, 0xf40}; typedef struct azt2316a_t { int type; int wss_interrupt_after_config; uint8_t wss_config; uint16_t cur_addr, cur_wss_addr, cur_mpu401_addr; uint8_t cur_irq, cur_dma, opl_emu; // sb uint8_t cur_wss_enabled, cur_wss_irq, cur_wss_dma; uint8_t cur_mpu401_irq; uint32_t config_word; uint32_t config_word_unlocked; uint8_t cur_mode; ad1848_t ad1848; sb_t *sb; } azt2316a_t; uint8_t azt2316a_wss_read(uint16_t addr, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint8_t temp; // pclog("azt2316a_read - addr %04X\n", addr); // TODO: when windows is initializing, writing 0x48, 0x58 and 0x60 to // 0x530 makes reading from 0x533 return 0x44, but writing 0x50 // makes this return 0x04. Why? if (addr & 1) temp = 4 | (azt2316a->wss_config & 0x40); else temp = 4 | (azt2316a->wss_config & 0xC0); // pclog("return %02X\n", temp); return temp; } void azt2316a_wss_write(uint16_t addr, uint8_t val, void *p) { int interrupt = 0; azt2316a_t *azt2316a = (azt2316a_t *)p; // pclog("azt2316a_write - addr %04X val %02X\n", addr, val); if (azt2316a->wss_interrupt_after_config) if ((azt2316a->wss_config & 0x40) && !(val & 0x40)) // TODO: is this the right edge? interrupt = 1; azt2316a->wss_config = val; azt2316a->cur_wss_dma = azt2316a_wss_dma[val & 3]; azt2316a->cur_wss_irq = azt2316a_wss_irq[(val >> 3) & 7]; ad1848_setdma(&azt2316a->ad1848, azt2316a_wss_dma[val & 3]); ad1848_setirq(&azt2316a->ad1848, azt2316a_wss_irq[(val >> 3) & 7]); if (interrupt) picint(1 << azt2316a->cur_wss_irq); } // generate a config word based on current settings void azt1605_create_config_word(void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint32_t temp = 0; // not implemented / hardcoded uint8_t game_enable = 1; uint8_t mpu401_enable = 1; uint8_t cd_type = 0; // TODO: see if the cd-rom was originally connected there on the real machines emulated by PCem (Packard Bell Legend 100CD, Itautec Infoway Multimidia, etc) uint8_t cd_dma8 = -1; uint8_t cd_irq = 0; switch (azt2316a->cur_addr) { case 0x220: // do nothing //temp += 0 << 0; break; case 0x240: temp += 1 << 0; break; /* case 0x260: // TODO: INVALID? temp += 2 << 0; break; case 0x280: // TODO: INVALID? temp += 3 << 0; break; */ default: fatal("Bad AZT1605 addr %04X\n", azt2316a->cur_addr); } switch (azt2316a->cur_irq) { case 2: temp += 1 << 8; break; case 3: temp += 1 << 9; break; case 5: temp += 1 << 10; break; case 7: temp += 1 << 11; break; default: fatal("Bad AZT1605 irq %02X\n", azt2316a->cur_irq); } switch (azt2316a->cur_wss_addr) { case 0x530: // do nothing //temp += 0 << 16; break; case 0x604: temp += 1 << 16; break; case 0xE80: temp += 2 << 16; break; case 0xF40: temp += 3 << 16; break; default: fatal("Bad AZT1605 WSS addr %04X\n", azt2316a->cur_wss_addr); } if (azt2316a->cur_wss_enabled) temp += 1 << 18; if (game_enable) temp += 1 << 4; switch (azt2316a->cur_mpu401_addr) { case 0x300: // do nothing //temp += 0 << 2; break; case 0x330: temp += 1 << 2; break; default: fatal("Bad AZT1605 MPU401 addr %04X\n", azt2316a->cur_mpu401_addr); } if (mpu401_enable) temp += 1 << 3; switch (cd_type) { case 0: // disabled // do nothing //temp += 0 << 5; break; case 1: // panasonic temp += 1 << 5; break; case 2: // mitsumi/sony/aztech temp += 2 << 5; break; case 3: // all enabled temp += 3 << 5; break; case 4: // unused temp += 4 << 5; break; case 5: // unused temp += 5 << 5; break; case 6: // unused temp += 6 << 5; break; case 7: // unused temp += 7 << 5; break; default: fatal("Bad AZT1605 CD type %02X\n", cd_type); } switch (cd_dma8) { case 0xFF: // -1 // do nothing //temp += 0 << 22; break; case 0: temp += 1 << 22; break; case 1: temp += 2 << 22; break; case 3: temp += 3 << 22; break; default: fatal("Bad AZT1605 cd dma8 %02X\n", cd_dma8); } switch (azt2316a->cur_mpu401_irq) { case 2: temp += 1 << 12; break; case 3: temp += 1 << 13; break; case 5: temp += 1 << 14; break; case 7: temp += 1 << 15; break; default: fatal("Bad AZT1605 mpu401 irq %02X\n", azt2316a->cur_mpu401_irq); } switch (cd_irq) { case 0: // disabled // do nothing break; case 11: temp += 1 << 19; break; case 12: temp += 1 << 20; break; case 15: temp += 1 << 21; break; default: fatal("Bad AZT1605 cd irq %02X\n", cd_irq); } azt2316a->config_word = temp; } void azt2316a_create_config_word(void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint32_t temp = 0; // not implemented / hardcoded uint8_t game_enable = 1; uint8_t mpu401_enable = 1; uint16_t cd_addr = 0x310; uint8_t cd_type = 0; // TODO: see if the cd-rom was originally connected there on the real machines emulated by PCem (Packard Bell Legend 100CD, Itautec Infoway Multimidia, etc) uint8_t cd_dma8 = -1; uint8_t cd_dma16 = -1; uint8_t cd_irq = 15; if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt1605_create_config_word(p); return; } switch (azt2316a->cur_addr) { case 0x220: // do nothing //temp += 0 << 0; break; case 0x240: temp += 1 << 0; break; /* case 0x260: // TODO: INVALID? temp += 2 << 0; break; case 0x280: // TODO: INVALID? temp += 3 << 0; break; */ default: fatal("Bad AZT2316A addr %04X\n", azt2316a->cur_addr); } switch (azt2316a->cur_irq) { case 2: temp += 1 << 2; break; case 5: temp += 1 << 3; break; case 7: temp += 1 << 4; break; case 10: temp += 1 << 5; break; default: fatal("Bad AZT2316A irq %02X\n", azt2316a->cur_irq); } switch (azt2316a->cur_dma) { /* // TODO: INVALID? case 0xFF: // -1 // do nothing //temp += 0 << 6; break; */ case 0: temp += 1 << 6; break; case 1: temp += 2 << 6; break; case 3: temp += 3 << 6; break; default: fatal("Bad AZT2316A dma %02X\n", azt2316a->cur_dma); } switch (azt2316a->cur_wss_addr) { case 0x530: // do nothing //temp += 0 << 8; break; case 0x604: temp += 1 << 8; break; case 0xE80: temp += 2 << 8; break; case 0xF40: temp += 3 << 8; break; default: fatal("Bad AZT2316A WSS addr %04X\n", azt2316a->cur_wss_addr); } if (azt2316a->cur_wss_enabled) temp += 1 << 10; if (game_enable) temp += 1 << 11; switch (azt2316a->cur_mpu401_addr) { case 0x300: // do nothing //temp += 0 << 12; break; case 0x330: temp += 1 << 12; break; default: fatal("Bad AZT2316A MPU401 addr %04X\n", azt2316a->cur_mpu401_addr); } if (mpu401_enable) temp += 1 << 13; switch (cd_addr) { case 0x310: // do nothing //temp += 0 << 14; break; case 0x320: temp += 1 << 14; break; case 0x340: temp += 2 << 14; break; case 0x350: temp += 3 << 14; break; default: fatal("Bad AZT2316A CD addr %04X\n", cd_addr); } switch (cd_type) { case 0: // disabled // do nothing //temp += 0 << 16; break; case 1: // panasonic temp += 1 << 16; break; case 2: // sony temp += 2 << 16; break; case 3: // mitsumi temp += 3 << 16; break; case 4: // aztech temp += 4 << 16; break; case 5: // unused temp += 5 << 16; break; case 6: // unused temp += 6 << 16; break; case 7: // unused temp += 7 << 16; break; default: fatal("Bad AZT2316A CD type %02X\n", cd_type); } switch (cd_dma8) { case 0xFF: // -1 // do nothing //temp += 0 << 20; break; case 0: temp += 1 << 20; break; /* case 1: // TODO: INVALID? temp += 2 << 20; break; */ case 3: temp += 3 << 20; break; default: fatal("Bad AZT2316A cd dma8 %02X\n", cd_dma8); } switch (cd_dma16) { case 0xFF: // -1 // do nothing //temp += 0 << 22; break; case 5: temp += 1 << 22; break; case 6: temp += 2 << 22; break; case 7: temp += 3 << 22; break; default: fatal("Bad AZT2316A cd dma16 %02X\n", cd_dma16); } switch (azt2316a->cur_mpu401_irq) { case 2: temp += 1 << 24; break; case 5: temp += 1 << 25; break; case 7: temp += 1 << 26; break; case 10: temp += 1 << 27; break; default: fatal("Bad AZT2316A mpu401 irq %02X\n", azt2316a->cur_mpu401_irq); } switch (cd_irq) { case 5: temp += 1 << 28; break; case 11: temp += 1 << 29; break; case 12: temp += 1 << 30; break; case 15: temp += 1 << 31; break; default: fatal("Bad AZT2316A cd irq %02X\n", cd_irq); } azt2316a->config_word = temp; } uint8_t azt2316a_config_read(uint16_t addr, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint8_t temp; // pclog("azt2316a_config_read - addr %04X\n", addr); // Some WSS config here + config change enable bit // (setting bit 7 and writing back) if (addr == azt2316a->cur_addr + 0x404) { // TODO: what is the real meaning of the read value? // I got a mention of bit 0x10 for WSS from disassembling the source // code of the driver, and when playing with the I/O ports on real // hardware after doing some configuration, but didn't dig into it. // Bit 0x08 seems to be a busy flag and generates a timeout // (continuous re-reading when initializing windows 98) temp = azt2316a->cur_mode ? 0x07 : 0x0F; if (azt2316a->config_word_unlocked) temp |= 0x80; } else { // Rest of config. These are documented in the Linux driver. switch (addr & 0x3) { case 0: temp = azt2316a->config_word & 0xFF; break; case 1: temp = (azt2316a->config_word >> 8) & 0xFF; break; case 2: temp = (azt2316a->config_word >> 16) & 0xFF; break; case 3: temp = (azt2316a->config_word >> 24) & 0xFF; break; } } // pclog("return %02X\n", temp); return temp; } void azt1605_config_write(uint16_t addr, uint8_t val, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint8_t temp; // pclog("azt2316a_config_write - addr %04X val %02X\n", addr, val); if (addr == azt2316a->cur_addr + 0x404) { if (val & 0x80) azt2316a->config_word_unlocked = 1; else azt2316a->config_word_unlocked = 0; } else if (azt2316a->config_word_unlocked) { if (val == 0xFF) // TODO: check if this still happens on eeprom.sys after having more complete emulation! return; switch (addr & 0x3) { case 0: azt2316a->config_word = (azt2316a->config_word & 0xFFFFFF00) + val; temp = val & 0x3; if (temp == 0) azt2316a->cur_addr = 0x220; else if (temp == 1) azt2316a->cur_addr = 0x240; /* else if (temp == 2) azt2316a->cur_addr = 0x260; // TODO: INVALID else if (temp == 3) azt2316a->cur_addr = 0x280; // TODO: INVALID */ if (val & 0x4) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; // mpu401_enabled is harcoded //if (val & 0x8) // azt2316a->cur_mpu401_enabled = 1; //else // azt2316a->cur_mpu401_enabled = 0; // game_enabled is hardcoded //if (val & 0x10) // azt2316a->cur_game_enabled = 1; //else // azt2316a->cur_game_enabled = 0; // cd_type is hardcoded //azt2316a->cur_cd_type = (val >> 5) & 0x7; break; case 1: azt2316a->config_word = (azt2316a->config_word & 0xFFFF00FF) + (val << 8); if (val & 0x1) azt2316a->cur_irq = 2; else if (val & 0x2) azt2316a->cur_irq = 3; else if (val & 0x4) azt2316a->cur_irq = 5; else if (val & 0x8) azt2316a->cur_irq = 7; // else undefined? if (val & 0x10) azt2316a->cur_mpu401_irq = 2; else if (val & 0x20) azt2316a->cur_mpu401_irq = 3; else if (val & 0x40) azt2316a->cur_mpu401_irq = 5; else if (val & 0x80) azt2316a->cur_mpu401_irq = 7; // else undefined? break; case 2: azt2316a->config_word = (azt2316a->config_word & 0xFF00FFFF) + (val << 16); io_removehandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_removehandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); temp = val & 0x3; if (temp == 0) azt2316a->cur_wss_addr = 0x530; else if (temp == 1) azt2316a->cur_wss_addr = 0x604; else if (temp == 2) azt2316a->cur_wss_addr = 0xE80; else if (temp == 3) azt2316a->cur_wss_addr = 0xF40; io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); // no actual effect if (val & 0x4) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; // cd_irq is hardcoded //if (val & 0x8) // azt2316a->cur_cd_irq = 11; //else if (val & 0x10) // azt2316a->cur_cd_irq = 12; //else if (val & 0x20) // azt2316a->cur_cd_irq = 15; // else disable? // cd_dma8 is hardcoded //temp = (val >> 6) & 0x3; //if (temp == 0) // azt2316a->cur_cd_dma8 = -1; //else if (temp == 1) // azt2316a->cur_cd_dma8 = 0; //else if (temp == 3) // azt2316a->cur_cd_dma8 = 3; //else error break; case 3: break; } // update sbprov2 configs sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); mpu401_uart_update_addr(&azt2316a->sb->mpu, azt2316a->cur_mpu401_addr); mpu401_uart_update_irq(&azt2316a->sb->mpu, azt2316a->cur_mpu401_irq); } } void azt2316a_config_write(uint16_t addr, uint8_t val, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; uint8_t temp; // pclog("azt2316a_config_write - addr %04X val %02X\n", addr, val); if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt1605_config_write(addr, val, p); return; } if (addr == azt2316a->cur_addr + 0x404) { if (val & 0x80) azt2316a->config_word_unlocked = 1; else azt2316a->config_word_unlocked = 0; } else if (azt2316a->config_word_unlocked) { if (val == 0xFF) // TODO: check if this still happens on eeprom.sys after having more complete emulation! return; switch (addr & 0x3) { case 0: azt2316a->config_word = (azt2316a->config_word & 0xFFFFFF00) + val; temp = val & 0x3; if (temp == 0) azt2316a->cur_addr = 0x220; else if (temp == 1) azt2316a->cur_addr = 0x240; /* else if (temp == 2) azt2316a->cur_addr = 0x260; // TODO: INVALID else if (temp == 3) azt2316a->cur_addr = 0x280; // TODO: INVALID */ if (val & 0x4) azt2316a->cur_irq = 2; else if (val & 0x8) azt2316a->cur_irq = 5; else if (val & 0x10) azt2316a->cur_irq = 7; else if (val & 0x20) azt2316a->cur_irq = 10; // else undefined? temp = (val >> 6) & 0x3; /* if (temp == 0) azt2316a->cur_dma = -1; // TODO: INVALID? else */if (temp == 1) azt2316a->cur_dma = 0; else if (temp == 2) azt2316a->cur_dma = 1; else if (temp == 3) azt2316a->cur_dma = 3; break; case 1: azt2316a->config_word = (azt2316a->config_word & 0xFFFF00FF) + (val << 8); io_removehandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_removehandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); temp = val & 0x3; if (temp == 0) azt2316a->cur_wss_addr = 0x530; else if (temp == 1) azt2316a->cur_wss_addr = 0x604; else if (temp == 2) azt2316a->cur_wss_addr = 0xE80; else if (temp == 3) azt2316a->cur_wss_addr = 0xF40; io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); // no actual effect if (val & 0x4) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; // game_enabled is hardcoded //if (val & 0x8) // azt2316a->cur_game_enabled = 1; //else // azt2316a->cur_game_enabled = 0; if (val & 0x10) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; // mpu401_enabled is harcoded //if (val & 0x20) // azt2316a->cur_mpu401_enabled = 1; //else // azt2316a->cur_mpu401_enabled = 0; // cd_addr is hardcoded //temp = (val >> 6) & 0x3; //if (temp == 0) // azt2316a->cur_cd_addr = 0x310; //else if (temp == 1) // azt2316a->cur_cd_addr = 0x320; //else if (temp == 2) // azt2316a->cur_cd_addr = 0x340; //else if (temp == 3) // azt2316a->cur_cd_addr = 0x350; break; case 2: azt2316a->config_word = (azt2316a->config_word & 0xFF00FFFF) + (val << 16); // cd_type is hardcoded //azt2316a->cur_cd_type = val & 0x7; // cd_dma8 is hardcoded //temp = (val >> 4) & 0x3; //if (temp == 0) // azt2316a->cur_cd_dma8 = -1; //else if (temp == 1) // azt2316a->cur_cd_dma8 = 0; //else if (temp == 2) // azt2316a->cur_cd_dma8 = 1; //else if (temp == 3) // azt2316a->cur_cd_dma8 = 3; // cd_dma16 is hardcoded //temp = (val >> 6) & 0x3; //if (temp == 0) // azt2316a->cur_cd_dma16 = -1; //else if (temp == 1) // azt2316a->cur_cd_dma16 = 5; //else if (temp == 2) // azt2316a->cur_cd_dma16 = 6; //else if (temp == 3) // azt2316a->cur_cd_dma16 = 7; break; case 3: azt2316a->config_word = (azt2316a->config_word & 0x00FFFFFF) + (val << 24); if (val & 0x1) azt2316a->cur_mpu401_irq = 2; else if (val & 0x2) azt2316a->cur_mpu401_irq = 5; else if (val & 0x4) azt2316a->cur_mpu401_irq = 7; else if (val & 0x8) azt2316a->cur_mpu401_irq = 10; // else undefined? // cd_irq is hardcoded //if (val & 0x10) // azt2316a->cur_cd_irq = 5; //else if (val & 0x20) // azt2316a->cur_cd_irq = 11; //else if (val & 0x40) // azt2316a->cur_cd_irq = 12; //else if (val & 0x80) // azt2316a->cur_cd_irq = 15; // else undefined? break; } // update sbprov2 configs sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); mpu401_uart_update_addr(&azt2316a->sb->mpu, azt2316a->cur_mpu401_addr); mpu401_uart_update_irq(&azt2316a->sb->mpu, azt2316a->cur_mpu401_irq); } } // How it behaves when one or another is activated may affect games auto-detecting (and will also use more of the limited system resources!) void azt2316a_enable_wss(uint8_t enable, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; if (enable) { azt2316a->cur_mode = 1; if (!azt2316a->cur_wss_enabled) { // apparently it doesn't work like this! // azt2316a->cur_wss_enabled = 1; // azt2316a->config_word |= 1 << 10; } } else { azt2316a->cur_mode = 0; if (azt2316a->cur_wss_enabled) { // apparently it doesn't work like this! // azt2316a->cur_wss_enabled = 0; // azt2316a->config_word &= 0xFFFFFFFF - (1 << 10); } } } static void azt2316a_get_buffer(int32_t *buffer, int len, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; int c; // wss part ad1848_update(&azt2316a->ad1848); for (c = 0; c < len * 2; c++) { buffer[c] += (azt2316a->ad1848.buffer[c] / 2); } azt2316a->ad1848.pos = 0; // sbprov2 part sb_get_buffer_sbpro(buffer, len, azt2316a->sb); } void *azt_common_init(const int type, char *nvr_filename) { int i; int loaded_from_eeprom = 0; uint16_t addr_setting; uint8_t read_eeprom[AZTECH_EEPROM_SIZE]; azt2316a_t *azt2316a = malloc(sizeof(azt2316a_t)); memset(azt2316a, 0, sizeof(azt2316a_t)); // load configs from eeprom FILE *f; f = nvrfopen(nvr_filename, "rb"); if (f) { uint8_t checksum = 0x7F; uint8_t saved_checksum; size_t res; // avoid warning res = fread(read_eeprom, AZTECH_EEPROM_SIZE, 1, f); for (i = 0; i < AZTECH_EEPROM_SIZE; i++) checksum += read_eeprom[i]; res = fread(&saved_checksum, sizeof(saved_checksum), 1, f); (void)res; fclose(f); if (checksum == saved_checksum) loaded_from_eeprom = 1; } // no eeprom saved or invalid checksum, load defaults if (!loaded_from_eeprom) { if (type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { read_eeprom[0] = 0x00; read_eeprom[1] = 0x00; read_eeprom[2] = 0x00; read_eeprom[3] = 0x00; read_eeprom[4] = 0x00; read_eeprom[5] = 0x00; read_eeprom[6] = 0x00; read_eeprom[7] = 0x00; read_eeprom[8] = 0x00; read_eeprom[9] = 0x00; read_eeprom[10] = 0x00; read_eeprom[11] = 0x88; read_eeprom[12] = 0xbc; read_eeprom[13] = 0x00; read_eeprom[14] = 0x01; read_eeprom[15] = 0x00; } else if (type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { read_eeprom[0] = 0x80; read_eeprom[1] = 0x80; read_eeprom[2] = 0x9F; read_eeprom[3] = 0x13; read_eeprom[4] = 0x16; read_eeprom[5] = 0x13; read_eeprom[6] = 0x00; read_eeprom[7] = 0x00; read_eeprom[8] = 0x16; read_eeprom[9] = 0x0B; read_eeprom[10] = 0x06; read_eeprom[11] = 0x01; read_eeprom[12] = 0x1C; read_eeprom[13] = 0x14; read_eeprom[14] = 0x04; read_eeprom[15] = 0x1C; } else fatal("Aztech: unknown type %d\n", type); } // restore settings from EEPROM bytes if (type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { azt2316a->config_word = read_eeprom[11] + (read_eeprom[12] << 8) + (read_eeprom[13] << 16) + (read_eeprom[14] << 24); switch (azt2316a->config_word & (3 << 0)) { case 0: azt2316a->cur_addr = 0x220; break; case 1: azt2316a->cur_addr = 0x240; break; default: fatal("AZT2316A: invalid sb addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 2)) azt2316a->cur_irq = 2; else if (azt2316a->config_word & (1 << 3)) azt2316a->cur_irq = 5; else if (azt2316a->config_word & (1 << 4)) azt2316a->cur_irq = 7; else if (azt2316a->config_word & (1 << 5)) azt2316a->cur_irq = 10; else fatal("AZT2316A: invalid sb irq in config word %08X\n", azt2316a->config_word); switch (azt2316a->config_word & (3 << 6)) { case 1 << 6: azt2316a->cur_dma = 0; break; case 2 << 6: azt2316a->cur_dma = 1; break; case 3 << 6: azt2316a->cur_dma = 3; break; default: fatal("AZT2316A: invalid sb dma in config word %08X\n", azt2316a->config_word); } switch (azt2316a->config_word & (3 << 8)) { case 0: azt2316a->cur_wss_addr = 0x530; break; case 1 << 8: azt2316a->cur_wss_addr = 0x604; break; case 2 << 8: azt2316a->cur_wss_addr = 0xE80; break; case 3 << 8: azt2316a->cur_wss_addr = 0xF40; break; default: fatal("AZT2316A: invalid wss addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 10)) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; // game_enabled is hardcoded //if (azt2316a->config_word & (1 << 11)) // azt2316a->cur_game_enabled = 1; //else // azt2316a->cur_game_enabled = 0; if (azt2316a->config_word & (1 << 12)) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; // mpu401_enabled is hardcoded //if (azt2316a->config_word & (1 << 13)) // azt2316a->cur_mpu401_enabled = 1; //else // azt2316a->cur_mpu401_enabled = 0; // cd_addr is hardcoded //switch (azt2316a->config_word & (3 << 14)) //{ // case 0: // azt2316a->cur_cd_addr = 0x310; // break; // case 1 << 14: // azt2316a->cur_cd_addr = 0x320; // break; // case 2 << 14: // azt2316a->cur_cd_addr = 0x340; // break; // case 3 << 14: // azt2316a->cur_cd_addr = 0x350; // break; // default: // fatal("AZT2316A: invalid cd addr in config word %08X\n", azt2316a->config_word); //} // cd_type is hardcoded //azt2316a->cur_cd_type = (azt2316a->config_word >> 16) & 0x7; // cd_dma8 is hardcoded //switch (azt2316a->config_word & (3 << 20)) //{ // case 0: // azt2316a->cur_cd_dma8 = -1; // break; // case 1 << 20: // azt2316a->cur_cd_dma8 = 0; // break; // case 2 << 20: // azt2316a->cur_cd_dma8 = 1; // break; // case 3 << 20: // azt2316a->cur_cd_dma8 = 3; // break; // default: // fatal("AZT2316A: invalid cd dma8 in config word %08X\n", azt2316a->config_word); //} // cd_dma16 is hardcoded //switch (azt2316a->config_word & (3 << 22)) //{ // case 0: // azt2316a->cur_cd_dma16 = -1; // break; // case 1 << 22: // azt2316a->cur_cd_dma16 = 5; // break; // case 2 << 22: // azt2316a->cur_cd_dma16 = 6; // break; // case 3 << 22: // azt2316a->cur_cd_dma16 = 7; // break; // default: // fatal("AZT2316A: invalid cd dma16 in config word %08X\n", azt2316a->config_word); //} if (azt2316a->config_word & (1 << 24)) azt2316a->cur_mpu401_irq = 2; else if (azt2316a->config_word & (1 << 25)) azt2316a->cur_mpu401_irq = 5; else if (azt2316a->config_word & (1 << 26)) azt2316a->cur_mpu401_irq = 7; else if (azt2316a->config_word & (1 << 27)) azt2316a->cur_mpu401_irq = 10; else fatal("AZT2316A: invalid mpu401 irq in config word %08X\n", azt2316a->config_word); // cd_irq is hardcoded //if (azt2316a->config_word & (1 << 28)) // azt2316a->cur_cd_irq = 5; //else if (azt2316a->config_word & (1 << 29)) // azt2316a->cur_cd_irq = 11; //else if (azt2316a->config_word & (1 << 30)) // azt2316a->cur_cd_irq = 12; //else if (azt2316a->config_word & (1 << 31)) // azt2316a->cur_cd_irq = 15; //else // fatal("AZT2316A: invalid cd irq in config word %08X\n", azt2316a->config_word); // these are not present on the EEPROM azt2316a->cur_wss_irq = 10; azt2316a->cur_wss_dma = 0; azt2316a->cur_mode = 0; } else if (type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt2316a->config_word = read_eeprom[12] + (read_eeprom[13] << 8) + (read_eeprom[14] << 16); switch (azt2316a->config_word & (3 << 0)) { case 0: azt2316a->cur_addr = 0x220; break; case 1: azt2316a->cur_addr = 0x240; break; default: fatal("AZT1605: invalid sb addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 2)) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; // mpu401_enabled is hardcoded //if (azt2316a->config_word & (1 << 3)) // azt2316a->cur_mpu401_enabled = 1; //else // azt2316a->cur_mpu401_enabled = 0; // game_enabled is hardcoded //if (azt2316a->config_word & (1 << 4)) // azt2316a->cur_game_enabled = 1; //else // azt2316a->cur_game_enabled = 0; // cd_type is hardcoded //azt2316a->cur_cd_type = (azt2316a->config_word >> 5) & 0x7; if (azt2316a->config_word & (1 << 8)) azt2316a->cur_irq = 2; else if (azt2316a->config_word & (1 << 9)) azt2316a->cur_irq = 3; else if (azt2316a->config_word & (1 << 10)) azt2316a->cur_irq = 5; else if (azt2316a->config_word & (1 << 11)) azt2316a->cur_irq = 7; else fatal("AZT1605: invalid sb irq in config word %08X\n", azt2316a->config_word); if (azt2316a->config_word & (1 << 12)) azt2316a->cur_mpu401_irq = 2; else if (azt2316a->config_word & (1 << 13)) azt2316a->cur_mpu401_irq = 3; else if (azt2316a->config_word & (1 << 14)) azt2316a->cur_mpu401_irq = 5; else if (azt2316a->config_word & (1 << 15)) azt2316a->cur_mpu401_irq = 7; else fatal("AZT1605: invalid mpu401 irq in config word %08X\n", azt2316a->config_word); switch (azt2316a->config_word & (3 << 16)) { case 0: azt2316a->cur_wss_addr = 0x530; break; case 1 << 16: azt2316a->cur_wss_addr = 0x604; break; case 2 << 16: azt2316a->cur_wss_addr = 0xE80; break; case 3 << 16: azt2316a->cur_wss_addr = 0xF40; break; default: fatal("AZT1605: invalid wss addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 18)) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; // cd_irq is hardcoded //if (azt2316a->config_word & (1 << 19)) // azt2316a->cur_cd_irq = 11; //else if (azt2316a->config_word & (1 << 20)) // azt2316a->cur_cd_irq = 12; //else if (azt2316a->config_word & (1 << 21)) // azt2316a->cur_cd_irq = 15; //else // fatal("AZT1605: invalid cd irq in config word %08X\n", azt2316a->config_word); // cd_dma8 is hardcoded //switch (azt2316a->config_word & (3 << 22)) //{ // case 0: // azt2316a->cur_cd_dma8 = -1; // break; // case 1 << 22: // azt2316a->cur_cd_dma8 = 0; // break; // case 2 << 22: // azt2316a->cur_cd_dma8 = 1; // break; // case 3 << 22: // azt2316a->cur_cd_dma8 = 3; // break; // default: // fatal("AZT1605: invalid cd dma8 in config word %08X\n", azt2316a->config_word); //} // these are not present on the EEPROM azt2316a->cur_dma = 1; // TODO: investigate TSR to make this work with it - there is no software configurable DMA8? azt2316a->cur_wss_irq = 10; azt2316a->cur_wss_dma = 0; azt2316a->cur_mode = 0; } else fatal("Aztech: unknown type %d\n", type); // check for sb addr override jumper addr_setting = device_get_config_int("addr"); if (addr_setting) azt2316a->cur_addr = addr_setting; // now we can continue initializing azt2316a->opl_emu = device_get_config_int("opl_emu"); azt2316a->wss_interrupt_after_config = device_get_config_int("wss_interrupt_after_config"); azt2316a->type = type; // wss part ad1848_init(&azt2316a->ad1848, device_get_config_int("codec")); ad1848_setirq(&azt2316a->ad1848, azt2316a->cur_wss_irq); ad1848_setdma(&azt2316a->ad1848, azt2316a->cur_wss_dma); io_sethandler(azt2316a->cur_addr + 0x0400, 0x0040, azt2316a_config_read, NULL, NULL, azt2316a_config_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); // sbprov2 part /*sbpro port mappings. 220h or 240h. 2x0 to 2x3 -> FM chip (18 voices) 2x4 to 2x5 -> Mixer interface 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip (9 voices).*/ azt2316a->sb = malloc(sizeof(sb_t)); memset(azt2316a->sb, 0, sizeof(sb_t)); for (i = 0; i < AZTECH_EEPROM_SIZE; i++) azt2316a->sb->dsp.azt_eeprom[i] = read_eeprom[i]; azt2316a->sb->opl_emu = azt2316a->opl_emu; opl3_init(&azt2316a->sb->opl, azt2316a->sb->opl_emu); sb_dsp_init(&azt2316a->sb->dsp, SBPRO2, azt2316a->type, azt2316a); sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); sb_ct1345_mixer_reset(azt2316a->sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ io_sethandler(azt2316a->cur_addr+0, 0x0004, opl3_read, NULL, NULL, opl3_write, NULL, NULL, &azt2316a->sb->opl); io_sethandler(azt2316a->cur_addr+8, 0x0002, opl3_read, NULL, NULL, opl3_write, NULL, NULL, &azt2316a->sb->opl); io_sethandler(0x0388, 0x0004, opl3_read, NULL, NULL, opl3_write, NULL, NULL, &azt2316a->sb->opl); io_sethandler(azt2316a->cur_addr+4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, azt2316a->sb); mpu401_uart_init(&azt2316a->sb->mpu, azt2316a->cur_mpu401_addr, azt2316a->cur_mpu401_irq, 1); azt2316a_create_config_word(azt2316a); // recreate even if we have read it from EEPROM, because we have some overrides (CD interfaces always off, etc) sound_add_handler(azt2316a_get_buffer, azt2316a); return azt2316a; } void *azt2316a_init() { return azt_common_init(SB_SUBTYPE_CLONE_AZT2316A_0X11, "azt2316a.nvr"); } void *azt1605_init() { return azt_common_init(SB_SUBTYPE_CLONE_AZT1605_0X0C, "azt1605.nvr"); } void azt_common_close(void *p, char *nvr_filename) { azt2316a_t *azt2316a = (azt2316a_t *)p; int i; uint8_t checksum = 0x7F; // always save to eeprom (recover from bad values) FILE *f = nvrfopen(nvr_filename, "wb"); if (f) { for (i = 0; i < AZTECH_EEPROM_SIZE; i++) checksum += azt2316a->sb->dsp.azt_eeprom[i]; fwrite(azt2316a->sb->dsp.azt_eeprom, AZTECH_EEPROM_SIZE, 1, f); // TODO: confirm any models saving mixer settings to EEPROM and implement reading back // TODO: should remember to save wss duplex setting if PCem has voice recording implemented in the future? Also, default azt2316a->wss_config // TODO: azt2316a->cur_mode is not saved to EEPROM? fwrite(&checksum, sizeof(checksum), 1, f); fclose(f); } sb_close(azt2316a->sb); free(azt2316a); } void azt2316a_close(void *p) { azt_common_close(p, "azt2316a.nvr"); } void azt1605_close(void *p) { azt_common_close(p, "azt1605.nvr"); } void azt2316a_speed_changed(void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; ad1848_speed_changed(&azt2316a->ad1848); sb_speed_changed(azt2316a->sb); } void azt2316a_add_status_info(char *s, int max_len, void *p) { azt2316a_t *azt2316a = (azt2316a_t *)p; sb_dsp_add_status_info(s, max_len, &azt2316a->sb->dsp); } static device_config_t azt2316a_config[] = { { .name = "codec", .description = "CODEC", .type = CONFIG_SELECTION, .selection = { { .description = "CS4248", .value = AD1848_TYPE_CS4248 }, { .description = "CS4231", .value = AD1848_TYPE_CS4231 }, }, .default_int = AD1848_TYPE_CS4248 }, { .name = "wss_interrupt_after_config", .description = "Raise CODEC interrupt on CODEC setup (needed by some drivers)", .type = CONFIG_BINARY, .default_int = 0 }, { .name = "addr", .description = "SB Address", .type = CONFIG_SELECTION, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "Use EEPROM setting", .value = 0 }, { .description = "" } }, .default_int = 0 }, { .name = "midi", .description = "MIDI out device", .type = CONFIG_MIDI, .default_int = 0 }, { .name = "opl_emu", .description = "OPL emulator", .type = CONFIG_SELECTION, .selection = { { .description = "DBOPL", .value = OPL_DBOPL }, { .description = "NukedOPL", .value = OPL_NUKED }, }, .default_int = OPL_DBOPL }, { .type = -1 } }; device_t azt2316a_device = { "Aztech Sound Galaxy Pro 16 AB (Washington)", 0, azt2316a_init, azt2316a_close, NULL, azt2316a_speed_changed, NULL, azt2316a_add_status_info, azt2316a_config }; device_t azt1605_device = { "Aztech Sound Galaxy Nova 16 Extra (Clinton)", DEVICE_NOT_WORKING, azt1605_init, azt1605_close, NULL, azt2316a_speed_changed, NULL, azt2316a_add_status_info, azt2316a_config };
965246.c
/* main.c - Application main entry point */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <linker/sections.h> #include <tc_util.h> #include <zephyr/types.h> #include <stddef.h> #include <string.h> #include <errno.h> #include <device.h> #include <init.h> #include <net/net_core.h> #include <net/net_pkt.h> #include <net/net_ip.h> #include <net/arp.h> #include <ztest.h> #define NET_LOG_ENABLED 1 #include "net_private.h" static bool req_test; static char *app_data = "0123456789"; struct net_arp_context { u8_t mac_addr[sizeof(struct net_eth_addr)]; struct net_linkaddr ll_addr; }; int net_arp_dev_init(struct device *dev) { struct net_arp_context *net_arp_context = dev->driver_data; net_arp_context = net_arp_context; return 0; } static u8_t *net_arp_get_mac(struct device *dev) { struct net_arp_context *context = dev->driver_data; if (context->mac_addr[2] == 0x00) { /* 00-00-5E-00-53-xx Documentation RFC 7042 */ context->mac_addr[0] = 0x00; context->mac_addr[1] = 0x00; context->mac_addr[2] = 0x5E; context->mac_addr[3] = 0x00; context->mac_addr[4] = 0x53; context->mac_addr[5] = sys_rand32_get(); } return context->mac_addr; } static void net_arp_iface_init(struct net_if *iface) { u8_t *mac = net_arp_get_mac(net_if_get_device(iface)); net_if_set_link_addr(iface, mac, 6, NET_LINK_ETHERNET); } static struct net_pkt *pending_pkt; static struct net_eth_addr hwaddr = { { 0x42, 0x11, 0x69, 0xde, 0xfa, 0xec } }; static int send_status = -EINVAL; static int tester_send(struct net_if *iface, struct net_pkt *pkt) { struct net_eth_hdr *hdr; if (!pkt->frags) { printk("No data to send!\n"); return -ENODATA; } if (net_pkt_ll_reserve(pkt) != sizeof(struct net_eth_hdr)) { printk("No ethernet header in pkt %p", pkt); send_status = -EINVAL; return send_status; } hdr = (struct net_eth_hdr *)net_pkt_ll(pkt); if (ntohs(hdr->type) == NET_ETH_PTYPE_ARP) { struct net_arp_hdr *arp_hdr = NET_ARP_HDR(pkt); if (ntohs(arp_hdr->opcode) == NET_ARP_REPLY) { if (!req_test && pkt != pending_pkt) { printk("Pending data but to be sent is wrong, " "expecting %p but got %p\n", pending_pkt, pkt); return -EINVAL; } if (!req_test && memcmp(&hdr->dst, &hwaddr, sizeof(struct net_eth_addr))) { char out[sizeof("xx:xx:xx:xx:xx:xx")]; snprintk(out, sizeof(out), "%s", net_sprint_ll_addr( (u8_t *)&hdr->dst, sizeof(struct net_eth_addr))); printk("Invalid hwaddr %s, should be %s\n", out, net_sprint_ll_addr( (u8_t *)&hwaddr, sizeof(struct net_eth_addr))); send_status = -EINVAL; return send_status; } } else if (ntohs(arp_hdr->opcode) == NET_ARP_REQUEST) { if (memcmp(&hdr->src, &hwaddr, sizeof(struct net_eth_addr))) { char out[sizeof("xx:xx:xx:xx:xx:xx")]; snprintk(out, sizeof(out), "%s", net_sprint_ll_addr( (u8_t *)&hdr->src, sizeof(struct net_eth_addr))); printk("Invalid hwaddr %s, should be %s\n", out, net_sprint_ll_addr( (u8_t *)&hwaddr, sizeof(struct net_eth_addr))); send_status = -EINVAL; return send_status; } } } net_pkt_unref(pkt); send_status = 0; return 0; } static inline struct in_addr *if_get_addr(struct net_if *iface) { int i; for (i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { if (iface->ipv4.unicast[i].is_used && iface->ipv4.unicast[i].address.family == AF_INET && iface->ipv4.unicast[i].addr_state == NET_ADDR_PREFERRED) { return &iface->ipv4.unicast[i].address.in_addr; } } return NULL; } static inline struct net_pkt *prepare_arp_reply(struct net_if *iface, struct net_pkt *req, struct net_eth_addr *addr) { struct net_pkt *pkt; struct net_buf *frag; struct net_arp_hdr *hdr; struct net_eth_hdr *eth; pkt = net_pkt_get_reserve_tx(sizeof(struct net_eth_hdr), K_FOREVER); if (!pkt) { goto fail; } frag = net_pkt_get_frag(pkt, K_FOREVER); if (!frag) { goto fail; } net_pkt_frag_add(pkt, frag); net_pkt_set_iface(pkt, iface); hdr = NET_ARP_HDR(pkt); eth = NET_ETH_HDR(pkt); eth->type = htons(NET_ETH_PTYPE_ARP); memset(&eth->dst.addr, 0xff, sizeof(struct net_eth_addr)); memcpy(&eth->src.addr, net_if_get_link_addr(iface)->addr, sizeof(struct net_eth_addr)); hdr->hwtype = htons(NET_ARP_HTYPE_ETH); hdr->protocol = htons(NET_ETH_PTYPE_IP); hdr->hwlen = sizeof(struct net_eth_addr); hdr->protolen = sizeof(struct in_addr); hdr->opcode = htons(NET_ARP_REPLY); memcpy(&hdr->dst_hwaddr.addr, &eth->src.addr, sizeof(struct net_eth_addr)); memcpy(&hdr->src_hwaddr.addr, addr, sizeof(struct net_eth_addr)); net_ipaddr_copy(&hdr->dst_ipaddr, &NET_ARP_HDR(req)->src_ipaddr); net_ipaddr_copy(&hdr->src_ipaddr, &NET_ARP_HDR(req)->dst_ipaddr); net_buf_add(frag, sizeof(struct net_arp_hdr)); return pkt; fail: net_pkt_unref(pkt); return NULL; } static inline struct net_pkt *prepare_arp_request(struct net_if *iface, struct net_pkt *req, struct net_eth_addr *addr) { struct net_pkt *pkt; struct net_buf *frag; struct net_arp_hdr *hdr, *req_hdr; struct net_eth_hdr *eth, *eth_req; pkt = net_pkt_get_reserve_rx(sizeof(struct net_eth_hdr), K_FOREVER); if (!pkt) { goto fail; } frag = net_pkt_get_frag(pkt, K_FOREVER); if (!frag) { goto fail; } net_pkt_frag_add(pkt, frag); net_pkt_set_iface(pkt, iface); hdr = NET_ARP_HDR(pkt); eth = NET_ETH_HDR(pkt); req_hdr = NET_ARP_HDR(req); eth_req = NET_ETH_HDR(req); eth->type = htons(NET_ETH_PTYPE_ARP); memset(&eth->dst.addr, 0xff, sizeof(struct net_eth_addr)); memcpy(&eth->src.addr, addr, sizeof(struct net_eth_addr)); hdr->hwtype = htons(NET_ARP_HTYPE_ETH); hdr->protocol = htons(NET_ETH_PTYPE_IP); hdr->hwlen = sizeof(struct net_eth_addr); hdr->protolen = sizeof(struct in_addr); hdr->opcode = htons(NET_ARP_REQUEST); memset(&hdr->dst_hwaddr.addr, 0x00, sizeof(struct net_eth_addr)); memcpy(&hdr->src_hwaddr.addr, addr, sizeof(struct net_eth_addr)); net_ipaddr_copy(&hdr->src_ipaddr, &req_hdr->src_ipaddr); net_ipaddr_copy(&hdr->dst_ipaddr, &req_hdr->dst_ipaddr); net_buf_add(frag, sizeof(struct net_arp_hdr)); return pkt; fail: net_pkt_unref(pkt); return NULL; } static void setup_eth_header(struct net_if *iface, struct net_pkt *pkt, struct net_eth_addr *hwaddr, u16_t type) { struct net_eth_hdr *hdr = (struct net_eth_hdr *)net_pkt_ll(pkt); memcpy(&hdr->dst.addr, hwaddr, sizeof(struct net_eth_addr)); memcpy(&hdr->src.addr, net_if_get_link_addr(iface)->addr, sizeof(struct net_eth_addr)); hdr->type = htons(type); } struct net_arp_context net_arp_context_data; static struct net_if_api net_arp_if_api = { .init = net_arp_iface_init, .send = tester_send, }; #if defined(CONFIG_NET_ARP) && defined(CONFIG_NET_L2_ETHERNET) #define _ETH_L2_LAYER ETHERNET_L2 #define _ETH_L2_CTX_TYPE NET_L2_GET_CTX_TYPE(ETHERNET_L2) #else #define _ETH_L2_LAYER DUMMY_L2 #define _ETH_L2_CTX_TYPE NET_L2_GET_CTX_TYPE(DUMMY_L2) #endif NET_DEVICE_INIT(net_arp_test, "net_arp_test", net_arp_dev_init, &net_arp_context_data, NULL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, &net_arp_if_api, _ETH_L2_LAYER, _ETH_L2_CTX_TYPE, 127); void run_tests(void) { k_thread_priority_set(k_current_get(), K_PRIO_COOP(7)); struct net_pkt *pkt, *pkt2; struct net_buf *frag; struct net_if *iface; struct net_if_addr *ifaddr; struct net_arp_hdr *arp_hdr; struct net_ipv4_hdr *ipv4; struct net_eth_hdr *eth_hdr; int len; struct in_addr dst = { { { 192, 168, 0, 2 } } }; struct in_addr dst_far = { { { 10, 11, 12, 13 } } }; struct in_addr dst_far2 = { { { 172, 16, 14, 186 } } }; struct in_addr src = { { { 192, 168, 0, 1 } } }; struct in_addr netmask = { { { 255, 255, 255, 0 } } }; struct in_addr gw = { { { 192, 168, 0, 42 } } }; net_arp_init(); iface = net_if_get_default(); net_if_ipv4_set_gw(iface, &gw); net_if_ipv4_set_netmask(iface, &netmask); /* Unicast test */ ifaddr = net_if_ipv4_addr_add(iface, &src, NET_ADDR_MANUAL, 0); ifaddr->addr_state = NET_ADDR_PREFERRED; /* Application data for testing */ pkt = net_pkt_get_reserve_tx(sizeof(struct net_eth_hdr), K_FOREVER); /**TESTPOINTS: Check if out of memory*/ zassert_not_null(pkt, "Out of mem TX"); frag = net_pkt_get_frag(pkt, K_FOREVER); zassert_not_null(frag, "Out of mem DATA"); net_pkt_frag_add(pkt, frag); net_pkt_set_iface(pkt, iface); setup_eth_header(iface, pkt, &hwaddr, NET_ETH_PTYPE_IP); len = strlen(app_data); if (net_pkt_ll_reserve(pkt) != sizeof(struct net_eth_hdr)) { printk("LL reserve invalid, should be %zd was %d\n", sizeof(struct net_eth_hdr), net_pkt_ll_reserve(pkt)); zassert_true(0, "exiting"); } ipv4 = (struct net_ipv4_hdr *)net_buf_add(frag, sizeof(struct net_ipv4_hdr)); net_ipaddr_copy(&ipv4->src, &src); net_ipaddr_copy(&ipv4->dst, &dst); memcpy(net_buf_add(frag, len), app_data, len); pkt2 = net_arp_prepare(pkt); /* pkt2 is the ARP packet and pkt is the IPv4 packet and it was * stored in ARP table. */ /**TESTPOINTS: Check packets*/ zassert_not_equal((void *)(pkt2), (void *)(pkt), /* The packets cannot be the same as the ARP cache has * still room for the pkt. */ "ARP cache should still have free space"); zassert_not_null(pkt2, "ARP pkt is empty"); /* The ARP cache should now have a link to pending net_pkt * that is to be sent after we have got an ARP reply. */ zassert_not_null(pkt->frags, "Pending pkt fragment is NULL"); pending_pkt = pkt; /* pkt2 should contain the arp header, verify it */ if (memcmp(net_pkt_ll(pkt2), net_eth_broadcast_addr(), sizeof(struct net_eth_addr))) { printk("ARP ETH dest address invalid\n"); net_hexdump("ETH dest wrong ", net_pkt_ll(pkt2), sizeof(struct net_eth_addr)); net_hexdump("ETH dest correct", (u8_t *)net_eth_broadcast_addr(), sizeof(struct net_eth_addr)); zassert_true(0, "exiting"); } if (memcmp(net_pkt_ll(pkt2) + sizeof(struct net_eth_addr), iface->link_addr.addr, sizeof(struct net_eth_addr))) { printk("ARP ETH source address invalid\n"); net_hexdump("ETH src correct", iface->link_addr.addr, sizeof(struct net_eth_addr)); net_hexdump("ETH src wrong ", net_pkt_ll(pkt2) + sizeof(struct net_eth_addr), sizeof(struct net_eth_addr)); zassert_true(0, "exiting"); } arp_hdr = NET_ARP_HDR(pkt2); eth_hdr = NET_ETH_HDR(pkt2); if (eth_hdr->type != htons(NET_ETH_PTYPE_ARP)) { printk("ETH type 0x%x, should be 0x%x\n", eth_hdr->type, htons(NET_ETH_PTYPE_ARP)); zassert_true(0, "exiting"); } if (arp_hdr->hwtype != htons(NET_ARP_HTYPE_ETH)) { printk("ARP hwtype 0x%x, should be 0x%x\n", arp_hdr->hwtype, htons(NET_ARP_HTYPE_ETH)); zassert_true(0, "exiting"); } if (arp_hdr->protocol != htons(NET_ETH_PTYPE_IP)) { printk("ARP protocol 0x%x, should be 0x%x\n", arp_hdr->protocol, htons(NET_ETH_PTYPE_IP)); zassert_true(0, "exiting"); } if (arp_hdr->hwlen != sizeof(struct net_eth_addr)) { printk("ARP hwlen 0x%x, should be 0x%zx\n", arp_hdr->hwlen, sizeof(struct net_eth_addr)); zassert_true(0, "exiting"); } if (arp_hdr->protolen != sizeof(struct in_addr)) { printk("ARP IP addr len 0x%x, should be 0x%zx\n", arp_hdr->protolen, sizeof(struct in_addr)); zassert_true(0, "exiting"); } if (arp_hdr->opcode != htons(NET_ARP_REQUEST)) { printk("ARP opcode 0x%x, should be 0x%x\n", arp_hdr->opcode, htons(NET_ARP_REQUEST)); zassert_true(0, "exiting"); } if (!net_ipv4_addr_cmp(&arp_hdr->dst_ipaddr, &NET_IPV4_HDR(pkt)->dst)) { char out[sizeof("xxx.xxx.xxx.xxx")]; snprintk(out, sizeof(out), "%s", net_sprint_ipv4_addr(&arp_hdr->dst_ipaddr)); printk("ARP IP dest invalid %s, should be %s", out, net_sprint_ipv4_addr(&NET_IPV4_HDR(pkt)->dst)); zassert_true(0, "exiting"); } if (!net_ipv4_addr_cmp(&arp_hdr->src_ipaddr, &NET_IPV4_HDR(pkt)->src)) { char out[sizeof("xxx.xxx.xxx.xxx")]; snprintk(out, sizeof(out), "%s", net_sprint_ipv4_addr(&arp_hdr->src_ipaddr)); printk("ARP IP src invalid %s, should be %s", out, net_sprint_ipv4_addr(&NET_IPV4_HDR(pkt)->src)); zassert_true(0, "exiting"); } /* We could have send the new ARP request but for this test we * just free it. */ net_pkt_unref(pkt2); zassert_equal(pkt->ref, 2, "ARP cache should own the original packet"); /* Then a case where target is not in the same subnet */ net_ipaddr_copy(&ipv4->dst, &dst_far); pkt2 = net_arp_prepare(pkt); zassert_not_equal((void *)(pkt2), (void *)(pkt), "ARP cache should not find anything"); /**TESTPOINTS: Check if packets not empty*/ zassert_not_null(pkt2, "ARP pkt2 is empty"); arp_hdr = NET_ARP_HDR(pkt2); if (!net_ipv4_addr_cmp(&arp_hdr->dst_ipaddr, &iface->ipv4.gw)) { char out[sizeof("xxx.xxx.xxx.xxx")]; snprintk(out, sizeof(out), "%s", net_sprint_ipv4_addr(&arp_hdr->dst_ipaddr)); printk("ARP IP dst invalid %s, should be %s\n", out, net_sprint_ipv4_addr(&iface->ipv4.gw)); zassert_true(0, "exiting"); } net_pkt_unref(pkt2); /* Try to find the same destination again, this should fail as there * is a pending request in ARP cache. */ net_ipaddr_copy(&ipv4->dst, &dst_far); /* Make sure prepare will not free the pkt because it will be * needed in the later test case. */ net_pkt_ref(pkt); pkt2 = net_arp_prepare(pkt); zassert_not_null(pkt2, "ARP cache is not sending the request again"); net_pkt_unref(pkt2); /* Try to find the different destination, this should fail too * as the cache table should be full. */ net_ipaddr_copy(&ipv4->dst, &dst_far2); /* Make sure prepare will not free the pkt because it will be * needed in the next test case. */ net_pkt_ref(pkt); pkt2 = net_arp_prepare(pkt); zassert_not_null(pkt2, "ARP cache did not send a req"); /* Restore the original address so that following test case can * work properly. */ net_ipaddr_copy(&ipv4->dst, &dst); /* The arp request packet is now verified, create an arp reply. * The previous value of pkt is stored in arp table and is not lost. */ pkt = net_pkt_get_reserve_rx(sizeof(struct net_eth_hdr), K_FOREVER); zassert_not_null(pkt, "Out of mem RX reply"); printk("%d pkt %p\n", __LINE__, pkt); frag = net_pkt_get_frag(pkt, K_FOREVER); zassert_not_null(frag, "Out of mem DATA reply"); printk("%d frag %p\n", __LINE__, frag); net_pkt_frag_add(pkt, frag); net_pkt_set_iface(pkt, iface); arp_hdr = NET_ARP_HDR(pkt); net_buf_add(frag, sizeof(struct net_arp_hdr)); net_ipaddr_copy(&arp_hdr->dst_ipaddr, &dst); net_ipaddr_copy(&arp_hdr->src_ipaddr, &src); pkt2 = prepare_arp_reply(iface, pkt, &hwaddr); zassert_not_null(pkt2, "ARP reply generation failed."); /* The pending packet should now be sent */ switch (net_arp_input(pkt2)) { case NET_OK: case NET_CONTINUE: break; case NET_DROP: break; } /* Yielding so that network interface TX thread can proceed. */ k_yield(); /**TESTPOINTS: Check ARP reply*/ zassert_false(send_status < 0, "ARP reply was not sent"); zassert_equal(pkt->ref, 1, "ARP cache should no longer own the original packet"); net_pkt_unref(pkt); /* Then feed in ARP request */ pkt = net_pkt_get_reserve_rx(sizeof(struct net_eth_hdr), K_FOREVER); /**TESTPOINTS: Check if out of memory*/ zassert_not_null(pkt, "Out of mem RX request"); frag = net_pkt_get_frag(pkt, K_FOREVER); zassert_not_null(frag, "Out of mem DATA request"); net_pkt_frag_add(pkt, frag); net_pkt_set_iface(pkt, iface); send_status = -EINVAL; arp_hdr = NET_ARP_HDR(pkt); net_buf_add(frag, sizeof(struct net_arp_hdr)); net_ipaddr_copy(&arp_hdr->dst_ipaddr, &src); net_ipaddr_copy(&arp_hdr->src_ipaddr, &dst); setup_eth_header(iface, pkt, &hwaddr, NET_ETH_PTYPE_ARP); pkt2 = prepare_arp_request(iface, pkt, &hwaddr); /**TESTPOINT: Check if ARP request generation failed*/ zassert_not_null(pkt2, "ARP request generation failed."); req_test = true; switch (net_arp_input(pkt2)) { case NET_OK: case NET_CONTINUE: break; case NET_DROP: break; } /* Yielding so that network interface TX thread can proceed. */ k_yield(); /**TESTPOINT: Check if ARP request sent*/ zassert_false(send_status < 0, "ARP req was not sent"); net_pkt_unref(pkt); } void test_main(void) { ztest_test_suite(test_arp_fn, ztest_unit_test(run_tests)); ztest_run_test_suite(test_arp_fn); }
942500.c
/******************************************************************************* System Interrupts File Company: Microchip Technology Inc. File Name: interrupt.c Summary: Interrupt vectors mapping Description: This file maps all the interrupt vectors to their corresponding implementations. If a particular module interrupt is used, then its ISR definition can be found in corresponding PLIB source file. If a module interrupt is not used, then its ISR implementation is mapped to dummy handler. *******************************************************************************/ // DOM-IGNORE-BEGIN /******************************************************************************* * Copyright (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. *******************************************************************************/ // DOM-IGNORE-END // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** #include "configuration.h" #include "definitions.h" // ***************************************************************************** // ***************************************************************************** // Section: System Interrupt Vector Functions // ***************************************************************************** // ***************************************************************************** extern uint32_t _stack; /* Brief default interrupt handler for unused IRQs.*/ void __attribute__((optimize("-O1"),section(".text.Dummy_Handler"),long_call))Dummy_Handler(void) { while (1) { } } /* Device vectors list dummy definition*/ void Reset_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void NonMaskableInt_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void HardFault_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SVCall_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void PendSV_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SysTick_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SYSTEM_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void WDT_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void RTC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void EIC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void FREQM_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TSENS_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void NVMCTRL_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void DMAC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void EVSYS_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM0_6_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM1_7_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM2_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM3_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM4_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SERCOM5_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void CAN0_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void CAN1_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TCC0_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TCC1_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TCC2_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC0_TimerInterruptHandler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC5_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC1_6_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC2_7_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC3_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void TC4_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void ADC0_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void ADC1_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void AC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void DAC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void SDADC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); void PTC_Handler ( void ) __attribute__((weak, alias("Dummy_Handler"))); /* Mutiple handlers for vector */ void TC0_5_Handler( void ) { TC0_TimerInterruptHandler(); } __attribute__ ((section(".vectors"))) const DeviceVectors exception_table= { /* Configure Initial Stack Pointer, using linker-generated symbols */ .pvStack = (void*) (&_stack), .pfnReset_Handler = ( void * ) Reset_Handler, .pfnNonMaskableInt_Handler = ( void * ) NonMaskableInt_Handler, .pfnHardFault_Handler = ( void * ) HardFault_Handler, .pfnSVCall_Handler = ( void * ) SVCall_Handler, .pfnPendSV_Handler = ( void * ) PendSV_Handler, .pfnSysTick_Handler = ( void * ) SysTick_Handler, .pfnSYSTEM_Handler = ( void * ) SYSTEM_Handler, .pfnWDT_Handler = ( void * ) WDT_Handler, .pfnRTC_Handler = ( void * ) RTC_Handler, .pfnEIC_Handler = ( void * ) EIC_Handler, .pfnFREQM_Handler = ( void * ) FREQM_Handler, .pfnTSENS_Handler = ( void * ) TSENS_Handler, .pfnNVMCTRL_Handler = ( void * ) NVMCTRL_Handler, .pfnDMAC_Handler = ( void * ) DMAC_Handler, .pfnEVSYS_Handler = ( void * ) EVSYS_Handler, .pfnSERCOM0_6_Handler = ( void * ) SERCOM0_6_Handler, .pfnSERCOM1_7_Handler = ( void * ) SERCOM1_7_Handler, .pfnSERCOM2_Handler = ( void * ) SERCOM2_Handler, .pfnSERCOM3_Handler = ( void * ) SERCOM3_Handler, .pfnSERCOM4_Handler = ( void * ) SERCOM4_Handler, .pfnSERCOM5_Handler = ( void * ) SERCOM5_Handler, .pfnCAN0_Handler = ( void * ) CAN0_Handler, .pfnCAN1_Handler = ( void * ) CAN1_Handler, .pfnTCC0_Handler = ( void * ) TCC0_Handler, .pfnTCC1_Handler = ( void * ) TCC1_Handler, .pfnTCC2_Handler = ( void * ) TCC2_Handler, .pfnTC0_5_Handler = ( void * ) TC0_5_Handler, .pfnTC1_6_Handler = ( void * ) TC1_6_Handler, .pfnTC2_7_Handler = ( void * ) TC2_7_Handler, .pfnTC3_Handler = ( void * ) TC3_Handler, .pfnTC4_Handler = ( void * ) TC4_Handler, .pfnADC0_Handler = ( void * ) ADC0_Handler, .pfnADC1_Handler = ( void * ) ADC1_Handler, .pfnAC_Handler = ( void * ) AC_Handler, .pfnDAC_Handler = ( void * ) DAC_Handler, .pfnSDADC_Handler = ( void * ) SDADC_Handler, .pfnPTC_Handler = ( void * ) PTC_Handler, }; /******************************************************************************* End of File */
198421.c
/* * drv.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * DSP/BIOS Bridge resource allocation module. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <linux/types.h> #include <linux/list.h> /* ----------------------------------- Host OS */ #include <dspbridge/host_os.h> /* ----------------------------------- DSP/BIOS Bridge */ #include <dspbridge/dbdefs.h> /* ----------------------------------- Trace & Debug */ #include <dspbridge/dbc.h> /* ----------------------------------- This */ #include <dspbridge/drv.h> #include <dspbridge/dev.h> #include <dspbridge/node.h> #include <dspbridge/proc.h> #include <dspbridge/strm.h> #include <dspbridge/nodepriv.h> #include <dspbridge/dspchnl.h> #include <dspbridge/resourcecleanup.h> /* ----------------------------------- Defines, Data Structures, Typedefs */ struct drv_object { struct list_head dev_list; struct list_head dev_node_string; }; /* * This is the Device Extension. Named with the Prefix * DRV_ since it is living in this module */ struct drv_ext { struct list_head link; char sz_string[MAXREGPATHLENGTH]; }; /* ----------------------------------- Globals */ static s32 refs; static bool ext_phys_mem_pool_enabled; struct ext_phys_mem_pool { u32 phys_mem_base; u32 phys_mem_size; u32 virt_mem_base; u32 next_phys_alloc_ptr; }; static struct ext_phys_mem_pool ext_mem_pool; /* ----------------------------------- Function Prototypes */ static int request_bridge_resources(struct cfg_hostres *res); /* GPP PROCESS CLEANUP CODE */ static int drv_proc_free_node_res(int id, void *p, void *data); /* Allocate and add a node resource element * This function is called from .Node_Allocate. */ int drv_insert_node_res_element(void *hnode, void *node_resource, void *process_ctxt) { struct node_res_object **node_res_obj = (struct node_res_object **)node_resource; struct process_context *ctxt = (struct process_context *)process_ctxt; int status = 0; int retval; *node_res_obj = kzalloc(sizeof(struct node_res_object), GFP_KERNEL); if (!*node_res_obj) { status = -ENOMEM; goto func_end; } (*node_res_obj)->node = hnode; retval = idr_get_new(ctxt->node_id, *node_res_obj, &(*node_res_obj)->id); if (retval == -EAGAIN) { if (!idr_pre_get(ctxt->node_id, GFP_KERNEL)) { pr_err("%s: OUT OF MEMORY\n", __func__); status = -ENOMEM; goto func_end; } retval = idr_get_new(ctxt->node_id, *node_res_obj, &(*node_res_obj)->id); } if (retval) { pr_err("%s: FAILED, IDR is FULL\n", __func__); status = -EFAULT; } func_end: if (status) kfree(*node_res_obj); return status; } /* Release all Node resources and its context * Actual Node De-Allocation */ static int drv_proc_free_node_res(int id, void *p, void *data) { struct process_context *ctxt = data; int status; struct node_res_object *node_res_obj = p; u32 node_state; if (node_res_obj->node_allocated) { node_state = node_get_state(node_res_obj->node); if (node_state <= NODE_DELETING) { if ((node_state == NODE_RUNNING) || (node_state == NODE_PAUSED) || (node_state == NODE_TERMINATING)) node_terminate (node_res_obj->node, &status); node_delete(node_res_obj, ctxt); } } return 0; } /* Release all Mapped and Reserved DMM resources */ int drv_remove_all_dmm_res_elements(void *process_ctxt) { struct process_context *ctxt = (struct process_context *)process_ctxt; int status = 0; struct dmm_map_object *temp_map, *map_obj; struct dmm_rsv_object *temp_rsv, *rsv_obj; /* Free DMM mapped memory resources */ list_for_each_entry_safe(map_obj, temp_map, &ctxt->dmm_map_list, link) { status = proc_un_map(ctxt->processor, (void *)map_obj->dsp_addr, ctxt); if (status) pr_err("%s: proc_un_map failed!" " status = 0x%xn", __func__, status); } /* Free DMM reserved memory resources */ list_for_each_entry_safe(rsv_obj, temp_rsv, &ctxt->dmm_rsv_list, link) { status = proc_un_reserve_memory(ctxt->processor, (void *) rsv_obj->dsp_reserved_addr, ctxt); if (status) pr_err("%s: proc_un_reserve_memory failed!" " status = 0x%xn", __func__, status); } return status; } /* Update Node allocation status */ void drv_proc_node_update_status(void *node_resource, s32 status) { struct node_res_object *node_res_obj = (struct node_res_object *)node_resource; DBC_ASSERT(node_resource != NULL); node_res_obj->node_allocated = status; } /* Update Node Heap status */ void drv_proc_node_update_heap_status(void *node_resource, s32 status) { struct node_res_object *node_res_obj = (struct node_res_object *)node_resource; DBC_ASSERT(node_resource != NULL); node_res_obj->heap_allocated = status; } /* Release all Node resources and its context * This is called from .bridge_release. */ int drv_remove_all_node_res_elements(void *process_ctxt) { struct process_context *ctxt = process_ctxt; idr_for_each(ctxt->node_id, drv_proc_free_node_res, ctxt); idr_destroy(ctxt->node_id); return 0; } /* Allocate the STRM resource element * This is called after the actual resource is allocated */ int drv_proc_insert_strm_res_element(void *stream_obj, void *strm_res, void *process_ctxt) { struct strm_res_object **pstrm_res = (struct strm_res_object **)strm_res; struct process_context *ctxt = (struct process_context *)process_ctxt; int status = 0; int retval; *pstrm_res = kzalloc(sizeof(struct strm_res_object), GFP_KERNEL); if (*pstrm_res == NULL) { status = -EFAULT; goto func_end; } (*pstrm_res)->stream = stream_obj; retval = idr_get_new(ctxt->stream_id, *pstrm_res, &(*pstrm_res)->id); if (retval == -EAGAIN) { if (!idr_pre_get(ctxt->stream_id, GFP_KERNEL)) { pr_err("%s: OUT OF MEMORY\n", __func__); status = -ENOMEM; goto func_end; } retval = idr_get_new(ctxt->stream_id, *pstrm_res, &(*pstrm_res)->id); } if (retval) { pr_err("%s: FAILED, IDR is FULL\n", __func__); status = -EPERM; } func_end: return status; } static int drv_proc_free_strm_res(int id, void *p, void *process_ctxt) { struct process_context *ctxt = process_ctxt; struct strm_res_object *strm_res = p; struct stream_info strm_info; struct dsp_streaminfo user; u8 **ap_buffer = NULL; u8 *buf_ptr; u32 ul_bytes; u32 dw_arg; s32 ul_buf_size; if (strm_res->num_bufs) { ap_buffer = kmalloc((strm_res->num_bufs * sizeof(u8 *)), GFP_KERNEL); if (ap_buffer) { strm_free_buffer(strm_res, ap_buffer, strm_res->num_bufs, ctxt); kfree(ap_buffer); } } strm_info.user_strm = &user; user.number_bufs_in_stream = 0; strm_get_info(strm_res->stream, &strm_info, sizeof(strm_info)); while (user.number_bufs_in_stream--) strm_reclaim(strm_res->stream, &buf_ptr, &ul_bytes, (u32 *) &ul_buf_size, &dw_arg); strm_close(strm_res, ctxt); return 0; } /* Release all Stream resources and its context * This is called from .bridge_release. */ int drv_remove_all_strm_res_elements(void *process_ctxt) { struct process_context *ctxt = process_ctxt; idr_for_each(ctxt->stream_id, drv_proc_free_strm_res, ctxt); idr_destroy(ctxt->stream_id); return 0; } /* Updating the stream resource element */ int drv_proc_update_strm_res(u32 num_bufs, void *strm_resources) { int status = 0; struct strm_res_object **strm_res = (struct strm_res_object **)strm_resources; (*strm_res)->num_bufs = num_bufs; return status; } /* GPP PROCESS CLEANUP CODE END */ /* * ======== = drv_create ======== = * Purpose: * DRV Object gets created only once during Driver Loading. */ int drv_create(struct drv_object **drv_obj) { int status = 0; struct drv_object *pdrv_object = NULL; struct drv_data *drv_datap = dev_get_drvdata(bridge); DBC_REQUIRE(drv_obj != NULL); DBC_REQUIRE(refs > 0); pdrv_object = kzalloc(sizeof(struct drv_object), GFP_KERNEL); if (pdrv_object) { /* Create and Initialize List of device objects */ INIT_LIST_HEAD(&pdrv_object->dev_list); INIT_LIST_HEAD(&pdrv_object->dev_node_string); } else { status = -ENOMEM; } /* Store the DRV Object in the driver data */ if (!status) { if (drv_datap) { drv_datap->drv_object = (void *)pdrv_object; } else { status = -EPERM; pr_err("%s: Failed to store DRV object\n", __func__); } } if (!status) { *drv_obj = pdrv_object; } else { /* Free the DRV Object */ kfree(pdrv_object); } DBC_ENSURE(status || pdrv_object); return status; } /* * ======== drv_exit ======== * Purpose: * Discontinue usage of the DRV module. */ void drv_exit(void) { DBC_REQUIRE(refs > 0); refs--; DBC_ENSURE(refs >= 0); } /* * ======== = drv_destroy ======== = * purpose: * Invoked during bridge de-initialization */ int drv_destroy(struct drv_object *driver_obj) { int status = 0; struct drv_object *pdrv_object = (struct drv_object *)driver_obj; struct drv_data *drv_datap = dev_get_drvdata(bridge); DBC_REQUIRE(refs > 0); DBC_REQUIRE(pdrv_object); kfree(pdrv_object); /* Update the DRV Object in the driver data */ if (drv_datap) { drv_datap->drv_object = NULL; } else { status = -EPERM; pr_err("%s: Failed to store DRV object\n", __func__); } return status; } /* * ======== drv_get_dev_object ======== * Purpose: * Given a index, returns a handle to DevObject from the list. */ int drv_get_dev_object(u32 index, struct drv_object *hdrv_obj, struct dev_object **device_obj) { int status = 0; #ifdef CONFIG_TIDSPBRIDGE_DEBUG /* used only for Assertions and debug messages */ struct drv_object *pdrv_obj = (struct drv_object *)hdrv_obj; #endif struct dev_object *dev_obj; u32 i; DBC_REQUIRE(pdrv_obj); DBC_REQUIRE(device_obj != NULL); DBC_REQUIRE(index >= 0); DBC_REQUIRE(refs > 0); DBC_ASSERT(!(list_empty(&pdrv_obj->dev_list))); dev_obj = (struct dev_object *)drv_get_first_dev_object(); for (i = 0; i < index; i++) { dev_obj = (struct dev_object *)drv_get_next_dev_object((u32) dev_obj); } if (dev_obj) { *device_obj = (struct dev_object *)dev_obj; } else { *device_obj = NULL; status = -EPERM; } return status; } /* * ======== drv_get_first_dev_object ======== * Purpose: * Retrieve the first Device Object handle from an internal linked list of * of DEV_OBJECTs maintained by DRV. */ u32 drv_get_first_dev_object(void) { u32 dw_dev_object = 0; struct drv_object *pdrv_obj; struct drv_data *drv_datap = dev_get_drvdata(bridge); if (drv_datap && drv_datap->drv_object) { pdrv_obj = drv_datap->drv_object; if (!list_empty(&pdrv_obj->dev_list)) dw_dev_object = (u32) pdrv_obj->dev_list.next; } else { pr_err("%s: Failed to retrieve the object handle\n", __func__); } return dw_dev_object; } /* * ======== DRV_GetFirstDevNodeString ======== * Purpose: * Retrieve the first Device Extension from an internal linked list of * of Pointer to dev_node Strings maintained by DRV. */ u32 drv_get_first_dev_extension(void) { u32 dw_dev_extension = 0; struct drv_object *pdrv_obj; struct drv_data *drv_datap = dev_get_drvdata(bridge); if (drv_datap && drv_datap->drv_object) { pdrv_obj = drv_datap->drv_object; if (!list_empty(&pdrv_obj->dev_node_string)) { dw_dev_extension = (u32) pdrv_obj->dev_node_string.next; } } else { pr_err("%s: Failed to retrieve the object handle\n", __func__); } return dw_dev_extension; } /* * ======== drv_get_next_dev_object ======== * Purpose: * Retrieve the next Device Object handle from an internal linked list of * of DEV_OBJECTs maintained by DRV, after having previously called * drv_get_first_dev_object() and zero or more DRV_GetNext. */ u32 drv_get_next_dev_object(u32 hdev_obj) { u32 dw_next_dev_object = 0; struct drv_object *pdrv_obj; struct drv_data *drv_datap = dev_get_drvdata(bridge); struct list_head *curr; if (drv_datap && drv_datap->drv_object) { pdrv_obj = drv_datap->drv_object; if (!list_empty(&pdrv_obj->dev_list)) { curr = (struct list_head *)hdev_obj; if (list_is_last(curr, &pdrv_obj->dev_list)) return 0; dw_next_dev_object = (u32) curr->next; } } else { pr_err("%s: Failed to retrieve the object handle\n", __func__); } return dw_next_dev_object; } /* * ======== drv_get_next_dev_extension ======== * Purpose: * Retrieve the next Device Extension from an internal linked list of * of pointer to DevNodeString maintained by DRV, after having previously * called drv_get_first_dev_extension() and zero or more * drv_get_next_dev_extension(). */ u32 drv_get_next_dev_extension(u32 dev_extension) { u32 dw_dev_extension = 0; struct drv_object *pdrv_obj; struct drv_data *drv_datap = dev_get_drvdata(bridge); struct list_head *curr; if (drv_datap && drv_datap->drv_object) { pdrv_obj = drv_datap->drv_object; if (!list_empty(&pdrv_obj->dev_node_string)) { curr = (struct list_head *)dev_extension; if (list_is_last(curr, &pdrv_obj->dev_node_string)) return 0; dw_dev_extension = (u32) curr->next; } } else { pr_err("%s: Failed to retrieve the object handle\n", __func__); } return dw_dev_extension; } /* * ======== drv_init ======== * Purpose: * Initialize DRV module private state. */ int drv_init(void) { s32 ret = 1; /* function return value */ DBC_REQUIRE(refs >= 0); if (ret) refs++; DBC_ENSURE((ret && (refs > 0)) || (!ret && (refs >= 0))); return ret; } /* * ======== drv_insert_dev_object ======== * Purpose: * Insert a DevObject into the list of Manager object. */ int drv_insert_dev_object(struct drv_object *driver_obj, struct dev_object *hdev_obj) { struct drv_object *pdrv_object = (struct drv_object *)driver_obj; DBC_REQUIRE(refs > 0); DBC_REQUIRE(hdev_obj != NULL); DBC_REQUIRE(pdrv_object); list_add_tail((struct list_head *)hdev_obj, &pdrv_object->dev_list); return 0; } /* * ======== drv_remove_dev_object ======== * Purpose: * Search for and remove a DeviceObject from the given list of DRV * objects. */ int drv_remove_dev_object(struct drv_object *driver_obj, struct dev_object *hdev_obj) { int status = -EPERM; struct drv_object *pdrv_object = (struct drv_object *)driver_obj; struct list_head *cur_elem; DBC_REQUIRE(refs > 0); DBC_REQUIRE(pdrv_object); DBC_REQUIRE(hdev_obj != NULL); DBC_REQUIRE(!list_empty(&pdrv_object->dev_list)); /* Search list for p_proc_object: */ list_for_each(cur_elem, &pdrv_object->dev_list) { /* If found, remove it. */ if ((struct dev_object *)cur_elem == hdev_obj) { list_del(cur_elem); status = 0; break; } } return status; } /* * ======== drv_request_resources ======== * Purpose: * Requests resources from the OS. */ int drv_request_resources(u32 dw_context, u32 *dev_node_strg) { int status = 0; struct drv_object *pdrv_object; struct drv_ext *pszdev_node; struct drv_data *drv_datap = dev_get_drvdata(bridge); DBC_REQUIRE(dw_context != 0); DBC_REQUIRE(dev_node_strg != NULL); /* * Allocate memory to hold the string. This will live until * it is freed in the Release resources. Update the driver object * list. */ if (!drv_datap || !drv_datap->drv_object) status = -ENODATA; else pdrv_object = drv_datap->drv_object; if (!status) { pszdev_node = kzalloc(sizeof(struct drv_ext), GFP_KERNEL); if (pszdev_node) { strncpy(pszdev_node->sz_string, (char *)dw_context, MAXREGPATHLENGTH - 1); pszdev_node->sz_string[MAXREGPATHLENGTH - 1] = '\0'; /* Update the Driver Object List */ *dev_node_strg = (u32) pszdev_node->sz_string; list_add_tail(&pszdev_node->link, &pdrv_object->dev_node_string); } else { status = -ENOMEM; *dev_node_strg = 0; } } else { dev_dbg(bridge, "%s: Failed to get Driver Object from Registry", __func__); *dev_node_strg = 0; } DBC_ENSURE((!status && dev_node_strg != NULL && !list_empty(&pdrv_object->dev_node_string)) || (status && *dev_node_strg == 0)); return status; } /* * ======== drv_release_resources ======== * Purpose: * Releases resources from the OS. */ int drv_release_resources(u32 dw_context, struct drv_object *hdrv_obj) { int status = 0; struct drv_ext *pszdev_node; /* * Irrespective of the status go ahead and clean it * The following will over write the status. */ for (pszdev_node = (struct drv_ext *)drv_get_first_dev_extension(); pszdev_node != NULL; pszdev_node = (struct drv_ext *) drv_get_next_dev_extension((u32) pszdev_node)) { if ((u32) pszdev_node == dw_context) { /* Found it */ /* Delete from the Driver object list */ list_del(&pszdev_node->link); kfree(pszdev_node); break; } } return status; } /* * ======== request_bridge_resources ======== * Purpose: * Reserves shared memory for bridge. */ static int request_bridge_resources(struct cfg_hostres *res) { struct cfg_hostres *host_res = res; /* num_mem_windows must not be more than CFG_MAXMEMREGISTERS */ host_res->num_mem_windows = 2; /* First window is for DSP internal memory */ dev_dbg(bridge, "mem_base[0] 0x%x\n", host_res->mem_base[0]); dev_dbg(bridge, "mem_base[3] 0x%x\n", host_res->mem_base[3]); dev_dbg(bridge, "dmmu_base %p\n", host_res->dmmu_base); /* for 24xx base port is not mapping the mamory for DSP * internal memory TODO Do a ioremap here */ /* Second window is for DSP external memory shared with MPU */ /* These are hard-coded values */ host_res->birq_registers = 0; host_res->birq_attrib = 0; host_res->offset_for_monitor = 0; host_res->chnl_offset = 0; /* CHNL_MAXCHANNELS */ host_res->num_chnls = CHNL_MAXCHANNELS; host_res->chnl_buf_size = 0x400; return 0; } /* * ======== drv_request_bridge_res_dsp ======== * Purpose: * Reserves shared memory for bridge. */ int drv_request_bridge_res_dsp(void **phost_resources) { int status = 0; struct cfg_hostres *host_res; u32 dw_buff_size; u32 dma_addr; u32 shm_size; struct drv_data *drv_datap = dev_get_drvdata(bridge); dw_buff_size = sizeof(struct cfg_hostres); host_res = kzalloc(dw_buff_size, GFP_KERNEL); if (host_res != NULL) { request_bridge_resources(host_res); /* num_mem_windows must not be more than CFG_MAXMEMREGISTERS */ host_res->num_mem_windows = 4; host_res->mem_base[0] = 0; host_res->mem_base[2] = (u32) ioremap(OMAP_DSP_MEM1_BASE, OMAP_DSP_MEM1_SIZE); host_res->mem_base[3] = (u32) ioremap(OMAP_DSP_MEM2_BASE, OMAP_DSP_MEM2_SIZE); host_res->mem_base[4] = (u32) ioremap(OMAP_DSP_MEM3_BASE, OMAP_DSP_MEM3_SIZE); host_res->per_base = ioremap(OMAP_PER_CM_BASE, OMAP_PER_CM_SIZE); host_res->per_pm_base = (u32) ioremap(OMAP_PER_PRM_BASE, OMAP_PER_PRM_SIZE); host_res->core_pm_base = (u32) ioremap(OMAP_CORE_PRM_BASE, OMAP_CORE_PRM_SIZE); host_res->dmmu_base = ioremap(OMAP_DMMU_BASE, OMAP_DMMU_SIZE); dev_dbg(bridge, "mem_base[0] 0x%x\n", host_res->mem_base[0]); dev_dbg(bridge, "mem_base[1] 0x%x\n", host_res->mem_base[1]); dev_dbg(bridge, "mem_base[2] 0x%x\n", host_res->mem_base[2]); dev_dbg(bridge, "mem_base[3] 0x%x\n", host_res->mem_base[3]); dev_dbg(bridge, "mem_base[4] 0x%x\n", host_res->mem_base[4]); dev_dbg(bridge, "dmmu_base %p\n", host_res->dmmu_base); shm_size = drv_datap->shm_size; if (shm_size >= 0x10000) { /* Allocate Physically contiguous, * non-cacheable memory */ host_res->mem_base[1] = (u32) mem_alloc_phys_mem(shm_size, 0x100000, &dma_addr); if (host_res->mem_base[1] == 0) { status = -ENOMEM; pr_err("shm reservation Failed\n"); } else { host_res->mem_length[1] = shm_size; host_res->mem_phys[1] = dma_addr; dev_dbg(bridge, "%s: Bridge shm address 0x%x " "dma_addr %x size %x\n", __func__, host_res->mem_base[1], dma_addr, shm_size); } } if (!status) { /* These are hard-coded values */ host_res->birq_registers = 0; host_res->birq_attrib = 0; host_res->offset_for_monitor = 0; host_res->chnl_offset = 0; /* CHNL_MAXCHANNELS */ host_res->num_chnls = CHNL_MAXCHANNELS; host_res->chnl_buf_size = 0x400; dw_buff_size = sizeof(struct cfg_hostres); } *phost_resources = host_res; } /* End Mem alloc */ return status; } void mem_ext_phys_pool_init(u32 pool_phys_base, u32 pool_size) { u32 pool_virt_base; /* get the virtual address for the physical memory pool passed */ pool_virt_base = (u32) ioremap(pool_phys_base, pool_size); if ((void **)pool_virt_base == NULL) { pr_err("%s: external physical memory map failed\n", __func__); ext_phys_mem_pool_enabled = false; } else { ext_mem_pool.phys_mem_base = pool_phys_base; ext_mem_pool.phys_mem_size = pool_size; ext_mem_pool.virt_mem_base = pool_virt_base; ext_mem_pool.next_phys_alloc_ptr = pool_phys_base; ext_phys_mem_pool_enabled = true; } } void mem_ext_phys_pool_release(void) { if (ext_phys_mem_pool_enabled) { iounmap((void *)(ext_mem_pool.virt_mem_base)); ext_phys_mem_pool_enabled = false; } } /* * ======== mem_ext_phys_mem_alloc ======== * Purpose: * Allocate physically contiguous, uncached memory from external memory pool */ static void *mem_ext_phys_mem_alloc(u32 bytes, u32 align, u32 * phys_addr) { u32 new_alloc_ptr; u32 offset; u32 virt_addr; if (align == 0) align = 1; if (bytes > ((ext_mem_pool.phys_mem_base + ext_mem_pool.phys_mem_size) - ext_mem_pool.next_phys_alloc_ptr)) { phys_addr = NULL; return NULL; } else { offset = (ext_mem_pool.next_phys_alloc_ptr & (align - 1)); if (offset == 0) new_alloc_ptr = ext_mem_pool.next_phys_alloc_ptr; else new_alloc_ptr = (ext_mem_pool.next_phys_alloc_ptr) + (align - offset); if ((new_alloc_ptr + bytes) <= (ext_mem_pool.phys_mem_base + ext_mem_pool.phys_mem_size)) { /* we can allocate */ *phys_addr = new_alloc_ptr; ext_mem_pool.next_phys_alloc_ptr = new_alloc_ptr + bytes; virt_addr = ext_mem_pool.virt_mem_base + (new_alloc_ptr - ext_mem_pool. phys_mem_base); return (void *)virt_addr; } else { *phys_addr = 0; return NULL; } } } /* * ======== mem_alloc_phys_mem ======== * Purpose: * Allocate physically contiguous, uncached memory */ void *mem_alloc_phys_mem(u32 byte_size, u32 align_mask, u32 *physical_address) { void *va_mem = NULL; dma_addr_t pa_mem; if (byte_size > 0) { if (ext_phys_mem_pool_enabled) { va_mem = mem_ext_phys_mem_alloc(byte_size, align_mask, (u32 *) &pa_mem); } else va_mem = dma_alloc_coherent(NULL, byte_size, &pa_mem, GFP_KERNEL); if (va_mem == NULL) *physical_address = 0; else *physical_address = pa_mem; } return va_mem; } /* * ======== mem_free_phys_mem ======== * Purpose: * Free the given block of physically contiguous memory. */ void mem_free_phys_mem(void *virtual_address, u32 physical_address, u32 byte_size) { DBC_REQUIRE(virtual_address != NULL); if (!ext_phys_mem_pool_enabled) dma_free_coherent(NULL, byte_size, virtual_address, physical_address); }
984488.c
#include "crypto_core.h" static unsigned char multiply(unsigned int c,unsigned int d) { unsigned char f[8]; unsigned char g[8]; unsigned char h[15]; unsigned char result; int i; int j; for (i = 0;i < 8;++i) f[i] = 1 & (c >> i); for (i = 0;i < 8;++i) g[i] = 1 & (d >> i); for (i = 0;i < 15;++i) h[i] = 0; for (i = 0;i < 8;++i) for (j = 0;j < 8;++j) h[i + j] ^= f[i] & g[j]; for (i = 6;i >= 0;--i) { h[i + 0] ^= h[i + 8]; h[i + 1] ^= h[i + 8]; h[i + 3] ^= h[i + 8]; h[i + 4] ^= h[i + 8]; h[i + 8] ^= h[i + 8]; } result = 0; for (i = 0;i < 8;++i) result |= h[i] << i; return result; } static unsigned char square(unsigned char c) { return multiply(c,c); } static unsigned char xtime(unsigned char c) { return multiply(c,2); } static unsigned char bytesub(unsigned char c) { unsigned char c3 = multiply(square(c),c); unsigned char c7 = multiply(square(c3),c); unsigned char c63 = multiply(square(square(square(c7))),c7); unsigned char c127 = multiply(square(c63),c); unsigned char c254 = square(c127); unsigned char f[8]; unsigned char h[8]; unsigned char result; int i; for (i = 0;i < 8;++i) f[i] = 1 & (c254 >> i); h[0] = f[0] ^ f[4] ^ f[5] ^ f[6] ^ f[7] ^ 1; h[1] = f[1] ^ f[5] ^ f[6] ^ f[7] ^ f[0] ^ 1; h[2] = f[2] ^ f[6] ^ f[7] ^ f[0] ^ f[1]; h[3] = f[3] ^ f[7] ^ f[0] ^ f[1] ^ f[2]; h[4] = f[4] ^ f[0] ^ f[1] ^ f[2] ^ f[3]; h[5] = f[5] ^ f[1] ^ f[2] ^ f[3] ^ f[4] ^ 1; h[6] = f[6] ^ f[2] ^ f[3] ^ f[4] ^ f[5] ^ 1; h[7] = f[7] ^ f[3] ^ f[4] ^ f[5] ^ f[6]; result = 0; for (i = 0;i < 8;++i) result |= h[i] << i; return result; } int crypto_core( unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c ) { unsigned char expanded[4][60]; unsigned char state[4][4]; unsigned char newstate[4][4]; unsigned char roundconstant; int i; int j; int r; for (j = 0;j < 8;++j) for (i = 0;i < 4;++i) expanded[i][j] = k[j * 4 + i]; roundconstant = 1; for (j = 8;j < 60;++j) { unsigned char temp[4]; if (j % 4) for (i = 0;i < 4;++i) temp[i] = expanded[i][j - 1]; else if (j % 8) for (i = 0;i < 4;++i) temp[i] = bytesub(expanded[i][j - 1]); else { for (i = 0;i < 4;++i) temp[i] = bytesub(expanded[(i + 1) % 4][j - 1]); temp[0] ^= roundconstant; roundconstant = xtime(roundconstant); } for (i = 0;i < 4;++i) expanded[i][j] = temp[i] ^ expanded[i][j - 8]; } for (j = 0;j < 4;++j) for (i = 0;i < 4;++i) state[i][j] = in[j * 4 + i] ^ expanded[i][j]; for (r = 0;r < 14;++r) { for (i = 0;i < 4;++i) for (j = 0;j < 4;++j) newstate[i][j] = bytesub(state[i][j]); for (i = 0;i < 4;++i) for (j = 0;j < 4;++j) state[i][j] = newstate[i][(j + i) % 4]; if (r < 13) for (j = 0;j < 4;++j) { unsigned char a0 = state[0][j]; unsigned char a1 = state[1][j]; unsigned char a2 = state[2][j]; unsigned char a3 = state[3][j]; state[0][j] = xtime(a0 ^ a1) ^ a1 ^ a2 ^ a3; state[1][j] = xtime(a1 ^ a2) ^ a2 ^ a3 ^ a0; state[2][j] = xtime(a2 ^ a3) ^ a3 ^ a0 ^ a1; state[3][j] = xtime(a3 ^ a0) ^ a0 ^ a1 ^ a2; } for (i = 0;i < 4;++i) for (j = 0;j < 4;++j) state[i][j] ^= expanded[i][r * 4 + 4 + j]; } for (j = 0;j < 4;++j) for (i = 0;i < 4;++i) out[j * 4 + i] = state[i][j]; return 0; }
518085.c
/* * C character handling library. * tolower() * ANSI 4.3.2.1. * Convert character to lower case. */ #include <ctype.h> int tolower(c) int c; { return (isupper(c) ? _tolower(c) : c); }
259902.c
/** * Programa para gerar um arquivo com uma matriz com valores inteiros. * * Autor Andre Leon S. Gradvohl, Dr. * * Ultima atualizacao: Sex 13 Out 2017 19:23:49 -03 * * Observacao: os nomes das funcoes estao em ingles. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "MatrixIO.h" /** * Funcao para gerar uma matriz com numeros inteiros. * * @param lines Numero de linhas da matriz. * @param columns Numero de colunas da matriz. * @param lowerLimit Valor do menor inteiro na matriz. * @param upperLimit Valor do maior inteiro na matriz. * * @return Ponteiro para uma matriz com lines x columns */ int *generateRandomMatriz(unsigned int lines, unsigned int columns, int lowerLimit, int upperLimit) { register unsigned int i, j; int *mat = (int *) malloc(sizeof(int) * lines * columns); if (mat == NULL) { perror("I cannot allocate memory\n"); exit(EXIT_FAILURE); return NULL; } /* Cria a semente para a geração de numeros aleatorios.*/ srand( time(NULL) ); /* Preenche a matriz com numeros aleatorios entre o limite inferior e limite superior.*/ for (i=0; i<lines; i++) for(j=0; j<columns; j++) mat[i*columns + j] = (rand() % ((upperLimit + 1) - lowerLimit)) + lowerLimit; return mat; } int main (int argc, char **argv) { unsigned int lines, columns; int lowerLimit, upperLimit; char *fileName; int *mat; /* O comando switch a seguir trata os parametros enviados pela linha de comando */ switch(argc) { case 0: case 1: case 2: fprintf(stderr, "Uso:\n\t %s <numero de linhas> <numero de colunas>\n or", argv[0]); fprintf(stderr, "\n\t %s <numero de linhas> <numero de colunas> <output file>\n or", argv[0]); fprintf(stderr, "\n\t %s <numero de linhas> <numero de colunas> <minimo> <maximo>\n or", argv[0]); fprintf(stderr, "\n\t %s <numero de linhas> <numero de colunas> <minimo> <maximo> <arquivo de saida>\n", argv[0]); exit(EXIT_FAILURE); break; case 3: lines = atoi(argv[1]); columns = atoi(argv[2]); lowerLimit = -(lines*columns); upperLimit = (lines*columns); fileName = NULL; fprintf(stdout, "Gerando uma matriz %d x %d sem valores limites para a saida padrao.\n", lines, columns); break; case 4: lines = atoi(argv[1]); columns = atoi(argv[2]); lowerLimit = -(lines*columns); upperLimit = (lines*columns); fileName = argv[3]; fprintf(stdout, "Gerando uma matriz %d x %d sem valores limites para o arquivo %s\n", lines, columns, fileName); break; case 5: lines = atoi(argv[1]); columns = atoi(argv[2]); lowerLimit = atoi(argv[3]); upperLimit = atoi(argv[4]); fileName = NULL; fprintf(stdout, "Gerando uma matriz %d x %d com os limites [%ld, %ld] para a saida padrao\n", lines, columns, lowerLimit, upperLimit); break; case 6: lines = atoi(argv[1]); columns = atoi(argv[2]); lowerLimit = atoi(argv[3]); upperLimit = atoi(argv[4]); fileName = argv[5]; fprintf(stdout, "Gerando uma matriz %d x %d com os limites [%ld, %ld] para o arquivo %s\n", lines, columns, lowerLimit, upperLimit, fileName); break; } /* Cria a matriz na memoria e a preenche com valores inteiros aleatorios */ mat = generateRandomMatriz(lines, columns, lowerLimit, upperLimit); /* Grava a matriz no arquivo. A funcao printMatrix esta definida em outro arquivo */ printMatrix(mat, lines, columns, fileName); /* Libera a memoria ocupada pela matriz */ free(mat); return 0; }
327279.c
/* A Bison parser, made by GNU Bison 3.8.2. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-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 <https://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, especially those whose name start with YY_ or yy_. They are private implementation details that can be changed or removed. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output, and Bison version. */ #define YYBISON 30802 /* Bison version string. */ #define YYBISON_VERSION "3.8.2" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #line 1 "parser.y" #include "sym_tab.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define YYSTYPE char* /* declare variables to help you keep track or store properties scope can be default value for this lab(implementation in the next lab) */ void yyerror(char* s); // error handling function int yylex(); // declare the function performing lexical analysis extern int yylineno; // track the line number extern char* yytext; extern table* t; int type_specifier = 0; int size = 0; #line 92 "y.tab.c" # ifndef YY_CAST # ifdef __cplusplus # define YY_CAST(Type, Val) static_cast<Type> (Val) # define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) # else # define YY_CAST(Type, Val) ((Type) (Val)) # define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) # endif # endif # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Use api.header.include to #include this header instead of duplicating it here. */ #ifndef YY_YY_Y_TAB_H_INCLUDED # define YY_YY_Y_TAB_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token kinds. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { YYEMPTY = -2, YYEOF = 0, /* "end of file" */ YYerror = 256, /* error */ YYUNDEF = 257, /* "invalid token" */ T_INT = 258, /* T_INT */ T_CHAR = 259, /* T_CHAR */ T_DOUBLE = 260, /* T_DOUBLE */ T_WHILE = 261, /* T_WHILE */ T_INC = 262, /* T_INC */ T_DEC = 263, /* T_DEC */ T_OROR = 264, /* T_OROR */ T_ANDAND = 265, /* T_ANDAND */ T_EQCOMP = 266, /* T_EQCOMP */ T_NOTEQUAL = 267, /* T_NOTEQUAL */ T_GREATEREQ = 268, /* T_GREATEREQ */ T_LESSEREQ = 269, /* T_LESSEREQ */ T_LEFTSHIFT = 270, /* T_LEFTSHIFT */ T_RIGHTSHIFT = 271, /* T_RIGHTSHIFT */ T_PRINTLN = 272, /* T_PRINTLN */ T_STRING = 273, /* T_STRING */ T_FLOAT = 274, /* T_FLOAT */ T_BOOLEAN = 275, /* T_BOOLEAN */ T_IF = 276, /* T_IF */ T_ELSE = 277, /* T_ELSE */ T_STRLITERAL = 278, /* T_STRLITERAL */ T_DO = 279, /* T_DO */ T_INCLUDE = 280, /* T_INCLUDE */ T_HEADER = 281, /* T_HEADER */ T_MAIN = 282, /* T_MAIN */ T_ID = 283, /* T_ID */ T_NUM = 284 /* T_NUM */ }; typedef enum yytokentype yytoken_kind_t; #endif /* Token kinds. */ #define YYEMPTY -2 #define YYEOF 0 #define YYerror 256 #define YYUNDEF 257 #define T_INT 258 #define T_CHAR 259 #define T_DOUBLE 260 #define T_WHILE 261 #define T_INC 262 #define T_DEC 263 #define T_OROR 264 #define T_ANDAND 265 #define T_EQCOMP 266 #define T_NOTEQUAL 267 #define T_GREATEREQ 268 #define T_LESSEREQ 269 #define T_LEFTSHIFT 270 #define T_RIGHTSHIFT 271 #define T_PRINTLN 272 #define T_STRING 273 #define T_FLOAT 274 #define T_BOOLEAN 275 #define T_IF 276 #define T_ELSE 277 #define T_STRLITERAL 278 #define T_DO 279 #define T_INCLUDE 280 #define T_HEADER 281 #define T_MAIN 282 #define T_ID 283 #define T_NUM 284 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_Y_TAB_H_INCLUDED */ /* Symbol kind. */ enum yysymbol_kind_t { YYSYMBOL_YYEMPTY = -2, YYSYMBOL_YYEOF = 0, /* "end of file" */ YYSYMBOL_YYerror = 1, /* error */ YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ YYSYMBOL_T_INT = 3, /* T_INT */ YYSYMBOL_T_CHAR = 4, /* T_CHAR */ YYSYMBOL_T_DOUBLE = 5, /* T_DOUBLE */ YYSYMBOL_T_WHILE = 6, /* T_WHILE */ YYSYMBOL_T_INC = 7, /* T_INC */ YYSYMBOL_T_DEC = 8, /* T_DEC */ YYSYMBOL_T_OROR = 9, /* T_OROR */ YYSYMBOL_T_ANDAND = 10, /* T_ANDAND */ YYSYMBOL_T_EQCOMP = 11, /* T_EQCOMP */ YYSYMBOL_T_NOTEQUAL = 12, /* T_NOTEQUAL */ YYSYMBOL_T_GREATEREQ = 13, /* T_GREATEREQ */ YYSYMBOL_T_LESSEREQ = 14, /* T_LESSEREQ */ YYSYMBOL_T_LEFTSHIFT = 15, /* T_LEFTSHIFT */ YYSYMBOL_T_RIGHTSHIFT = 16, /* T_RIGHTSHIFT */ YYSYMBOL_T_PRINTLN = 17, /* T_PRINTLN */ YYSYMBOL_T_STRING = 18, /* T_STRING */ YYSYMBOL_T_FLOAT = 19, /* T_FLOAT */ YYSYMBOL_T_BOOLEAN = 20, /* T_BOOLEAN */ YYSYMBOL_T_IF = 21, /* T_IF */ YYSYMBOL_T_ELSE = 22, /* T_ELSE */ YYSYMBOL_T_STRLITERAL = 23, /* T_STRLITERAL */ YYSYMBOL_T_DO = 24, /* T_DO */ YYSYMBOL_T_INCLUDE = 25, /* T_INCLUDE */ YYSYMBOL_T_HEADER = 26, /* T_HEADER */ YYSYMBOL_T_MAIN = 27, /* T_MAIN */ YYSYMBOL_T_ID = 28, /* T_ID */ YYSYMBOL_T_NUM = 29, /* T_NUM */ YYSYMBOL_30_ = 30, /* ';' */ YYSYMBOL_31_ = 31, /* ',' */ YYSYMBOL_32_ = 32, /* '=' */ YYSYMBOL_33_ = 33, /* '+' */ YYSYMBOL_34_ = 34, /* '-' */ YYSYMBOL_35_ = 35, /* '*' */ YYSYMBOL_36_ = 36, /* '/' */ YYSYMBOL_37_ = 37, /* '(' */ YYSYMBOL_38_ = 38, /* ')' */ YYSYMBOL_39_ = 39, /* '<' */ YYSYMBOL_40_ = 40, /* '>' */ YYSYMBOL_41_ = 41, /* '{' */ YYSYMBOL_42_ = 42, /* '}' */ YYSYMBOL_YYACCEPT = 43, /* $accept */ YYSYMBOL_START = 44, /* START */ YYSYMBOL_PROG = 45, /* PROG */ YYSYMBOL_DECLR = 46, /* DECLR */ YYSYMBOL_LISTVAR = 47, /* LISTVAR */ YYSYMBOL_VAR = 48, /* VAR */ YYSYMBOL_TYPE = 49, /* TYPE */ YYSYMBOL_ASSGN = 50, /* ASSGN */ YYSYMBOL_EXPR = 51, /* EXPR */ YYSYMBOL_E = 52, /* E */ YYSYMBOL_T = 53, /* T */ YYSYMBOL_F = 54, /* F */ YYSYMBOL_REL_OP = 55, /* REL_OP */ YYSYMBOL_MAIN = 56, /* MAIN */ YYSYMBOL_EMPTY_LISTVAR = 57, /* EMPTY_LISTVAR */ YYSYMBOL_STMT = 58, /* STMT */ YYSYMBOL_STMT_NO_BLOCK = 59, /* STMT_NO_BLOCK */ YYSYMBOL_BLOCK = 60 /* BLOCK */ }; typedef enum yysymbol_kind_t yysymbol_kind_t; #ifdef short # undef short #endif /* On compilers that do not define __PTRDIFF_MAX__ etc., make sure <limits.h> and (if available) <stdint.h> are included so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ # include <limits.h> /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stdint.h> /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H # endif #endif /* Narrow types that promote to a signed type and that can represent a signed or unsigned integer of at least N bits. In tables they can save space and decrease cache pressure. Promoting to a signed type helps avoid bugs in integer arithmetic. */ #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; #elif defined YY_STDINT_H typedef int_least8_t yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; #elif defined YY_STDINT_H typedef int_least16_t yytype_int16; #else typedef short yytype_int16; #endif /* Work around bug in HP-UX 11.23, which defines these macros incorrectly for preprocessor constants. This workaround can likely be removed in 2023, as HPE has promised support for HP-UX 11.23 (aka HP-UX 11i v2) only through the end of 2022; see Table 2 of <https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */ #ifdef __hpux # undef UINT_LEAST8_MAX # undef UINT_LEAST16_MAX # define UINT_LEAST8_MAX 255 # define UINT_LEAST16_MAX 65535 #endif #if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; #elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ && UINT_LEAST8_MAX <= INT_MAX) typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif #if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; #elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ # define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # endif # define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else # define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM \ YY_CAST (YYPTRDIFF_T, \ (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ ? YYPTRDIFF_MAXIMUM \ : YY_CAST (YYSIZE_T, -1))) #define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) /* Stored state numbers (used for stacks). */ typedef yytype_int8 yy_state_t; /* State numbers in computations. */ typedef int yy_state_fast_t; #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif #endif #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YY_USE(E) ((void) (E)) #else # define YY_USE(E) /* empty */ #endif /* Suppress an incorrect diagnostic about yylval being uninitialized. */ #if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ # if __GNUC__ * 100 + __GNUC_MINOR__ < 407 # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") # else # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # endif # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ # define YY_IGNORE_USELESS_CAST_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") # define YY_IGNORE_USELESS_CAST_END \ _Pragma ("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_END #endif #define YY_ASSERT(E) ((void) (0 && (E))) #if !defined yyoverflow /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* !defined yyoverflow */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yy_state_t yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYPTRDIFF_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / YYSIZEOF (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYPTRDIFF_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 13 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 75 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 43 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 18 /* YYNRULES -- Number of rules. */ #define YYNRULES 43 /* YYNSTATES -- Number of states. */ #define YYNSTATES 72 /* YYMAXUTOK -- Last valid token kind. */ #define YYMAXUTOK 284 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ #define YYTRANSLATE(YYX) \ (0 <= (YYX) && (YYX) <= YYMAXUTOK \ ? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \ : YYSYMBOL_YYUNDEF) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ static const yytype_int8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 37, 38, 35, 33, 31, 34, 2, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 30, 39, 32, 40, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 41, 2, 42, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 28, 28, 31, 32, 33, 34, 38, 42, 43, 46, 47, 71, 72, 73, 74, 78, 81, 82, 85, 86, 87, 91, 92, 93, 96, 97, 98, 99, 102, 103, 104, 105, 106, 107, 112, 114, 115, 118, 119, 120, 124, 125, 128 }; #endif /** Accessing symbol of state STATE. */ #define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State]) #if YYDEBUG || 0 /* The user-facing name of the symbol whose (internal) number is YYSYMBOL. No bounds checking. */ static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "\"end of file\"", "error", "\"invalid token\"", "T_INT", "T_CHAR", "T_DOUBLE", "T_WHILE", "T_INC", "T_DEC", "T_OROR", "T_ANDAND", "T_EQCOMP", "T_NOTEQUAL", "T_GREATEREQ", "T_LESSEREQ", "T_LEFTSHIFT", "T_RIGHTSHIFT", "T_PRINTLN", "T_STRING", "T_FLOAT", "T_BOOLEAN", "T_IF", "T_ELSE", "T_STRLITERAL", "T_DO", "T_INCLUDE", "T_HEADER", "T_MAIN", "T_ID", "T_NUM", "';'", "','", "'='", "'+'", "'-'", "'*'", "'/'", "'('", "')'", "'<'", "'>'", "'{'", "'}'", "$accept", "START", "PROG", "DECLR", "LISTVAR", "VAR", "TYPE", "ASSGN", "EXPR", "E", "T", "F", "REL_OP", "MAIN", "EMPTY_LISTVAR", "STMT", "STMT_NO_BLOCK", "BLOCK", YY_NULLPTR }; static const char * yysymbol_name (yysymbol_kind_t yysymbol) { return yytname[yysymbol]; } #endif #define YYPACT_NINF (-38) #define yypact_value_is_default(Yyn) \ ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-1) #define yytable_value_is_error(Yyn) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int8 yypact[] = { 9, -38, -38, -38, -38, -21, 19, -38, -1, 14, 3, 9, 11, -38, 9, -15, 15, 33, -38, 9, -38, -38, -38, -38, 11, -4, 21, 25, -38, -38, 37, 11, 37, -38, -8, -38, -38, -38, -38, -38, -38, 11, 11, 11, 11, 11, 33, 28, -4, -38, -38, 21, 25, 25, -38, -38, 26, -3, -3, 38, 37, 39, 29, -3, -3, 30, -38, -38, -38, -38, -38, -38 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int8 yydefact[] = { 6, 12, 15, 14, 13, 0, 0, 2, 0, 0, 0, 6, 0, 1, 6, 0, 11, 7, 9, 6, 3, 28, 26, 27, 0, 16, 18, 21, 24, 4, 37, 0, 0, 5, 0, 33, 34, 30, 29, 31, 32, 0, 0, 0, 0, 0, 36, 0, 10, 8, 25, 17, 19, 20, 22, 23, 0, 40, 40, 0, 0, 0, 0, 40, 40, 0, 41, 42, 35, 38, 39, 43 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -38, -38, 4, -37, 40, 41, -14, -12, -7, 34, 20, 12, -38, -38, -38, -5, -38, -38 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { 0, 6, 7, 8, 17, 18, 9, 10, 25, 26, 27, 28, 41, 11, 47, 62, 63, 64 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int8 yytable[] = { 1, 2, 3, 35, 36, 37, 38, 35, 36, 37, 38, 12, 1, 2, 3, 20, 4, 34, 29, 13, 59, 59, 30, 33, 48, 5, 59, 59, 4, 14, 50, 39, 40, 19, 21, 39, 40, 5, 58, 22, 23, 15, 16, 60, 60, 61, 61, 31, 24, 60, 60, 61, 61, 65, 42, 43, 54, 55, 69, 70, 44, 45, 52, 53, 32, 16, 56, 57, 66, 67, 46, 68, 71, 49, 0, 51 }; static const yytype_int8 yycheck[] = { 3, 4, 5, 11, 12, 13, 14, 11, 12, 13, 14, 32, 3, 4, 5, 11, 19, 24, 14, 0, 57, 58, 37, 19, 31, 28, 63, 64, 19, 30, 38, 39, 40, 30, 23, 39, 40, 28, 41, 28, 29, 27, 28, 57, 58, 57, 58, 32, 37, 63, 64, 63, 64, 58, 33, 34, 44, 45, 63, 64, 35, 36, 42, 43, 31, 28, 38, 41, 30, 30, 30, 42, 42, 32, -1, 41 }; /* YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of state STATE-NUM. */ static const yytype_int8 yystos[] = { 0, 3, 4, 5, 19, 28, 44, 45, 46, 49, 50, 56, 32, 0, 30, 27, 28, 47, 48, 30, 45, 23, 28, 29, 37, 51, 52, 53, 54, 45, 37, 32, 31, 45, 51, 11, 12, 13, 14, 39, 40, 55, 33, 34, 35, 36, 47, 57, 51, 48, 38, 52, 53, 53, 54, 54, 38, 41, 41, 46, 49, 50, 58, 59, 60, 58, 30, 30, 42, 58, 58, 42 }; /* YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. */ static const yytype_int8 yyr1[] = { 0, 43, 44, 45, 45, 45, 45, 46, 47, 47, 48, 48, 49, 49, 49, 49, 50, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 56, 57, 57, 58, 58, 58, 59, 59, 60 }; /* YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. */ static const yytype_int8 yyr2[] = { 0, 2, 1, 2, 3, 3, 0, 2, 3, 1, 3, 1, 1, 1, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 0, 2, 2, 0, 2, 2, 3 }; enum { YYENOMEM = -2 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYNOMEM goto yyexhaustedlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Backward compatibility with an undocumented macro. Use YYerror or YYUNDEF. */ #define YYERRCODE YYUNDEF /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Kind, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) { FILE *yyoutput = yyo; YY_USE (yyoutput); if (!yyvaluep) return; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) { YYFPRINTF (yyo, "%s %s (", yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind)); yy_symbol_value_print (yyo, yykind, yyvaluep); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule) { int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]), &yyvsp[(yyi + 1) - (yynrhs)]); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) ((void) 0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, yysymbol_kind_t yykind, YYSTYPE *yyvaluep) { YY_USE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /* Lookahead token kind. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (void) { yy_state_fast_t yystate = 0; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus = 0; /* Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* Their size. */ YYPTRDIFF_T yystacksize = YYINITDEPTH; /* The state stack: array, bottom, top. */ yy_state_t yyssa[YYINITDEPTH]; yy_state_t *yyss = yyssa; yy_state_t *yyssp = yyss; /* The semantic value stack: array, bottom, top. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp = yyvs; int yyn; /* The return value of yyparse. */ int yyresult; /* Lookahead symbol kind. */ yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: YYDPRINTF ((stderr, "Entering state %d\n", yystate)); YY_ASSERT (0 <= yystate && yystate < YYNSTATES); YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END YY_STACK_PRINT (yyss, yyssp); if (yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE YYNOMEM; #else { /* Get the current used size of the three stacks, in elements. */ YYPTRDIFF_T yysize = yyssp - yyss + 1; # if defined yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ yy_state_t *yyss1 = yyss; YYSTYPE *yyvs1 = yyvs; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * YYSIZEOF (*yyssp), &yyvs1, yysize * YYSIZEOF (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } # else /* defined YYSTACK_RELOCATE */ /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) YYNOMEM; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yy_state_t *yyss1 = yyss; union yyalloc *yyptr = YY_CAST (union yyalloc *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); if (! yyptr) YYNOMEM; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YY_IGNORE_USELESS_CAST_BEGIN YYDPRINTF ((stderr, "Stack size increased to %ld\n", YY_CAST (long, yystacksize))); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) YYABORT; } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token\n")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = YYEOF; yytoken = YYSYMBOL_YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else if (yychar == YYerror) { /* The scanner already issued an error message, process directly to error recovery. But do not keep the error token as lookahead, it is too special and may lead us to an endless loop in error recovery. */ yychar = YYUNDEF; yytoken = YYSYMBOL_YYerror; goto yyerrlab1; } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Discard the shifted token. */ yychar = YYEMPTY; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* START: PROG */ #line 28 "parser.y" { printf("Valid syntax\n"); YYACCEPT; } #line 1282 "y.tab.c" break; case 10: /* VAR: T_ID '=' EXPR */ #line 46 "parser.y" {/*to be done in lab 3*/} #line 1288 "y.tab.c" break; case 11: /* VAR: T_ID */ #line 47 "parser.y" { /* check if symbol is in table if it is then print error for redeclared variable else make an entry and insert into the table revert variables to default values:type */ // printf("Checking if T_ID is present in table\n"); if(check_symbol_table(yyvsp[0])==0){ // printf("Inserting into empty table\n"); symbol* s = allocate_space_for_table_entry(yyvsp[0], size, type_specifier, yylineno, 1); if(!insert_into_table(s)){ printf("\033[91mSymbol Table Error\033[0m:%s at %d \n",yyvsp[0],yylineno); } } else{ printf("\033[91mSymbol Table Error\033[0m: %d Variable %s already declared \n",yylineno,yyvsp[0]); } } #line 1313 "y.tab.c" break; case 12: /* TYPE: T_INT */ #line 71 "parser.y" {type_specifier=2; size=4;} #line 1319 "y.tab.c" break; case 13: /* TYPE: T_FLOAT */ #line 72 "parser.y" {type_specifier=3; size=4;} #line 1325 "y.tab.c" break; case 14: /* TYPE: T_DOUBLE */ #line 73 "parser.y" {type_specifier=4;size=8;} #line 1331 "y.tab.c" break; case 15: /* TYPE: T_CHAR */ #line 74 "parser.y" {type_specifier=1;size=1;} #line 1337 "y.tab.c" break; case 16: /* ASSGN: T_ID '=' EXPR */ #line 78 "parser.y" {/*to be done in lab 3*/} #line 1343 "y.tab.c" break; #line 1347 "y.tab.c" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; yyerror (YY_("syntax error")); } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (0) YYERROR; ++yynerrs; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ /* Pop stack until we find a state that shifts the error token. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYSYMBOL_YYerror; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", YY_ACCESSING_SYMBOL (yystate), yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturnlab; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturnlab; /*-----------------------------------------------------------. | yyexhaustedlab -- YYNOMEM (memory exhaustion) comes here. | `-----------------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; goto yyreturnlab; /*----------------------------------------------------------. | yyreturnlab -- parsing is finished, clean up and return. | `----------------------------------------------------------*/ yyreturnlab: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", YY_ACCESSING_SYMBOL (+*yyssp), yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif return yyresult; } #line 135 "parser.y" /* error handling function */ void yyerror(char* s) { printf("Error :%s at %d \n",s,yylineno); } int main(int argc, char* argv[]) { /* initialise table here */ // printf("table allocation\n"); t = allocate_space_for_table(); yyparse(); /* display final symbol table*/ display_symbol_table(); return 0; }
912948.c
/* subst.c -- The part of the shell that does parameter, command, arithmetic, and globbing substitutions. */ /* ``Have a little faith, there's magic in the night. You ain't a beauty, but, hey, you're alright.'' */ /* Copyright (C) 1987-2020 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash 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. Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "bashtypes.h" #include <stdio.h> #include "chartypes.h" #if defined (HAVE_PWD_H) # include <pwd.h> #endif #include <signal.h> #include <errno.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #define NEED_FPURGE_DECL #include "bashansi.h" #include "posixstat.h" #include "bashintl.h" #include "shell.h" #include "parser.h" #include "flags.h" #include "jobs.h" #include "execute_cmd.h" #include "filecntl.h" #include "trap.h" #include "pathexp.h" #include "mailcheck.h" #include "shmbutil.h" #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR) # include <mbstr.h> /* mbschr */ #endif #include "typemax.h" #include "builtins/getopt.h" #include "builtins/common.h" #include "builtins/builtext.h" #include <tilde/tilde.h> #include <glob/strmatch.h> #if !defined (errno) extern int errno; #endif /* !errno */ /* The size that strings change by. */ #define DEFAULT_INITIAL_ARRAY_SIZE 112 #define DEFAULT_ARRAY_SIZE 128 /* Variable types. */ #define VT_VARIABLE 0 #define VT_POSPARMS 1 #define VT_ARRAYVAR 2 #define VT_ARRAYMEMBER 3 #define VT_ASSOCVAR 4 #define VT_STARSUB 128 /* $* or ${array[*]} -- used to split */ /* Flags for quoted_strchr */ #define ST_BACKSL 0x01 #define ST_CTLESC 0x02 #define ST_SQUOTE 0x04 /* unused yet */ #define ST_DQUOTE 0x08 /* unused yet */ /* These defs make it easier to use the editor. */ #define LBRACE '{' #define RBRACE '}' #define LPAREN '(' #define RPAREN ')' #define LBRACK '[' #define RBRACK ']' #if defined (HANDLE_MULTIBYTE) #define WLPAREN L'(' #define WRPAREN L')' #endif #define DOLLAR_AT_STAR(c) ((c) == '@' || (c) == '*') #define STR_DOLLAR_AT_STAR(s) (DOLLAR_AT_STAR ((s)[0]) && (s)[1] == '\0') /* Evaluates to 1 if C is one of the shell's special parameters whose length can be taken, but is also one of the special expansion characters. */ #define VALID_SPECIAL_LENGTH_PARAM(c) \ ((c) == '-' || (c) == '?' || (c) == '#' || (c) == '@') /* Evaluates to 1 if C is one of the shell's special parameters for which an indirect variable reference may be made. */ #define VALID_INDIR_PARAM(c) \ ((posixly_correct == 0 && (c) == '#') || (posixly_correct == 0 && (c) == '?') || (c) == '@' || (c) == '*') /* Evaluates to 1 if C is one of the OP characters that follows the parameter in ${parameter[:]OPword}. */ #define VALID_PARAM_EXPAND_CHAR(c) (sh_syntaxtab[(unsigned char)c] & CSUBSTOP) /* Evaluates to 1 if this is one of the shell's special variables. */ #define SPECIAL_VAR(name, wi) \ (*name && ((DIGIT (*name) && all_digits (name)) || \ (name[1] == '\0' && (sh_syntaxtab[(unsigned char)*name] & CSPECVAR)) || \ (wi && name[2] == '\0' && VALID_INDIR_PARAM (name[1])))) /* This can be used by all of the *_extract_* functions that have a similar structure. It can't just be wrapped in a do...while(0) loop because of the embedded `break'. The dangling else accommodates a trailing semicolon; we could also put in a do ; while (0) */ #define CHECK_STRING_OVERRUN(oind, ind, len, ch) \ if (ind >= len) \ { \ oind = len; \ ch = 0; \ break; \ } \ else \ /* An expansion function that takes a string and a quoted flag and returns a WORD_LIST *. Used as the type of the third argument to expand_string_if_necessary(). */ typedef WORD_LIST *EXPFUNC PARAMS((char *, int)); /* Process ID of the last command executed within command substitution. */ pid_t last_command_subst_pid = NO_PID; pid_t current_command_subst_pid = NO_PID; /* Variables used to keep track of the characters in IFS. */ SHELL_VAR *ifs_var; char *ifs_value; unsigned char ifs_cmap[UCHAR_MAX + 1]; int ifs_is_set, ifs_is_null; #if defined (HANDLE_MULTIBYTE) unsigned char ifs_firstc[MB_LEN_MAX]; size_t ifs_firstc_len; #else unsigned char ifs_firstc; #endif /* If non-zero, command substitution inherits the value of errexit option */ int inherit_errexit = 0; /* Sentinel to tell when we are performing variable assignments preceding a command name and putting them into the environment. Used to make sure we use the temporary environment when looking up variable values. */ int assigning_in_environment; /* Used to hold a list of variable assignments preceding a command. Global so the SIGCHLD handler in jobs.c can unwind-protect it when it runs a SIGCHLD trap and so it can be saved and restored by the trap handlers. */ WORD_LIST *subst_assign_varlist = (WORD_LIST *)NULL; /* Tell the expansion functions to not longjmp back to top_level on fatal errors. Enabled when doing completion and prompt string expansion. */ int no_longjmp_on_fatal_error = 0; /* Non-zero means to allow unmatched globbed filenames to expand to a null file. */ int allow_null_glob_expansion; /* Non-zero means to throw an error when globbing fails to match anything. */ int fail_glob_expansion; /* Extern functions and variables from different files. */ extern struct fd_bitmap *current_fds_to_close; extern int wordexp_only; #if defined (JOB_CONTROL) && defined (PROCESS_SUBSTITUTION) extern PROCESS *last_procsub_child; #endif #if !defined (HAVE_WCSDUP) && defined (HANDLE_MULTIBYTE) extern wchar_t *wcsdup PARAMS((const wchar_t *)); #endif #if 0 /* Variables to keep track of which words in an expanded word list (the output of expand_word_list_internal) are the result of globbing expansions. GLOB_ARGV_FLAGS is used by execute_cmd.c. (CURRENTLY UNUSED). */ char *glob_argv_flags; static int glob_argv_flags_size; #endif static WORD_LIST *cached_quoted_dollar_at = 0; /* Distinguished error values to return from expansion functions */ static WORD_LIST expand_word_error, expand_word_fatal; static WORD_DESC expand_wdesc_error, expand_wdesc_fatal; static char expand_param_error, expand_param_fatal, expand_param_unset; static char extract_string_error, extract_string_fatal; /* Set by expand_word_unsplit and several of the expand_string_XXX functions; used to inhibit splitting and re-joining $* on $IFS, primarily when doing assignment statements. The idea is that if we're in a context where this is set, we're not going to be performing word splitting, so we use the same rules to expand $* as we would if it appeared within double quotes. */ static int expand_no_split_dollar_star = 0; /* A WORD_LIST of words to be expanded by expand_word_list_internal, without any leading variable assignments. */ static WORD_LIST *garglist = (WORD_LIST *)NULL; static char *quoted_substring PARAMS((char *, int, int)); static int quoted_strlen PARAMS((char *)); static char *quoted_strchr PARAMS((char *, int, int)); static char *expand_string_if_necessary PARAMS((char *, int, EXPFUNC *)); static inline char *expand_string_to_string_internal PARAMS((char *, int, EXPFUNC *)); static WORD_LIST *call_expand_word_internal PARAMS((WORD_DESC *, int, int, int *, int *)); static WORD_LIST *expand_string_internal PARAMS((char *, int)); static WORD_LIST *expand_string_leave_quoted PARAMS((char *, int)); static WORD_LIST *expand_string_for_rhs PARAMS((char *, int, int, int, int *, int *)); static WORD_LIST *expand_string_for_pat PARAMS((char *, int, int *, int *)); static char *quote_escapes_internal PARAMS((const char *, int)); static WORD_LIST *list_quote_escapes PARAMS((WORD_LIST *)); static WORD_LIST *list_dequote_escapes PARAMS((WORD_LIST *)); static char *make_quoted_char PARAMS((int)); static WORD_LIST *quote_list PARAMS((WORD_LIST *)); static int unquoted_substring PARAMS((char *, char *)); static int unquoted_member PARAMS((int, char *)); #if defined (ARRAY_VARS) static SHELL_VAR *do_compound_assignment PARAMS((char *, char *, int)); #endif static int do_assignment_internal PARAMS((const WORD_DESC *, int)); static char *string_extract_verbatim PARAMS((char *, size_t, int *, char *, int)); static char *string_extract PARAMS((char *, int *, char *, int)); static char *string_extract_double_quoted PARAMS((char *, int *, int)); static inline char *string_extract_single_quoted PARAMS((char *, int *)); static inline int skip_single_quoted PARAMS((const char *, size_t, int, int)); static int skip_double_quoted PARAMS((char *, size_t, int, int)); static char *extract_delimited_string PARAMS((char *, int *, char *, char *, char *, int)); static char *extract_dollar_brace_string PARAMS((char *, int *, int, int)); static int skip_matched_pair PARAMS((const char *, int, int, int, int)); static char *pos_params PARAMS((char *, int, int, int, int)); static unsigned char *mb_getcharlens PARAMS((char *, int)); static char *remove_upattern PARAMS((char *, char *, int)); #if defined (HANDLE_MULTIBYTE) static wchar_t *remove_wpattern PARAMS((wchar_t *, size_t, wchar_t *, int)); #endif static char *remove_pattern PARAMS((char *, char *, int)); static int match_upattern PARAMS((char *, char *, int, char **, char **)); #if defined (HANDLE_MULTIBYTE) static int match_wpattern PARAMS((wchar_t *, char **, size_t, wchar_t *, int, char **, char **)); #endif static int match_pattern PARAMS((char *, char *, int, char **, char **)); static int getpatspec PARAMS((int, char *)); static char *getpattern PARAMS((char *, int, int)); static char *variable_remove_pattern PARAMS((char *, char *, int, int)); static char *list_remove_pattern PARAMS((WORD_LIST *, char *, int, int, int)); static char *parameter_list_remove_pattern PARAMS((int, char *, int, int)); #ifdef ARRAY_VARS static char *array_remove_pattern PARAMS((SHELL_VAR *, char *, int, int, int)); #endif static char *parameter_brace_remove_pattern PARAMS((char *, char *, int, char *, int, int, int)); static char *string_var_assignment PARAMS((SHELL_VAR *, char *)); #if defined (ARRAY_VARS) static char *array_var_assignment PARAMS((SHELL_VAR *, int, int, int)); #endif static char *pos_params_assignment PARAMS((WORD_LIST *, int, int)); static char *string_transform PARAMS((int, SHELL_VAR *, char *)); static char *list_transform PARAMS((int, SHELL_VAR *, WORD_LIST *, int, int)); static char *parameter_list_transform PARAMS((int, int, int)); #if defined ARRAY_VARS static char *array_transform PARAMS((int, SHELL_VAR *, int, int)); #endif static char *parameter_brace_transform PARAMS((char *, char *, int, char *, int, int, int, int)); static int valid_parameter_transform PARAMS((char *)); static char *process_substitute PARAMS((char *, int)); static char *read_comsub PARAMS((int, int, int, int *)); #ifdef ARRAY_VARS static arrayind_t array_length_reference PARAMS((char *)); #endif static int valid_brace_expansion_word PARAMS((char *, int)); static int chk_atstar PARAMS((char *, int, int, int *, int *)); static int chk_arithsub PARAMS((const char *, int)); static WORD_DESC *parameter_brace_expand_word PARAMS((char *, int, int, int, arrayind_t *)); static char *parameter_brace_find_indir PARAMS((char *, int, int, int)); static WORD_DESC *parameter_brace_expand_indir PARAMS((char *, int, int, int, int *, int *)); static WORD_DESC *parameter_brace_expand_rhs PARAMS((char *, char *, int, int, int, int *, int *)); static void parameter_brace_expand_error PARAMS((char *, char *, int)); static int valid_length_expression PARAMS((char *)); static intmax_t parameter_brace_expand_length PARAMS((char *)); static char *skiparith PARAMS((char *, int)); static int verify_substring_values PARAMS((SHELL_VAR *, char *, char *, int, intmax_t *, intmax_t *)); static int get_var_and_type PARAMS((char *, char *, arrayind_t, int, int, SHELL_VAR **, char **)); static char *mb_substring PARAMS((char *, int, int)); static char *parameter_brace_substring PARAMS((char *, char *, int, char *, int, int, int)); static int shouldexp_replacement PARAMS((char *)); static char *pos_params_pat_subst PARAMS((char *, char *, char *, int)); static char *parameter_brace_patsub PARAMS((char *, char *, int, char *, int, int, int)); static char *pos_params_casemod PARAMS((char *, char *, int, int)); static char *parameter_brace_casemod PARAMS((char *, char *, int, int, char *, int, int, int)); static WORD_DESC *parameter_brace_expand PARAMS((char *, int *, int, int, int *, int *)); static WORD_DESC *param_expand PARAMS((char *, int *, int, int *, int *, int *, int *, int)); static WORD_LIST *expand_word_internal PARAMS((WORD_DESC *, int, int, int *, int *)); static WORD_LIST *word_list_split PARAMS((WORD_LIST *)); static void exp_jump_to_top_level PARAMS((int)); static WORD_LIST *separate_out_assignments PARAMS((WORD_LIST *)); static WORD_LIST *glob_expand_word_list PARAMS((WORD_LIST *, int)); #ifdef BRACE_EXPANSION static WORD_LIST *brace_expand_word_list PARAMS((WORD_LIST *, int)); #endif #if defined (ARRAY_VARS) static int make_internal_declare PARAMS((char *, char *, char *)); static void expand_compound_assignment_word PARAMS((WORD_LIST *, int)); static WORD_LIST *expand_declaration_argument PARAMS((WORD_LIST *, WORD_LIST *)); #endif static WORD_LIST *shell_expand_word_list PARAMS((WORD_LIST *, int)); static WORD_LIST *expand_word_list_internal PARAMS((WORD_LIST *, int)); /* **************************************************************** */ /* */ /* Utility Functions */ /* */ /* **************************************************************** */ #if defined (DEBUG) void dump_word_flags (flags) int flags; { int f; f = flags; fprintf (stderr, "%d -> ", f); if (f & W_ARRAYIND) { f &= ~W_ARRAYIND; fprintf (stderr, "W_ARRAYIND%s", f ? "|" : ""); } if (f & W_ASSIGNASSOC) { f &= ~W_ASSIGNASSOC; fprintf (stderr, "W_ASSIGNASSOC%s", f ? "|" : ""); } if (f & W_ASSIGNARRAY) { f &= ~W_ASSIGNARRAY; fprintf (stderr, "W_ASSIGNARRAY%s", f ? "|" : ""); } if (f & W_SAWQUOTEDNULL) { f &= ~W_SAWQUOTEDNULL; fprintf (stderr, "W_SAWQUOTEDNULL%s", f ? "|" : ""); } if (f & W_NOPROCSUB) { f &= ~W_NOPROCSUB; fprintf (stderr, "W_NOPROCSUB%s", f ? "|" : ""); } if (f & W_DQUOTE) { f &= ~W_DQUOTE; fprintf (stderr, "W_DQUOTE%s", f ? "|" : ""); } if (f & W_HASQUOTEDNULL) { f &= ~W_HASQUOTEDNULL; fprintf (stderr, "W_HASQUOTEDNULL%s", f ? "|" : ""); } if (f & W_ASSIGNARG) { f &= ~W_ASSIGNARG; fprintf (stderr, "W_ASSIGNARG%s", f ? "|" : ""); } if (f & W_ASSNBLTIN) { f &= ~W_ASSNBLTIN; fprintf (stderr, "W_ASSNBLTIN%s", f ? "|" : ""); } if (f & W_ASSNGLOBAL) { f &= ~W_ASSNGLOBAL; fprintf (stderr, "W_ASSNGLOBAL%s", f ? "|" : ""); } if (f & W_COMPASSIGN) { f &= ~W_COMPASSIGN; fprintf (stderr, "W_COMPASSIGN%s", f ? "|" : ""); } if (f & W_EXPANDRHS) { f &= ~W_EXPANDRHS; fprintf (stderr, "W_EXPANDRHS%s", f ? "|" : ""); } if (f & W_ITILDE) { f &= ~W_ITILDE; fprintf (stderr, "W_ITILDE%s", f ? "|" : ""); } if (f & W_NOTILDE) { f &= ~W_NOTILDE; fprintf (stderr, "W_NOTILDE%s", f ? "|" : ""); } if (f & W_ASSIGNRHS) { f &= ~W_ASSIGNRHS; fprintf (stderr, "W_ASSIGNRHS%s", f ? "|" : ""); } if (f & W_NOASSNTILDE) { f &= ~W_NOASSNTILDE; fprintf (stderr, "W_NOASSNTILDE%s", f ? "|" : ""); } if (f & W_NOCOMSUB) { f &= ~W_NOCOMSUB; fprintf (stderr, "W_NOCOMSUB%s", f ? "|" : ""); } if (f & W_DOLLARSTAR) { f &= ~W_DOLLARSTAR; fprintf (stderr, "W_DOLLARSTAR%s", f ? "|" : ""); } if (f & W_DOLLARAT) { f &= ~W_DOLLARAT; fprintf (stderr, "W_DOLLARAT%s", f ? "|" : ""); } if (f & W_TILDEEXP) { f &= ~W_TILDEEXP; fprintf (stderr, "W_TILDEEXP%s", f ? "|" : ""); } if (f & W_NOSPLIT2) { f &= ~W_NOSPLIT2; fprintf (stderr, "W_NOSPLIT2%s", f ? "|" : ""); } if (f & W_NOSPLIT) { f &= ~W_NOSPLIT; fprintf (stderr, "W_NOSPLIT%s", f ? "|" : ""); } if (f & W_NOBRACE) { f &= ~W_NOBRACE; fprintf (stderr, "W_NOBRACE%s", f ? "|" : ""); } if (f & W_NOGLOB) { f &= ~W_NOGLOB; fprintf (stderr, "W_NOGLOB%s", f ? "|" : ""); } if (f & W_SPLITSPACE) { f &= ~W_SPLITSPACE; fprintf (stderr, "W_SPLITSPACE%s", f ? "|" : ""); } if (f & W_ASSIGNMENT) { f &= ~W_ASSIGNMENT; fprintf (stderr, "W_ASSIGNMENT%s", f ? "|" : ""); } if (f & W_QUOTED) { f &= ~W_QUOTED; fprintf (stderr, "W_QUOTED%s", f ? "|" : ""); } if (f & W_HASDOLLAR) { f &= ~W_HASDOLLAR; fprintf (stderr, "W_HASDOLLAR%s", f ? "|" : ""); } if (f & W_COMPLETE) { f &= ~W_COMPLETE; fprintf (stderr, "W_COMPLETE%s", f ? "|" : ""); } if (f & W_CHKLOCAL) { f &= ~W_CHKLOCAL; fprintf (stderr, "W_CHKLOCAL%s", f ? "|" : ""); } if (f & W_FORCELOCAL) { f &= ~W_FORCELOCAL; fprintf (stderr, "W_FORCELOCAL%s", f ? "|" : ""); } fprintf (stderr, "\n"); fflush (stderr); } #endif #ifdef INCLUDE_UNUSED static char * quoted_substring (string, start, end) char *string; int start, end; { register int len, l; register char *result, *s, *r; len = end - start; /* Move to string[start], skipping quoted characters. */ for (s = string, l = 0; *s && l < start; ) { if (*s == CTLESC) { s++; continue; } l++; if (*s == 0) break; } r = result = (char *)xmalloc (2*len + 1); /* save room for quotes */ /* Copy LEN characters, including quote characters. */ s = string + l; for (l = 0; l < len; s++) { if (*s == CTLESC) *r++ = *s++; *r++ = *s; l++; if (*s == 0) break; } *r = '\0'; return result; } #endif #ifdef INCLUDE_UNUSED /* Return the length of S, skipping over quoted characters */ static int quoted_strlen (s) char *s; { register char *p; int i; i = 0; for (p = s; *p; p++) { if (*p == CTLESC) { p++; if (*p == 0) return (i + 1); } i++; } return i; } #endif #ifdef INCLUDE_UNUSED /* Find the first occurrence of character C in string S, obeying shell quoting rules. If (FLAGS & ST_BACKSL) is non-zero, backslash-escaped characters are skipped. If (FLAGS & ST_CTLESC) is non-zero, characters escaped with CTLESC are skipped. */ static char * quoted_strchr (s, c, flags) char *s; int c, flags; { register char *p; for (p = s; *p; p++) { if (((flags & ST_BACKSL) && *p == '\\') || ((flags & ST_CTLESC) && *p == CTLESC)) { p++; if (*p == '\0') return ((char *)NULL); continue; } else if (*p == c) return p; } return ((char *)NULL); } /* Return 1 if CHARACTER appears in an unquoted portion of STRING. Return 0 otherwise. CHARACTER must be a single-byte character. */ static int unquoted_member (character, string) int character; char *string; { size_t slen; int sindex, c; DECLARE_MBSTATE; slen = strlen (string); sindex = 0; while (c = string[sindex]) { if (c == character) return (1); switch (c) { default: ADVANCE_CHAR (string, slen, sindex); break; case '\\': sindex++; if (string[sindex]) ADVANCE_CHAR (string, slen, sindex); break; case '\'': sindex = skip_single_quoted (string, slen, ++sindex, 0); break; case '"': sindex = skip_double_quoted (string, slen, ++sindex, 0); break; } } return (0); } /* Return 1 if SUBSTR appears in an unquoted portion of STRING. */ static int unquoted_substring (substr, string) char *substr, *string; { size_t slen; int sindex, c, sublen; DECLARE_MBSTATE; if (substr == 0 || *substr == '\0') return (0); slen = strlen (string); sublen = strlen (substr); for (sindex = 0; c = string[sindex]; ) { if (STREQN (string + sindex, substr, sublen)) return (1); switch (c) { case '\\': sindex++; if (string[sindex]) ADVANCE_CHAR (string, slen, sindex); break; case '\'': sindex = skip_single_quoted (string, slen, ++sindex, 0); break; case '"': sindex = skip_double_quoted (string, slen, ++sindex, 0); break; default: ADVANCE_CHAR (string, slen, sindex); break; } } return (0); } #endif /* Most of the substitutions must be done in parallel. In order to avoid using tons of unclear goto's, I have some functions for manipulating malloc'ed strings. They all take INDX, a pointer to an integer which is the offset into the string where manipulation is taking place. They also take SIZE, a pointer to an integer which is the current length of the character array for this string. */ /* Append SOURCE to TARGET at INDEX. SIZE is the current amount of space allocated to TARGET. SOURCE can be NULL, in which case nothing happens. Gets rid of SOURCE by freeing it. Returns TARGET in case the location has changed. */ INLINE char * sub_append_string (source, target, indx, size) char *source, *target; int *indx; size_t *size; { if (source) { int n; size_t srclen; srclen = STRLEN (source); if (srclen >= (int)(*size - *indx)) { n = srclen + *indx; n = (n + DEFAULT_ARRAY_SIZE) - (n % DEFAULT_ARRAY_SIZE); target = (char *)xrealloc (target, (*size = n)); } FASTCOPY (source, target + *indx, srclen); *indx += srclen; target[*indx] = '\0'; free (source); } return (target); } #if 0 /* UNUSED */ /* Append the textual representation of NUMBER to TARGET. INDX and SIZE are as in SUB_APPEND_STRING. */ char * sub_append_number (number, target, indx, size) intmax_t number; char *target; int *indx; size_t *size; { char *temp; temp = itos (number); return (sub_append_string (temp, target, indx, size)); } #endif /* Extract a substring from STRING, starting at SINDEX and ending with one of the characters in CHARLIST. Don't make the ending character part of the string. Leave SINDEX pointing at the ending character. Understand about backslashes in the string. If (flags & SX_VARNAME) is non-zero, and array variables have been compiled into the shell, everything between a `[' and a corresponding `]' is skipped over. If (flags & SX_NOALLOC) is non-zero, don't return the substring, just update SINDEX. If (flags & SX_REQMATCH) is non-zero, the string must contain a closing character from CHARLIST. */ static char * string_extract (string, sindex, charlist, flags) char *string; int *sindex; char *charlist; int flags; { register int c, i; int found; size_t slen; char *temp; DECLARE_MBSTATE; slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0; i = *sindex; found = 0; while (c = string[i]) { if (c == '\\') { if (string[i + 1]) i++; else break; } #if defined (ARRAY_VARS) else if ((flags & SX_VARNAME) && c == LBRACK) { int ni; /* If this is an array subscript, skip over it and continue. */ ni = skipsubscript (string, i, 0); if (string[ni] == RBRACK) i = ni; } #endif else if (MEMBER (c, charlist)) { found = 1; break; } ADVANCE_CHAR (string, slen, i); } /* If we had to have a matching delimiter and didn't find one, return an error and let the caller deal with it. */ if ((flags & SX_REQMATCH) && found == 0) { *sindex = i; return (&extract_string_error); } temp = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i); *sindex = i; return (temp); } /* Extract the contents of STRING as if it is enclosed in double quotes. SINDEX, when passed in, is the offset of the character immediately following the opening double quote; on exit, SINDEX is left pointing after the closing double quote. If STRIPDQ is non-zero, unquoted double quotes are stripped and the string is terminated by a null byte. Backslashes between the embedded double quotes are processed. If STRIPDQ is zero, an unquoted `"' terminates the string. */ static char * string_extract_double_quoted (string, sindex, flags) char *string; int *sindex, flags; { size_t slen; char *send; int j, i, t; unsigned char c; char *temp, *ret; /* The new string we return. */ int pass_next, backquote, si; /* State variables for the machine. */ int dquote; int stripdq; DECLARE_MBSTATE; slen = strlen (string + *sindex) + *sindex; send = string + slen; stripdq = (flags & SX_STRIPDQ); pass_next = backquote = dquote = 0; temp = (char *)xmalloc (1 + slen - *sindex); j = 0; i = *sindex; while (c = string[i]) { /* Process a character that was quoted by a backslash. */ if (pass_next) { /* XXX - take another look at this in light of Interp 221 */ /* Posix.2 sez: ``The backslash shall retain its special meaning as an escape character only when followed by one of the characters: $ ` " \ <newline>''. If STRIPDQ is zero, we handle the double quotes here and let expand_word_internal handle the rest. If STRIPDQ is non-zero, we have already been through one round of backslash stripping, and want to strip these backslashes only if DQUOTE is non-zero, indicating that we are inside an embedded double-quoted string. */ /* If we are in an embedded quoted string, then don't strip backslashes before characters for which the backslash retains its special meaning, but remove backslashes in front of other characters. If we are not in an embedded quoted string, don't strip backslashes at all. This mess is necessary because the string was already surrounded by double quotes (and sh has some really weird quoting rules). The returned string will be run through expansion as if it were double-quoted. */ if ((stripdq == 0 && c != '"') || (stripdq && ((dquote && (sh_syntaxtab[c] & CBSDQUOTE)) || dquote == 0))) temp[j++] = '\\'; pass_next = 0; add_one_character: COPY_CHAR_I (temp, j, string, send, i); continue; } /* A backslash protects the next character. The code just above handles preserving the backslash in front of any character but a double quote. */ if (c == '\\') { pass_next++; i++; continue; } /* Inside backquotes, ``the portion of the quoted string from the initial backquote and the characters up to the next backquote that is not preceded by a backslash, having escape characters removed, defines that command''. */ if (backquote) { if (c == '`') backquote = 0; temp[j++] = c; /* COPY_CHAR_I? */ i++; continue; } if (c == '`') { temp[j++] = c; backquote++; i++; continue; } /* Pass everything between `$(' and the matching `)' or a quoted ${ ... } pair through according to the Posix.2 specification. */ if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE))) { int free_ret = 1; si = i + 2; if (string[i + 1] == LPAREN) ret = extract_command_subst (string, &si, (flags & SX_COMPLETE)); else ret = extract_dollar_brace_string (string, &si, Q_DOUBLE_QUOTES, 0); temp[j++] = '$'; temp[j++] = string[i + 1]; /* Just paranoia; ret will not be 0 unless no_longjmp_on_fatal_error is set. */ if (ret == 0 && no_longjmp_on_fatal_error) { free_ret = 0; ret = string + i + 2; } /* XXX - CHECK_STRING_OVERRUN here? */ for (t = 0; ret[t]; t++, j++) temp[j] = ret[t]; temp[j] = string[si]; if (si < i + 2) /* we went back? */ i += 2; else if (string[si]) { j++; i = si + 1; } else i = si; if (free_ret) free (ret); continue; } /* Add any character but a double quote to the quoted string we're accumulating. */ if (c != '"') goto add_one_character; /* c == '"' */ if (stripdq) { dquote ^= 1; i++; continue; } break; } temp[j] = '\0'; /* Point to after the closing quote. */ if (c) i++; *sindex = i; return (temp); } /* This should really be another option to string_extract_double_quoted. */ static int skip_double_quoted (string, slen, sind, flags) char *string; size_t slen; int sind; int flags; { int c, i; char *ret; int pass_next, backquote, si; DECLARE_MBSTATE; pass_next = backquote = 0; i = sind; while (c = string[i]) { if (pass_next) { pass_next = 0; ADVANCE_CHAR (string, slen, i); continue; } else if (c == '\\') { pass_next++; i++; continue; } else if (backquote) { if (c == '`') backquote = 0; ADVANCE_CHAR (string, slen, i); continue; } else if (c == '`') { backquote++; i++; continue; } else if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE))) { si = i + 2; if (string[i + 1] == LPAREN) ret = extract_command_subst (string, &si, SX_NOALLOC|(flags&SX_COMPLETE)); else ret = extract_dollar_brace_string (string, &si, Q_DOUBLE_QUOTES, SX_NOALLOC); /* These can consume the entire string if they are unterminated */ CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } else if (c != '"') { ADVANCE_CHAR (string, slen, i); continue; } else break; } if (c) i++; return (i); } /* Extract the contents of STRING as if it is enclosed in single quotes. SINDEX, when passed in, is the offset of the character immediately following the opening single quote; on exit, SINDEX is left pointing after the closing single quote. */ static inline char * string_extract_single_quoted (string, sindex) char *string; int *sindex; { register int i; size_t slen; char *t; DECLARE_MBSTATE; /* Don't need slen for ADVANCE_CHAR unless multibyte chars possible. */ slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0; i = *sindex; while (string[i] && string[i] != '\'') ADVANCE_CHAR (string, slen, i); t = substring (string, *sindex, i); if (string[i]) i++; *sindex = i; return (t); } /* Skip over a single-quoted string. We overload the SX_COMPLETE flag to mean that we are splitting out words for completion and have encountered a $'...' string, which allows backslash-escaped single quotes. */ static inline int skip_single_quoted (string, slen, sind, flags) const char *string; size_t slen; int sind; int flags; { register int c; DECLARE_MBSTATE; c = sind; while (string[c] && string[c] != '\'') { if ((flags & SX_COMPLETE) && string[c] == '\\' && string[c+1] == '\'' && string[c+2]) ADVANCE_CHAR (string, slen, c); ADVANCE_CHAR (string, slen, c); } if (string[c]) c++; return c; } /* Just like string_extract, but doesn't hack backslashes or any of that other stuff. Obeys CTLESC quoting. Used to do splitting on $IFS. */ static char * string_extract_verbatim (string, slen, sindex, charlist, flags) char *string; size_t slen; int *sindex; char *charlist; int flags; { register int i; #if defined (HANDLE_MULTIBYTE) wchar_t *wcharlist; #endif int c; char *temp; DECLARE_MBSTATE; if ((flags & SX_NOCTLESC) && charlist[0] == '\'' && charlist[1] == '\0') { temp = string_extract_single_quoted (string, sindex); --*sindex; /* leave *sindex at separator character */ return temp; } /* This can never be called with charlist == NULL. If *charlist == NULL, we can skip the loop and just return a copy of the string, updating *sindex */ if (*charlist == 0) { temp = string + *sindex; c = (*sindex == 0) ? slen : STRLEN (temp); temp = savestring (temp); *sindex += c; return temp; } i = *sindex; #if defined (HANDLE_MULTIBYTE) wcharlist = 0; #endif while (c = string[i]) { #if defined (HANDLE_MULTIBYTE) size_t mblength; #endif if ((flags & SX_NOCTLESC) == 0 && c == CTLESC) { i += 2; CHECK_STRING_OVERRUN (i, i, slen, c); continue; } /* Even if flags contains SX_NOCTLESC, we let CTLESC quoting CTLNUL through, to protect the CTLNULs from later calls to remove_quoted_nulls. */ else if ((flags & SX_NOESCCTLNUL) == 0 && c == CTLESC && string[i+1] == CTLNUL) { i += 2; CHECK_STRING_OVERRUN (i, i, slen, c); continue; } #if defined (HANDLE_MULTIBYTE) if (locale_utf8locale && slen > i && UTF8_SINGLEBYTE (string[i])) mblength = (string[i] != 0) ? 1 : 0; else mblength = MBLEN (string + i, slen - i); if (mblength > 1) { wchar_t wc; mblength = mbtowc (&wc, string + i, slen - i); if (MB_INVALIDCH (mblength)) { if (MEMBER (c, charlist)) break; } else { if (wcharlist == 0) { size_t len; len = mbstowcs (wcharlist, charlist, 0); if (len == -1) len = 0; wcharlist = (wchar_t *)xmalloc (sizeof (wchar_t) * (len + 1)); mbstowcs (wcharlist, charlist, len + 1); } if (wcschr (wcharlist, wc)) break; } } else #endif if (MEMBER (c, charlist)) break; ADVANCE_CHAR (string, slen, i); } #if defined (HANDLE_MULTIBYTE) FREE (wcharlist); #endif temp = substring (string, *sindex, i); *sindex = i; return (temp); } /* Extract the $( construct in STRING, and return a new string. Start extracting at (SINDEX) as if we had just seen "$(". Make (SINDEX) get the position of the matching ")". ) XFLAGS is additional flags to pass to other extraction functions. */ char * extract_command_subst (string, sindex, xflags) char *string; int *sindex; int xflags; { char *ret; if (string[*sindex] == LPAREN || (xflags & SX_COMPLETE)) return (extract_delimited_string (string, sindex, "$(", "(", ")", xflags|SX_COMMAND)); /*)*/ else { xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0); ret = xparse_dolparen (string, string+*sindex, sindex, xflags); return ret; } } /* Extract the $[ construct in STRING, and return a new string. (]) Start extracting at (SINDEX) as if we had just seen "$[". Make (SINDEX) get the position of the matching "]". */ char * extract_arithmetic_subst (string, sindex) char *string; int *sindex; { return (extract_delimited_string (string, sindex, "$[", "[", "]", 0)); /*]*/ } #if defined (PROCESS_SUBSTITUTION) /* Extract the <( or >( construct in STRING, and return a new string. Start extracting at (SINDEX) as if we had just seen "<(". Make (SINDEX) get the position of the matching ")". */ /*))*/ char * extract_process_subst (string, starter, sindex, xflags) char *string; char *starter; int *sindex; int xflags; { #if 0 /* XXX - check xflags&SX_COMPLETE here? */ return (extract_delimited_string (string, sindex, starter, "(", ")", SX_COMMAND)); #else xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0); return (xparse_dolparen (string, string+*sindex, sindex, xflags)); #endif } #endif /* PROCESS_SUBSTITUTION */ #if defined (ARRAY_VARS) /* This can be fooled by unquoted right parens in the passed string. If each caller verifies that the last character in STRING is a right paren, we don't even need to call extract_delimited_string. */ char * extract_array_assignment_list (string, sindex) char *string; int *sindex; { int slen; char *ret; slen = strlen (string); if (string[slen - 1] == RPAREN) { ret = substring (string, *sindex, slen - 1); *sindex = slen - 1; return ret; } return 0; } #endif /* Extract and create a new string from the contents of STRING, a character string delimited with OPENER and CLOSER. SINDEX is the address of an int describing the current offset in STRING; it should point to just after the first OPENER found. On exit, SINDEX gets the position of the last character of the matching CLOSER. If OPENER is more than a single character, ALT_OPENER, if non-null, contains a character string that can also match CLOSER and thus needs to be skipped. */ static char * extract_delimited_string (string, sindex, opener, alt_opener, closer, flags) char *string; int *sindex; char *opener, *alt_opener, *closer; int flags; { int i, c, si; size_t slen; char *t, *result; int pass_character, nesting_level, in_comment; int len_closer, len_opener, len_alt_opener; DECLARE_MBSTATE; slen = strlen (string + *sindex) + *sindex; len_opener = STRLEN (opener); len_alt_opener = STRLEN (alt_opener); len_closer = STRLEN (closer); pass_character = in_comment = 0; nesting_level = 1; i = *sindex; while (nesting_level) { c = string[i]; /* If a recursive call or a call to ADVANCE_CHAR leaves the index beyond the end of the string, catch it and cut the loop. */ if (i > slen) { i = slen; c = string[i = slen]; break; } if (c == 0) break; if (in_comment) { if (c == '\n') in_comment = 0; ADVANCE_CHAR (string, slen, i); continue; } if (pass_character) /* previous char was backslash */ { pass_character = 0; ADVANCE_CHAR (string, slen, i); continue; } /* Not exactly right yet; should handle shell metacharacters and multibyte characters, too. See COMMENT_BEGIN define in parse.y */ if ((flags & SX_COMMAND) && c == '#' && (i == 0 || string[i - 1] == '\n' || shellblank (string[i - 1]))) { in_comment = 1; ADVANCE_CHAR (string, slen, i); continue; } if (c == CTLESC || c == '\\') { pass_character++; i++; continue; } /* Process a nested command substitution, but only if we're parsing an arithmetic substitution. */ if ((flags & SX_COMMAND) && string[i] == '$' && string[i+1] == LPAREN) { si = i + 2; t = extract_command_subst (string, &si, flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } /* Process a nested OPENER. */ if (STREQN (string + i, opener, len_opener)) { si = i + len_opener; t = extract_delimited_string (string, &si, opener, alt_opener, closer, flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } /* Process a nested ALT_OPENER */ if (len_alt_opener && STREQN (string + i, alt_opener, len_alt_opener)) { si = i + len_alt_opener; t = extract_delimited_string (string, &si, alt_opener, alt_opener, closer, flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } /* If the current substring terminates the delimited string, decrement the nesting level. */ if (STREQN (string + i, closer, len_closer)) { i += len_closer - 1; /* move to last byte of the closer */ nesting_level--; if (nesting_level == 0) break; } /* Pass old-style command substitution through verbatim. */ if (c == '`') { si = i + 1; t = string_extract (string, &si, "`", flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } /* Pass single-quoted and double-quoted strings through verbatim. */ if (c == '\'' || c == '"') { si = i + 1; i = (c == '\'') ? skip_single_quoted (string, slen, si, 0) : skip_double_quoted (string, slen, si, 0); continue; } /* move past this character, which was not special. */ ADVANCE_CHAR (string, slen, i); } if (c == 0 && nesting_level) { if (no_longjmp_on_fatal_error == 0) { last_command_exit_value = EXECUTION_FAILURE; report_error (_("bad substitution: no closing `%s' in %s"), closer, string); exp_jump_to_top_level (DISCARD); } else { *sindex = i; return (char *)NULL; } } si = i - *sindex - len_closer + 1; if (flags & SX_NOALLOC) result = (char *)NULL; else { result = (char *)xmalloc (1 + si); strncpy (result, string + *sindex, si); result[si] = '\0'; } *sindex = i; return (result); } /* Extract a parameter expansion expression within ${ and } from STRING. Obey the Posix.2 rules for finding the ending `}': count braces while skipping over enclosed quoted strings and command substitutions. SINDEX is the address of an int describing the current offset in STRING; it should point to just after the first `{' found. On exit, SINDEX gets the position of the matching `}'. QUOTED is non-zero if this occurs inside double quotes. */ /* XXX -- this is very similar to extract_delimited_string -- XXX */ static char * extract_dollar_brace_string (string, sindex, quoted, flags) char *string; int *sindex, quoted, flags; { register int i, c; size_t slen; int pass_character, nesting_level, si, dolbrace_state; char *result, *t; DECLARE_MBSTATE; pass_character = 0; nesting_level = 1; slen = strlen (string + *sindex) + *sindex; /* The handling of dolbrace_state needs to agree with the code in parse.y: parse_matched_pair(). The different initial value is to handle the case where this function is called to parse the word in ${param op word} (SX_WORD). */ dolbrace_state = (flags & SX_WORD) ? DOLBRACE_WORD : DOLBRACE_PARAM; if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && (flags & SX_POSIXEXP)) dolbrace_state = DOLBRACE_QUOTE; i = *sindex; while (c = string[i]) { if (pass_character) { pass_character = 0; ADVANCE_CHAR (string, slen, i); continue; } /* CTLESCs and backslashes quote the next character. */ if (c == CTLESC || c == '\\') { pass_character++; i++; continue; } if (string[i] == '$' && string[i+1] == LBRACE) { nesting_level++; i += 2; continue; } if (c == RBRACE) { nesting_level--; if (nesting_level == 0) break; i++; continue; } /* Pass the contents of old-style command substitutions through verbatim. */ if (c == '`') { si = i + 1; t = string_extract (string, &si, "`", flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } /* Pass the contents of new-style command substitutions and arithmetic substitutions through verbatim. */ if (string[i] == '$' && string[i+1] == LPAREN) { si = i + 2; t = extract_command_subst (string, &si, flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } #if defined (PROCESS_SUBSTITUTION) /* Technically this should only work at the start of a word */ if ((string[i] == '<' || string[i] == '>') && string[i+1] == LPAREN) { si = i + 2; t = extract_process_subst (string, (string[i] == '<' ? "<(" : ">)"), &si, flags|SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si + 1; continue; } #endif /* Pass the contents of double-quoted strings through verbatim. */ if (c == '"') { si = i + 1; i = skip_double_quoted (string, slen, si, 0); /* skip_XXX_quoted leaves index one past close quote */ continue; } if (c == '\'') { /*itrace("extract_dollar_brace_string: c == single quote flags = %d quoted = %d dolbrace_state = %d", flags, quoted, dolbrace_state);*/ if (posixly_correct && shell_compatibility_level > 42 && dolbrace_state != DOLBRACE_QUOTE && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ADVANCE_CHAR (string, slen, i); else { si = i + 1; i = skip_single_quoted (string, slen, si, 0); } continue; } #if defined (ARRAY_VARS) if (c == LBRACK && dolbrace_state == DOLBRACE_PARAM) { si = skipsubscript (string, i, 0); CHECK_STRING_OVERRUN (i, si, slen, c); if (string[si] == RBRACK) c = string[i = si]; } #endif /* move past this character, which was not special. */ ADVANCE_CHAR (string, slen, i); /* This logic must agree with parse.y:parse_matched_pair, since they share the same defines. */ if (dolbrace_state == DOLBRACE_PARAM && c == '%' && (i - *sindex) > 1) dolbrace_state = DOLBRACE_QUOTE; else if (dolbrace_state == DOLBRACE_PARAM && c == '#' && (i - *sindex) > 1) dolbrace_state = DOLBRACE_QUOTE; else if (dolbrace_state == DOLBRACE_PARAM && c == '/' && (i - *sindex) > 1) dolbrace_state = DOLBRACE_QUOTE2; /* XXX */ else if (dolbrace_state == DOLBRACE_PARAM && c == '^' && (i - *sindex) > 1) dolbrace_state = DOLBRACE_QUOTE; else if (dolbrace_state == DOLBRACE_PARAM && c == ',' && (i - *sindex) > 1) dolbrace_state = DOLBRACE_QUOTE; /* This is intended to handle all of the [:]op expansions and the substring/ length/pattern removal/pattern substitution expansions. */ else if (dolbrace_state == DOLBRACE_PARAM && strchr ("#%^,~:-=?+/", c) != 0) dolbrace_state = DOLBRACE_OP; else if (dolbrace_state == DOLBRACE_OP && strchr ("#%^,~:-=?+/", c) == 0) dolbrace_state = DOLBRACE_WORD; } if (c == 0 && nesting_level) { if (no_longjmp_on_fatal_error == 0) { /* { */ last_command_exit_value = EXECUTION_FAILURE; report_error (_("bad substitution: no closing `%s' in %s"), "}", string); exp_jump_to_top_level (DISCARD); } else { *sindex = i; return ((char *)NULL); } } result = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i); *sindex = i; return (result); } /* Remove backslashes which are quoting backquotes from STRING. Modifies STRING, and returns a pointer to it. */ char * de_backslash (string) char *string; { register size_t slen; register int i, j, prev_i; DECLARE_MBSTATE; slen = strlen (string); i = j = 0; /* Loop copying string[i] to string[j], i >= j. */ while (i < slen) { if (string[i] == '\\' && (string[i + 1] == '`' || string[i + 1] == '\\' || string[i + 1] == '$')) i++; prev_i = i; ADVANCE_CHAR (string, slen, i); if (j < prev_i) do string[j++] = string[prev_i++]; while (prev_i < i); else j = i; } string[j] = '\0'; return (string); } #if 0 /*UNUSED*/ /* Replace instances of \! in a string with !. */ void unquote_bang (string) char *string; { register int i, j; register char *temp; temp = (char *)xmalloc (1 + strlen (string)); for (i = 0, j = 0; (temp[j] = string[i]); i++, j++) { if (string[i] == '\\' && string[i + 1] == '!') { temp[j] = '!'; i++; } } strcpy (string, temp); free (temp); } #endif #define CQ_RETURN(x) do { no_longjmp_on_fatal_error = oldjmp; return (x); } while (0) /* This function assumes s[i] == open; returns with s[ret] == close; used to parse array subscripts. FLAGS & 1 means to not attempt to skip over matched pairs of quotes or backquotes, or skip word expansions; it is intended to be used after expansion has been performed and during final assignment parsing (see arrayfunc.c:assign_compound_array_list()) or during execution by a builtin which has already undergone word expansion. */ static int skip_matched_pair (string, start, open, close, flags) const char *string; int start, open, close, flags; { int i, pass_next, backq, si, c, count, oldjmp; size_t slen; char *temp, *ss; DECLARE_MBSTATE; slen = strlen (string + start) + start; oldjmp = no_longjmp_on_fatal_error; no_longjmp_on_fatal_error = 1; i = start + 1; /* skip over leading bracket */ count = 1; pass_next = backq = 0; ss = (char *)string; while (c = string[i]) { if (pass_next) { pass_next = 0; if (c == 0) CQ_RETURN(i); ADVANCE_CHAR (string, slen, i); continue; } else if ((flags & 1) == 0 && c == '\\') { pass_next = 1; i++; continue; } else if (backq) { if (c == '`') backq = 0; ADVANCE_CHAR (string, slen, i); continue; } else if ((flags & 1) == 0 && c == '`') { backq = 1; i++; continue; } else if ((flags & 1) == 0 && c == open) { count++; i++; continue; } else if (c == close) { count--; if (count == 0) break; i++; continue; } else if ((flags & 1) == 0 && (c == '\'' || c == '"')) { i = (c == '\'') ? skip_single_quoted (ss, slen, ++i, 0) : skip_double_quoted (ss, slen, ++i, 0); /* no increment, the skip functions increment past the closing quote. */ } else if ((flags&1) == 0 && c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE)) { si = i + 2; if (string[si] == '\0') CQ_RETURN(si); /* XXX - extract_command_subst here? */ if (string[i+1] == LPAREN) temp = extract_delimited_string (ss, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */ else temp = extract_dollar_brace_string (ss, &si, 0, SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si; if (string[i] == '\0') /* don't increment i past EOS in loop */ break; i++; continue; } else ADVANCE_CHAR (string, slen, i); } CQ_RETURN(i); } #if defined (ARRAY_VARS) /* Flags has 1 as a reserved value, since skip_matched_pair uses it for skipping over quoted strings and taking the first instance of the closing character. */ int skipsubscript (string, start, flags) const char *string; int start, flags; { return (skip_matched_pair (string, start, '[', ']', flags)); } #endif /* Skip characters in STRING until we find a character in DELIMS, and return the index of that character. START is the index into string at which we begin. This is similar in spirit to strpbrk, but it returns an index into STRING and takes a starting index. This little piece of code knows quite a lot of shell syntax. It's very similar to skip_double_quoted and other functions of that ilk. */ int skip_to_delim (string, start, delims, flags) char *string; int start; char *delims; int flags; { int i, pass_next, backq, dquote, si, c, oldjmp; int invert, skipquote, skipcmd, noprocsub, completeflag; int arithexp, skipcol; size_t slen; char *temp, open[3]; DECLARE_MBSTATE; slen = strlen (string + start) + start; oldjmp = no_longjmp_on_fatal_error; if (flags & SD_NOJMP) no_longjmp_on_fatal_error = 1; invert = (flags & SD_INVERT); skipcmd = (flags & SD_NOSKIPCMD) == 0; noprocsub = (flags & SD_NOPROCSUB); completeflag = (flags & SD_COMPLETE) ? SX_COMPLETE : 0; arithexp = (flags & SD_ARITHEXP); skipcol = 0; i = start; pass_next = backq = dquote = 0; while (c = string[i]) { /* If this is non-zero, we should not let quote characters be delimiters and the current character is a single or double quote. We should not test whether or not it's a delimiter until after we skip single- or double-quoted strings. */ skipquote = ((flags & SD_NOQUOTEDELIM) && (c == '\'' || c =='"')); if (pass_next) { pass_next = 0; if (c == 0) CQ_RETURN(i); ADVANCE_CHAR (string, slen, i); continue; } else if (c == '\\') { pass_next = 1; i++; continue; } else if (backq) { if (c == '`') backq = 0; ADVANCE_CHAR (string, slen, i); continue; } else if (c == '`') { backq = 1; i++; continue; } else if (arithexp && skipcol && c == ':') { skipcol--; i++; continue; } else if (arithexp && c == '?') { skipcol++; i++; continue; } else if (skipquote == 0 && invert == 0 && member (c, delims)) break; /* the usual case is to use skip_xxx_quoted, but we don't skip over double quoted strings when looking for the history expansion character as a delimiter. */ /* special case for programmable completion which takes place before parser converts backslash-escaped single quotes between $'...' to `regular' single-quoted strings. */ else if (completeflag && i > 0 && string[i-1] == '$' && c == '\'') i = skip_single_quoted (string, slen, ++i, SX_COMPLETE); else if (c == '\'') i = skip_single_quoted (string, slen, ++i, 0); else if (c == '"') i = skip_double_quoted (string, slen, ++i, completeflag); else if (c == LPAREN && arithexp) { si = i + 1; if (string[si] == '\0') CQ_RETURN(si); temp = extract_delimited_string (string, &si, "(", "(", ")", SX_NOALLOC); /* ) */ i = si; if (string[i] == '\0') /* don't increment i past EOS in loop */ break; i++; continue; } else if (c == '$' && ((skipcmd && string[i+1] == LPAREN) || string[i+1] == LBRACE)) { si = i + 2; if (string[si] == '\0') CQ_RETURN(si); if (string[i+1] == LPAREN) temp = extract_delimited_string (string, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */ else temp = extract_dollar_brace_string (string, &si, 0, SX_NOALLOC); CHECK_STRING_OVERRUN (i, si, slen, c); i = si; if (string[i] == '\0') /* don't increment i past EOS in loop */ break; i++; continue; } #if defined (PROCESS_SUBSTITUTION) else if (skipcmd && noprocsub == 0 && (c == '<' || c == '>') && string[i+1] == LPAREN) { si = i + 2; if (string[si] == '\0') CQ_RETURN(si); temp = extract_delimited_string (string, &si, (c == '<') ? "<(" : ">(", "(", ")", SX_COMMAND|SX_NOALLOC); /* )) */ CHECK_STRING_OVERRUN (i, si, slen, c); i = si; if (string[i] == '\0') break; i++; continue; } #endif /* PROCESS_SUBSTITUTION */ #if defined (EXTENDED_GLOB) else if ((flags & SD_EXTGLOB) && extended_glob && string[i+1] == LPAREN && member (c, "?*+!@")) { si = i + 2; if (string[si] == '\0') CQ_RETURN(si); open[0] = c; open[1] = LPAREN; open[2] = '\0'; temp = extract_delimited_string (string, &si, open, "(", ")", SX_NOALLOC); /* ) */ CHECK_STRING_OVERRUN (i, si, slen, c); i = si; if (string[i] == '\0') /* don't increment i past EOS in loop */ break; i++; continue; } #endif else if ((flags & SD_GLOB) && c == LBRACK) { si = i + 1; if (string[si] == '\0') CQ_RETURN(si); temp = extract_delimited_string (string, &si, "[", "[", "]", SX_NOALLOC); /* ] */ i = si; if (string[i] == '\0') /* don't increment i past EOS in loop */ break; i++; continue; } else if ((skipquote || invert) && (member (c, delims) == 0)) break; else ADVANCE_CHAR (string, slen, i); } CQ_RETURN(i); } #if defined (BANG_HISTORY) /* Skip to the history expansion character (delims[0]), paying attention to quoted strings and command and process substitution. This is a stripped- down version of skip_to_delims. The essential difference is that this resets the quoting state when starting a command substitution */ int skip_to_histexp (string, start, delims, flags) char *string; int start; char *delims; int flags; { int i, pass_next, backq, dquote, c, oldjmp; int histexp_comsub, histexp_backq, old_dquote; size_t slen; DECLARE_MBSTATE; slen = strlen (string + start) + start; oldjmp = no_longjmp_on_fatal_error; if (flags & SD_NOJMP) no_longjmp_on_fatal_error = 1; histexp_comsub = histexp_backq = old_dquote = 0; i = start; pass_next = backq = dquote = 0; while (c = string[i]) { if (pass_next) { pass_next = 0; if (c == 0) CQ_RETURN(i); ADVANCE_CHAR (string, slen, i); continue; } else if (c == '\\') { pass_next = 1; i++; continue; } else if (backq && c == '`') { backq = 0; histexp_backq--; dquote = old_dquote; i++; continue; } else if (c == '`') { backq = 1; histexp_backq++; old_dquote = dquote; /* simple - one level for now */ dquote = 0; i++; continue; } /* When in double quotes, act as if the double quote is a member of history_no_expand_chars, like the history library does */ else if (dquote && c == delims[0] && string[i+1] == '"') { i++; continue; } else if (c == delims[0]) break; /* the usual case is to use skip_xxx_quoted, but we don't skip over double quoted strings when looking for the history expansion character as a delimiter. */ else if (dquote && c == '\'') { i++; continue; } else if (c == '\'') i = skip_single_quoted (string, slen, ++i, 0); /* The posixly_correct test makes posix-mode shells allow double quotes to quote the history expansion character */ else if (posixly_correct == 0 && c == '"') { dquote = 1 - dquote; i++; continue; } else if (c == '"') i = skip_double_quoted (string, slen, ++i, 0); #if defined (PROCESS_SUBSTITUTION) else if ((c == '$' || c == '<' || c == '>') && string[i+1] == LPAREN && string[i+2] != LPAREN) #else else if (c == '$' && string[i+1] == LPAREN && string[i+2] != LPAREN) #endif { if (string[i+2] == '\0') CQ_RETURN(i+2); i += 2; histexp_comsub++; old_dquote = dquote; dquote = 0; } else if (histexp_comsub && c == RPAREN) { histexp_comsub--; dquote = old_dquote; i++; continue; } else if (backq) /* placeholder */ { ADVANCE_CHAR (string, slen, i); continue; } else ADVANCE_CHAR (string, slen, i); } CQ_RETURN(i); } #endif /* BANG_HISTORY */ #if defined (READLINE) /* Return 1 if the portion of STRING ending at EINDEX is quoted (there is an unclosed quoted string), or if the character at EINDEX is quoted by a backslash. NO_LONGJMP_ON_FATAL_ERROR is used to flag that the various single and double-quoted string parsing functions should not return an error if there are unclosed quotes or braces. The characters that this recognizes need to be the same as the contents of rl_completer_quote_characters. */ int char_is_quoted (string, eindex) char *string; int eindex; { int i, pass_next, c, oldjmp; size_t slen; DECLARE_MBSTATE; slen = strlen (string); oldjmp = no_longjmp_on_fatal_error; no_longjmp_on_fatal_error = 1; i = pass_next = 0; while (i <= eindex) { c = string[i]; if (pass_next) { pass_next = 0; if (i >= eindex) /* XXX was if (i >= eindex - 1) */ CQ_RETURN(1); ADVANCE_CHAR (string, slen, i); continue; } else if (c == '\\') { pass_next = 1; i++; continue; } else if (c == '$' && string[i+1] == '\'' && string[i+2]) { i += 2; i = skip_single_quoted (string, slen, i, SX_COMPLETE); if (i > eindex) CQ_RETURN (i); } else if (c == '\'' || c == '"') { i = (c == '\'') ? skip_single_quoted (string, slen, ++i, 0) : skip_double_quoted (string, slen, ++i, SX_COMPLETE); if (i > eindex) CQ_RETURN(1); /* no increment, the skip_xxx functions go one past end */ } else ADVANCE_CHAR (string, slen, i); } CQ_RETURN(0); } int unclosed_pair (string, eindex, openstr) char *string; int eindex; char *openstr; { int i, pass_next, openc, olen; size_t slen; DECLARE_MBSTATE; slen = strlen (string); olen = strlen (openstr); i = pass_next = openc = 0; while (i <= eindex) { if (pass_next) { pass_next = 0; if (i >= eindex) /* XXX was if (i >= eindex - 1) */ return 0; ADVANCE_CHAR (string, slen, i); continue; } else if (string[i] == '\\') { pass_next = 1; i++; continue; } else if (STREQN (string + i, openstr, olen)) { openc = 1 - openc; i += olen; } /* XXX - may want to handle $'...' specially here */ else if (string[i] == '\'' || string[i] == '"') { i = (string[i] == '\'') ? skip_single_quoted (string, slen, i, 0) : skip_double_quoted (string, slen, i, SX_COMPLETE); if (i > eindex) return 0; } else ADVANCE_CHAR (string, slen, i); } return (openc); } /* Split STRING (length SLEN) at DELIMS, and return a WORD_LIST with the individual words. If DELIMS is NULL, the current value of $IFS is used to split the string, and the function follows the shell field splitting rules. SENTINEL is an index to look for. NWP, if non-NULL, gets the number of words in the returned list. CWP, if non-NULL, gets the index of the word containing SENTINEL. Non-whitespace chars in DELIMS delimit separate fields. This is used by programmable completion. */ WORD_LIST * split_at_delims (string, slen, delims, sentinel, flags, nwp, cwp) char *string; int slen; char *delims; int sentinel, flags; int *nwp, *cwp; { int ts, te, i, nw, cw, ifs_split, dflags; char *token, *d, *d2; WORD_LIST *ret, *tl; if (string == 0 || *string == '\0') { if (nwp) *nwp = 0; if (cwp) *cwp = 0; return ((WORD_LIST *)NULL); } d = (delims == 0) ? ifs_value : delims; ifs_split = delims == 0; /* Make d2 the non-whitespace characters in delims */ d2 = 0; if (delims) { size_t slength; #if defined (HANDLE_MULTIBYTE) size_t mblength = 1; #endif DECLARE_MBSTATE; slength = strlen (delims); d2 = (char *)xmalloc (slength + 1); i = ts = 0; while (delims[i]) { #if defined (HANDLE_MULTIBYTE) mbstate_t state_bak; state_bak = state; mblength = MBRLEN (delims + i, slength, &state); if (MB_INVALIDCH (mblength)) state = state_bak; else if (mblength > 1) { memcpy (d2 + ts, delims + i, mblength); ts += mblength; i += mblength; slength -= mblength; continue; } #endif if (whitespace (delims[i]) == 0) d2[ts++] = delims[i]; i++; slength--; } d2[ts] = '\0'; } ret = (WORD_LIST *)NULL; /* Remove sequences of whitespace characters at the start of the string, as long as those characters are delimiters. */ for (i = 0; member (string[i], d) && spctabnl (string[i]); i++) ; if (string[i] == '\0') { FREE (d2); return (ret); } ts = i; nw = 0; cw = -1; dflags = flags|SD_NOJMP; while (1) { te = skip_to_delim (string, ts, d, dflags); /* If we have a non-whitespace delimiter character, use it to make a separate field. This is just about what $IFS splitting does and is closer to the behavior of the shell parser. */ if (ts == te && d2 && member (string[ts], d2)) { te = ts + 1; /* If we're using IFS splitting, the non-whitespace delimiter char and any additional IFS whitespace delimits a field. */ if (ifs_split) while (member (string[te], d) && spctabnl (string[te]) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"'))) te++; else while (member (string[te], d2) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"'))) te++; } token = substring (string, ts, te); ret = add_string_to_list (token, ret); /* XXX */ free (token); nw++; if (sentinel >= ts && sentinel <= te) cw = nw; /* If the cursor is at whitespace just before word start, set the sentinel word to the current word. */ if (cwp && cw == -1 && sentinel == ts-1) cw = nw; /* If the cursor is at whitespace between two words, make a new, empty word, add it before (well, after, since the list is in reverse order) the word we just added, and set the current word to that one. */ if (cwp && cw == -1 && sentinel < ts) { tl = make_word_list (make_word (""), ret->next); ret->next = tl; cw = nw; nw++; } if (string[te] == 0) break; i = te; /* XXX - honor SD_NOQUOTEDELIM here */ while (member (string[i], d) && (ifs_split || spctabnl(string[i])) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"'))) i++; if (string[i]) ts = i; else break; } /* Special case for SENTINEL at the end of STRING. If we haven't found the word containing SENTINEL yet, and the index we're looking for is at the end of STRING (or past the end of the previously-found token, possible if the end of the line is composed solely of IFS whitespace) add an additional null argument and set the current word pointer to that. */ if (cwp && cw == -1 && (sentinel >= slen || sentinel >= te)) { if (whitespace (string[sentinel - 1])) { token = ""; ret = add_string_to_list (token, ret); nw++; } cw = nw; } if (nwp) *nwp = nw; if (cwp) *cwp = cw; FREE (d2); return (REVERSE_LIST (ret, WORD_LIST *)); } #endif /* READLINE */ #if 0 /* UNUSED */ /* Extract the name of the variable to bind to from the assignment string. */ char * assignment_name (string) char *string; { int offset; char *temp; offset = assignment (string, 0); if (offset == 0) return (char *)NULL; temp = substring (string, 0, offset); return (temp); } #endif /* **************************************************************** */ /* */ /* Functions to convert strings to WORD_LISTs and vice versa */ /* */ /* **************************************************************** */ /* Return a single string of all the words in LIST. SEP is the separator to put between individual elements of LIST in the output string. */ char * string_list_internal (list, sep) WORD_LIST *list; char *sep; { register WORD_LIST *t; char *result, *r; size_t word_len, sep_len, result_size; if (list == 0) return ((char *)NULL); /* Short-circuit quickly if we don't need to separate anything. */ if (list->next == 0) return (savestring (list->word->word)); /* This is nearly always called with either sep[0] == 0 or sep[1] == 0. */ sep_len = STRLEN (sep); result_size = 0; for (t = list; t; t = t->next) { if (t != list) result_size += sep_len; result_size += strlen (t->word->word); } r = result = (char *)xmalloc (result_size + 1); for (t = list; t; t = t->next) { if (t != list && sep_len) { if (sep_len > 1) { FASTCOPY (sep, r, sep_len); r += sep_len; } else *r++ = sep[0]; } word_len = strlen (t->word->word); FASTCOPY (t->word->word, r, word_len); r += word_len; } *r = '\0'; return (result); } /* Return a single string of all the words present in LIST, separating each word with a space. */ char * string_list (list) WORD_LIST *list; { return (string_list_internal (list, " ")); } /* An external interface that can be used by the rest of the shell to obtain a string containing the first character in $IFS. Handles all the multibyte complications. If LENP is non-null, it is set to the length of the returned string. */ char * ifs_firstchar (lenp) int *lenp; { char *ret; int len; ret = xmalloc (MB_LEN_MAX + 1); #if defined (HANDLE_MULTIBYTE) if (ifs_firstc_len == 1) { ret[0] = ifs_firstc[0]; ret[1] = '\0'; len = ret[0] ? 1 : 0; } else { memcpy (ret, ifs_firstc, ifs_firstc_len); ret[len = ifs_firstc_len] = '\0'; } #else ret[0] = ifs_firstc; ret[1] = '\0'; len = ret[0] ? 0 : 1; #endif if (lenp) *lenp = len; return ret; } /* Return a single string of all the words present in LIST, obeying the quoting rules for "$*", to wit: (P1003.2, draft 11, 3.5.2) "If the expansion [of $*] appears within a double quoted string, it expands to a single field with the value of each parameter separated by the first character of the IFS variable, or by a <space> if IFS is unset." */ /* Posix interpretation 888 changes this when IFS is null by specifying that when unquoted, this expands to separate arguments */ char * string_list_dollar_star (list, quoted, flags) WORD_LIST *list; int quoted, flags; { char *ret; #if defined (HANDLE_MULTIBYTE) # if defined (__GNUC__) char sep[MB_CUR_MAX + 1]; # else char *sep = 0; # endif #else char sep[2]; #endif #if defined (HANDLE_MULTIBYTE) # if !defined (__GNUC__) sep = (char *)xmalloc (MB_CUR_MAX + 1); # endif /* !__GNUC__ */ if (ifs_firstc_len == 1) { sep[0] = ifs_firstc[0]; sep[1] = '\0'; } else { memcpy (sep, ifs_firstc, ifs_firstc_len); sep[ifs_firstc_len] = '\0'; } #else sep[0] = ifs_firstc; sep[1] = '\0'; #endif ret = string_list_internal (list, sep); #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__) free (sep); #endif return ret; } /* Turn $@ into a string. If (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) is non-zero, the $@ appears within double quotes, and we should quote the list before converting it into a string. If IFS is unset, and the word is not quoted, we just need to quote CTLESC and CTLNUL characters in the words in the list, because the default value of $IFS is <space><tab><newline>, IFS characters in the words in the list should also be split. If IFS is null, and the word is not quoted, we need to quote the words in the list to preserve the positional parameters exactly. Valid values for the FLAGS argument are the PF_ flags in command.h, the only one we care about is PF_ASSIGNRHS. $@ is supposed to expand to the positional parameters separated by spaces no matter what IFS is set to if in a context where word splitting is not performed. The only one that we didn't handle before is assignment statement arguments to declaration builtins like `declare'. */ char * string_list_dollar_at (list, quoted, flags) WORD_LIST *list; int quoted; int flags; { char *ifs, *ret; #if defined (HANDLE_MULTIBYTE) # if defined (__GNUC__) char sep[MB_CUR_MAX + 1]; # else char *sep = 0; # endif /* !__GNUC__ */ #else char sep[2]; #endif WORD_LIST *tlist; /* XXX this could just be ifs = ifs_value; */ ifs = ifs_var ? value_cell (ifs_var) : (char *)0; #if defined (HANDLE_MULTIBYTE) # if !defined (__GNUC__) sep = (char *)xmalloc (MB_CUR_MAX + 1); # endif /* !__GNUC__ */ /* XXX - testing PF_ASSIGNRHS to make sure positional parameters are separated with a space even when word splitting will not occur. */ if (flags & PF_ASSIGNRHS) { sep[0] = ' '; sep[1] = '\0'; } else if (ifs && *ifs) { if (ifs_firstc_len == 1) { sep[0] = ifs_firstc[0]; sep[1] = '\0'; } else { memcpy (sep, ifs_firstc, ifs_firstc_len); sep[ifs_firstc_len] = '\0'; } } else { sep[0] = ' '; sep[1] = '\0'; } #else /* !HANDLE_MULTIBYTE */ /* XXX - PF_ASSIGNRHS means no word splitting, so we want positional parameters separated by a space. */ sep[0] = ((flags & PF_ASSIGNRHS) || ifs == 0 || *ifs == 0) ? ' ' : *ifs; sep[1] = '\0'; #endif /* !HANDLE_MULTIBYTE */ /* XXX -- why call quote_list if ifs == 0? we can get away without doing it now that quote_escapes quotes spaces */ tlist = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES|Q_PATQUOTE)) ? quote_list (list) : list_quote_escapes (list); ret = string_list_internal (tlist, sep); #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__) free (sep); #endif return ret; } /* Turn the positional parameters into a string, understanding quoting and the various subtleties of using the first character of $IFS as the separator. Calls string_list_dollar_at, string_list_dollar_star, and string_list as appropriate. */ /* This needs to fully understand the additional contexts where word splitting does not occur (W_ASSIGNRHS, etc.) */ char * string_list_pos_params (pchar, list, quoted, pflags) int pchar; WORD_LIST *list; int quoted, pflags; { char *ret; WORD_LIST *tlist; if (pchar == '*' && (quoted & Q_DOUBLE_QUOTES)) { tlist = quote_list (list); word_list_remove_quoted_nulls (tlist); ret = string_list_dollar_star (tlist, 0, 0); } else if (pchar == '*' && (quoted & Q_HERE_DOCUMENT)) { tlist = quote_list (list); word_list_remove_quoted_nulls (tlist); ret = string_list (tlist); } else if (pchar == '*' && quoted == 0 && ifs_is_null) /* XXX */ ret = expand_no_split_dollar_star ? string_list_dollar_star (list, quoted, 0) : string_list_dollar_at (list, quoted, 0); /* Posix interp 888 */ else if (pchar == '*' && quoted == 0 && (pflags & PF_ASSIGNRHS)) /* XXX */ ret = expand_no_split_dollar_star ? string_list_dollar_star (list, quoted, 0) : string_list_dollar_at (list, quoted, 0); /* Posix interp 888 */ else if (pchar == '*') { /* Even when unquoted, string_list_dollar_star does the right thing making sure that the first character of $IFS is used as the separator. */ ret = string_list_dollar_star (list, quoted, 0); } else if (pchar == '@' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) /* We use string_list_dollar_at, but only if the string is quoted, since that quotes the escapes if it's not, which we don't want. We could use string_list (the old code did), but that doesn't do the right thing if the first character of $IFS is not a space. We use string_list_dollar_star if the string is unquoted so we make sure that the elements of $@ are separated by the first character of $IFS for later splitting. */ ret = string_list_dollar_at (list, quoted, 0); else if (pchar == '@' && quoted == 0 && ifs_is_null) /* XXX */ ret = string_list_dollar_at (list, quoted, 0); /* Posix interp 888 */ else if (pchar == '@' && quoted == 0 && (pflags & PF_ASSIGNRHS)) ret = string_list_dollar_at (list, quoted, pflags); /* Posix interp 888 */ else if (pchar == '@') ret = string_list_dollar_star (list, quoted, 0); else ret = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (list) : list); return ret; } /* Return the list of words present in STRING. Separate the string into words at any of the characters found in SEPARATORS. If QUOTED is non-zero then word in the list will have its quoted flag set, otherwise the quoted flag is left as make_word () deemed fit. This obeys the P1003.2 word splitting semantics. If `separators' is exactly <space><tab><newline>, then the splitting algorithm is that of the Bourne shell, which treats any sequence of characters from `separators' as a delimiter. If IFS is unset, which results in `separators' being set to "", no splitting occurs. If separators has some other value, the following rules are applied (`IFS white space' means zero or more occurrences of <space>, <tab>, or <newline>, as long as those characters are in `separators'): 1) IFS white space is ignored at the start and the end of the string. 2) Each occurrence of a character in `separators' that is not IFS white space, along with any adjacent occurrences of IFS white space delimits a field. 3) Any nonzero-length sequence of IFS white space delimits a field. */ /* BEWARE! list_string strips null arguments. Don't call it twice and expect to have "" preserved! */ /* This performs word splitting and quoted null character removal on STRING. */ #define issep(c) \ (((separators)[0]) ? ((separators)[1] ? isifs(c) \ : (c) == (separators)[0]) \ : 0) /* member of the space character class in the current locale */ #define ifs_whitespace(c) ISSPACE(c) /* "adjacent IFS white space" */ #define ifs_whitesep(c) ((sh_style_split || separators == 0) ? spctabnl (c) \ : ifs_whitespace (c)) WORD_LIST * list_string (string, separators, quoted) register char *string, *separators; int quoted; { WORD_LIST *result; WORD_DESC *t; char *current_word, *s; int sindex, sh_style_split, whitesep, xflags, free_word; size_t slen; if (!string || !*string) return ((WORD_LIST *)NULL); sh_style_split = separators && separators[0] == ' ' && separators[1] == '\t' && separators[2] == '\n' && separators[3] == '\0'; for (xflags = 0, s = ifs_value; s && *s; s++) { if (*s == CTLESC) xflags |= SX_NOCTLESC; else if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL; } slen = 0; /* Remove sequences of whitespace at the beginning of STRING, as long as those characters appear in IFS. Do not do this if STRING is quoted or if there are no separator characters. We use the Posix definition of whitespace as a member of the space character class in the current locale. */ #if 0 if (!quoted || !separators || !*separators) #else /* issep() requires that separators be non-null, and always returns 0 if separator is the empty string, so don't bother if we get an empty string for separators. We already returned NULL above if STRING is empty. */ if (!quoted && separators && *separators) #endif { for (s = string; *s && issep (*s) && ifs_whitespace (*s); s++); if (!*s) return ((WORD_LIST *)NULL); string = s; } /* OK, now STRING points to a word that does not begin with white space. The splitting algorithm is: extract a word, stopping at a separator skip sequences of whitespace characters as long as they are separators This obeys the field splitting rules in Posix.2. */ slen = STRLEN (string); for (result = (WORD_LIST *)NULL, sindex = 0; string[sindex]; ) { /* Don't need string length in ADVANCE_CHAR unless multibyte chars are possible, but need it in string_extract_verbatim for bounds checking */ current_word = string_extract_verbatim (string, slen, &sindex, separators, xflags); if (current_word == 0) break; free_word = 1; /* If non-zero, we free current_word */ /* If we have a quoted empty string, add a quoted null argument. We want to preserve the quoted null character iff this is a quoted empty string; otherwise the quoted null characters are removed below. */ if (QUOTED_NULL (current_word)) { t = alloc_word_desc (); t->word = make_quoted_char ('\0'); t->flags |= W_QUOTED|W_HASQUOTEDNULL; result = make_word_list (t, result); } else if (current_word[0] != '\0') { /* If we have something, then add it regardless. However, perform quoted null character removal on the current word. */ remove_quoted_nulls (current_word); /* We don't want to set the word flags based on the string contents here -- that's mostly for the parser -- so we just allocate a WORD_DESC *, assign current_word (noting that we don't want to free it), and skip all of make_word. */ t = alloc_word_desc (); t->word = current_word; result = make_word_list (t, result); free_word = 0; result->word->flags &= ~W_HASQUOTEDNULL; /* just to be sure */ if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) result->word->flags |= W_QUOTED; /* If removing quoted null characters leaves an empty word, note that we saw this for the caller to act on. */ if (current_word == 0 || current_word[0] == '\0') result->word->flags |= W_SAWQUOTEDNULL; } /* If we're not doing sequences of separators in the traditional Bourne shell style, then add a quoted null argument. */ else if (!sh_style_split && !ifs_whitespace (string[sindex])) { t = alloc_word_desc (); t->word = make_quoted_char ('\0'); t->flags |= W_QUOTED|W_HASQUOTEDNULL; result = make_word_list (t, result); } if (free_word) free (current_word); /* Note whether or not the separator is IFS whitespace, used later. */ whitesep = string[sindex] && ifs_whitesep (string[sindex]); /* Move past the current separator character. */ if (string[sindex]) { DECLARE_MBSTATE; ADVANCE_CHAR (string, slen, sindex); } /* Now skip sequences of whitespace characters if they are in the list of separators. */ while (string[sindex] && ifs_whitesep (string[sindex]) && issep (string[sindex])) sindex++; /* If the first separator was IFS whitespace and the current character is a non-whitespace IFS character, it should be part of the current field delimiter, not a separate delimiter that would result in an empty field. Look at POSIX.2, 3.6.5, (3)(b). */ if (string[sindex] && whitesep && issep (string[sindex]) && !ifs_whitesep (string[sindex])) { sindex++; /* An IFS character that is not IFS white space, along with any adjacent IFS white space, shall delimit a field. (SUSv3) */ while (string[sindex] && ifs_whitesep (string[sindex]) && isifs (string[sindex])) sindex++; } } return (REVERSE_LIST (result, WORD_LIST *)); } /* Parse a single word from STRING, using SEPARATORS to separate fields. ENDPTR is set to the first character after the word. This is used by the `read' builtin. This is never called with SEPARATORS != $IFS, and takes advantage of that. XXX - this function is very similar to list_string; they should be combined - XXX */ /* character is in $IFS */ #define islocalsep(c) (local_cmap[(unsigned char)(c)] != 0) char * get_word_from_string (stringp, separators, endptr) char **stringp, *separators, **endptr; { register char *s; char *current_word; int sindex, sh_style_split, whitesep, xflags; unsigned char local_cmap[UCHAR_MAX+1]; /* really only need single-byte chars here */ size_t slen; if (!stringp || !*stringp || !**stringp) return ((char *)NULL); sh_style_split = separators && separators[0] == ' ' && separators[1] == '\t' && separators[2] == '\n' && separators[3] == '\0'; memset (local_cmap, '\0', sizeof (local_cmap)); for (xflags = 0, s = separators; s && *s; s++) { if (*s == CTLESC) xflags |= SX_NOCTLESC; if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL; local_cmap[(unsigned char)*s] = 1; /* local charmap of separators */ } s = *stringp; slen = 0; /* Remove sequences of whitespace at the beginning of STRING, as long as those characters appear in SEPARATORS. This happens if SEPARATORS == $' \t\n' or if IFS is unset. */ if (sh_style_split || separators == 0) for (; *s && spctabnl (*s) && islocalsep (*s); s++); else for (; *s && ifs_whitespace (*s) && islocalsep (*s); s++); /* If the string is nothing but whitespace, update it and return. */ if (!*s) { *stringp = s; if (endptr) *endptr = s; return ((char *)NULL); } /* OK, S points to a word that does not begin with white space. Now extract a word, stopping at a separator, save a pointer to the first character after the word, then skip sequences of spc, tab, or nl as long as they are separators. This obeys the field splitting rules in Posix.2. */ sindex = 0; /* Don't need string length in ADVANCE_CHAR unless multibyte chars are possible, but need it in string_extract_verbatim for bounds checking */ slen = STRLEN (s); current_word = string_extract_verbatim (s, slen, &sindex, separators, xflags); /* Set ENDPTR to the first character after the end of the word. */ if (endptr) *endptr = s + sindex; /* Note whether or not the separator is IFS whitespace, used later. */ whitesep = s[sindex] && ifs_whitesep (s[sindex]); /* Move past the current separator character. */ if (s[sindex]) { DECLARE_MBSTATE; ADVANCE_CHAR (s, slen, sindex); } /* Now skip sequences of space, tab, or newline characters if they are in the list of separators. */ while (s[sindex] && spctabnl (s[sindex]) && islocalsep (s[sindex])) sindex++; /* If the first separator was IFS whitespace and the current character is a non-whitespace IFS character, it should be part of the current field delimiter, not a separate delimiter that would result in an empty field. Look at POSIX.2, 3.6.5, (3)(b). */ if (s[sindex] && whitesep && islocalsep (s[sindex]) && !ifs_whitesep (s[sindex])) { sindex++; /* An IFS character that is not IFS white space, along with any adjacent IFS white space, shall delimit a field. */ while (s[sindex] && ifs_whitesep (s[sindex]) && islocalsep(s[sindex])) sindex++; } /* Update STRING to point to the next field. */ *stringp = s + sindex; return (current_word); } /* Remove IFS white space at the end of STRING. Start at the end of the string and walk backwards until the beginning of the string or we find a character that's not IFS white space and not CTLESC. Only let CTLESC escape a white space character if SAW_ESCAPE is non-zero. */ char * strip_trailing_ifs_whitespace (string, separators, saw_escape) char *string, *separators; int saw_escape; { char *s; s = string + STRLEN (string) - 1; while (s > string && ((spctabnl (*s) && isifs (*s)) || (saw_escape && *s == CTLESC && spctabnl (s[1])))) s--; *++s = '\0'; return string; } #if 0 /* UNUSED */ /* Split STRING into words at whitespace. Obeys shell-style quoting with backslashes, single and double quotes. */ WORD_LIST * list_string_with_quotes (string) char *string; { WORD_LIST *list; char *token, *s; size_t s_len; int c, i, tokstart, len; for (s = string; s && *s && spctabnl (*s); s++) ; if (s == 0 || *s == 0) return ((WORD_LIST *)NULL); s_len = strlen (s); tokstart = i = 0; list = (WORD_LIST *)NULL; while (1) { c = s[i]; if (c == '\\') { i++; if (s[i]) i++; } else if (c == '\'') i = skip_single_quoted (s, s_len, ++i, 0); else if (c == '"') i = skip_double_quoted (s, s_len, ++i, 0); else if (c == 0 || spctabnl (c)) { /* We have found the end of a token. Make a word out of it and add it to the word list. */ token = substring (s, tokstart, i); list = add_string_to_list (token, list); free (token); while (spctabnl (s[i])) i++; if (s[i]) tokstart = i; else break; } else i++; /* normal character */ } return (REVERSE_LIST (list, WORD_LIST *)); } #endif /********************************************************/ /* */ /* Functions to perform assignment statements */ /* */ /********************************************************/ #if defined (ARRAY_VARS) static SHELL_VAR * do_compound_assignment (name, value, flags) char *name, *value; int flags; { SHELL_VAR *v; int mklocal, mkassoc, mkglobal, chklocal; WORD_LIST *list; char *newname; /* used for local nameref references */ mklocal = flags & ASS_MKLOCAL; mkassoc = flags & ASS_MKASSOC; mkglobal = flags & ASS_MKGLOBAL; chklocal = flags & ASS_CHKLOCAL; if (mklocal && variable_context) { v = find_variable (name); /* follows namerefs */ newname = (v == 0) ? nameref_transform_name (name, flags) : v->name; if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v))) { if (readonly_p (v)) err_readonly (name); return (v); /* XXX */ } list = expand_compound_array_assignment (v, value, flags); if (mkassoc) v = make_local_assoc_variable (newname, 0); else if (v == 0 || (array_p (v) == 0 && assoc_p (v) == 0) || v->context != variable_context) v = make_local_array_variable (newname, 0); if (v) assign_compound_array_list (v, list, flags); if (list) dispose_words (list); } /* In a function but forcing assignment in global context. CHKLOCAL means to check for an existing local variable first. */ else if (mkglobal && variable_context) { v = chklocal ? find_variable (name) : 0; if (v && (local_p (v) == 0 || v->context != variable_context)) v = 0; if (v == 0) v = find_global_variable (name); if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v))) { if (readonly_p (v)) err_readonly (name); return (v); /* XXX */ } /* sanity check */ newname = (v == 0) ? nameref_transform_name (name, flags) : name; list = expand_compound_array_assignment (v, value, flags); if (v == 0 && mkassoc) v = make_new_assoc_variable (newname); else if (v && mkassoc && assoc_p (v) == 0) v = convert_var_to_assoc (v); else if (v == 0) v = make_new_array_variable (newname); else if (v && mkassoc == 0 && array_p (v) == 0) v = convert_var_to_array (v); if (v) assign_compound_array_list (v, list, flags); if (list) dispose_words (list); } else { v = assign_array_from_string (name, value, flags); if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v))) { if (readonly_p (v)) err_readonly (name); return (v); /* XXX */ } } return (v); } #endif /* Given STRING, an assignment string, get the value of the right side of the `=', and bind it to the left side. If EXPAND is true, then perform parameter expansion, command substitution, and arithmetic expansion on the right-hand side. Perform tilde expansion in any case. Do not perform word splitting on the result of expansion. */ static int do_assignment_internal (word, expand) const WORD_DESC *word; int expand; { int offset, appendop, assign_list, aflags, retval; char *name, *value, *temp; SHELL_VAR *entry; #if defined (ARRAY_VARS) char *t; int ni; #endif const char *string; if (word == 0 || word->word == 0) return 0; appendop = assign_list = aflags = 0; string = word->word; offset = assignment (string, 0); name = savestring (string); value = (char *)NULL; if (name[offset] == '=') { if (name[offset - 1] == '+') { appendop = 1; name[offset - 1] = '\0'; } name[offset] = 0; /* might need this set later */ temp = name + offset + 1; #if defined (ARRAY_VARS) if (expand && (word->flags & W_COMPASSIGN)) { assign_list = ni = 1; value = extract_array_assignment_list (temp, &ni); } else #endif if (expand && temp[0]) value = expand_string_if_necessary (temp, 0, expand_string_assignment); else value = savestring (temp); } if (value == 0) { value = (char *)xmalloc (1); value[0] = '\0'; } if (echo_command_at_execute) { if (appendop) name[offset - 1] = '+'; xtrace_print_assignment (name, value, assign_list, 1); if (appendop) name[offset - 1] = '\0'; } #define ASSIGN_RETURN(r) do { FREE (value); free (name); return (r); } while (0) if (appendop) aflags |= ASS_APPEND; #if defined (ARRAY_VARS) if (t = mbschr (name, LBRACK)) { if (assign_list) { report_error (_("%s: cannot assign list to array member"), name); ASSIGN_RETURN (0); } entry = assign_array_element (name, value, aflags); if (entry == 0) ASSIGN_RETURN (0); } else if (assign_list) { if ((word->flags & W_ASSIGNARG) && (word->flags & W_CHKLOCAL)) aflags |= ASS_CHKLOCAL; if ((word->flags & W_ASSIGNARG) && (word->flags & W_ASSNGLOBAL) == 0) aflags |= ASS_MKLOCAL; if ((word->flags & W_ASSIGNARG) && (word->flags & W_ASSNGLOBAL)) aflags |= ASS_MKGLOBAL; if (word->flags & W_ASSIGNASSOC) aflags |= ASS_MKASSOC; entry = do_compound_assignment (name, value, aflags); } else #endif /* ARRAY_VARS */ entry = bind_variable (name, value, aflags); if (entry) stupidly_hack_special_variables (entry->name); /* might be a nameref */ else stupidly_hack_special_variables (name); /* Return 1 if the assignment seems to have been performed correctly. */ if (entry == 0 || readonly_p (entry)) retval = 0; /* assignment failure */ else if (noassign_p (entry)) { set_exit_status (EXECUTION_FAILURE); retval = 1; /* error status, but not assignment failure */ } else retval = 1; if (entry && retval != 0 && noassign_p (entry) == 0) VUNSETATTR (entry, att_invisible); ASSIGN_RETURN (retval); } /* Perform the assignment statement in STRING, and expand the right side by doing tilde, command and parameter expansion. */ int do_assignment (string) char *string; { WORD_DESC td; td.flags = W_ASSIGNMENT; td.word = string; return do_assignment_internal (&td, 1); } int do_word_assignment (word, flags) WORD_DESC *word; int flags; { return do_assignment_internal (word, 1); } /* Given STRING, an assignment string, get the value of the right side of the `=', and bind it to the left side. Do not perform any word expansions on the right hand side. */ int do_assignment_no_expand (string) char *string; { WORD_DESC td; td.flags = W_ASSIGNMENT; td.word = string; return (do_assignment_internal (&td, 0)); } /*************************************************** * * * Functions to manage the positional parameters * * * ***************************************************/ /* Return the word list that corresponds to `$*'. */ WORD_LIST * list_rest_of_args () { register WORD_LIST *list, *args; int i; /* Break out of the loop as soon as one of the dollar variables is null. */ for (i = 1, list = (WORD_LIST *)NULL; i < 10 && dollar_vars[i]; i++) list = make_word_list (make_bare_word (dollar_vars[i]), list); for (args = rest_of_args; args; args = args->next) list = make_word_list (make_bare_word (args->word->word), list); return (REVERSE_LIST (list, WORD_LIST *)); } /* Return the value of a positional parameter. This handles values > 10. */ char * get_dollar_var_value (ind) intmax_t ind; { char *temp; WORD_LIST *p; if (ind < 10) temp = dollar_vars[ind] ? savestring (dollar_vars[ind]) : (char *)NULL; else /* We want something like ${11} */ { ind -= 10; for (p = rest_of_args; p && ind--; p = p->next) ; temp = p ? savestring (p->word->word) : (char *)NULL; } return (temp); } /* Make a single large string out of the dollar digit variables, and the rest_of_args. If DOLLAR_STAR is 1, then obey the special case of "$*" with respect to IFS. */ char * string_rest_of_args (dollar_star) int dollar_star; { register WORD_LIST *list; char *string; list = list_rest_of_args (); string = dollar_star ? string_list_dollar_star (list, 0, 0) : string_list (list); dispose_words (list); return (string); } /* Return a string containing the positional parameters from START to END, inclusive. If STRING[0] == '*', we obey the rules for $*, which only makes a difference if QUOTED is non-zero. If QUOTED includes Q_HERE_DOCUMENT or Q_DOUBLE_QUOTES, this returns a quoted list, otherwise no quoting chars are added. */ static char * pos_params (string, start, end, quoted, pflags) char *string; int start, end, quoted, pflags; { WORD_LIST *save, *params, *h, *t; char *ret; int i; /* see if we can short-circuit. if start == end, we want 0 parameters. */ if (start == end) return ((char *)NULL); save = params = list_rest_of_args (); if (save == 0 && start > 0) return ((char *)NULL); if (start == 0) /* handle ${@:0[:x]} specially */ { t = make_word_list (make_word (dollar_vars[0]), params); save = params = t; } for (i = start ? 1 : 0; params && i < start; i++) params = params->next; if (params == 0) { dispose_words (save); return ((char *)NULL); } for (h = t = params; params && i < end; i++) { t = params; params = params->next; } t->next = (WORD_LIST *)NULL; ret = string_list_pos_params (string[0], h, quoted, pflags); if (t != params) t->next = params; dispose_words (save); return (ret); } /******************************************************************/ /* */ /* Functions to expand strings to strings or WORD_LISTs */ /* */ /******************************************************************/ #if defined (PROCESS_SUBSTITUTION) #define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC || s == '~') #else #define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC || s == '~') #endif /* If there are any characters in STRING that require full expansion, then call FUNC to expand STRING; otherwise just perform quote removal if necessary. This returns a new string. */ static char * expand_string_if_necessary (string, quoted, func) char *string; int quoted; EXPFUNC *func; { WORD_LIST *list; size_t slen; int i, saw_quote; char *ret; DECLARE_MBSTATE; /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */ slen = (MB_CUR_MAX > 1) ? strlen (string) : 0; i = saw_quote = 0; while (string[i]) { if (EXP_CHAR (string[i])) break; else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"') saw_quote = 1; ADVANCE_CHAR (string, slen, i); } if (string[i]) { list = (*func) (string, quoted); if (list) { ret = string_list (list); dispose_words (list); } else ret = (char *)NULL; } else if (saw_quote && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) ret = string_quote_removal (string, quoted); else ret = savestring (string); return ret; } static inline char * expand_string_to_string_internal (string, quoted, func) char *string; int quoted; EXPFUNC *func; { WORD_LIST *list; char *ret; if (string == 0 || *string == '\0') return ((char *)NULL); list = (*func) (string, quoted); if (list) { ret = string_list (list); dispose_words (list); } else ret = (char *)NULL; return (ret); } char * expand_string_to_string (string, quoted) char *string; int quoted; { return (expand_string_to_string_internal (string, quoted, expand_string)); } char * expand_string_unsplit_to_string (string, quoted) char *string; int quoted; { return (expand_string_to_string_internal (string, quoted, expand_string_unsplit)); } char * expand_assignment_string_to_string (string, quoted) char *string; int quoted; { return (expand_string_to_string_internal (string, quoted, expand_string_assignment)); } char * expand_arith_string (string, quoted) char *string; int quoted; { WORD_DESC td; WORD_LIST *list, *tlist; size_t slen; int i, saw_quote; char *ret; DECLARE_MBSTATE; /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */ slen = (MB_CUR_MAX > 1) ? strlen (string) : 0; i = saw_quote = 0; while (string[i]) { if (EXP_CHAR (string[i])) break; else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"') saw_quote = 1; ADVANCE_CHAR (string, slen, i); } if (string[i]) { /* This is expanded version of expand_string_internal as it's called by expand_string_leave_quoted */ td.flags = W_NOPROCSUB|W_NOTILDE; /* don't want process substitution or tilde expansion */ #if 0 /* TAG: bash-5.2 */ if (quoted & Q_ARRAYSUB) td.flags |= W_NOCOMSUB; #endif td.word = savestring (string); list = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL); /* This takes care of the calls from expand_string_leave_quoted and expand_string */ if (list) { tlist = word_list_split (list); dispose_words (list); list = tlist; if (list) dequote_list (list); } /* This comes from expand_string_if_necessary */ if (list) { ret = string_list (list); dispose_words (list); } else ret = (char *)NULL; FREE (td.word); } else if (saw_quote && (quoted & Q_ARITH)) ret = string_quote_removal (string, quoted); else if (saw_quote && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) ret = string_quote_removal (string, quoted); else ret = savestring (string); return ret; } #if defined (COND_COMMAND) /* Just remove backslashes in STRING. Returns a new string. */ char * remove_backslashes (string) char *string; { char *r, *ret, *s; r = ret = (char *)xmalloc (strlen (string) + 1); for (s = string; s && *s; ) { if (*s == '\\') s++; if (*s == 0) break; *r++ = *s++; } *r = '\0'; return ret; } /* This needs better error handling. */ /* Expand W for use as an argument to a unary or binary operator in a [[...]] expression. If SPECIAL is 1, this is the rhs argument to the != or == operator, and should be treated as a pattern. In this case, we quote the string specially for the globbing code. If SPECIAL is 2, this is an rhs argument for the =~ operator, and should be quoted appropriately for regcomp/regexec. The caller is responsible for removing the backslashes if the unquoted word is needed later. In any case, since we don't perform word splitting, we need to do quoted null character removal. */ char * cond_expand_word (w, special) WORD_DESC *w; int special; { char *r, *p; WORD_LIST *l; int qflags; if (w->word == 0 || w->word[0] == '\0') return ((char *)NULL); expand_no_split_dollar_star = 1; w->flags |= W_NOSPLIT2; l = call_expand_word_internal (w, 0, 0, (int *)0, (int *)0); expand_no_split_dollar_star = 0; if (l) { if (special == 0) /* LHS */ { if (l->word) word_list_remove_quoted_nulls (l); dequote_list (l); r = string_list (l); } else { /* Need to figure out whether or not we should call dequote_escapes or a new dequote_ctlnul function here, and under what circumstances. */ qflags = QGLOB_CVTNULL|QGLOB_CTLESC; if (special == 2) qflags |= QGLOB_REGEXP; word_list_remove_quoted_nulls (l); p = string_list (l); r = quote_string_for_globbing (p, qflags); free (p); } dispose_words (l); } else r = (char *)NULL; return r; } #endif /* Call expand_word_internal to expand W and handle error returns. A convenience function for functions that don't want to handle any errors or free any memory before aborting. */ static WORD_LIST * call_expand_word_internal (w, q, i, c, e) WORD_DESC *w; int q, i, *c, *e; { WORD_LIST *result; result = expand_word_internal (w, q, i, c, e); if (result == &expand_word_error || result == &expand_word_fatal) { /* By convention, each time this error is returned, w->word has already been freed (it sometimes may not be in the fatal case, but that doesn't result in a memory leak because we're going to exit in most cases). */ w->word = (char *)NULL; last_command_exit_value = EXECUTION_FAILURE; exp_jump_to_top_level ((result == &expand_word_error) ? DISCARD : FORCE_EOF); /* NOTREACHED */ return (NULL); } else return (result); } /* Perform parameter expansion, command substitution, and arithmetic expansion on STRING, as if it were a word. Leave the result quoted. Since this does not perform word splitting, it leaves quoted nulls in the result. */ static WORD_LIST * expand_string_internal (string, quoted) char *string; int quoted; { WORD_DESC td; WORD_LIST *tresult; if (string == 0 || *string == 0) return ((WORD_LIST *)NULL); td.flags = 0; td.word = savestring (string); tresult = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL); FREE (td.word); return (tresult); } /* Expand STRING by performing parameter expansion, command substitution, and arithmetic expansion. Dequote the resulting WORD_LIST before returning it, but do not perform word splitting. The call to remove_quoted_nulls () is in here because word splitting normally takes care of quote removal. */ WORD_LIST * expand_string_unsplit (string, quoted) char *string; int quoted; { WORD_LIST *value; if (string == 0 || *string == '\0') return ((WORD_LIST *)NULL); expand_no_split_dollar_star = 1; value = expand_string_internal (string, quoted); expand_no_split_dollar_star = 0; if (value) { if (value->word) { remove_quoted_nulls (value->word->word); /* XXX */ value->word->flags &= ~W_HASQUOTEDNULL; } dequote_list (value); } return (value); } /* Expand the rhs of an assignment statement */ WORD_LIST * expand_string_assignment (string, quoted) char *string; int quoted; { WORD_DESC td; WORD_LIST *value; if (string == 0 || *string == '\0') return ((WORD_LIST *)NULL); expand_no_split_dollar_star = 1; #if 0 /* Other shells (ksh93) do it this way, which affects how $@ is expanded in constructs like bar=${@#0} (preserves the spaces resulting from the expansion of $@ in a context where you don't do word splitting); Posix interp 888 makes the expansion of $@ in contexts where word splitting is not performed unspecified. */ td.flags = W_ASSIGNRHS|W_NOSPLIT2; /* Posix interp 888 */ #else td.flags = W_ASSIGNRHS; #endif td.word = savestring (string); value = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL); FREE (td.word); expand_no_split_dollar_star = 0; if (value) { if (value->word) { remove_quoted_nulls (value->word->word); /* XXX */ value->word->flags &= ~W_HASQUOTEDNULL; } dequote_list (value); } return (value); } /* Expand one of the PS? prompt strings. This is a sort of combination of expand_string_unsplit and expand_string_internal, but returns the passed string when an error occurs. Might want to trap other calls to jump_to_top_level here so we don't endlessly loop. */ WORD_LIST * expand_prompt_string (string, quoted, wflags) char *string; int quoted; int wflags; { WORD_LIST *value; WORD_DESC td; if (string == 0 || *string == 0) return ((WORD_LIST *)NULL); td.flags = wflags; td.word = savestring (string); no_longjmp_on_fatal_error = 1; value = expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL); no_longjmp_on_fatal_error = 0; if (value == &expand_word_error || value == &expand_word_fatal) { value = make_word_list (make_bare_word (string), (WORD_LIST *)NULL); return value; } FREE (td.word); if (value) { if (value->word) { remove_quoted_nulls (value->word->word); /* XXX */ value->word->flags &= ~W_HASQUOTEDNULL; } dequote_list (value); } return (value); } /* Expand STRING just as if you were expanding a word, but do not dequote the resultant WORD_LIST. This is called only from within this file, and is used to correctly preserve quoted characters when expanding things like ${1+"$@"}. This does parameter expansion, command substitution, arithmetic expansion, and word splitting. */ static WORD_LIST * expand_string_leave_quoted (string, quoted) char *string; int quoted; { WORD_LIST *tlist; WORD_LIST *tresult; if (string == 0 || *string == '\0') return ((WORD_LIST *)NULL); tlist = expand_string_internal (string, quoted); if (tlist) { tresult = word_list_split (tlist); dispose_words (tlist); return (tresult); } return ((WORD_LIST *)NULL); } /* This does not perform word splitting or dequote the WORD_LIST it returns. */ static WORD_LIST * expand_string_for_rhs (string, quoted, op, pflags, dollar_at_p, expanded_p) char *string; int quoted, op, pflags; int *dollar_at_p, *expanded_p; { WORD_DESC td; WORD_LIST *tresult; int old_nosplit; if (string == 0 || *string == '\0') return (WORD_LIST *)NULL; /* We want field splitting to be determined by what is going to be done with the entire ${parameterOPword} expansion, so we don't want to split the RHS we expand here. However, the expansion of $* is determined by whether we are going to eventually perform word splitting, so we want to set this depending on whether or not are are going to be splitting: if the expansion is quoted, if the OP is `=', or if IFS is set to the empty string, we are not going to be splitting, so we set expand_no_split_dollar_star to note this to callees. We pass through PF_ASSIGNRHS as W_ASSIGNRHS if this is on the RHS of an assignment statement. */ /* The updated treatment of $* is the result of Posix interp 888 */ /* This was further clarified on the austin-group list in March, 2017 and in Posix bug 1129 */ old_nosplit = expand_no_split_dollar_star; expand_no_split_dollar_star = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || op == '=' || ifs_is_null == 0; /* XXX - was 1 */ td.flags = W_EXPANDRHS; /* expanding RHS of ${paramOPword} */ td.flags |= W_NOSPLIT2; /* no splitting, remove "" and '' */ if (pflags & PF_ASSIGNRHS) /* pass through */ td.flags |= W_ASSIGNRHS; if (op == '=') #if 0 td.flags |= W_ASSIGNRHS; /* expand b in ${a=b} like assignment */ #else td.flags |= W_ASSIGNRHS|W_NOASSNTILDE; /* expand b in ${a=b} like assignment */ #endif td.word = string; tresult = call_expand_word_internal (&td, quoted, 1, dollar_at_p, expanded_p); expand_no_split_dollar_star = old_nosplit; return (tresult); } /* This does not perform word splitting or dequote the WORD_LIST it returns and it treats $* as if it were quoted. */ static WORD_LIST * expand_string_for_pat (string, quoted, dollar_at_p, expanded_p) char *string; int quoted, *dollar_at_p, *expanded_p; { WORD_DESC td; WORD_LIST *tresult; int oexp; if (string == 0 || *string == '\0') return (WORD_LIST *)NULL; oexp = expand_no_split_dollar_star; expand_no_split_dollar_star = 1; td.flags = W_NOSPLIT2; /* no splitting, remove "" and '' */ td.word = string; tresult = call_expand_word_internal (&td, quoted, 1, dollar_at_p, expanded_p); expand_no_split_dollar_star = oexp; return (tresult); } /* Expand STRING just as if you were expanding a word. This also returns a list of words. Note that filename globbing is *NOT* done for word or string expansion, just when the shell is expanding a command. This does parameter expansion, command substitution, arithmetic expansion, and word splitting. Dequote the resultant WORD_LIST before returning. */ WORD_LIST * expand_string (string, quoted) char *string; int quoted; { WORD_LIST *result; if (string == 0 || *string == '\0') return ((WORD_LIST *)NULL); result = expand_string_leave_quoted (string, quoted); return (result ? dequote_list (result) : result); } /******************************************* * * * Functions to expand WORD_DESCs * * * *******************************************/ /* Expand WORD, performing word splitting on the result. This does parameter expansion, command substitution, arithmetic expansion, word splitting, and quote removal. */ WORD_LIST * expand_word (word, quoted) WORD_DESC *word; int quoted; { WORD_LIST *result, *tresult; tresult = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL); result = word_list_split (tresult); dispose_words (tresult); return (result ? dequote_list (result) : result); } /* Expand WORD, but do not perform word splitting on the result. This does parameter expansion, command substitution, arithmetic expansion, and quote removal. */ WORD_LIST * expand_word_unsplit (word, quoted) WORD_DESC *word; int quoted; { WORD_LIST *result; result = expand_word_leave_quoted (word, quoted); return (result ? dequote_list (result) : result); } /* Perform shell expansions on WORD, but do not perform word splitting or quote removal on the result. Virtually identical to expand_word_unsplit; could be combined if implementations don't diverge. */ WORD_LIST * expand_word_leave_quoted (word, quoted) WORD_DESC *word; int quoted; { WORD_LIST *result; expand_no_split_dollar_star = 1; if (ifs_is_null) word->flags |= W_NOSPLIT; word->flags |= W_NOSPLIT2; result = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL); expand_no_split_dollar_star = 0; return result; } /*************************************************** * * * Functions to handle quoting chars * * * ***************************************************/ /* Conventions: A string with s[0] == CTLNUL && s[1] == 0 is a quoted null string. The parser passes CTLNUL as CTLESC CTLNUL. */ /* Quote escape characters in string s, but no other characters. This is used to protect CTLESC and CTLNUL in variable values from the rest of the word expansion process after the variable is expanded (word splitting and filename generation). If IFS is null, we quote spaces as well, just in case we split on spaces later (in the case of unquoted $@, we will eventually attempt to split the entire word on spaces). Corresponding code exists in dequote_escapes. Even if we don't end up splitting on spaces, quoting spaces is not a problem. This should never be called on a string that is quoted with single or double quotes or part of a here document (effectively double-quoted). FLAGS says whether or not we are going to split the result. If we are not, and there is a CTLESC or CTLNUL in IFS, we need to quote CTLESC and CTLNUL, respectively, to prevent them from being removed as part of dequoting. */ static char * quote_escapes_internal (string, flags) const char *string; int flags; { const char *s, *send; char *t, *result; size_t slen; int quote_spaces, skip_ctlesc, skip_ctlnul, nosplit; DECLARE_MBSTATE; slen = strlen (string); send = string + slen; quote_spaces = (ifs_value && *ifs_value == 0); nosplit = (flags & PF_NOSPLIT2); for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++) { skip_ctlesc |= (nosplit == 0 && *s == CTLESC); skip_ctlnul |= (nosplit == 0 && *s == CTLNUL); } t = result = (char *)xmalloc ((slen * 2) + 1); s = string; while (*s) { if ((skip_ctlesc == 0 && *s == CTLESC) || (skip_ctlnul == 0 && *s == CTLNUL) || (quote_spaces && *s == ' ')) *t++ = CTLESC; COPY_CHAR_P (t, s, send); } *t = '\0'; return (result); } char * quote_escapes (string) const char *string; { return (quote_escapes_internal (string, 0)); } char * quote_rhs (string) const char *string; { return (quote_escapes_internal (string, PF_NOSPLIT2)); } static WORD_LIST * list_quote_escapes (list) WORD_LIST *list; { register WORD_LIST *w; char *t; for (w = list; w; w = w->next) { t = w->word->word; w->word->word = quote_escapes (t); free (t); } return list; } /* Inverse of quote_escapes; remove CTLESC protecting CTLESC or CTLNUL. The parser passes us CTLESC as CTLESC CTLESC and CTLNUL as CTLESC CTLNUL. This is necessary to make unquoted CTLESC and CTLNUL characters in the data stream pass through properly. We need to remove doubled CTLESC characters inside quoted strings before quoting the entire string, so we do not double the number of CTLESC characters. Also used by parts of the pattern substitution code. */ char * dequote_escapes (string) const char *string; { const char *s, *send; char *t, *result; size_t slen; int quote_spaces; DECLARE_MBSTATE; if (string == 0) return (char *)0; slen = strlen (string); send = string + slen; t = result = (char *)xmalloc (slen + 1); if (strchr (string, CTLESC) == 0) return (strcpy (result, string)); quote_spaces = (ifs_value && *ifs_value == 0); s = string; while (*s) { if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL || (quote_spaces && s[1] == ' '))) { s++; if (*s == '\0') break; } COPY_CHAR_P (t, s, send); } *t = '\0'; return result; } #if defined (INCLUDE_UNUSED) static WORD_LIST * list_dequote_escapes (list) WORD_LIST *list; { register WORD_LIST *w; char *t; for (w = list; w; w = w->next) { t = w->word->word; w->word->word = dequote_escapes (t); free (t); } return list; } #endif /* Return a new string with the quoted representation of character C. This turns "" into QUOTED_NULL, so the W_HASQUOTEDNULL flag needs to be set in any resultant WORD_DESC where this value is the word. */ static char * make_quoted_char (c) int c; { char *temp; temp = (char *)xmalloc (3); if (c == 0) { temp[0] = CTLNUL; temp[1] = '\0'; } else { temp[0] = CTLESC; temp[1] = c; temp[2] = '\0'; } return (temp); } /* Quote STRING, returning a new string. This turns "" into QUOTED_NULL, so the W_HASQUOTEDNULL flag needs to be set in any resultant WORD_DESC where this value is the word. */ char * quote_string (string) char *string; { register char *t; size_t slen; char *result, *send; if (*string == 0) { result = (char *)xmalloc (2); result[0] = CTLNUL; result[1] = '\0'; } else { DECLARE_MBSTATE; slen = strlen (string); send = string + slen; result = (char *)xmalloc ((slen * 2) + 1); for (t = result; string < send; ) { *t++ = CTLESC; COPY_CHAR_P (t, string, send); } *t = '\0'; } return (result); } /* De-quote quoted characters in STRING. */ char * dequote_string (string) char *string; { register char *s, *t; size_t slen; char *result, *send; DECLARE_MBSTATE; #if defined (DEBUG) if (string[0] == CTLESC && string[1] == 0) internal_inform ("dequote_string: string with bare CTLESC"); #endif slen = STRLEN (string); t = result = (char *)xmalloc (slen + 1); if (QUOTED_NULL (string)) { result[0] = '\0'; return (result); } /* A string consisting of only a single CTLESC should pass through unchanged */ if (string[0] == CTLESC && string[1] == 0) { result[0] = CTLESC; result[1] = '\0'; return (result); } /* If no character in the string can be quoted, don't bother examining each character. Just return a copy of the string passed to us. */ if (strchr (string, CTLESC) == NULL) return (strcpy (result, string)); send = string + slen; s = string; while (*s) { if (*s == CTLESC) { s++; if (*s == '\0') break; } COPY_CHAR_P (t, s, send); } *t = '\0'; return (result); } /* Quote the entire WORD_LIST list. */ static WORD_LIST * quote_list (list) WORD_LIST *list; { register WORD_LIST *w; char *t; for (w = list; w; w = w->next) { t = w->word->word; w->word->word = quote_string (t); if (*t == 0) w->word->flags |= W_HASQUOTEDNULL; /* XXX - turn on W_HASQUOTEDNULL here? */ w->word->flags |= W_QUOTED; free (t); } return list; } WORD_DESC * dequote_word (word) WORD_DESC *word; { register char *s; s = dequote_string (word->word); if (QUOTED_NULL (word->word)) word->flags &= ~W_HASQUOTEDNULL; free (word->word); word->word = s; return word; } /* De-quote quoted characters in each word in LIST. */ WORD_LIST * dequote_list (list) WORD_LIST *list; { register char *s; register WORD_LIST *tlist; for (tlist = list; tlist; tlist = tlist->next) { s = dequote_string (tlist->word->word); if (QUOTED_NULL (tlist->word->word)) tlist->word->flags &= ~W_HASQUOTEDNULL; free (tlist->word->word); tlist->word->word = s; } return list; } /* Remove CTLESC protecting a CTLESC or CTLNUL in place. Return the passed string. */ char * remove_quoted_escapes (string) char *string; { char *t; if (string) { t = dequote_escapes (string); strcpy (string, t); free (t); } return (string); } /* Remove quoted $IFS characters from STRING. Quoted IFS characters are added to protect them from word splitting, but we need to remove them if no word splitting takes place. This returns newly-allocated memory, so callers can use it to replace savestring(). */ char * remove_quoted_ifs (string) char *string; { register size_t slen; register int i, j; char *ret, *send; DECLARE_MBSTATE; slen = strlen (string); send = string + slen; i = j = 0; ret = (char *)xmalloc (slen + 1); while (i < slen) { if (string[i] == CTLESC) { i++; if (string[i] == 0 || isifs (string[i]) == 0) ret[j++] = CTLESC; if (i == slen) break; } COPY_CHAR_I (ret, j, string, send, i); } ret[j] = '\0'; return (ret); } char * remove_quoted_nulls (string) char *string; { register size_t slen; register int i, j, prev_i; DECLARE_MBSTATE; if (strchr (string, CTLNUL) == 0) /* XXX */ return string; /* XXX */ slen = strlen (string); i = j = 0; while (i < slen) { if (string[i] == CTLESC) { /* Old code had j++, but we cannot assume that i == j at this point -- what if a CTLNUL has already been removed from the string? We don't want to drop the CTLESC or recopy characters that we've already copied down. */ i++; string[j++] = CTLESC; if (i == slen) break; } else if (string[i] == CTLNUL) { i++; continue; } prev_i = i; ADVANCE_CHAR (string, slen, i); /* COPY_CHAR_I? */ if (j < prev_i) { do string[j++] = string[prev_i++]; while (prev_i < i); } else j = i; } string[j] = '\0'; return (string); } /* Perform quoted null character removal on each element of LIST. This modifies LIST. */ void word_list_remove_quoted_nulls (list) WORD_LIST *list; { register WORD_LIST *t; for (t = list; t; t = t->next) { remove_quoted_nulls (t->word->word); t->word->flags &= ~W_HASQUOTEDNULL; } } /* **************************************************************** */ /* */ /* Functions for Matching and Removing Patterns */ /* */ /* **************************************************************** */ #if defined (HANDLE_MULTIBYTE) # ifdef INCLUDE_UNUSED static unsigned char * mb_getcharlens (string, len) char *string; int len; { int i, offset, last; unsigned char *ret; char *p; DECLARE_MBSTATE; i = offset = 0; last = 0; ret = (unsigned char *)xmalloc (len); memset (ret, 0, len); while (string[last]) { ADVANCE_CHAR (string, len, offset); ret[last] = offset - last; last = offset; } return ret; } # endif #endif /* Remove the portion of PARAM matched by PATTERN according to OP, where OP can have one of 4 values: RP_LONG_LEFT remove longest matching portion at start of PARAM RP_SHORT_LEFT remove shortest matching portion at start of PARAM RP_LONG_RIGHT remove longest matching portion at end of PARAM RP_SHORT_RIGHT remove shortest matching portion at end of PARAM */ #define RP_LONG_LEFT 1 #define RP_SHORT_LEFT 2 #define RP_LONG_RIGHT 3 #define RP_SHORT_RIGHT 4 /* Returns its first argument if nothing matched; new memory otherwise */ static char * remove_upattern (param, pattern, op) char *param, *pattern; int op; { register size_t len; register char *end; register char *p, *ret, c; len = STRLEN (param); end = param + len; switch (op) { case RP_LONG_LEFT: /* remove longest match at start */ for (p = end; p >= param; p--) { c = *p; *p = '\0'; if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH) { *p = c; return (savestring (p)); } *p = c; } break; case RP_SHORT_LEFT: /* remove shortest match at start */ for (p = param; p <= end; p++) { c = *p; *p = '\0'; if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH) { *p = c; return (savestring (p)); } *p = c; } break; case RP_LONG_RIGHT: /* remove longest match at end */ for (p = param; p <= end; p++) { if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH) { c = *p; *p = '\0'; ret = savestring (param); *p = c; return (ret); } } break; case RP_SHORT_RIGHT: /* remove shortest match at end */ for (p = end; p >= param; p--) { if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH) { c = *p; *p = '\0'; ret = savestring (param); *p = c; return (ret); } } break; } return (param); /* no match, return original string */ } #if defined (HANDLE_MULTIBYTE) /* Returns its first argument if nothing matched; new memory otherwise */ static wchar_t * remove_wpattern (wparam, wstrlen, wpattern, op) wchar_t *wparam; size_t wstrlen; wchar_t *wpattern; int op; { wchar_t wc, *ret; int n; switch (op) { case RP_LONG_LEFT: /* remove longest match at start */ for (n = wstrlen; n >= 0; n--) { wc = wparam[n]; wparam[n] = L'\0'; if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH) { wparam[n] = wc; return (wcsdup (wparam + n)); } wparam[n] = wc; } break; case RP_SHORT_LEFT: /* remove shortest match at start */ for (n = 0; n <= wstrlen; n++) { wc = wparam[n]; wparam[n] = L'\0'; if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH) { wparam[n] = wc; return (wcsdup (wparam + n)); } wparam[n] = wc; } break; case RP_LONG_RIGHT: /* remove longest match at end */ for (n = 0; n <= wstrlen; n++) { if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH) { wc = wparam[n]; wparam[n] = L'\0'; ret = wcsdup (wparam); wparam[n] = wc; return (ret); } } break; case RP_SHORT_RIGHT: /* remove shortest match at end */ for (n = wstrlen; n >= 0; n--) { if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH) { wc = wparam[n]; wparam[n] = L'\0'; ret = wcsdup (wparam); wparam[n] = wc; return (ret); } } break; } return (wparam); /* no match, return original string */ } #endif /* HANDLE_MULTIBYTE */ static char * remove_pattern (param, pattern, op) char *param, *pattern; int op; { char *xret; if (param == NULL) return (param); if (*param == '\0' || pattern == NULL || *pattern == '\0') /* minor optimization */ return (savestring (param)); #if defined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1) { wchar_t *ret, *oret; size_t n; wchar_t *wparam, *wpattern; mbstate_t ps; /* XXX - could optimize here by checking param and pattern for multibyte chars with mbsmbchar and calling remove_upattern. */ n = xdupmbstowcs (&wpattern, NULL, pattern); if (n == (size_t)-1) { xret = remove_upattern (param, pattern, op); return ((xret == param) ? savestring (param) : xret); } n = xdupmbstowcs (&wparam, NULL, param); if (n == (size_t)-1) { free (wpattern); xret = remove_upattern (param, pattern, op); return ((xret == param) ? savestring (param) : xret); } oret = ret = remove_wpattern (wparam, n, wpattern, op); /* Don't bother to convert wparam back to multibyte string if nothing matched; just return copy of original string */ if (ret == wparam) { free (wparam); free (wpattern); return (savestring (param)); } free (wparam); free (wpattern); n = strlen (param); xret = (char *)xmalloc (n + 1); memset (&ps, '\0', sizeof (mbstate_t)); n = wcsrtombs (xret, (const wchar_t **)&ret, n, &ps); xret[n] = '\0'; /* just to make sure */ free (oret); return xret; } else #endif { xret = remove_upattern (param, pattern, op); return ((xret == param) ? savestring (param) : xret); } } /* Match PAT anywhere in STRING and return the match boundaries. This returns 1 in case of a successful match, 0 otherwise. SP and EP are pointers into the string where the match begins and ends, respectively. MTYPE controls what kind of match is attempted. MATCH_BEG and MATCH_END anchor the match at the beginning and end of the string, respectively. The longest match is returned. */ static int match_upattern (string, pat, mtype, sp, ep) char *string, *pat; int mtype; char **sp, **ep; { int c, mlen; size_t len; register char *p, *p1, *npat; char *end; /* If the pattern doesn't match anywhere in the string, go ahead and short-circuit right away. A minor optimization, saves a bunch of unnecessary calls to strmatch (up to N calls for a string of N characters) if the match is unsuccessful. To preserve the semantics of the substring matches below, we make sure that the pattern has `*' as first and last character, making a new pattern if necessary. */ /* XXX - check this later if I ever implement `**' with special meaning, since this will potentially result in `**' at the beginning or end */ len = STRLEN (pat); if (pat[0] != '*' || (pat[0] == '*' && pat[1] == LPAREN && extended_glob) || pat[len - 1] != '*') { int unescaped_backslash; char *pp; p = npat = (char *)xmalloc (len + 3); p1 = pat; if ((mtype != MATCH_BEG) && (*p1 != '*' || (*p1 == '*' && p1[1] == LPAREN && extended_glob))) *p++ = '*'; while (*p1) *p++ = *p1++; #if 1 /* Need to also handle a pattern that ends with an unescaped backslash. For right now, we ignore it because the pattern matching code will fail the match anyway */ /* If the pattern ends with a `*' we leave it alone if it's preceded by an even number of backslashes, but if it's escaped by a backslash we need to add another `*'. */ if ((mtype != MATCH_END) && (p1[-1] == '*' && (unescaped_backslash = p1[-2] == '\\'))) { pp = p1 - 3; while (pp >= pat && *pp-- == '\\') unescaped_backslash = 1 - unescaped_backslash; if (unescaped_backslash) *p++ = '*'; } else if (mtype != MATCH_END && p1[-1] != '*') *p++ = '*'; #else if (p1[-1] != '*' || p1[-2] == '\\') *p++ = '*'; #endif *p = '\0'; } else npat = pat; c = strmatch (npat, string, FNMATCH_EXTFLAG | FNMATCH_IGNCASE); if (npat != pat) free (npat); if (c == FNM_NOMATCH) return (0); len = STRLEN (string); end = string + len; mlen = umatchlen (pat, len); if (mlen > (int)len) return (0); switch (mtype) { case MATCH_ANY: for (p = string; p <= end; p++) { if (match_pattern_char (pat, p, FNMATCH_IGNCASE)) { p1 = (mlen == -1) ? end : p + mlen; /* p1 - p = length of portion of string to be considered p = current position in string mlen = number of characters consumed by match (-1 for entire string) end = end of string we want to break immediately if the potential match len is greater than the number of characters remaining in the string */ if (p1 > end) break; for ( ; p1 >= p; p1--) { c = *p1; *p1 = '\0'; if (strmatch (pat, p, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { *p1 = c; *sp = p; *ep = p1; return 1; } *p1 = c; #if 1 /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; #endif } } } return (0); case MATCH_BEG: if (match_pattern_char (pat, string, FNMATCH_IGNCASE) == 0) return (0); for (p = (mlen == -1) ? end : string + mlen; p >= string; p--) { c = *p; *p = '\0'; if (strmatch (pat, string, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { *p = c; *sp = string; *ep = p; return 1; } *p = c; /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; } return (0); case MATCH_END: for (p = end - ((mlen == -1) ? len : mlen); p <= end; p++) { if (strmatch (pat, p, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { *sp = p; *ep = end; return 1; } /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; } return (0); } return (0); } #if defined (HANDLE_MULTIBYTE) #define WFOLD(c) (match_ignore_case && iswupper (c) ? towlower (c) : (c)) /* Match WPAT anywhere in WSTRING and return the match boundaries. This returns 1 in case of a successful match, 0 otherwise. Wide character version. */ static int match_wpattern (wstring, indices, wstrlen, wpat, mtype, sp, ep) wchar_t *wstring; char **indices; size_t wstrlen; wchar_t *wpat; int mtype; char **sp, **ep; { wchar_t wc, *wp, *nwpat, *wp1; size_t len; int mlen; int n, n1, n2, simple; simple = (wpat[0] != L'\\' && wpat[0] != L'*' && wpat[0] != L'?' && wpat[0] != L'['); #if defined (EXTENDED_GLOB) if (extended_glob) simple &= (wpat[1] != L'(' || (wpat[0] != L'*' && wpat[0] != L'?' && wpat[0] != L'+' && wpat[0] != L'!' && wpat[0] != L'@')); /*)*/ #endif /* If the pattern doesn't match anywhere in the string, go ahead and short-circuit right away. A minor optimization, saves a bunch of unnecessary calls to strmatch (up to N calls for a string of N characters) if the match is unsuccessful. To preserve the semantics of the substring matches below, we make sure that the pattern has `*' as first and last character, making a new pattern if necessary. */ len = wcslen (wpat); if (wpat[0] != L'*' || (wpat[0] == L'*' && wpat[1] == WLPAREN && extended_glob) || wpat[len - 1] != L'*') { int unescaped_backslash; wchar_t *wpp; wp = nwpat = (wchar_t *)xmalloc ((len + 3) * sizeof (wchar_t)); wp1 = wpat; if (*wp1 != L'*' || (*wp1 == '*' && wp1[1] == WLPAREN && extended_glob)) *wp++ = L'*'; while (*wp1 != L'\0') *wp++ = *wp1++; #if 1 /* See comments above in match_upattern. */ if (wp1[-1] == L'*' && (unescaped_backslash = wp1[-2] == L'\\')) { wpp = wp1 - 3; while (wpp >= wpat && *wpp-- == L'\\') unescaped_backslash = 1 - unescaped_backslash; if (unescaped_backslash) *wp++ = L'*'; } else if (wp1[-1] != L'*') *wp++ = L'*'; #else if (wp1[-1] != L'*' || wp1[-2] == L'\\') *wp++ = L'*'; #endif *wp = '\0'; } else nwpat = wpat; len = wcsmatch (nwpat, wstring, FNMATCH_EXTFLAG | FNMATCH_IGNCASE); if (nwpat != wpat) free (nwpat); if (len == FNM_NOMATCH) return (0); mlen = wmatchlen (wpat, wstrlen); if (mlen > (int)wstrlen) return (0); /* itrace("wmatchlen (%ls) -> %d", wpat, mlen); */ switch (mtype) { case MATCH_ANY: for (n = 0; n <= wstrlen; n++) { n2 = simple ? (WFOLD(*wpat) == WFOLD(wstring[n])) : match_pattern_wchar (wpat, wstring + n, FNMATCH_IGNCASE); if (n2) { n1 = (mlen == -1) ? wstrlen : n + mlen; if (n1 > wstrlen) break; for ( ; n1 >= n; n1--) { wc = wstring[n1]; wstring[n1] = L'\0'; if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { wstring[n1] = wc; *sp = indices[n]; *ep = indices[n1]; return 1; } wstring[n1] = wc; /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; } } } return (0); case MATCH_BEG: if (match_pattern_wchar (wpat, wstring, FNMATCH_IGNCASE) == 0) return (0); for (n = (mlen == -1) ? wstrlen : mlen; n >= 0; n--) { wc = wstring[n]; wstring[n] = L'\0'; if (wcsmatch (wpat, wstring, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { wstring[n] = wc; *sp = indices[0]; *ep = indices[n]; return 1; } wstring[n] = wc; /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; } return (0); case MATCH_END: for (n = wstrlen - ((mlen == -1) ? wstrlen : mlen); n <= wstrlen; n++) { if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0) { *sp = indices[n]; *ep = indices[wstrlen]; return 1; } /* If MLEN != -1, we have a fixed length pattern. */ if (mlen != -1) break; } return (0); } return (0); } #undef WFOLD #endif /* HANDLE_MULTIBYTE */ static int match_pattern (string, pat, mtype, sp, ep) char *string, *pat; int mtype; char **sp, **ep; { #if defined (HANDLE_MULTIBYTE) int ret; size_t n; wchar_t *wstring, *wpat; char **indices; #endif if (string == 0 || pat == 0 || *pat == 0) return (0); #if defined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1) { if (mbsmbchar (string) == 0 && mbsmbchar (pat) == 0) return (match_upattern (string, pat, mtype, sp, ep)); n = xdupmbstowcs (&wpat, NULL, pat); if (n == (size_t)-1) return (match_upattern (string, pat, mtype, sp, ep)); n = xdupmbstowcs (&wstring, &indices, string); if (n == (size_t)-1) { free (wpat); return (match_upattern (string, pat, mtype, sp, ep)); } ret = match_wpattern (wstring, indices, n, wpat, mtype, sp, ep); free (wpat); free (wstring); free (indices); return (ret); } else #endif return (match_upattern (string, pat, mtype, sp, ep)); } static int getpatspec (c, value) int c; char *value; { if (c == '#') return ((*value == '#') ? RP_LONG_LEFT : RP_SHORT_LEFT); else /* c == '%' */ return ((*value == '%') ? RP_LONG_RIGHT : RP_SHORT_RIGHT); } /* Posix.2 says that the WORD should be run through tilde expansion, parameter expansion, command substitution and arithmetic expansion. This leaves the result quoted, so quote_string_for_globbing () has to be called to fix it up for strmatch (). If QUOTED is non-zero, it means that the entire expression was enclosed in double quotes. This means that quoting characters in the pattern do not make any special pattern characters quoted. For example, the `*' in the following retains its special meaning: "${foo#'*'}". */ static char * getpattern (value, quoted, expandpat) char *value; int quoted, expandpat; { char *pat, *tword; WORD_LIST *l; #if 0 int i; #endif /* There is a problem here: how to handle single or double quotes in the pattern string when the whole expression is between double quotes? POSIX.2 says that enclosing double quotes do not cause the pattern to be quoted, but does that leave us a problem with @ and array[@] and their expansions inside a pattern? */ #if 0 if (expandpat && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *tword) { i = 0; pat = string_extract_double_quoted (tword, &i, SX_STRIPDQ); free (tword); tword = pat; } #endif /* expand_string_for_pat () leaves WORD quoted and does not perform word splitting. */ l = *value ? expand_string_for_pat (value, (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? Q_PATQUOTE : quoted, (int *)NULL, (int *)NULL) : (WORD_LIST *)0; if (l) word_list_remove_quoted_nulls (l); pat = string_list (l); dispose_words (l); if (pat) { tword = quote_string_for_globbing (pat, QGLOB_CVTNULL); free (pat); pat = tword; } return (pat); } #if 0 /* Handle removing a pattern from a string as a result of ${name%[%]value} or ${name#[#]value}. */ static char * variable_remove_pattern (value, pattern, patspec, quoted) char *value, *pattern; int patspec, quoted; { char *tword; tword = remove_pattern (value, pattern, patspec); return (tword); } #endif static char * list_remove_pattern (list, pattern, patspec, itype, quoted) WORD_LIST *list; char *pattern; int patspec, itype, quoted; { WORD_LIST *new, *l; WORD_DESC *w; char *tword; for (new = (WORD_LIST *)NULL, l = list; l; l = l->next) { tword = remove_pattern (l->word->word, pattern, patspec); w = alloc_word_desc (); w->word = tword ? tword : savestring (""); new = make_word_list (w, new); } l = REVERSE_LIST (new, WORD_LIST *); tword = string_list_pos_params (itype, l, quoted, 0); dispose_words (l); return (tword); } static char * parameter_list_remove_pattern (itype, pattern, patspec, quoted) int itype; char *pattern; int patspec, quoted; { char *ret; WORD_LIST *list; list = list_rest_of_args (); if (list == 0) return ((char *)NULL); ret = list_remove_pattern (list, pattern, patspec, itype, quoted); dispose_words (list); return (ret); } #if defined (ARRAY_VARS) static char * array_remove_pattern (var, pattern, patspec, starsub, quoted) SHELL_VAR *var; char *pattern; int patspec; int starsub; /* so we can figure out how it's indexed */ int quoted; { ARRAY *a; HASH_TABLE *h; int itype; char *ret; WORD_LIST *list; SHELL_VAR *v; v = var; /* XXX - for now */ itype = starsub ? '*' : '@'; a = (v && array_p (v)) ? array_cell (v) : 0; h = (v && assoc_p (v)) ? assoc_cell (v) : 0; list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0); if (list == 0) return ((char *)NULL); ret = list_remove_pattern (list, pattern, patspec, itype, quoted); dispose_words (list); return ret; } #endif /* ARRAY_VARS */ static char * parameter_brace_remove_pattern (varname, value, ind, patstr, rtype, quoted, flags) char *varname, *value; int ind; char *patstr; int rtype, quoted, flags; { int vtype, patspec, starsub; char *temp1, *val, *pattern, *oname; SHELL_VAR *v; if (value == 0) return ((char *)NULL); oname = this_command_name; this_command_name = varname; vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val); if (vtype == -1) { this_command_name = oname; return ((char *)NULL); } starsub = vtype & VT_STARSUB; vtype &= ~VT_STARSUB; patspec = getpatspec (rtype, patstr); if (patspec == RP_LONG_LEFT || patspec == RP_LONG_RIGHT) patstr++; /* Need to pass getpattern newly-allocated memory in case of expansion -- the expansion code will free the passed string on an error. */ temp1 = savestring (patstr); pattern = getpattern (temp1, quoted, 1); free (temp1); temp1 = (char *)NULL; /* shut up gcc */ switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: temp1 = remove_pattern (val, pattern, patspec); if (vtype == VT_VARIABLE) FREE (val); if (temp1) { val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_string (temp1) : quote_escapes (temp1); free (temp1); temp1 = val; } break; #if defined (ARRAY_VARS) case VT_ARRAYVAR: temp1 = array_remove_pattern (v, pattern, patspec, starsub, quoted); if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) { val = quote_escapes (temp1); free (temp1); temp1 = val; } break; #endif case VT_POSPARMS: temp1 = parameter_list_remove_pattern (varname[0], pattern, patspec, quoted); if (temp1 && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) { val = quote_escapes (temp1); free (temp1); temp1 = val; } break; } this_command_name = oname; FREE (pattern); return temp1; } #if defined (PROCESS_SUBSTITUTION) static void reap_some_procsubs PARAMS((int)); /*****************************************************************/ /* */ /* Hacking Process Substitution */ /* */ /*****************************************************************/ #if !defined (HAVE_DEV_FD) /* Named pipes must be removed explicitly with `unlink'. This keeps a list of FIFOs the shell has open. unlink_fifo_list will walk the list and unlink the ones that don't have a living process on the other end. unlink_all_fifos will walk the list and unconditionally unlink them, trying to open and close the FIFO first to release any child processes sleeping on the FIFO. add_fifo_list adds the name of an open FIFO to the list. NFIFO is a count of the number of FIFOs in the list. */ #define FIFO_INCR 20 /* PROC value of -1 means the process has been reaped and the FIFO needs to be removed. PROC value of 0 means the slot is unused. */ struct temp_fifo { char *file; pid_t proc; }; static struct temp_fifo *fifo_list = (struct temp_fifo *)NULL; static int nfifo; static int fifo_list_size; void clear_fifo_list () { int i; for (i = 0; i < fifo_list_size; i++) { if (fifo_list[i].file) free (fifo_list[i].file); fifo_list[i].file = NULL; fifo_list[i].proc = 0; } nfifo = 0; } void * copy_fifo_list (sizep) int *sizep; { if (sizep) *sizep = 0; return (void *)NULL; } static void add_fifo_list (pathname) char *pathname; { int osize, i; if (nfifo >= fifo_list_size - 1) { osize = fifo_list_size; fifo_list_size += FIFO_INCR; fifo_list = (struct temp_fifo *)xrealloc (fifo_list, fifo_list_size * sizeof (struct temp_fifo)); for (i = osize; i < fifo_list_size; i++) { fifo_list[i].file = (char *)NULL; fifo_list[i].proc = 0; /* unused */ } } fifo_list[nfifo].file = savestring (pathname); nfifo++; } void unlink_fifo (i) int i; { if ((fifo_list[i].proc == (pid_t)-1) || (fifo_list[i].proc > 0 && (kill(fifo_list[i].proc, 0) == -1))) { unlink (fifo_list[i].file); free (fifo_list[i].file); fifo_list[i].file = (char *)NULL; fifo_list[i].proc = 0; } } void unlink_fifo_list () { int saved, i, j; if (nfifo == 0) return; for (i = saved = 0; i < nfifo; i++) { if ((fifo_list[i].proc == (pid_t)-1) || (fifo_list[i].proc > 0 && (kill(fifo_list[i].proc, 0) == -1))) { unlink (fifo_list[i].file); free (fifo_list[i].file); fifo_list[i].file = (char *)NULL; fifo_list[i].proc = 0; } else saved++; } /* If we didn't remove some of the FIFOs, compact the list. */ if (saved) { for (i = j = 0; i < nfifo; i++) if (fifo_list[i].file) { if (i != j) { fifo_list[j].file = fifo_list[i].file; fifo_list[j].proc = fifo_list[i].proc; fifo_list[i].file = (char *)NULL; fifo_list[i].proc = 0; } j++; } nfifo = j; } else nfifo = 0; } void unlink_all_fifos () { int i, fd; if (nfifo == 0) return; for (i = 0; i < nfifo; i++) { fifo_list[i].proc = (pid_t)-1; fd = open (fifo_list[i].file, O_RDWR|O_NONBLOCK); unlink_fifo (i); if (fd >= 0) close (fd); } nfifo = 0; } /* Take LIST, which is a bitmap denoting active FIFOs in fifo_list from some point in the past, and close all open FIFOs in fifo_list that are not marked as active in LIST. If LIST is NULL, close everything in fifo_list. LSIZE is the number of elements in LIST, in case it's larger than fifo_list_size (size of fifo_list). */ void close_new_fifos (list, lsize) void *list; int lsize; { int i; char *plist; if (list == 0) { unlink_fifo_list (); return; } for (plist = (char *)list, i = 0; i < lsize; i++) if (plist[i] == 0 && i < fifo_list_size && fifo_list[i].proc != -1) unlink_fifo (i); for (i = lsize; i < fifo_list_size; i++) unlink_fifo (i); } int find_procsub_child (pid) pid_t pid; { int i; for (i = 0; i < nfifo; i++) if (fifo_list[i].proc == pid) return i; return -1; } void set_procsub_status (ind, pid, status) int ind; pid_t pid; int status; { if (ind >= 0 && ind < nfifo) fifo_list[ind].proc = (pid_t)-1; /* sentinel */ } /* If we've marked the process for this procsub as dead, close the associated file descriptor and delete the FIFO. */ static void reap_some_procsubs (max) int max; { int i; for (i = 0; i < max; i++) if (fifo_list[i].proc == (pid_t)-1) /* reaped */ unlink_fifo (i); } void reap_procsubs () { reap_some_procsubs (nfifo); } #if 0 /* UNUSED */ void wait_procsubs () { int i, r; for (i = 0; i < nfifo; i++) { if (fifo_list[i].proc != (pid_t)-1 && fifo_list[i].proc > 0) { r = wait_for (fifo_list[i].proc, 0); save_proc_status (fifo_list[i].proc, r); fifo_list[i].proc = (pid_t)-1; } } } #endif int fifos_pending () { return nfifo; } int num_fifos () { return nfifo; } static char * make_named_pipe () { char *tname; tname = sh_mktmpname ("sh-np", MT_USERANDOM|MT_USETMPDIR); if (mkfifo (tname, 0600) < 0) { free (tname); return ((char *)NULL); } add_fifo_list (tname); return (tname); } #else /* HAVE_DEV_FD */ /* DEV_FD_LIST is a bitmap of file descriptors attached to pipes the shell has open to children. NFDS is a count of the number of bits currently set in DEV_FD_LIST. TOTFDS is a count of the highest possible number of open files. */ /* dev_fd_list[I] value of -1 means the process has been reaped and file descriptor I needs to be closed. Value of 0 means the slot is unused. */ static pid_t *dev_fd_list = (pid_t *)NULL; static int nfds; static int totfds; /* The highest possible number of open files. */ void clear_fifo (i) int i; { if (dev_fd_list[i]) { dev_fd_list[i] = 0; nfds--; } } void clear_fifo_list () { register int i; if (nfds == 0) return; for (i = 0; nfds && i < totfds; i++) clear_fifo (i); nfds = 0; } void * copy_fifo_list (sizep) int *sizep; { void *ret; if (nfds == 0 || totfds == 0) { if (sizep) *sizep = 0; return (void *)NULL; } if (sizep) *sizep = totfds; ret = xmalloc (totfds * sizeof (pid_t)); return (memcpy (ret, dev_fd_list, totfds * sizeof (pid_t))); } static void add_fifo_list (fd) int fd; { if (dev_fd_list == 0 || fd >= totfds) { int ofds; ofds = totfds; totfds = getdtablesize (); if (totfds < 0 || totfds > 256) totfds = 256; if (fd >= totfds) totfds = fd + 2; dev_fd_list = (pid_t *)xrealloc (dev_fd_list, totfds * sizeof (dev_fd_list[0])); /* XXX - might need a loop for this */ memset (dev_fd_list + ofds, '\0', (totfds - ofds) * sizeof (pid_t)); } dev_fd_list[fd] = 1; /* marker; updated later */ nfds++; } int fifos_pending () { return 0; /* used for cleanup; not needed with /dev/fd */ } int num_fifos () { return nfds; } void unlink_fifo (fd) int fd; { if (dev_fd_list[fd]) { close (fd); dev_fd_list[fd] = 0; nfds--; } } void unlink_fifo_list () { register int i; if (nfds == 0) return; for (i = totfds-1; nfds && i >= 0; i--) unlink_fifo (i); nfds = 0; } void unlink_all_fifos () { unlink_fifo_list (); } /* Take LIST, which is a snapshot copy of dev_fd_list from some point in the past, and close all open fds in dev_fd_list that are not marked as open in LIST. If LIST is NULL, close everything in dev_fd_list. LSIZE is the number of elements in LIST, in case it's larger than totfds (size of dev_fd_list). */ void close_new_fifos (list, lsize) void *list; int lsize; { int i; pid_t *plist; if (list == 0) { unlink_fifo_list (); return; } for (plist = (pid_t *)list, i = 0; i < lsize; i++) if (plist[i] == 0 && i < totfds && dev_fd_list[i]) unlink_fifo (i); for (i = lsize; i < totfds; i++) unlink_fifo (i); } int find_procsub_child (pid) pid_t pid; { int i; if (nfds == 0) return -1; for (i = 0; i < totfds; i++) if (dev_fd_list[i] == pid) return i; return -1; } void set_procsub_status (ind, pid, status) int ind; pid_t pid; int status; { if (ind >= 0 && ind < totfds) dev_fd_list[ind] = (pid_t)-1; /* sentinel */ } /* If we've marked the process for this procsub as dead, close the associated file descriptor. */ static void reap_some_procsubs (max) int max; { int i; for (i = 0; nfds > 0 && i < max; i++) if (dev_fd_list[i] == (pid_t)-1) unlink_fifo (i); } void reap_procsubs () { reap_some_procsubs (totfds); } #if 0 /* UNUSED */ void wait_procsubs () { int i, r; for (i = 0; nfds > 0 && i < totfds; i++) { if (dev_fd_list[i] != (pid_t)-1 && dev_fd_list[i] > 0) { r = wait_for (dev_fd_list[i], 0); save_proc_status (dev_fd_list[i], r); dev_fd_list[i] = (pid_t)-1; } } } #endif #if defined (NOTDEF) print_dev_fd_list () { register int i; fprintf (stderr, "pid %ld: dev_fd_list:", (long)getpid ()); fflush (stderr); for (i = 0; i < totfds; i++) { if (dev_fd_list[i]) fprintf (stderr, " %d", i); } fprintf (stderr, "\n"); } #endif /* NOTDEF */ static char * make_dev_fd_filename (fd) int fd; { char *ret, intbuf[INT_STRLEN_BOUND (int) + 1], *p; ret = (char *)xmalloc (sizeof (DEV_FD_PREFIX) + 8); strcpy (ret, DEV_FD_PREFIX); p = inttostr (fd, intbuf, sizeof (intbuf)); strcpy (ret + sizeof (DEV_FD_PREFIX) - 1, p); add_fifo_list (fd); return (ret); } #endif /* HAVE_DEV_FD */ /* Return a filename that will open a connection to the process defined by executing STRING. HAVE_DEV_FD, if defined, means open a pipe and return a filename in /dev/fd corresponding to a descriptor that is one of the ends of the pipe. If not defined, we use named pipes on systems that have them. Systems without /dev/fd and named pipes are out of luck. OPEN_FOR_READ_IN_CHILD, if 1, means open the named pipe for reading or use the read end of the pipe and dup that file descriptor to fd 0 in the child. If OPEN_FOR_READ_IN_CHILD is 0, we open the named pipe for writing or use the write end of the pipe in the child, and dup that file descriptor to fd 1 in the child. The parent does the opposite. */ static char * process_substitute (string, open_for_read_in_child) char *string; int open_for_read_in_child; { char *pathname; int fd, result, rc, function_value; pid_t old_pid, pid; #if defined (HAVE_DEV_FD) int parent_pipe_fd, child_pipe_fd; int fildes[2]; #endif /* HAVE_DEV_FD */ #if defined (JOB_CONTROL) pid_t old_pipeline_pgrp; #endif if (!string || !*string || wordexp_only) return ((char *)NULL); #if !defined (HAVE_DEV_FD) pathname = make_named_pipe (); #else /* HAVE_DEV_FD */ if (pipe (fildes) < 0) { sys_error ("%s", _("cannot make pipe for process substitution")); return ((char *)NULL); } /* If OPEN_FOR_READ_IN_CHILD == 1, we want to use the write end of the pipe in the parent, otherwise the read end. */ parent_pipe_fd = fildes[open_for_read_in_child]; child_pipe_fd = fildes[1 - open_for_read_in_child]; /* Move the parent end of the pipe to some high file descriptor, to avoid clashes with FDs used by the script. */ parent_pipe_fd = move_to_high_fd (parent_pipe_fd, 1, 64); pathname = make_dev_fd_filename (parent_pipe_fd); #endif /* HAVE_DEV_FD */ if (pathname == 0) { sys_error ("%s", _("cannot make pipe for process substitution")); return ((char *)NULL); } old_pid = last_made_pid; #if defined (JOB_CONTROL) old_pipeline_pgrp = pipeline_pgrp; if (pipeline_pgrp == 0 || (subshell_environment & (SUBSHELL_PIPE|SUBSHELL_FORK|SUBSHELL_ASYNC)) == 0) pipeline_pgrp = shell_pgrp; save_pipeline (1); #endif /* JOB_CONTROL */ pid = make_child ((char *)NULL, FORK_ASYNC); if (pid == 0) { #if 0 int old_interactive; old_interactive = interactive; #endif /* The currently-executing shell is not interactive */ interactive = 0; reset_terminating_signals (); /* XXX */ free_pushed_string_input (); /* Cancel traps, in trap.c. */ restore_original_signals (); /* XXX - what about special builtins? bash-4.2 */ QUIT; /* catch any interrupts we got post-fork */ setup_async_signals (); #if 0 if (open_for_read_in_child == 0 && old_interactive && (bash_input.type == st_stdin || bash_input.type == st_stream)) async_redirect_stdin (); #endif subshell_environment |= SUBSHELL_COMSUB|SUBSHELL_PROCSUB|SUBSHELL_ASYNC; /* We don't inherit the verbose option for command substitutions now, so let's try it for process substitutions. */ change_flag ('v', FLAG_OFF); /* if we're expanding a redirection, we shouldn't have access to the temporary environment, but commands in the subshell should have access to their own temporary environment. */ if (expanding_redir) flush_temporary_env (); } #if defined (JOB_CONTROL) set_sigchld_handler (); stop_making_children (); /* XXX - should we only do this in the parent? (as in command subst) */ pipeline_pgrp = old_pipeline_pgrp; #else stop_making_children (); #endif /* JOB_CONTROL */ if (pid < 0) { sys_error ("%s", _("cannot make child for process substitution")); free (pathname); #if defined (HAVE_DEV_FD) close (parent_pipe_fd); close (child_pipe_fd); #endif /* HAVE_DEV_FD */ #if defined (JOB_CONTROL) restore_pipeline (1); #endif return ((char *)NULL); } if (pid > 0) { #if defined (JOB_CONTROL) last_procsub_child = restore_pipeline (0); /* We assume that last_procsub_child->next == last_procsub_child because of how jobs.c:add_process() works. */ last_procsub_child->next = 0; procsub_add (last_procsub_child); #endif #if defined (HAVE_DEV_FD) dev_fd_list[parent_pipe_fd] = pid; #else fifo_list[nfifo-1].proc = pid; #endif last_made_pid = old_pid; #if defined (JOB_CONTROL) && defined (PGRP_PIPE) close_pgrp_pipe (); #endif /* JOB_CONTROL && PGRP_PIPE */ #if defined (HAVE_DEV_FD) close (child_pipe_fd); #endif /* HAVE_DEV_FD */ return (pathname); } set_sigint_handler (); #if defined (JOB_CONTROL) /* make sure we don't have any job control */ set_job_control (0); /* Clear out any existing list of process substitutions */ procsub_clear (); /* The idea is that we want all the jobs we start from an async process substitution to be in the same process group, but not the same pgrp as our parent shell, since we don't want to affect our parent shell's jobs if we get a SIGHUP and end up calling hangup_all_jobs, for example. If pipeline_pgrp != shell_pgrp, we assume that there is a job control shell somewhere in our parent process chain (since make_child initializes pipeline_pgrp to shell_pgrp if job_control == 0). What we do in this case is to set pipeline_pgrp to our PID, so all jobs started by this process have that same pgrp and we are basically the process group leader. This should not have negative effects on child processes surviving after we exit, since we wait for the children we create, but that is something to watch for. */ if (pipeline_pgrp != shell_pgrp) pipeline_pgrp = getpid (); #endif /* JOB_CONTROL */ #if !defined (HAVE_DEV_FD) /* Open the named pipe in the child. */ fd = open (pathname, open_for_read_in_child ? O_RDONLY : O_WRONLY); if (fd < 0) { /* Two separate strings for ease of translation. */ if (open_for_read_in_child) sys_error (_("cannot open named pipe %s for reading"), pathname); else sys_error (_("cannot open named pipe %s for writing"), pathname); exit (127); } if (open_for_read_in_child) { if (sh_unset_nodelay_mode (fd) < 0) { sys_error (_("cannot reset nodelay mode for fd %d"), fd); exit (127); } } #else /* HAVE_DEV_FD */ fd = child_pipe_fd; #endif /* HAVE_DEV_FD */ /* Discard buffered stdio output before replacing the underlying file descriptor. */ if (open_for_read_in_child == 0) fpurge (stdout); if (dup2 (fd, open_for_read_in_child ? 0 : 1) < 0) { sys_error (_("cannot duplicate named pipe %s as fd %d"), pathname, open_for_read_in_child ? 0 : 1); exit (127); } if (fd != (open_for_read_in_child ? 0 : 1)) close (fd); /* Need to close any files that this process has open to pipes inherited from its parent. */ if (current_fds_to_close) { close_fd_bitmap (current_fds_to_close); current_fds_to_close = (struct fd_bitmap *)NULL; } #if defined (HAVE_DEV_FD) /* Make sure we close the parent's end of the pipe and clear the slot in the fd list so it is not closed later, if reallocated by, for instance, pipe(2). */ close (parent_pipe_fd); dev_fd_list[parent_pipe_fd] = 0; #endif /* HAVE_DEV_FD */ /* subshells shouldn't have this flag, which controls using the temporary environment for variable lookups. We have already flushed the temporary environment above in the case we're expanding a redirection, so processes executed by this command need to be able to set it independently of their parent. */ expanding_redir = 0; remove_quoted_escapes (string); #if 0 /* TAG: bash-5.2 */ startup_state = 2; /* see if we can avoid a fork */ parse_and_execute_level = 0; #endif /* Give process substitution a place to jump back to on failure, so we don't go back up to main (). */ result = setjmp_nosigs (top_level); /* If we're running a process substitution inside a shell function, trap `return' so we don't return from the function in the subshell and go off to never-never land. */ if (result == 0 && return_catch_flag) function_value = setjmp_nosigs (return_catch); else function_value = 0; if (result == ERREXIT) rc = last_command_exit_value; else if (result == EXITPROG) rc = last_command_exit_value; else if (result) rc = EXECUTION_FAILURE; else if (function_value) rc = return_catch_value; else { subshell_level++; rc = parse_and_execute (string, "process substitution", (SEVAL_NONINT|SEVAL_NOHIST)); /* leave subshell level intact for any exit trap */ } #if !defined (HAVE_DEV_FD) /* Make sure we close the named pipe in the child before we exit. */ close (open_for_read_in_child ? 0 : 1); #endif /* !HAVE_DEV_FD */ last_command_exit_value = rc; rc = run_exit_trap (); exit (rc); /*NOTREACHED*/ } #endif /* PROCESS_SUBSTITUTION */ /***********************************/ /* */ /* Command Substitution */ /* */ /***********************************/ static char * read_comsub (fd, quoted, flags, rflag) int fd, quoted, flags; int *rflag; { char *istring, buf[512], *bufp; int istring_index, c, tflag, skip_ctlesc, skip_ctlnul; int mb_cur_max; size_t istring_size; ssize_t bufn; int nullbyte; #if defined (HANDLE_MULTIBYTE) mbstate_t ps; wchar_t wc; size_t mblen; int i; #endif istring = (char *)NULL; istring_index = istring_size = bufn = tflag = 0; skip_ctlesc = ifs_cmap[CTLESC]; skip_ctlnul = ifs_cmap[CTLNUL]; mb_cur_max = MB_CUR_MAX; nullbyte = 0; /* Read the output of the command through the pipe. */ while (1) { if (fd < 0) break; if (--bufn <= 0) { bufn = zread (fd, buf, sizeof (buf)); if (bufn <= 0) break; bufp = buf; } c = *bufp++; if (c == 0) { #if 1 if (nullbyte == 0) { internal_warning ("%s", _("command substitution: ignored null byte in input")); nullbyte = 1; } #endif continue; } /* Add the character to ISTRING, possibly after resizing it. */ RESIZE_MALLOCED_BUFFER (istring, istring_index, mb_cur_max+1, istring_size, 512); /* This is essentially quote_string inline */ if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) /* || c == CTLESC || c == CTLNUL */) istring[istring_index++] = CTLESC; else if ((flags & PF_ASSIGNRHS) && skip_ctlesc && c == CTLESC) istring[istring_index++] = CTLESC; /* Escape CTLESC and CTLNUL in the output to protect those characters from the rest of the word expansions (word splitting and globbing.) This is essentially quote_escapes inline. */ else if (skip_ctlesc == 0 && c == CTLESC) istring[istring_index++] = CTLESC; else if ((skip_ctlnul == 0 && c == CTLNUL) || (c == ' ' && (ifs_value && *ifs_value == 0))) istring[istring_index++] = CTLESC; #if defined (HANDLE_MULTIBYTE) if ((locale_utf8locale && (c & 0x80)) || (locale_utf8locale == 0 && mb_cur_max > 1 && (unsigned char)c > 127)) { /* read a multibyte character from buf */ /* punt on the hard case for now */ memset (&ps, '\0', sizeof (mbstate_t)); mblen = mbrtowc (&wc, bufp-1, bufn+1, &ps); if (MB_INVALIDCH (mblen) || mblen == 0 || mblen == 1) istring[istring_index++] = c; else { istring[istring_index++] = c; for (i = 0; i < mblen-1; i++) istring[istring_index++] = *bufp++; bufn -= mblen - 1; } continue; } #endif istring[istring_index++] = c; } if (istring) istring[istring_index] = '\0'; /* If we read no output, just return now and save ourselves some trouble. */ if (istring_index == 0) { FREE (istring); if (rflag) *rflag = tflag; return (char *)NULL; } /* Strip trailing newlines from the output of the command. */ if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) { while (istring_index > 0) { if (istring[istring_index - 1] == '\n') { --istring_index; /* If the newline was quoted, remove the quoting char. */ if (istring[istring_index - 1] == CTLESC) --istring_index; } else break; } istring[istring_index] = '\0'; } else strip_trailing (istring, istring_index - 1, 1); if (rflag) *rflag = tflag; return istring; } /* Perform command substitution on STRING. This returns a WORD_DESC * with the contained string possibly quoted. */ WORD_DESC * command_substitute (string, quoted, flags) char *string; int quoted; int flags; { pid_t pid, old_pid, old_pipeline_pgrp, old_async_pid; char *istring, *s; int result, fildes[2], function_value, pflags, rc, tflag, fork_flags; WORD_DESC *ret; sigset_t set, oset; istring = (char *)NULL; /* Don't fork () if there is no need to. In the case of no command to run, just return NULL. */ #if 1 for (s = string; s && *s && (shellblank (*s) || *s == '\n'); s++) ; if (s == 0 || *s == 0) return ((WORD_DESC *)NULL); #else if (!string || !*string || (string[0] == '\n' && !string[1])) return ((WORD_DESC *)NULL); #endif if (wordexp_only && read_but_dont_execute) { last_command_exit_value = EX_WEXPCOMSUB; jump_to_top_level (EXITPROG); } /* We're making the assumption here that the command substitution will eventually run a command from the file system. Since we'll run maybe_make_export_env in this subshell before executing that command, the parent shell and any other shells it starts will have to remake the environment. If we make it before we fork, other shells won't have to. Don't bother if we have any temporary variable assignments, though, because the export environment will be remade after this command completes anyway, but do it if all the words to be expanded are variable assignments. */ if (subst_assign_varlist == 0 || garglist == 0) maybe_make_export_env (); /* XXX */ /* Flags to pass to parse_and_execute() */ pflags = (interactive && sourcelevel == 0) ? SEVAL_RESETLINE : 0; old_pid = last_made_pid; /* Pipe the output of executing STRING into the current shell. */ if (pipe (fildes) < 0) { sys_error ("%s", _("cannot make pipe for command substitution")); goto error_exit; } #if defined (JOB_CONTROL) old_pipeline_pgrp = pipeline_pgrp; /* Don't reset the pipeline pgrp if we're already a subshell in a pipeline or we've already forked to run a disk command (and are expanding redirections, for example). */ if ((subshell_environment & (SUBSHELL_FORK|SUBSHELL_PIPE)) == 0) pipeline_pgrp = shell_pgrp; cleanup_the_pipeline (); #endif /* JOB_CONTROL */ old_async_pid = last_asynchronous_pid; fork_flags = (subshell_environment&SUBSHELL_ASYNC) ? FORK_ASYNC : 0; pid = make_child ((char *)NULL, fork_flags|FORK_NOTERM); last_asynchronous_pid = old_async_pid; if (pid == 0) { /* Reset the signal handlers in the child, but don't free the trap strings. Set a flag noting that we have to free the trap strings if we run trap to change a signal disposition. */ reset_signal_handlers (); if (ISINTERRUPT) { kill (getpid (), SIGINT); CLRINTERRUPT; /* if we're ignoring SIGINT somehow */ } QUIT; /* catch any interrupts we got post-fork */ subshell_environment |= SUBSHELL_RESETTRAP; } #if defined (JOB_CONTROL) /* XXX DO THIS ONLY IN PARENT ? XXX */ set_sigchld_handler (); stop_making_children (); if (pid != 0) pipeline_pgrp = old_pipeline_pgrp; #else stop_making_children (); #endif /* JOB_CONTROL */ if (pid < 0) { sys_error (_("cannot make child for command substitution")); error_exit: last_made_pid = old_pid; FREE (istring); close (fildes[0]); close (fildes[1]); return ((WORD_DESC *)NULL); } if (pid == 0) { /* The currently executing shell is not interactive. */ interactive = 0; #if defined (JOB_CONTROL) /* Invariant: in child processes started to run command substitutions, pipeline_pgrp == shell_pgrp. Other parts of the shell assume this. */ if (pipeline_pgrp > 0 && pipeline_pgrp != shell_pgrp) shell_pgrp = pipeline_pgrp; #endif set_sigint_handler (); /* XXX */ free_pushed_string_input (); /* Discard buffered stdio output before replacing the underlying file descriptor. */ fpurge (stdout); if (dup2 (fildes[1], 1) < 0) { sys_error ("%s", _("command_substitute: cannot duplicate pipe as fd 1")); exit (EXECUTION_FAILURE); } /* If standard output is closed in the parent shell (such as after `exec >&-'), file descriptor 1 will be the lowest available file descriptor, and end up in fildes[0]. This can happen for stdin and stderr as well, but stdout is more important -- it will cause no output to be generated from this command. */ if ((fildes[1] != fileno (stdin)) && (fildes[1] != fileno (stdout)) && (fildes[1] != fileno (stderr))) close (fildes[1]); if ((fildes[0] != fileno (stdin)) && (fildes[0] != fileno (stdout)) && (fildes[0] != fileno (stderr))) close (fildes[0]); #ifdef __CYGWIN__ /* Let stdio know the fd may have changed from text to binary mode, and make sure to preserve stdout line buffering. */ freopen (NULL, "w", stdout); sh_setlinebuf (stdout); #endif /* __CYGWIN__ */ /* This is a subshell environment. */ subshell_environment |= SUBSHELL_COMSUB; /* Many shells do not appear to inherit the -v option for command substitutions. */ change_flag ('v', FLAG_OFF); /* When inherit_errexit option is not enabled, command substitution does not inherit the -e flag. It is enabled when Posix mode is enabled */ if (inherit_errexit == 0) { builtin_ignoring_errexit = 0; change_flag ('e', FLAG_OFF); } set_shellopts (); /* If we are expanding a redirection, we can dispose of any temporary environment we received, since redirections are not supposed to have access to the temporary environment. We will have to see whether this affects temporary environments supplied to `eval', but the temporary environment gets copied to builtin_env at some point. */ if (expanding_redir) { flush_temporary_env (); expanding_redir = 0; } remove_quoted_escapes (string); startup_state = 2; /* see if we can avoid a fork */ parse_and_execute_level = 0; /* Give command substitution a place to jump back to on failure, so we don't go back up to main (). */ result = setjmp_nosigs (top_level); /* If we're running a command substitution inside a shell function, trap `return' so we don't return from the function in the subshell and go off to never-never land. */ if (result == 0 && return_catch_flag) function_value = setjmp_nosigs (return_catch); else function_value = 0; if (result == ERREXIT) rc = last_command_exit_value; else if (result == EXITPROG) rc = last_command_exit_value; else if (result) rc = EXECUTION_FAILURE; else if (function_value) rc = return_catch_value; else { subshell_level++; rc = parse_and_execute (string, "command substitution", pflags|SEVAL_NOHIST); /* leave subshell level intact for any exit trap */ } last_command_exit_value = rc; rc = run_exit_trap (); #if defined (PROCESS_SUBSTITUTION) unlink_fifo_list (); #endif exit (rc); } else { int dummyfd; #if defined (JOB_CONTROL) && defined (PGRP_PIPE) close_pgrp_pipe (); #endif /* JOB_CONTROL && PGRP_PIPE */ close (fildes[1]); begin_unwind_frame ("read-comsub"); dummyfd = fildes[0]; add_unwind_protect (close, dummyfd); /* Block SIGINT while we're reading from the pipe. If the child process gets a SIGINT, it will either handle it or die, and the read will return. */ BLOCK_SIGNAL (SIGINT, set, oset); tflag = 0; istring = read_comsub (fildes[0], quoted, flags, &tflag); close (fildes[0]); discard_unwind_frame ("read-comsub"); UNBLOCK_SIGNAL (oset); current_command_subst_pid = pid; last_command_exit_value = wait_for (pid, JWAIT_NOTERM); last_command_subst_pid = pid; last_made_pid = old_pid; #if defined (JOB_CONTROL) /* If last_command_exit_value > 128, then the substituted command was terminated by a signal. If that signal was SIGINT, then send SIGINT to ourselves. This will break out of loops, for instance. */ if (last_command_exit_value == (128 + SIGINT) && last_command_exit_signal == SIGINT) kill (getpid (), SIGINT); #endif /* JOB_CONTROL */ ret = alloc_word_desc (); ret->word = istring; ret->flags = tflag; return ret; } } /******************************************************** * * * Utility functions for parameter expansion * * * ********************************************************/ #if defined (ARRAY_VARS) static arrayind_t array_length_reference (s) char *s; { int len; arrayind_t ind; char *akey; char *t, c; ARRAY *array; HASH_TABLE *h; SHELL_VAR *var; var = array_variable_part (s, 0, &t, &len); /* If unbound variables should generate an error, report one and return failure. */ if ((var == 0 || invisible_p (var) || (assoc_p (var) == 0 && array_p (var) == 0)) && unbound_vars_is_error) { c = *--t; *t = '\0'; set_exit_status (EXECUTION_FAILURE); err_unboundvar (s); *t = c; return (-1); } else if (var == 0 || invisible_p (var)) return 0; /* We support a couple of expansions for variables that are not arrays. We'll return the length of the value for v[0], and 1 for v[@] or v[*]. Return 0 for everything else. */ array = array_p (var) ? array_cell (var) : (ARRAY *)NULL; h = assoc_p (var) ? assoc_cell (var) : (HASH_TABLE *)NULL; if (ALL_ELEMENT_SUB (t[0]) && t[1] == RBRACK) { if (assoc_p (var)) return (h ? assoc_num_elements (h) : 0); else if (array_p (var)) return (array ? array_num_elements (array) : 0); else return (var_isset (var) ? 1 : 0); } if (assoc_p (var)) { t[len - 1] = '\0'; akey = expand_assignment_string_to_string (t, 0); /* [ */ t[len - 1] = RBRACK; if (akey == 0 || *akey == 0) { err_badarraysub (t); FREE (akey); return (-1); } t = assoc_reference (assoc_cell (var), akey); free (akey); } else { ind = array_expand_index (var, t, len, 0); /* negative subscripts to indexed arrays count back from end */ if (var && array_p (var) && ind < 0) ind = array_max_index (array_cell (var)) + 1 + ind; if (ind < 0) { err_badarraysub (t); return (-1); } if (array_p (var)) t = array_reference (array, ind); else t = (ind == 0) ? value_cell (var) : (char *)NULL; } len = MB_STRLEN (t); return (len); } #endif /* ARRAY_VARS */ static int valid_brace_expansion_word (name, var_is_special) char *name; int var_is_special; { if (DIGIT (*name) && all_digits (name)) return 1; else if (var_is_special) return 1; #if defined (ARRAY_VARS) else if (valid_array_reference (name, 0)) return 1; #endif /* ARRAY_VARS */ else if (legal_identifier (name)) return 1; else return 0; } static int chk_atstar (name, quoted, pflags, quoted_dollar_atp, contains_dollar_at) char *name; int quoted, pflags; int *quoted_dollar_atp, *contains_dollar_at; { char *temp1; if (name == 0) { if (quoted_dollar_atp) *quoted_dollar_atp = 0; if (contains_dollar_at) *contains_dollar_at = 0; return 0; } /* check for $@ and $* */ if (name[0] == '@' && name[1] == 0) { if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 1; if (contains_dollar_at) *contains_dollar_at = 1; return 1; } else if (name[0] == '*' && name[1] == '\0' && quoted == 0) { /* Need more checks here that parallel what string_list_pos_params and param_expand do. Check expand_no_split_dollar_star and ??? */ if (contains_dollar_at && expand_no_split_dollar_star == 0) *contains_dollar_at = 1; return 1; } /* Now check for ${array[@]} and ${array[*]} */ #if defined (ARRAY_VARS) else if (valid_array_reference (name, 0)) { temp1 = mbschr (name, LBRACK); if (temp1 && temp1[1] == '@' && temp1[2] == RBRACK) { if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 1; if (contains_dollar_at) *contains_dollar_at = 1; return 1; } /* ${array[*]}, when unquoted, should be treated like ${array[@]}, which should result in separate words even when IFS is unset. */ if (temp1 && temp1[1] == '*' && temp1[2] == RBRACK && quoted == 0) { if (contains_dollar_at) *contains_dollar_at = 1; return 1; } } #endif return 0; } /* Parameter expand NAME, and return a new string which is the expansion, or NULL if there was no expansion. NAME is as given in ${NAMEcWORD}. VAR_IS_SPECIAL is non-zero if NAME is one of the special variables in the shell, e.g., "@", "$", "*", etc. QUOTED, if non-zero, means that NAME was found inside of a double-quoted expression. */ static WORD_DESC * parameter_brace_expand_word (name, var_is_special, quoted, pflags, indp) char *name; int var_is_special, quoted, pflags; arrayind_t *indp; { WORD_DESC *ret; char *temp, *tt; intmax_t arg_index; SHELL_VAR *var; int atype, rflags; arrayind_t ind; ret = 0; temp = 0; rflags = 0; if (indp) *indp = INTMAX_MIN; /* Handle multiple digit arguments, as in ${11}. */ if (legal_number (name, &arg_index)) { tt = get_dollar_var_value (arg_index); if (tt) temp = (*tt && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) ? quote_string (tt) : quote_escapes (tt); else temp = (char *)NULL; FREE (tt); } else if (var_is_special) /* ${@} */ { int sindex; tt = (char *)xmalloc (2 + strlen (name)); tt[sindex = 0] = '$'; strcpy (tt + 1, name); ret = param_expand (tt, &sindex, quoted, (int *)NULL, (int *)NULL, (int *)NULL, (int *)NULL, pflags); free (tt); } #if defined (ARRAY_VARS) else if (valid_array_reference (name, 0)) { expand_arrayref: var = array_variable_part (name, 0, &tt, (int *)0); /* These are the cases where word splitting will not be performed */ if (pflags & PF_ASSIGNRHS) { if (ALL_ELEMENT_SUB (tt[0]) && tt[1] == RBRACK) { /* Only treat as double quoted if array variable */ if (var && (array_p (var) || assoc_p (var))) temp = array_value (name, quoted|Q_DOUBLE_QUOTES, AV_ASSIGNRHS, &atype, &ind); else temp = array_value (name, quoted, 0, &atype, &ind); } else temp = array_value (name, quoted, 0, &atype, &ind); } /* Posix interp 888 */ else if (pflags & PF_NOSPLIT2) { /* Special cases, then general case, for each of A[@], A[*], A[n] */ #if defined (HANDLE_MULTIBYTE) if (tt[0] == '@' && tt[1] == RBRACK && var && quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc[0] != ' ') #else if (tt[0] == '@' && tt[1] == RBRACK && var && quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc != ' ') #endif temp = array_value (name, Q_DOUBLE_QUOTES, AV_ASSIGNRHS, &atype, &ind); else if (tt[0] == '@' && tt[1] == RBRACK) temp = array_value (name, quoted, 0, &atype, &ind); else if (tt[0] == '*' && tt[1] == RBRACK && expand_no_split_dollar_star && ifs_is_null) temp = array_value (name, Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT, 0, &atype, &ind); else if (tt[0] == '*' && tt[1] == RBRACK) temp = array_value (name, quoted, 0, &atype, &ind); else temp = array_value (name, quoted, 0, &atype, &ind); } else if (tt[0] == '*' && tt[1] == RBRACK && expand_no_split_dollar_star && ifs_is_null) temp = array_value (name, Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT, 0, &atype, &ind); else temp = array_value (name, quoted, 0, &atype, &ind); if (atype == 0 && temp) { temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) ? quote_string (temp) : quote_escapes (temp); rflags |= W_ARRAYIND; if (indp) *indp = ind; } else if (atype == 1 && temp && QUOTED_NULL (temp) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) rflags |= W_HASQUOTEDNULL; } #endif else if (var = find_variable (name)) { if (var_isset (var) && invisible_p (var) == 0) { #if defined (ARRAY_VARS) /* We avoid a memory leak by saving TT as the memory allocated by assoc_to_string or array_to_string and leaving it 0 otherwise, then freeing TT after quoting temp. */ tt = (char *)NULL; if ((pflags & PF_ALLINDS) && assoc_p (var)) tt = temp = assoc_empty (assoc_cell (var)) ? (char *)NULL : assoc_to_string (assoc_cell (var), " ", quoted); else if ((pflags & PF_ALLINDS) && array_p (var)) tt = temp = array_empty (array_cell (var)) ? (char *)NULL : array_to_string (array_cell (var), " ", quoted); else if (assoc_p (var)) temp = assoc_reference (assoc_cell (var), "0"); else if (array_p (var)) temp = array_reference (array_cell (var), 0); else temp = value_cell (var); #else temp = value_cell (var); #endif if (temp) temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) ? quote_string (temp) : ((pflags & PF_ASSIGNRHS) ? quote_rhs (temp) : quote_escapes (temp)); FREE (tt); } else temp = (char *)NULL; } else if (var = find_variable_last_nameref (name, 0)) { temp = nameref_cell (var); #if defined (ARRAY_VARS) /* Handle expanding nameref whose value is x[n] */ if (temp && *temp && valid_array_reference (temp, 0)) { name = temp; goto expand_arrayref; } else #endif /* y=2 ; typeset -n x=y; echo ${x} is not the same as echo ${2} in ksh */ if (temp && *temp && legal_identifier (temp) == 0) { set_exit_status (EXECUTION_FAILURE); report_error (_("%s: invalid variable name for name reference"), temp); temp = &expand_param_error; } else temp = (char *)NULL; } else temp = (char *)NULL; if (ret == 0) { ret = alloc_word_desc (); ret->word = temp; ret->flags |= rflags; } return ret; } static char * parameter_brace_find_indir (name, var_is_special, quoted, find_nameref) char *name; int var_is_special, quoted, find_nameref; { char *temp, *t; WORD_DESC *w; SHELL_VAR *v; int pflags, oldex; if (find_nameref && var_is_special == 0 && (v = find_variable_last_nameref (name, 0)) && nameref_p (v) && (t = nameref_cell (v)) && *t) return (savestring (t)); /* If var_is_special == 0, and name is not an array reference, this does more expansion than necessary. It should really look up the variable's value and not try to expand it. */ pflags = PF_IGNUNBOUND; /* Note that we're not going to be doing word splitting here */ if (var_is_special) { pflags |= PF_ASSIGNRHS; /* suppresses word splitting */ oldex = expand_no_split_dollar_star; expand_no_split_dollar_star = 1; } w = parameter_brace_expand_word (name, var_is_special, quoted, pflags, 0); if (var_is_special) expand_no_split_dollar_star = oldex; t = w->word; /* Have to dequote here if necessary */ if (t) { temp = ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || var_is_special) ? dequote_string (t) : dequote_escapes (t); free (t); t = temp; } dispose_word_desc (w); return t; } /* Expand an indirect reference to a variable: ${!NAME} expands to the value of the variable whose name is the value of NAME. */ static WORD_DESC * parameter_brace_expand_indir (name, var_is_special, quoted, pflags, quoted_dollar_atp, contains_dollar_at) char *name; int var_is_special, quoted, pflags; int *quoted_dollar_atp, *contains_dollar_at; { char *t; WORD_DESC *w; SHELL_VAR *v; /* See if it's a nameref first, behave in ksh93-compatible fashion. There is at least one incompatibility: given ${!foo[0]} where foo=bar, bash performs an indirect lookup on foo[0] and expands the result; ksh93 expands bar[0]. We could do that here -- there are enough usable primitives to do that -- but do not at this point. */ if (var_is_special == 0 && (v = find_variable_last_nameref (name, 0))) { if (nameref_p (v) && (t = nameref_cell (v)) && *t) { w = alloc_word_desc (); w->word = savestring (t); w->flags = 0; return w; } } /* An indirect reference to a positional parameter or a special parameter is ok. Indirect references to array references, as explained above, are ok (currently). Only references to unset variables are errors at this point. */ if (legal_identifier (name) && v == 0) { report_error (_("%s: invalid indirect expansion"), name); w = alloc_word_desc (); w->word = &expand_param_error; w->flags = 0; return (w); } t = parameter_brace_find_indir (name, var_is_special, quoted, 0); chk_atstar (t, quoted, pflags, quoted_dollar_atp, contains_dollar_at); #if defined (ARRAY_VARS) /* Array references to unset variables are also an error */ if (t == 0 && valid_array_reference (name, 0)) { v = array_variable_part (name, 0, (char **)0, (int *)0); if (v == 0) { report_error (_("%s: invalid indirect expansion"), name); w = alloc_word_desc (); w->word = &expand_param_error; w->flags = 0; return (w); } else return (WORD_DESC *)NULL; } #endif if (t == 0) return (WORD_DESC *)NULL; if (valid_brace_expansion_word (t, SPECIAL_VAR (t, 0)) == 0) { report_error (_("%s: invalid variable name"), t); free (t); w = alloc_word_desc (); w->word = &expand_param_error; w->flags = 0; return (w); } w = parameter_brace_expand_word (t, SPECIAL_VAR(t, 0), quoted, pflags, 0); free (t); return w; } /* Expand the right side of a parameter expansion of the form ${NAMEcVALUE}, depending on the value of C, the separating character. C can be one of "-", "+", or "=". QUOTED is true if the entire brace expression occurs between double quotes. */ static WORD_DESC * parameter_brace_expand_rhs (name, value, op, quoted, pflags, qdollaratp, hasdollarat) char *name, *value; int op, quoted, pflags, *qdollaratp, *hasdollarat; { WORD_DESC *w; WORD_LIST *l, *tl; char *t, *t1, *temp, *vname; int l_hasdollat, sindex; SHELL_VAR *v; /*itrace("parameter_brace_expand_rhs: %s:%s pflags = %d", name, value, pflags);*/ /* If the entire expression is between double quotes, we want to treat the value as a double-quoted string, with the exception that we strip embedded unescaped double quotes (for sh backwards compatibility). */ if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *value) { sindex = 0; temp = string_extract_double_quoted (value, &sindex, SX_STRIPDQ); } else temp = value; w = alloc_word_desc (); l_hasdollat = 0; l = *temp ? expand_string_for_rhs (temp, quoted, op, pflags, &l_hasdollat, (int *)NULL) : (WORD_LIST *)0; if (hasdollarat) *hasdollarat = l_hasdollat || (l && l->next); if (temp != value) free (temp); /* list_string takes multiple CTLNULs and turns them into an empty word with W_SAWQUOTEDNULL set. Turn it back into a single CTLNUL for the rest of this function and the caller. */ for (tl = l; tl; tl = tl->next) { if (tl->word && (tl->word->word == 0 || tl->word->word[0] == 0) && (tl->word->flags | W_SAWQUOTEDNULL)) { t = make_quoted_char ('\0'); FREE (tl->word->word); tl->word->word = t; tl->word->flags |= W_QUOTED|W_HASQUOTEDNULL; tl->word->flags &= ~W_SAWQUOTEDNULL; } } if (l) { /* If l->next is not null, we know that TEMP contained "$@", since that is the only expansion that creates more than one word. */ if (qdollaratp && ((l_hasdollat && quoted) || l->next)) { /*itrace("parameter_brace_expand_rhs: %s:%s: l != NULL, set *qdollaratp", name, value);*/ *qdollaratp = 1; } /* The expansion of TEMP returned something. We need to treat things slightly differently if L_HASDOLLAT is non-zero. If we have "$@", the individual words have already been quoted. We need to turn them into a string with the words separated by the first character of $IFS without any additional quoting, so string_list_dollar_at won't do the right thing. If IFS is null, we want "$@" to split into separate arguments, not be concatenated, so we use string_list_internal and mark the word to be split on spaces later. We use string_list_dollar_star for "$@" otherwise. */ if (l->next && ifs_is_null) { temp = string_list_internal (l, " "); w->flags |= W_SPLITSPACE; } else if (l_hasdollat || l->next) temp = string_list_dollar_star (l, quoted, 0); else { temp = string_list (l); if (temp && (QUOTED_NULL (temp) == 0) && (l->word->flags & W_SAWQUOTEDNULL)) w->flags |= W_SAWQUOTEDNULL; /* XXX */ } /* If we have a quoted null result (QUOTED_NULL(temp)) and the word is a quoted null (l->next == 0 && QUOTED_NULL(l->word->word)), the flags indicate it (l->word->flags & W_HASQUOTEDNULL), and the expansion is quoted (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) (which is more paranoia than anything else), we need to return the quoted null string and set the flags to indicate it. */ if (l->next == 0 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && QUOTED_NULL (temp) && QUOTED_NULL (l->word->word) && (l->word->flags & W_HASQUOTEDNULL)) { w->flags |= W_HASQUOTEDNULL; /*itrace("parameter_brace_expand_rhs (%s:%s): returning quoted null, turning off qdollaratp", name, value);*/ /* If we return a quoted null with L_HASDOLLARAT, we either have a construct like "${@-$@}" or "${@-${@-$@}}" with no positional parameters or a quoted expansion of "$@" with $1 == ''. In either case, we don't want to enable special handling of $@. */ if (qdollaratp && l_hasdollat) *qdollaratp = 0; } dispose_words (l); } else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && l_hasdollat) { /* Posix interp 221 changed the rules on this. The idea is that something like "$xxx$@" should expand the same as "${foo-$xxx$@}" when foo and xxx are unset. The problem is that it's not in any way backwards compatible and few other shells do it. We're eventually going to try and split the difference (heh) a little bit here. */ /* l_hasdollat == 1 means we saw a quoted dollar at. */ /* The brace expansion occurred between double quotes and there was a $@ in TEMP. It does not matter if the $@ is quoted, as long as it does not expand to anything. In this case, we want to return a quoted empty string. Posix interp 888 */ temp = make_quoted_char ('\0'); w->flags |= W_HASQUOTEDNULL; /*itrace("parameter_brace_expand_rhs (%s:%s): returning quoted null", name, value);*/ } else temp = (char *)NULL; if (op == '-' || op == '+') { w->word = temp; return w; } /* op == '=' */ t1 = temp ? dequote_string (temp) : savestring (""); free (temp); /* bash-4.4/5.0 */ vname = name; if (*name == '!' && (legal_variable_starter ((unsigned char)name[1]) || DIGIT (name[1]) || VALID_INDIR_PARAM (name[1]))) { vname = parameter_brace_find_indir (name + 1, SPECIAL_VAR (name, 1), quoted, 1); if (vname == 0 || *vname == 0) { report_error (_("%s: invalid indirect expansion"), name); free (vname); free (t1); dispose_word (w); return &expand_wdesc_error; } if (legal_identifier (vname) == 0) { report_error (_("%s: invalid variable name"), vname); free (vname); free (t1); dispose_word (w); return &expand_wdesc_error; } } #if defined (ARRAY_VARS) if (valid_array_reference (vname, 0)) v = assign_array_element (vname, t1, 0); else #endif /* ARRAY_VARS */ v = bind_variable (vname, t1, 0); if (v == 0 || readonly_p (v) || noassign_p (v)) /* expansion error */ { if ((v == 0 || readonly_p (v)) && interactive_shell == 0 && posixly_correct) { last_command_exit_value = EXECUTION_FAILURE; exp_jump_to_top_level (FORCE_EOF); } else { if (vname != name) free (vname); last_command_exit_value = EX_BADUSAGE; exp_jump_to_top_level (DISCARD); } } stupidly_hack_special_variables (vname); if (vname != name) free (vname); /* From Posix group discussion Feb-March 2010. Issue 7 0000221 */ /* If we are double-quoted or if we are not going to be performing word splitting, we want to quote the value we return appropriately, like the other expansions this function handles. */ w->word = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) ? quote_string (t1) : quote_escapes (t1); /* If we have something that's non-null, that's not a quoted null string, and we're not going to be performing word splitting (we know we're not because the operator is `='), we can forget we saw a quoted null. */ if (w->word && w->word[0] && QUOTED_NULL (w->word) == 0) w->flags &= ~W_SAWQUOTEDNULL; free (t1); /* If we convert a null string into a quoted null, make sure the caller knows it. */ if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) && QUOTED_NULL (w->word)) w->flags |= W_HASQUOTEDNULL; return w; } /* Deal with the right hand side of a ${name:?value} expansion in the case that NAME is null or not set. If VALUE is non-null it is expanded and used as the error message to print, otherwise a standard message is printed. */ static void parameter_brace_expand_error (name, value, check_null) char *name, *value; int check_null; { WORD_LIST *l; char *temp; set_exit_status (EXECUTION_FAILURE); /* ensure it's non-zero */ if (value && *value) { l = expand_string (value, 0); temp = string_list (l); report_error ("%s: %s", name, temp ? temp : ""); /* XXX was value not "" */ FREE (temp); dispose_words (l); } else if (check_null == 0) report_error (_("%s: parameter not set"), name); else report_error (_("%s: parameter null or not set"), name); /* Free the data we have allocated during this expansion, since we are about to longjmp out. */ free (name); FREE (value); } /* Return 1 if NAME is something for which parameter_brace_expand_length is OK to do. */ static int valid_length_expression (name) char *name; { return (name[1] == '\0' || /* ${#} */ ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0') || /* special param */ (DIGIT (name[1]) && all_digits (name + 1)) || /* ${#11} */ #if defined (ARRAY_VARS) valid_array_reference (name + 1, 0) || /* ${#a[7]} */ #endif legal_identifier (name + 1)); /* ${#PS1} */ } /* Handle the parameter brace expansion that requires us to return the length of a parameter. */ static intmax_t parameter_brace_expand_length (name) char *name; { char *t, *newname; intmax_t number, arg_index; WORD_LIST *list; SHELL_VAR *var; var = (SHELL_VAR *)NULL; if (name[1] == '\0') /* ${#} */ number = number_of_args (); else if (DOLLAR_AT_STAR (name[1]) && name[2] == '\0') /* ${#@}, ${#*} */ number = number_of_args (); else if ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0') { /* Take the lengths of some of the shell's special parameters. */ switch (name[1]) { case '-': t = which_set_flags (); break; case '?': t = itos (last_command_exit_value); break; case '$': t = itos (dollar_dollar_pid); break; case '!': if (last_asynchronous_pid == NO_PID) t = (char *)NULL; /* XXX - error if set -u set? */ else t = itos (last_asynchronous_pid); break; case '#': t = itos (number_of_args ()); break; } number = STRLEN (t); FREE (t); } #if defined (ARRAY_VARS) else if (valid_array_reference (name + 1, 0)) number = array_length_reference (name + 1); #endif /* ARRAY_VARS */ else { number = 0; if (legal_number (name + 1, &arg_index)) /* ${#1} */ { t = get_dollar_var_value (arg_index); if (t == 0 && unbound_vars_is_error) return INTMAX_MIN; number = MB_STRLEN (t); FREE (t); } #if defined (ARRAY_VARS) else if ((var = find_variable (name + 1)) && (invisible_p (var) == 0) && (array_p (var) || assoc_p (var))) { if (assoc_p (var)) t = assoc_reference (assoc_cell (var), "0"); else t = array_reference (array_cell (var), 0); if (t == 0 && unbound_vars_is_error) return INTMAX_MIN; number = MB_STRLEN (t); } #endif /* Fast path for the common case of taking the length of a non-dynamic scalar variable value. */ else if ((var || (var = find_variable (name + 1))) && invisible_p (var) == 0 && array_p (var) == 0 && assoc_p (var) == 0 && var->dynamic_value == 0) number = value_cell (var) ? MB_STRLEN (value_cell (var)) : 0; else if (var == 0 && unbound_vars_is_error == 0) number = 0; else /* ${#PS1} */ { newname = savestring (name); newname[0] = '$'; list = expand_string (newname, Q_DOUBLE_QUOTES); t = list ? string_list (list) : (char *)NULL; free (newname); if (list) dispose_words (list); number = t ? MB_STRLEN (t) : 0; FREE (t); } } return (number); } /* Skip characters in SUBSTR until DELIM. SUBSTR is an arithmetic expression, so we do some ad-hoc parsing of an arithmetic expression to find the first DELIM, instead of using strchr(3). Two rules: 1. If the substring contains a `(', read until closing `)'. 2. If the substring contains a `?', read past one `:' for each `?'. The SD_ARITHEXP flag to skip_to_delim takes care of doing this. */ static char * skiparith (substr, delim) char *substr; int delim; { int i; char delims[2]; delims[0] = delim; delims[1] = '\0'; i = skip_to_delim (substr, 0, delims, SD_ARITHEXP); return (substr + i); } /* Verify and limit the start and end of the desired substring. If VTYPE == 0, a regular shell variable is being used; if it is 1, then the positional parameters are being used; if it is 2, then VALUE is really a pointer to an array variable that should be used. Return value is 1 if both values were OK, 0 if there was a problem with an invalid expression, or -1 if the values were out of range. */ static int verify_substring_values (v, value, substr, vtype, e1p, e2p) SHELL_VAR *v; char *value, *substr; int vtype; intmax_t *e1p, *e2p; { char *t, *temp1, *temp2; arrayind_t len; int expok; #if defined (ARRAY_VARS) ARRAY *a; HASH_TABLE *h; #endif /* duplicate behavior of strchr(3) */ t = skiparith (substr, ':'); if (*t && *t == ':') *t = '\0'; else t = (char *)0; temp1 = expand_arith_string (substr, Q_DOUBLE_QUOTES); *e1p = evalexp (temp1, 0, &expok); /* XXX - EXP_EXPANDED? */ free (temp1); if (expok == 0) return (0); len = -1; /* paranoia */ switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: len = MB_STRLEN (value); break; case VT_POSPARMS: len = number_of_args () + 1; if (*e1p == 0) len++; /* add one arg if counting from $0 */ break; #if defined (ARRAY_VARS) case VT_ARRAYVAR: /* For arrays, the first value deals with array indices. Negative offsets count from one past the array's maximum index. Associative arrays treat the number of elements as the maximum index. */ if (assoc_p (v)) { h = assoc_cell (v); len = assoc_num_elements (h) + (*e1p < 0); } else { a = (ARRAY *)value; len = array_max_index (a) + (*e1p < 0); /* arrays index from 0 to n - 1 */ } break; #endif } if (len == -1) /* paranoia */ return -1; if (*e1p < 0) /* negative offsets count from end */ *e1p += len; if (*e1p > len || *e1p < 0) return (-1); #if defined (ARRAY_VARS) /* For arrays, the second offset deals with the number of elements. */ if (vtype == VT_ARRAYVAR) len = assoc_p (v) ? assoc_num_elements (h) : array_num_elements (a); #endif if (t) { t++; temp2 = savestring (t); temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES); free (temp2); t[-1] = ':'; *e2p = evalexp (temp1, 0, &expok); /* XXX - EXP_EXPANDED? */ free (temp1); if (expok == 0) return (0); /* Should we allow positional parameter length < 0 to count backwards from end of positional parameters? */ #if 1 if ((vtype == VT_ARRAYVAR || vtype == VT_POSPARMS) && *e2p < 0) #else /* TAG: bash-5.2 */ if (vtype == VT_ARRAYVAR && *e2p < 0) #endif { internal_error (_("%s: substring expression < 0"), t); return (0); } #if defined (ARRAY_VARS) /* In order to deal with sparse arrays, push the intelligence about how to deal with the number of elements desired down to the array- specific functions. */ if (vtype != VT_ARRAYVAR) #endif { if (*e2p < 0) { *e2p += len; if (*e2p < 0 || *e2p < *e1p) { internal_error (_("%s: substring expression < 0"), t); return (0); } } else *e2p += *e1p; /* want E2 chars starting at E1 */ if (*e2p > len) *e2p = len; } } else *e2p = len; return (1); } /* Return the type of variable specified by VARNAME (simple variable, positional param, or array variable). Also return the value specified by VARNAME (value of a variable or a reference to an array element). QUOTED is the standard description of quoting state, using Q_* defines. FLAGS is currently a set of flags to pass to array_value. If IND is non-null and not INTMAX_MIN, and FLAGS includes AV_USEIND, IND is passed to array_value so the array index is not computed again. If this returns VT_VARIABLE, the caller assumes that CTLESC and CTLNUL characters in the value are quoted with CTLESC and takes appropriate steps. For convenience, *VALP is set to the dequoted VALUE. */ static int get_var_and_type (varname, value, ind, quoted, flags, varp, valp) char *varname, *value; arrayind_t ind; int quoted, flags; SHELL_VAR **varp; char **valp; { int vtype, want_indir; char *temp, *vname; SHELL_VAR *v; arrayind_t lind; want_indir = *varname == '!' && (legal_variable_starter ((unsigned char)varname[1]) || DIGIT (varname[1]) || VALID_INDIR_PARAM (varname[1])); if (want_indir) vname = parameter_brace_find_indir (varname+1, SPECIAL_VAR (varname, 1), quoted, 1); /* XXX - what if vname == 0 || *vname == 0 ? */ else vname = varname; if (vname == 0) { vtype = VT_VARIABLE; *varp = (SHELL_VAR *)NULL; *valp = (char *)NULL; return (vtype); } /* This sets vtype to VT_VARIABLE or VT_POSPARMS */ vtype = STR_DOLLAR_AT_STAR (vname); if (vtype == VT_POSPARMS && vname[0] == '*') vtype |= VT_STARSUB; *varp = (SHELL_VAR *)NULL; #if defined (ARRAY_VARS) if (valid_array_reference (vname, 0)) { v = array_variable_part (vname, 0, &temp, (int *)0); /* If we want to signal array_value to use an already-computed index, set LIND to that index */ lind = (ind != INTMAX_MIN && (flags & AV_USEIND)) ? ind : 0; if (v && invisible_p (v)) { vtype = VT_ARRAYMEMBER; *varp = (SHELL_VAR *)NULL; *valp = (char *)NULL; } if (v && (array_p (v) || assoc_p (v))) { if (ALL_ELEMENT_SUB (temp[0]) && temp[1] == RBRACK) { /* Callers have to differentiate between indexed and associative */ vtype = VT_ARRAYVAR; if (temp[0] == '*') vtype |= VT_STARSUB; *valp = array_p (v) ? (char *)array_cell (v) : (char *)assoc_cell (v); } else { vtype = VT_ARRAYMEMBER; *valp = array_value (vname, Q_DOUBLE_QUOTES, flags, (int *)NULL, &lind); } *varp = v; } else if (v && (ALL_ELEMENT_SUB (temp[0]) && temp[1] == RBRACK)) { vtype = VT_VARIABLE; *varp = v; if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) *valp = value ? dequote_string (value) : (char *)NULL; else *valp = value ? dequote_escapes (value) : (char *)NULL; } else { vtype = VT_ARRAYMEMBER; *varp = v; *valp = array_value (vname, Q_DOUBLE_QUOTES, flags, (int *)NULL, &lind); } } else if ((v = find_variable (vname)) && (invisible_p (v) == 0) && (assoc_p (v) || array_p (v))) { vtype = VT_ARRAYMEMBER; *varp = v; *valp = assoc_p (v) ? assoc_reference (assoc_cell (v), "0") : array_reference (array_cell (v), 0); } else #endif { if (value && vtype == VT_VARIABLE) { *varp = find_variable (vname); if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) *valp = dequote_string (value); else *valp = dequote_escapes (value); } else *valp = value; } if (want_indir) free (vname); return vtype; } /***********************************************************/ /* */ /* Functions to perform transformations on variable values */ /* */ /***********************************************************/ static char * string_var_assignment (v, s) SHELL_VAR *v; char *s; { char flags[MAX_ATTRIBUTES], *ret, *val; int i; val = (v && (invisible_p (v) || var_isset (v) == 0)) ? (char *)NULL : sh_quote_reusable (s, 0); i = var_attribute_string (v, 0, flags); if (i == 0 && val == 0) return (char *)NULL; ret = (char *)xmalloc (i + STRLEN (val) + strlen (v->name) + 16 + MAX_ATTRIBUTES); if (i > 0 && val == 0) sprintf (ret, "declare -%s %s", flags, v->name); else if (i > 0) sprintf (ret, "declare -%s %s=%s", flags, v->name, val); else sprintf (ret, "%s=%s", v->name, val); free (val); return ret; } #if defined (ARRAY_VARS) static char * array_var_assignment (v, itype, quoted, atype) SHELL_VAR *v; int itype, quoted, atype; { char *ret, *val, flags[MAX_ATTRIBUTES]; int i; if (v == 0) return (char *)NULL; if (atype == 2) val = array_p (v) ? array_to_kvpair (array_cell (v), 0) : assoc_to_kvpair (assoc_cell (v), 0); else val = array_p (v) ? array_to_assign (array_cell (v), 0) : assoc_to_assign (assoc_cell (v), 0); if (val == 0 && (invisible_p (v) || var_isset (v) == 0)) ; /* placeholder */ else if (val == 0) { val = (char *)xmalloc (3); val[0] = LPAREN; val[1] = RPAREN; val[2] = 0; } else { ret = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) ? quote_string (val) : quote_escapes (val); free (val); val = ret; } if (atype == 2) return val; i = var_attribute_string (v, 0, flags); ret = (char *)xmalloc (i + STRLEN (val) + strlen (v->name) + 16); if (val) sprintf (ret, "declare -%s %s=%s", flags, v->name, val); else sprintf (ret, "declare -%s %s", flags, v->name); free (val); return ret; } #endif static char * pos_params_assignment (list, itype, quoted) WORD_LIST *list; int itype; int quoted; { char *temp, *ret; /* first, we transform the list to quote each word. */ temp = list_transform ('Q', (SHELL_VAR *)0, list, itype, quoted); ret = (char *)xmalloc (strlen (temp) + 8); strcpy (ret, "set -- "); strcpy (ret + 7, temp); free (temp); return ret; } static char * string_transform (xc, v, s) int xc; SHELL_VAR *v; char *s; { char *ret, flags[MAX_ATTRIBUTES], *t; int i; if (((xc == 'A' || xc == 'a') && v == 0)) return (char *)NULL; else if (xc != 'a' && xc != 'A' && s == 0) return (char *)NULL; switch (xc) { /* Transformations that interrogate the variable */ case 'a': i = var_attribute_string (v, 0, flags); ret = (i > 0) ? savestring (flags) : (char *)NULL; break; case 'A': ret = string_var_assignment (v, s); break; case 'K': ret = sh_quote_reusable (s, 0); break; /* Transformations that modify the variable's value */ case 'E': t = ansiexpand (s, 0, strlen (s), (int *)0); ret = dequote_escapes (t); free (t); break; case 'P': ret = decode_prompt_string (s); break; case 'Q': ret = sh_quote_reusable (s, 0); break; case 'U': ret = sh_modcase (s, 0, CASE_UPPER); break; case 'u': ret = sh_modcase (s, 0, CASE_UPFIRST); /* capitalize */ break; case 'L': ret = sh_modcase (s, 0, CASE_LOWER); break; default: ret = (char *)NULL; break; } return ret; } static char * list_transform (xc, v, list, itype, quoted) int xc; SHELL_VAR *v; WORD_LIST *list; int itype, quoted; { WORD_LIST *new, *l; WORD_DESC *w; char *tword; int qflags; for (new = (WORD_LIST *)NULL, l = list; l; l = l->next) { tword = string_transform (xc, v, l->word->word); w = alloc_word_desc (); w->word = tword ? tword : savestring (""); /* XXX */ new = make_word_list (w, new); } l = REVERSE_LIST (new, WORD_LIST *); qflags = quoted; /* If we are expanding in a context where word splitting will not be performed, treat as quoted. This changes how $* will be expanded. */ if (itype == '*' && expand_no_split_dollar_star && ifs_is_null) qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */ tword = string_list_pos_params (itype, l, qflags, 0); dispose_words (l); return (tword); } static char * parameter_list_transform (xc, itype, quoted) int xc; int itype; int quoted; { char *ret; WORD_LIST *list; list = list_rest_of_args (); if (list == 0) return ((char *)NULL); if (xc == 'A') ret = pos_params_assignment (list, itype, quoted); else ret = list_transform (xc, (SHELL_VAR *)0, list, itype, quoted); dispose_words (list); return (ret); } #if defined (ARRAY_VARS) static char * array_transform (xc, var, starsub, quoted) int xc; SHELL_VAR *var; int starsub; /* so we can figure out how it's indexed */ int quoted; { ARRAY *a; HASH_TABLE *h; int itype; char *ret; WORD_LIST *list; SHELL_VAR *v; v = var; /* XXX - for now */ itype = starsub ? '*' : '@'; if (xc == 'A') return (array_var_assignment (v, itype, quoted, 1)); else if (xc == 'K') return (array_var_assignment (v, itype, quoted, 2)); /* special case for unset arrays and attributes */ if (xc == 'a' && (invisible_p (v) || var_isset (v) == 0)) { char flags[MAX_ATTRIBUTES]; int i; i = var_attribute_string (v, 0, flags); return ((i > 0) ? savestring (flags) : (char *)NULL); } a = (v && array_p (v)) ? array_cell (v) : 0; h = (v && assoc_p (v)) ? assoc_cell (v) : 0; list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0); if (list == 0) return ((char *)NULL); ret = list_transform (xc, v, list, itype, quoted); dispose_words (list); return ret; } #endif /* ARRAY_VARS */ static int valid_parameter_transform (xform) char *xform; { if (xform[1]) return 0; /* check for valid values of xform[0] */ switch (xform[0]) { case 'a': /* expand to a string with just attributes */ case 'A': /* expand as an assignment statement with attributes */ case 'K': /* expand assoc array to list of key/value pairs */ case 'E': /* expand like $'...' */ case 'P': /* expand like prompt string */ case 'Q': /* quote reusably */ case 'U': /* transform to uppercase */ case 'u': /* tranform by capitalizing */ case 'L': /* transform to lowercase */ return 1; default: return 0; } } static char * parameter_brace_transform (varname, value, ind, xform, rtype, quoted, pflags, flags) char *varname, *value; int ind; char *xform; int rtype, quoted, pflags, flags; { int vtype, xc, starsub; char *temp1, *val, *oname; SHELL_VAR *v; xc = xform[0]; if (value == 0 && xc != 'A' && xc != 'a') return ((char *)NULL); oname = this_command_name; this_command_name = varname; vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val); if (vtype == -1) { this_command_name = oname; return ((char *)NULL); } if (valid_parameter_transform (xform) == 0) { this_command_name = oname; #if 0 /* TAG: bash-5.2 Martin Schulte <[email protected]> 10/2020 */ return (interactive_shell ? &expand_param_error : &expand_param_fatal); #else return &expand_param_error; #endif } starsub = vtype & VT_STARSUB; vtype &= ~VT_STARSUB; /* If we are asked to display the attributes of an unset variable, V will be NULL after the call to get_var_and_type. Double-check here. */ if ((xc == 'a' || xc == 'A') && vtype == VT_VARIABLE && varname && v == 0) v = find_variable (varname); temp1 = (char *)NULL; /* shut up gcc */ switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: temp1 = string_transform (xc, v, val); if (vtype == VT_VARIABLE) FREE (val); if (temp1) { val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_string (temp1) : quote_escapes (temp1); free (temp1); temp1 = val; } break; #if defined (ARRAY_VARS) case VT_ARRAYVAR: temp1 = array_transform (xc, v, starsub, quoted); if (temp1 && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) { val = quote_escapes (temp1); free (temp1); temp1 = val; } break; #endif case VT_POSPARMS: temp1 = parameter_list_transform (xc, varname[0], quoted); if (temp1 && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)) { val = quote_escapes (temp1); free (temp1); temp1 = val; } break; } this_command_name = oname; return temp1; } /******************************************************/ /* */ /* Functions to extract substrings of variable values */ /* */ /******************************************************/ #if defined (HANDLE_MULTIBYTE) /* Character-oriented rather than strictly byte-oriented substrings. S and E, rather being strict indices into STRING, indicate character (possibly multibyte character) positions that require calculation. Used by the ${param:offset[:length]} expansion. */ static char * mb_substring (string, s, e) char *string; int s, e; { char *tt; int start, stop, i; size_t slen; DECLARE_MBSTATE; start = 0; /* Don't need string length in ADVANCE_CHAR unless multibyte chars possible. */ slen = (MB_CUR_MAX > 1) ? STRLEN (string) : 0; i = s; while (string[start] && i--) ADVANCE_CHAR (string, slen, start); stop = start; i = e - s; while (string[stop] && i--) ADVANCE_CHAR (string, slen, stop); tt = substring (string, start, stop); return tt; } #endif /* Process a variable substring expansion: ${name:e1[:e2]}. If VARNAME is `@', use the positional parameters; otherwise, use the value of VARNAME. If VARNAME is an array variable, use the array elements. */ static char * parameter_brace_substring (varname, value, ind, substr, quoted, pflags, flags) char *varname, *value; int ind; char *substr; int quoted, pflags, flags; { intmax_t e1, e2; int vtype, r, starsub; char *temp, *val, *tt, *oname; SHELL_VAR *v; if (value == 0 && ((varname[0] != '@' && varname[0] != '*') || varname[1])) return ((char *)NULL); oname = this_command_name; this_command_name = varname; vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val); if (vtype == -1) { this_command_name = oname; return ((char *)NULL); } starsub = vtype & VT_STARSUB; vtype &= ~VT_STARSUB; r = verify_substring_values (v, val, substr, vtype, &e1, &e2); this_command_name = oname; if (r <= 0) { if (vtype == VT_VARIABLE) FREE (val); return ((r == 0) ? &expand_param_error : (char *)NULL); } switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: #if defined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1) tt = mb_substring (val, e1, e2); else #endif tt = substring (val, e1, e2); if (vtype == VT_VARIABLE) FREE (val); if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) temp = quote_string (tt); else temp = tt ? quote_escapes (tt) : (char *)NULL; FREE (tt); break; case VT_POSPARMS: case VT_ARRAYVAR: if (vtype == VT_POSPARMS) tt = pos_params (varname, e1, e2, quoted, pflags); #if defined (ARRAY_VARS) /* assoc_subrange and array_subrange both call string_list_pos_params, so we can treat this case just like VT_POSPARAMS. */ else if (assoc_p (v)) /* we convert to list and take first e2 elements starting at e1th element -- officially undefined for now */ tt = assoc_subrange (assoc_cell (v), e1, e2, starsub, quoted, pflags); else /* We want E2 to be the number of elements desired (arrays can be sparse, so verify_substring_values just returns the numbers specified and we rely on array_subrange to understand how to deal with them). */ tt = array_subrange (array_cell (v), e1, e2, starsub, quoted, pflags); #endif /* We want to leave this alone in every case where pos_params/ string_list_pos_params quotes the list members */ if (tt && quoted == 0 && ifs_is_null) { temp = tt; /* Posix interp 888 */ } else if (tt && quoted == 0 && (pflags & PF_ASSIGNRHS)) { temp = tt; /* Posix interp 888 */ } else if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0) { temp = tt ? quote_escapes (tt) : (char *)NULL; FREE (tt); } else temp = tt; break; default: temp = (char *)NULL; } return temp; } /****************************************************************/ /* */ /* Functions to perform pattern substitution on variable values */ /* */ /****************************************************************/ #ifdef INCLUDE_UNUSED static int shouldexp_replacement (s) char *s; { register char *p; for (p = s; p && *p; p++) { if (*p == '\\') p++; else if (*p == '&') return 1; } return 0; } #endif char * pat_subst (string, pat, rep, mflags) char *string, *pat, *rep; int mflags; { char *ret, *s, *e, *str, *rstr, *mstr, *send; int rptr, mtype, rxpand, mlen; size_t rsize, l, replen, rslen; DECLARE_MBSTATE; if (string == 0) return (savestring ("")); mtype = mflags & MATCH_TYPEMASK; #if 0 /* TAG: bash-5.2? */ rxpand = (rep && *rep) ? shouldexp_replacement (rep) : 0; #else rxpand = 0; #endif /* Special cases: * 1. A null pattern with mtype == MATCH_BEG means to prefix STRING * with REP and return the result. * 2. A null pattern with mtype == MATCH_END means to append REP to * STRING and return the result. * 3. A null STRING with a matching pattern means to append REP to * STRING and return the result. * These don't understand or process `&' in the replacement string. */ if ((pat == 0 || *pat == 0) && (mtype == MATCH_BEG || mtype == MATCH_END)) { replen = STRLEN (rep); l = STRLEN (string); ret = (char *)xmalloc (replen + l + 2); if (replen == 0) strcpy (ret, string); else if (mtype == MATCH_BEG) { strcpy (ret, rep); strcpy (ret + replen, string); } else { strcpy (ret, string); strcpy (ret + l, rep); } return (ret); } else if (*string == 0 && (match_pattern (string, pat, mtype, &s, &e) != 0)) { replen = STRLEN (rep); ret = (char *)xmalloc (replen + 1); if (replen == 0) ret[0] = '\0'; else strcpy (ret, rep); return (ret); } ret = (char *)xmalloc (rsize = 64); ret[0] = '\0'; send = string + strlen (string); for (replen = STRLEN (rep), rptr = 0, str = string; *str;) { if (match_pattern (str, pat, mtype, &s, &e) == 0) break; l = s - str; if (rep && rxpand) { int x; mlen = e - s; mstr = xmalloc (mlen + 1); for (x = 0; x < mlen; x++) mstr[x] = s[x]; mstr[mlen] = '\0'; rstr = strcreplace (rep, '&', mstr, 0); free (mstr); rslen = strlen (rstr); } else { rstr = rep; rslen = replen; } RESIZE_MALLOCED_BUFFER (ret, rptr, (l + rslen), rsize, 64); /* OK, now copy the leading unmatched portion of the string (from str to s) to ret starting at rptr (the current offset). Then copy the replacement string at ret + rptr + (s - str). Increment rptr (if necessary) and str and go on. */ if (l) { strncpy (ret + rptr, str, l); rptr += l; } if (replen) { strncpy (ret + rptr, rstr, rslen); rptr += rslen; } str = e; /* e == end of match */ if (rstr != rep) free (rstr); if (((mflags & MATCH_GLOBREP) == 0) || mtype != MATCH_ANY) break; if (s == e) { /* On a zero-length match, make sure we copy one character, since we increment one character to avoid infinite recursion. */ char *p, *origp, *origs; size_t clen; RESIZE_MALLOCED_BUFFER (ret, rptr, locale_mb_cur_max, rsize, 64); #if defined (HANDLE_MULTIBYTE) p = origp = ret + rptr; origs = str; COPY_CHAR_P (p, str, send); rptr += p - origp; e += str - origs; #else ret[rptr++] = *str++; e++; /* avoid infinite recursion on zero-length match */ #endif } } /* Now copy the unmatched portion of the input string */ if (str && *str) { RESIZE_MALLOCED_BUFFER (ret, rptr, STRLEN(str) + 1, rsize, 64); strcpy (ret + rptr, str); } else ret[rptr] = '\0'; return ret; } /* Do pattern match and replacement on the positional parameters. */ static char * pos_params_pat_subst (string, pat, rep, mflags) char *string, *pat, *rep; int mflags; { WORD_LIST *save, *params; WORD_DESC *w; char *ret; int pchar, qflags, pflags; save = params = list_rest_of_args (); if (save == 0) return ((char *)NULL); for ( ; params; params = params->next) { ret = pat_subst (params->word->word, pat, rep, mflags); w = alloc_word_desc (); w->word = ret ? ret : savestring (""); dispose_word (params->word); params->word = w; } pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@'; qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0; pflags = (mflags & MATCH_ASSIGNRHS) == MATCH_ASSIGNRHS ? PF_ASSIGNRHS : 0; /* If we are expanding in a context where word splitting will not be performed, treat as quoted. This changes how $* will be expanded. */ if (pchar == '*' && (mflags & MATCH_ASSIGNRHS) && expand_no_split_dollar_star && ifs_is_null) qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */ ret = string_list_pos_params (pchar, save, qflags, pflags); dispose_words (save); return (ret); } /* Perform pattern substitution on VALUE, which is the expansion of VARNAME. PATSUB is an expression supplying the pattern to match and the string to substitute. QUOTED is a flags word containing the type of quoting currently in effect. */ static char * parameter_brace_patsub (varname, value, ind, patsub, quoted, pflags, flags) char *varname, *value; int ind; char *patsub; int quoted, pflags, flags; { int vtype, mflags, starsub, delim; char *val, *temp, *pat, *rep, *p, *lpatsub, *tt, *oname; SHELL_VAR *v; if (value == 0) return ((char *)NULL); oname = this_command_name; this_command_name = varname; /* error messages */ vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val); if (vtype == -1) { this_command_name = oname; return ((char *)NULL); } starsub = vtype & VT_STARSUB; vtype &= ~VT_STARSUB; mflags = 0; /* PATSUB is never NULL when this is called. */ if (*patsub == '/') { mflags |= MATCH_GLOBREP; patsub++; } /* Malloc this because expand_string_if_necessary or one of the expansion functions in its call chain may free it on a substitution error. */ lpatsub = savestring (patsub); if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) mflags |= MATCH_QUOTED; if (starsub) mflags |= MATCH_STARSUB; if (pflags & PF_ASSIGNRHS) mflags |= MATCH_ASSIGNRHS; /* If the pattern starts with a `/', make sure we skip over it when looking for the replacement delimiter. */ delim = skip_to_delim (lpatsub, ((*patsub == '/') ? 1 : 0), "/", 0); if (lpatsub[delim] == '/') { lpatsub[delim] = 0; rep = lpatsub + delim + 1; } else rep = (char *)NULL; if (rep && *rep == '\0') rep = (char *)NULL; /* Perform the same expansions on the pattern as performed by the pattern removal expansions. */ pat = getpattern (lpatsub, quoted, 1); if (rep) { /* We want to perform quote removal on the expanded replacement even if the entire expansion is double-quoted because the parser and string extraction functions treated quotes in the replacement string as special. THIS IS NOT BACKWARDS COMPATIBLE WITH BASH-4.2. */ if (shell_compatibility_level > 42) rep = expand_string_if_necessary (rep, quoted & ~(Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT), expand_string_unsplit); /* This is the bash-4.2 code. */ else if ((mflags & MATCH_QUOTED) == 0) rep = expand_string_if_necessary (rep, quoted, expand_string_unsplit); else rep = expand_string_to_string_internal (rep, quoted, expand_string_unsplit); } /* ksh93 doesn't allow the match specifier to be a part of the expanded pattern. This is an extension. Make sure we don't anchor the pattern at the beginning or end of the string if we're doing global replacement, though. */ p = pat; if (mflags & MATCH_GLOBREP) mflags |= MATCH_ANY; else if (pat && pat[0] == '#') { mflags |= MATCH_BEG; p++; } else if (pat && pat[0] == '%') { mflags |= MATCH_END; p++; } else mflags |= MATCH_ANY; /* OK, we now want to substitute REP for PAT in VAL. If flags & MATCH_GLOBREP is non-zero, the substitution is done everywhere, otherwise only the first occurrence of PAT is replaced. The pattern matching code doesn't understand CTLESC quoting CTLESC and CTLNUL so we use the dequoted variable values passed in (VT_VARIABLE) so the pattern substitution code works right. We need to requote special chars after we're done for VT_VARIABLE and VT_ARRAYMEMBER, and for the other cases if QUOTED == 0, since the posparams and arrays indexed by * or @ do special things when QUOTED != 0. */ switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: temp = pat_subst (val, p, rep, mflags); if (vtype == VT_VARIABLE) FREE (val); if (temp) { tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp); free (temp); temp = tt; } break; case VT_POSPARMS: /* This does the right thing for the case where we are not performing word splitting. MATCH_STARSUB restricts it to ${* /foo/bar}, and pos_params_pat_subst/string_list_pos_params will do the right thing in turn for the case where ifs_is_null. Posix interp 888 */ if ((pflags & PF_NOSPLIT2) && (mflags & MATCH_STARSUB)) mflags |= MATCH_ASSIGNRHS; temp = pos_params_pat_subst (val, p, rep, mflags); if (temp && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp && quoted == 0 && (pflags & PF_ASSIGNRHS)) { /* Posix interp 888 */ } else if (temp && (mflags & MATCH_QUOTED) == 0) { tt = quote_escapes (temp); free (temp); temp = tt; } break; #if defined (ARRAY_VARS) case VT_ARRAYVAR: /* If we are expanding in a context where word splitting will not be performed, treat as quoted. This changes how ${A[*]} will be expanded to make it identical to $*. */ if ((mflags & MATCH_STARSUB) && (mflags & MATCH_ASSIGNRHS) && ifs_is_null) mflags |= MATCH_QUOTED; /* Posix interp 888 */ /* these eventually call string_list_pos_params */ if (assoc_p (v)) temp = assoc_patsub (assoc_cell (v), p, rep, mflags); else temp = array_patsub (array_cell (v), p, rep, mflags); if (temp && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp && (mflags & MATCH_QUOTED) == 0) { tt = quote_escapes (temp); free (temp); temp = tt; } break; #endif } FREE (pat); FREE (rep); free (lpatsub); this_command_name = oname; return temp; } /****************************************************************/ /* */ /* Functions to perform case modification on variable values */ /* */ /****************************************************************/ /* Do case modification on the positional parameters. */ static char * pos_params_modcase (string, pat, modop, mflags) char *string, *pat; int modop; int mflags; { WORD_LIST *save, *params; WORD_DESC *w; char *ret; int pchar, qflags, pflags; save = params = list_rest_of_args (); if (save == 0) return ((char *)NULL); for ( ; params; params = params->next) { ret = sh_modcase (params->word->word, pat, modop); w = alloc_word_desc (); w->word = ret ? ret : savestring (""); dispose_word (params->word); params->word = w; } pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@'; qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0; pflags = (mflags & MATCH_ASSIGNRHS) == MATCH_ASSIGNRHS ? PF_ASSIGNRHS : 0; /* If we are expanding in a context where word splitting will not be performed, treat as quoted. This changes how $* will be expanded. */ if (pchar == '*' && (mflags & MATCH_ASSIGNRHS) && ifs_is_null) qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */ ret = string_list_pos_params (pchar, save, qflags, pflags); dispose_words (save); return (ret); } /* Perform case modification on VALUE, which is the expansion of VARNAME. MODSPEC is an expression supplying the type of modification to perform. QUOTED is a flags word containing the type of quoting currently in effect. */ static char * parameter_brace_casemod (varname, value, ind, modspec, patspec, quoted, pflags, flags) char *varname, *value; int ind, modspec; char *patspec; int quoted, pflags, flags; { int vtype, starsub, modop, mflags, x; char *val, *temp, *pat, *p, *lpat, *tt, *oname; SHELL_VAR *v; if (value == 0) return ((char *)NULL); oname = this_command_name; this_command_name = varname; vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val); if (vtype == -1) { this_command_name = oname; return ((char *)NULL); } starsub = vtype & VT_STARSUB; vtype &= ~VT_STARSUB; modop = 0; mflags = 0; if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) mflags |= MATCH_QUOTED; if (starsub) mflags |= MATCH_STARSUB; if (pflags & PF_ASSIGNRHS) mflags |= MATCH_ASSIGNRHS; p = patspec; if (modspec == '^') { x = p && p[0] == modspec; modop = x ? CASE_UPPER : CASE_UPFIRST; p += x; } else if (modspec == ',') { x = p && p[0] == modspec; modop = x ? CASE_LOWER : CASE_LOWFIRST; p += x; } else if (modspec == '~') { x = p && p[0] == modspec; modop = x ? CASE_TOGGLEALL : CASE_TOGGLE; p += x; } lpat = p ? savestring (p) : 0; /* Perform the same expansions on the pattern as performed by the pattern removal expansions. */ pat = lpat ? getpattern (lpat, quoted, 1) : 0; /* OK, now we do the case modification. */ switch (vtype) { case VT_VARIABLE: case VT_ARRAYMEMBER: temp = sh_modcase (val, pat, modop); if (vtype == VT_VARIABLE) FREE (val); if (temp) { tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp); free (temp); temp = tt; } break; case VT_POSPARMS: temp = pos_params_modcase (val, pat, modop, mflags); if (temp && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp && (mflags & MATCH_QUOTED) == 0) { tt = quote_escapes (temp); free (temp); temp = tt; } break; #if defined (ARRAY_VARS) case VT_ARRAYVAR: /* If we are expanding in a context where word splitting will not be performed, treat as quoted. This changes how ${A[*]} will be expanded to make it identical to $*. */ if ((mflags & MATCH_STARSUB) && (mflags & MATCH_ASSIGNRHS) && ifs_is_null) mflags |= MATCH_QUOTED; /* Posix interp 888 */ temp = assoc_p (v) ? assoc_modcase (assoc_cell (v), pat, modop, mflags) : array_modcase (array_cell (v), pat, modop, mflags); if (temp && quoted == 0 && ifs_is_null) { /* Posix interp 888 */ } else if (temp && (mflags & MATCH_QUOTED) == 0) { tt = quote_escapes (temp); free (temp); temp = tt; } break; #endif } FREE (pat); free (lpat); this_command_name = oname; return temp; } /* Check for unbalanced parens in S, which is the contents of $(( ... )). If any occur, this must be a nested command substitution, so return 0. Otherwise, return 1. A valid arithmetic expression must always have a ( before a matching ), so any cases where there are more right parens means that this must not be an arithmetic expression, though the parser will not accept it without a balanced total number of parens. */ static int chk_arithsub (s, len) const char *s; int len; { int i, count; DECLARE_MBSTATE; i = count = 0; while (i < len) { if (s[i] == LPAREN) count++; else if (s[i] == RPAREN) { count--; if (count < 0) return 0; } switch (s[i]) { default: ADVANCE_CHAR (s, len, i); break; case '\\': i++; if (s[i]) ADVANCE_CHAR (s, len, i); break; case '\'': i = skip_single_quoted (s, len, ++i, 0); break; case '"': i = skip_double_quoted ((char *)s, len, ++i, 0); break; } } return (count == 0); } /****************************************************************/ /* */ /* Functions to perform parameter expansion on a string */ /* */ /****************************************************************/ /* ${[#][!]name[[:][^[^]][,[,]]#[#]%[%]-=?+[word][:e1[:e2]]]} */ static WORD_DESC * parameter_brace_expand (string, indexp, quoted, pflags, quoted_dollar_atp, contains_dollar_at) char *string; int *indexp, quoted, pflags, *quoted_dollar_atp, *contains_dollar_at; { int check_nullness, var_is_set, var_is_null, var_is_special; int want_substring, want_indir, want_patsub, want_casemod, want_attributes; char *name, *value, *temp, *temp1; WORD_DESC *tdesc, *ret; int t_index, sindex, c, tflag, modspec, local_pflags, all_element_arrayref; intmax_t number; arrayind_t ind; temp = temp1 = value = (char *)NULL; var_is_set = var_is_null = var_is_special = check_nullness = 0; want_substring = want_indir = want_patsub = want_casemod = want_attributes = 0; local_pflags = 0; all_element_arrayref = 0; sindex = *indexp; t_index = ++sindex; /* ${#var} doesn't have any of the other parameter expansions on it. */ if (string[t_index] == '#' && legal_variable_starter (string[t_index+1])) /* {{ */ name = string_extract (string, &t_index, "}", SX_VARNAME); else #if defined (CASEMOD_EXPANSIONS) /* To enable case-toggling expansions using the `~' operator character define CASEMOD_TOGGLECASE in config-top.h */ # if defined (CASEMOD_TOGGLECASE) name = string_extract (string, &t_index, "#%^,~:-=?+/@}", SX_VARNAME); # else name = string_extract (string, &t_index, "#%^,:-=?+/@}", SX_VARNAME); # endif /* CASEMOD_TOGGLECASE */ #else name = string_extract (string, &t_index, "#%:-=?+/@}", SX_VARNAME); #endif /* CASEMOD_EXPANSIONS */ /* Handle ${@[stuff]} now that @ is a word expansion operator. Not exactly the cleanest code ever. */ if (*name == 0 && sindex == t_index && string[sindex] == '@') { name = (char *)xrealloc (name, 2); name[0] = '@'; name[1] = '\0'; t_index++; } else if (*name == '!' && t_index > sindex && string[t_index] == '@' && string[t_index+1] == RBRACE) { name = (char *)xrealloc (name, t_index - sindex + 2); name[t_index - sindex] = '@'; name[t_index - sindex + 1] = '\0'; t_index++; } ret = 0; tflag = 0; ind = INTMAX_MIN; /* If the name really consists of a special variable, then make sure that we have the entire name. We don't allow indirect references to special variables except `#', `?', `@' and `*'. This clause is designed to handle ${#SPECIAL} and ${!SPECIAL}, not anything more general. */ if ((sindex == t_index && VALID_SPECIAL_LENGTH_PARAM (string[t_index])) || (sindex == t_index && string[sindex] == '#' && VALID_SPECIAL_LENGTH_PARAM (string[sindex + 1])) || (sindex == t_index - 1 && string[sindex] == '!' && VALID_INDIR_PARAM (string[t_index]))) { t_index++; temp1 = string_extract (string, &t_index, "#%:-=?+/@}", 0); name = (char *)xrealloc (name, 3 + (strlen (temp1))); *name = string[sindex]; if (string[sindex] == '!') { /* indirect reference of $#, $?, $@, or $* */ name[1] = string[sindex + 1]; strcpy (name + 2, temp1); } else strcpy (name + 1, temp1); free (temp1); } sindex = t_index; /* Find out what character ended the variable name. Then do the appropriate thing. */ if (c = string[sindex]) sindex++; /* If c is followed by one of the valid parameter expansion characters, move past it as normal. If not, assume that a substring specification is being given, and do not move past it. */ if (c == ':' && VALID_PARAM_EXPAND_CHAR (string[sindex])) { check_nullness++; if (c = string[sindex]) sindex++; } else if (c == ':' && string[sindex] != RBRACE) want_substring = 1; else if (c == '/' /* && string[sindex] != RBRACE */) /* XXX */ want_patsub = 1; #if defined (CASEMOD_EXPANSIONS) else if (c == '^' || c == ',' || c == '~') { modspec = c; want_casemod = 1; } #endif else if (c == '@' && (string[sindex] == 'a' || string[sindex] == 'A') && string[sindex+1] == RBRACE) { /* special case because we do not want to shortcut foo as foo[0] here */ want_attributes = 1; local_pflags |= PF_ALLINDS; } /* Catch the valid and invalid brace expressions that made it through the tests above. */ /* ${#-} is a valid expansion and means to take the length of $-. Similarly for ${#?} and ${##}... */ if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 && VALID_SPECIAL_LENGTH_PARAM (c) && string[sindex] == RBRACE) { name = (char *)xrealloc (name, 3); name[1] = c; name[2] = '\0'; c = string[sindex++]; } /* ...but ${#%}, ${#:}, ${#=}, ${#+}, and ${#/} are errors. */ if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 && member (c, "%:=+/") && string[sindex] == RBRACE) { temp = (char *)NULL; goto bad_substitution; /* XXX - substitution error */ } /* Indirect expansion begins with a `!'. A valid indirect expansion is either a variable name, one of the positional parameters or a special variable that expands to one of the positional parameters. */ want_indir = *name == '!' && (legal_variable_starter ((unsigned char)name[1]) || DIGIT (name[1]) || VALID_INDIR_PARAM (name[1])); /* Determine the value of this variable whose name is NAME. */ /* Check for special variables, directly referenced. */ if (SPECIAL_VAR (name, want_indir)) var_is_special++; /* Check for special expansion things, like the length of a parameter */ if (*name == '#' && name[1]) { /* If we are not pointing at the character just after the closing brace, then we haven't gotten all of the name. Since it begins with a special character, this is a bad substitution. Also check NAME for validity before trying to go on. */ if (string[sindex - 1] != RBRACE || (valid_length_expression (name) == 0)) { temp = (char *)NULL; goto bad_substitution; /* substitution error */ } number = parameter_brace_expand_length (name); if (number == INTMAX_MIN && unbound_vars_is_error) { set_exit_status (EXECUTION_FAILURE); err_unboundvar (name+1); free (name); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } free (name); *indexp = sindex; if (number < 0) return (&expand_wdesc_error); else { ret = alloc_word_desc (); ret->word = itos (number); return ret; } } /* ${@} is identical to $@. */ if (name[0] == '@' && name[1] == '\0') { if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 1; if (contains_dollar_at) *contains_dollar_at = 1; tflag |= W_DOLLARAT; } /* Process ${!PREFIX*} expansion. */ if (want_indir && string[sindex - 1] == RBRACE && (string[sindex - 2] == '*' || string[sindex - 2] == '@') && legal_variable_starter ((unsigned char) name[1])) { char **x; WORD_LIST *xlist; temp1 = savestring (name + 1); number = strlen (temp1); temp1[number - 1] = '\0'; x = all_variables_matching_prefix (temp1); xlist = strvec_to_word_list (x, 0, 0); if (string[sindex - 2] == '*') temp = string_list_dollar_star (xlist, quoted, 0); else { temp = string_list_dollar_at (xlist, quoted, 0); if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 1; if (contains_dollar_at) *contains_dollar_at = 1; tflag |= W_DOLLARAT; } free (x); dispose_words (xlist); free (temp1); *indexp = sindex; free (name); ret = alloc_word_desc (); ret->word = temp; ret->flags = tflag; /* XXX */ return ret; } #if defined (ARRAY_VARS) /* Process ${!ARRAY[@]} and ${!ARRAY[*]} expansion. */ if (want_indir && string[sindex - 1] == RBRACE && string[sindex - 2] == RBRACK && valid_array_reference (name+1, 0)) { char *x, *x1; temp1 = savestring (name + 1); x = array_variable_name (temp1, 0, &x1, (int *)0); FREE (x); if (ALL_ELEMENT_SUB (x1[0]) && x1[1] == RBRACK) { temp = array_keys (temp1, quoted, pflags); /* handles assoc vars too */ if (x1[0] == '@') { if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 1; if (contains_dollar_at) *contains_dollar_at = 1; tflag |= W_DOLLARAT; } free (name); free (temp1); *indexp = sindex; ret = alloc_word_desc (); ret->word = temp; ret->flags = tflag; /* XXX */ return ret; } free (temp1); } #endif /* ARRAY_VARS */ /* Make sure that NAME is valid before trying to go on. */ if (valid_brace_expansion_word (want_indir ? name + 1 : name, var_is_special) == 0) { temp = (char *)NULL; goto bad_substitution; /* substitution error */ } if (want_indir) { tdesc = parameter_brace_expand_indir (name + 1, var_is_special, quoted, pflags|local_pflags, quoted_dollar_atp, contains_dollar_at); if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal) { temp = (char *)NULL; goto bad_substitution; } /* Turn off the W_ARRAYIND flag because there is no way for this function to return the index we're supposed to be using. */ if (tdesc && tdesc->flags) tdesc->flags &= ~W_ARRAYIND; } else { local_pflags |= PF_IGNUNBOUND|(pflags&(PF_NOSPLIT2|PF_ASSIGNRHS)); tdesc = parameter_brace_expand_word (name, var_is_special, quoted, local_pflags, &ind); } if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal) { tflag = 0; tdesc = 0; } if (tdesc) { temp = tdesc->word; tflag = tdesc->flags; dispose_word_desc (tdesc); } else temp = (char *)0; if (temp == &expand_param_error || temp == &expand_param_fatal) { FREE (name); FREE (value); return (temp == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal); } #if defined (ARRAY_VARS) if (valid_array_reference (name, 0)) { int qflags; char *t; qflags = quoted; /* If in a context where word splitting will not take place, treat as if double-quoted. Has effects with $* and ${array[*]} */ if (pflags & PF_ASSIGNRHS) qflags |= Q_DOUBLE_QUOTES; /* We duplicate a little code here */ t = mbschr (name, LBRACK); if (t && ALL_ELEMENT_SUB (t[1]) && t[2] == RBRACK) { all_element_arrayref = 1; if (expand_no_split_dollar_star && t[1] == '*') /* XXX */ qflags |= Q_DOUBLE_QUOTES; } chk_atstar (name, qflags, pflags, quoted_dollar_atp, contains_dollar_at); } #endif var_is_set = temp != (char *)0; var_is_null = check_nullness && (var_is_set == 0 || *temp == 0); /* XXX - this may not need to be restricted to special variables */ if (check_nullness) var_is_null |= var_is_set && var_is_special && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && QUOTED_NULL (temp); #if defined (ARRAY_VARS) if (check_nullness) var_is_null |= var_is_set && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && QUOTED_NULL (temp) && valid_array_reference (name, 0) && chk_atstar (name, 0, 0, (int *)0, (int *)0); #endif /* Get the rest of the stuff inside the braces. */ if (c && c != RBRACE) { /* Extract the contents of the ${ ... } expansion according to the Posix.2 rules. */ value = extract_dollar_brace_string (string, &sindex, quoted, (c == '%' || c == '#' || c =='/' || c == '^' || c == ',' || c ==':') ? SX_POSIXEXP|SX_WORD : SX_WORD); if (string[sindex] == RBRACE) sindex++; else goto bad_substitution; /* substitution error */ } else value = (char *)NULL; *indexp = sindex; /* All the cases where an expansion can possibly generate an unbound variable error. */ if (want_substring || want_patsub || want_casemod || c == '@' || c == '#' || c == '%' || c == RBRACE) { if (var_is_set == 0 && unbound_vars_is_error && ((name[0] != '@' && name[0] != '*') || name[1]) && all_element_arrayref == 0) { set_exit_status (EXECUTION_FAILURE); err_unboundvar (name); FREE (value); FREE (temp); free (name); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } } /* If this is a substring spec, process it and add the result. */ if (want_substring) { temp1 = parameter_brace_substring (name, temp, ind, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0); FREE (value); FREE (temp); if (temp1 == &expand_param_error || temp1 == &expand_param_fatal) { FREE (name); return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal); } ret = alloc_word_desc (); ret->word = temp1; /* We test quoted_dollar_atp because we want variants with double-quoted "$@" to take a different code path. In fact, we make sure at the end of expand_word_internal that we're only looking at these flags if quoted_dollar_at == 0. */ if (temp1 && (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ret->flags |= W_QUOTED|W_HASQUOTEDNULL; else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && (pflags & PF_ASSIGNRHS)) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */ else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ FREE (name); return ret; } else if (want_patsub) { temp1 = parameter_brace_patsub (name, temp, ind, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0); FREE (value); FREE (temp); if (temp1 == &expand_param_error || temp1 == &expand_param_fatal) { FREE (name); return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal); } ret = alloc_word_desc (); ret->word = temp1; if (temp1 && (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ret->flags |= W_QUOTED|W_HASQUOTEDNULL; /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */ else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ FREE (name); return ret; } #if defined (CASEMOD_EXPANSIONS) else if (want_casemod) { temp1 = parameter_brace_casemod (name, temp, ind, modspec, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0); FREE (value); FREE (temp); if (temp1 == &expand_param_error || temp1 == &expand_param_fatal) { FREE (name); return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal); } ret = alloc_word_desc (); ret->word = temp1; if (temp1 && (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ret->flags |= W_QUOTED|W_HASQUOTEDNULL; /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */ else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ FREE (name); return ret; } #endif /* Do the right thing based on which character ended the variable name. */ switch (c) { default: case '\0': bad_substitution: set_exit_status (EXECUTION_FAILURE); report_error (_("%s: bad substitution"), string ? string : "??"); FREE (value); FREE (temp); free (name); if (shell_compatibility_level <= 43) return &expand_wdesc_error; else return ((posixly_correct && interactive_shell == 0) ? &expand_wdesc_fatal : &expand_wdesc_error); case RBRACE: break; case '@': temp1 = parameter_brace_transform (name, temp, ind, value, c, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0); free (temp); free (value); if (temp1 == &expand_param_error || temp1 == &expand_param_fatal) { free (name); set_exit_status (EXECUTION_FAILURE); report_error (_("%s: bad substitution"), string ? string : "??"); return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal); } ret = alloc_word_desc (); ret->word = temp1; if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ret->flags |= W_QUOTED|W_HASQUOTEDNULL; /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */ else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ free (name); return ret; case '#': /* ${param#[#]pattern} */ case '%': /* ${param%[%]pattern} */ if (value == 0 || *value == '\0' || temp == 0 || *temp == '\0') { FREE (value); break; } temp1 = parameter_brace_remove_pattern (name, temp, ind, value, c, quoted, (tflag & W_ARRAYIND) ? AV_USEIND : 0); free (temp); free (value); ret = alloc_word_desc (); ret->word = temp1; if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ret->flags |= W_QUOTED|W_HASQUOTEDNULL; /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */ else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null) ret->flags |= W_SPLITSPACE; /* Posix interp 888 */ free (name); return ret; case '-': case '=': case '?': case '+': if (var_is_set && var_is_null == 0) { /* If the operator is `+', we don't want the value of the named variable for anything, just the value of the right hand side. */ if (c == '+') { /* XXX -- if we're double-quoted and the named variable is "$@", we want to turn off any special handling of "$@" -- we're not using it, so whatever is on the rhs applies. */ if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 0; if (contains_dollar_at) *contains_dollar_at = 0; FREE (temp); if (value) { /* From Posix discussion on austin-group list. Issue 221 requires that backslashes escaping `}' inside double-quoted ${...} be removed. */ if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) quoted |= Q_DOLBRACE; ret = parameter_brace_expand_rhs (name, value, c, quoted, pflags, quoted_dollar_atp, contains_dollar_at); /* XXX - fix up later, esp. noting presence of W_HASQUOTEDNULL in ret->flags */ free (value); } else temp = (char *)NULL; } else { FREE (value); } /* Otherwise do nothing; just use the value in TEMP. */ } else /* VAR not set or VAR is NULL. */ { FREE (temp); temp = (char *)NULL; if (c == '=' && var_is_special) { set_exit_status (EXECUTION_FAILURE); report_error (_("$%s: cannot assign in this way"), name); free (name); free (value); return &expand_wdesc_error; } else if (c == '?') { parameter_brace_expand_error (name, value, check_nullness); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } else if (c != '+') { /* XXX -- if we're double-quoted and the named variable is "$@", we want to turn off any special handling of "$@" -- we're not using it, so whatever is on the rhs applies. */ if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp) *quoted_dollar_atp = 0; if (contains_dollar_at) *contains_dollar_at = 0; /* From Posix discussion on austin-group list. Issue 221 requires that backslashes escaping `}' inside double-quoted ${...} be removed. */ if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) quoted |= Q_DOLBRACE; ret = parameter_brace_expand_rhs (name, value, c, quoted, pflags, quoted_dollar_atp, contains_dollar_at); /* XXX - fix up later, esp. noting presence of W_HASQUOTEDNULL in tdesc->flags */ } free (value); } break; } free (name); if (ret == 0) { ret = alloc_word_desc (); ret->flags = tflag; ret->word = temp; } return (ret); } /* Expand a single ${xxx} expansion. The braces are optional. When the braces are used, parameter_brace_expand() does the work, possibly calling param_expand recursively. */ static WORD_DESC * param_expand (string, sindex, quoted, expanded_something, contains_dollar_at, quoted_dollar_at_p, had_quoted_null_p, pflags) char *string; int *sindex, quoted, *expanded_something, *contains_dollar_at; int *quoted_dollar_at_p, *had_quoted_null_p, pflags; { char *temp, *temp1, uerror[3], *savecmd; int zindex, t_index, expok; unsigned char c; intmax_t number; SHELL_VAR *var; WORD_LIST *list, *l; WORD_DESC *tdesc, *ret; int tflag, nullarg; /*itrace("param_expand: `%s' pflags = %d", string+*sindex, pflags);*/ zindex = *sindex; c = string[++zindex]; temp = (char *)NULL; ret = tdesc = (WORD_DESC *)NULL; tflag = 0; /* Do simple cases first. Switch on what follows '$'. */ switch (c) { /* $0 .. $9? */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': temp1 = dollar_vars[TODIGIT (c)]; /* This doesn't get called when (pflags&PF_IGNUNBOUND) != 0 */ if (unbound_vars_is_error && temp1 == (char *)NULL) { uerror[0] = '$'; uerror[1] = c; uerror[2] = '\0'; set_exit_status (EXECUTION_FAILURE); err_unboundvar (uerror); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } if (temp1) temp = (*temp1 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ? quote_string (temp1) : quote_escapes (temp1); else temp = (char *)NULL; break; /* $$ -- pid of the invoking shell. */ case '$': temp = itos (dollar_dollar_pid); break; /* $# -- number of positional parameters. */ case '#': temp = itos (number_of_args ()); break; /* $? -- return value of the last synchronous command. */ case '?': temp = itos (last_command_exit_value); break; /* $- -- flags supplied to the shell on invocation or by `set'. */ case '-': temp = which_set_flags (); break; /* $! -- Pid of the last asynchronous command. */ case '!': /* If no asynchronous pids have been created, expand to nothing. If `set -u' has been executed, and no async processes have been created, this is an expansion error. */ if (last_asynchronous_pid == NO_PID) { if (expanded_something) *expanded_something = 0; temp = (char *)NULL; if (unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0) { uerror[0] = '$'; uerror[1] = c; uerror[2] = '\0'; set_exit_status (EXECUTION_FAILURE); err_unboundvar (uerror); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } } else temp = itos (last_asynchronous_pid); break; /* The only difference between this and $@ is when the arg is quoted. */ case '*': /* `$*' */ list = list_rest_of_args (); #if 0 /* According to austin-group posix proposal by Geoff Clare in <[email protected]> of 5 May 2009: "The shell shall write a message to standard error and immediately exit when it tries to expand an unset parameter other than the '@' and '*' special parameters." */ if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0) { uerror[0] = '$'; uerror[1] = '*'; uerror[2] = '\0'; set_exit_status (EXECUTION_FAILURE); err_unboundvar (uerror); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } #endif /* If there are no command-line arguments, this should just disappear if there are other characters in the expansion, even if it's quoted. */ if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && list == 0) temp = (char *)NULL; else if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES|Q_PATQUOTE)) { /* If we have "$*" we want to make a string of the positional parameters, separated by the first character of $IFS, and quote the whole string, including the separators. If IFS is unset, the parameters are separated by ' '; if $IFS is null, the parameters are concatenated. */ temp = (quoted & (Q_DOUBLE_QUOTES|Q_PATQUOTE)) ? string_list_dollar_star (list, quoted, 0) : string_list (list); if (temp) { temp1 = (quoted & Q_DOUBLE_QUOTES) ? quote_string (temp) : temp; if (*temp == 0) tflag |= W_HASQUOTEDNULL; if (temp != temp1) free (temp); temp = temp1; } } else { /* We check whether or not we're eventually going to split $* here, for example when IFS is empty and we are processing the rhs of an assignment statement. In that case, we don't separate the arguments at all. Otherwise, if the $* is not quoted it is identical to $@ */ if (expand_no_split_dollar_star && quoted == 0 && ifs_is_set == 0 && (pflags & PF_ASSIGNRHS)) { /* Posix interp 888: RHS of assignment, IFS unset: no splitting, separate with space */ temp1 = string_list_dollar_star (list, quoted, pflags); temp = temp1 ? quote_string (temp1) : temp1; /* XXX - tentative - note that we saw a quoted null here */ if (temp1 && *temp1 == 0 && QUOTED_NULL (temp)) tflag |= W_SAWQUOTEDNULL; FREE (temp1); } else if (expand_no_split_dollar_star && quoted == 0 && ifs_is_null && (pflags & PF_ASSIGNRHS)) { /* Posix interp 888: RHS of assignment, IFS set to '' */ temp1 = string_list_dollar_star (list, quoted, pflags); temp = temp1 ? quote_escapes (temp1) : temp1; FREE (temp1); } else if (expand_no_split_dollar_star && quoted == 0 && ifs_is_set && ifs_is_null == 0 && (pflags & PF_ASSIGNRHS)) { /* Posix interp 888: RHS of assignment, IFS set to non-null value */ temp1 = string_list_dollar_star (list, quoted, pflags); temp = temp1 ? quote_string (temp1) : temp1; /* XXX - tentative - note that we saw a quoted null here */ if (temp1 && *temp1 == 0 && QUOTED_NULL (temp)) tflag |= W_SAWQUOTEDNULL; FREE (temp1); } /* XXX - should we check ifs_is_set here as well? */ # if defined (HANDLE_MULTIBYTE) else if (expand_no_split_dollar_star && ifs_firstc[0] == 0) # else else if (expand_no_split_dollar_star && ifs_firstc == 0) # endif /* Posix interp 888: not RHS, no splitting, IFS set to '' */ temp = string_list_dollar_star (list, quoted, 0); else { temp = string_list_dollar_at (list, quoted, 0); /* Set W_SPLITSPACE to make sure the individual positional parameters are split into separate arguments */ #if 0 if (quoted == 0 && (ifs_is_set == 0 || ifs_is_null)) #else /* change with bash-5.0 */ if (quoted == 0 && ifs_is_null) #endif tflag |= W_SPLITSPACE; /* If we're not quoted but we still don't want word splitting, make we quote the IFS characters to protect them from splitting (e.g., when $@ is in the string as well). */ else if (temp && quoted == 0 && ifs_is_set && (pflags & PF_ASSIGNRHS)) { temp1 = quote_string (temp); free (temp); temp = temp1; } } if (expand_no_split_dollar_star == 0 && contains_dollar_at) *contains_dollar_at = 1; } dispose_words (list); break; /* When we have "$@" what we want is "$1" "$2" "$3" ... This means that we have to turn quoting off after we split into the individually quoted arguments so that the final split on the first character of $IFS is still done. */ case '@': /* `$@' */ list = list_rest_of_args (); #if 0 /* According to austin-group posix proposal by Geoff Clare in <[email protected]> of 5 May 2009: "The shell shall write a message to standard error and immediately exit when it tries to expand an unset parameter other than the '@' and '*' special parameters." */ if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0) { uerror[0] = '$'; uerror[1] = '@'; uerror[2] = '\0'; set_exit_status (EXECUTION_FAILURE); err_unboundvar (uerror); return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal); } #endif for (nullarg = 0, l = list; l; l = l->next) { if (l->word && (l->word->word == 0 || l->word->word[0] == 0)) nullarg = 1; } /* We want to flag the fact that we saw this. We can't turn off quoting entirely, because other characters in the string might need it (consider "\"$@\""), but we need some way to signal that the final split on the first character of $IFS should be done, even though QUOTED is 1. */ /* XXX - should this test include Q_PATQUOTE? */ if (quoted_dollar_at_p && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) *quoted_dollar_at_p = 1; if (contains_dollar_at) *contains_dollar_at = 1; /* We want to separate the positional parameters with the first character of $IFS in case $IFS is something other than a space. We also want to make sure that splitting is done no matter what -- according to POSIX.2, this expands to a list of the positional parameters no matter what IFS is set to. */ /* XXX - what to do when in a context where word splitting is not performed? Even when IFS is not the default, posix seems to imply that we have to expand $@ to all the positional parameters and separate them with spaces, which are preserved because word splitting doesn't take place. See below for how we use PF_NOSPLIT2 here. */ /* These are the cases where word splitting will not be performed. */ if (pflags & PF_ASSIGNRHS) { temp = string_list_dollar_at (list, (quoted|Q_DOUBLE_QUOTES), pflags); if (nullarg) tflag |= W_HASQUOTEDNULL; /* we know quoting produces quoted nulls */ } /* This needs to match what expand_word_internal does with non-quoted $@ does with separating with spaces. Passing Q_DOUBLE_QUOTES means that the characters in LIST will be quoted, and PF_ASSIGNRHS ensures that they will separated by spaces. After doing this, we need the special handling for PF_NOSPLIT2 in expand_word_internal to remove the CTLESC quotes. */ else if (pflags & PF_NOSPLIT2) { #if defined (HANDLE_MULTIBYTE) if (quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc[0] != ' ') #else if (quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc != ' ') #endif /* Posix interp 888 */ temp = string_list_dollar_at (list, Q_DOUBLE_QUOTES, pflags); else temp = string_list_dollar_at (list, quoted, pflags); } else temp = string_list_dollar_at (list, quoted, pflags); tflag |= W_DOLLARAT; dispose_words (list); break; case LBRACE: tdesc = parameter_brace_expand (string, &zindex, quoted, pflags, quoted_dollar_at_p, contains_dollar_at); if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal) return (tdesc); temp = tdesc ? tdesc->word : (char *)0; /* XXX */ /* Quoted nulls should be removed if there is anything else in the string. */ /* Note that we saw the quoted null so we can add one back at the end of this function if there are no other characters in the string, discard TEMP, and go on. The exception to this is when we have "${@}" and $1 is '', since $@ needs special handling. */ if (tdesc && tdesc->word && (tdesc->flags & W_HASQUOTEDNULL) && QUOTED_NULL (temp)) { if (had_quoted_null_p) *had_quoted_null_p = 1; if (*quoted_dollar_at_p == 0) { free (temp); tdesc->word = temp = (char *)NULL; } } ret = tdesc; goto return0; /* Do command or arithmetic substitution. */ case LPAREN: /* We have to extract the contents of this paren substitution. */ t_index = zindex + 1; /* XXX - might want to check for string[t_index+2] == LPAREN and parse as arithmetic substitution immediately. */ temp = extract_command_subst (string, &t_index, (pflags&PF_COMPLETE) ? SX_COMPLETE : 0); zindex = t_index; /* For Posix.2-style `$(( ))' arithmetic substitution, extract the expression and pass it to the evaluator. */ if (temp && *temp == LPAREN) { char *temp2; temp1 = temp + 1; temp2 = savestring (temp1); t_index = strlen (temp2) - 1; if (temp2[t_index] != RPAREN) { free (temp2); goto comsub; } /* Cut off ending `)' */ temp2[t_index] = '\0'; if (chk_arithsub (temp2, t_index) == 0) { free (temp2); #if 0 internal_warning (_("future versions of the shell will force evaluation as an arithmetic substitution")); #endif goto comsub; } /* Expand variables found inside the expression. */ temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES|Q_ARITH); free (temp2); arithsub: /* No error messages. */ savecmd = this_command_name; this_command_name = (char *)NULL; number = evalexp (temp1, EXP_EXPANDED, &expok); this_command_name = savecmd; free (temp); free (temp1); if (expok == 0) { if (interactive_shell == 0 && posixly_correct) { set_exit_status (EXECUTION_FAILURE); return (&expand_wdesc_fatal); } else return (&expand_wdesc_error); } temp = itos (number); break; } comsub: if (pflags & PF_NOCOMSUB) /* we need zindex+1 because string[zindex] == RPAREN */ temp1 = substring (string, *sindex, zindex+1); else { tdesc = command_substitute (temp, quoted, pflags&PF_ASSIGNRHS); temp1 = tdesc ? tdesc->word : (char *)NULL; if (tdesc) dispose_word_desc (tdesc); } FREE (temp); temp = temp1; break; /* Do POSIX.2d9-style arithmetic substitution. This will probably go away in a future bash release. */ case '[': /*]*/ /* Extract the contents of this arithmetic substitution. */ t_index = zindex + 1; temp = extract_arithmetic_subst (string, &t_index); zindex = t_index; if (temp == 0) { temp = savestring (string); if (expanded_something) *expanded_something = 0; goto return0; } /* Do initial variable expansion. */ temp1 = expand_arith_string (temp, Q_DOUBLE_QUOTES|Q_ARITH); goto arithsub; default: /* Find the variable in VARIABLE_LIST. */ temp = (char *)NULL; for (t_index = zindex; (c = string[zindex]) && legal_variable_char (c); zindex++) ; temp1 = (zindex > t_index) ? substring (string, t_index, zindex) : (char *)NULL; /* If this isn't a variable name, then just output the `$'. */ if (temp1 == 0 || *temp1 == '\0') { FREE (temp1); temp = (char *)xmalloc (2); temp[0] = '$'; temp[1] = '\0'; if (expanded_something) *expanded_something = 0; goto return0; } /* If the variable exists, return its value cell. */ var = find_variable (temp1); if (var && invisible_p (var) == 0 && var_isset (var)) { #if defined (ARRAY_VARS) if (assoc_p (var) || array_p (var)) { temp = array_p (var) ? array_reference (array_cell (var), 0) : assoc_reference (assoc_cell (var), "0"); if (temp) temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ? quote_string (temp) : quote_escapes (temp); else if (unbound_vars_is_error) goto unbound_variable; } else #endif { temp = value_cell (var); temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))) ? quote_string (temp) : ((pflags & PF_ASSIGNRHS) ? quote_rhs (temp) : quote_escapes (temp)); } free (temp1); goto return0; } else if (var && (invisible_p (var) || var_isset (var) == 0)) temp = (char *)NULL; else if ((var = find_variable_last_nameref (temp1, 0)) && var_isset (var) && invisible_p (var) == 0) { temp = nameref_cell (var); #if defined (ARRAY_VARS) if (temp && *temp && valid_array_reference (temp, 0)) { tdesc = parameter_brace_expand_word (temp, SPECIAL_VAR (temp, 0), quoted, pflags, (arrayind_t *)NULL); if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal) return (tdesc); ret = tdesc; goto return0; } else #endif /* y=2 ; typeset -n x=y; echo $x is not the same as echo $2 in ksh */ if (temp && *temp && legal_identifier (temp) == 0) { set_exit_status (EXECUTION_FAILURE); report_error (_("%s: invalid variable name for name reference"), temp); return (&expand_wdesc_error); /* XXX */ } else temp = (char *)NULL; } temp = (char *)NULL; unbound_variable: if (unbound_vars_is_error) { set_exit_status (EXECUTION_FAILURE); err_unboundvar (temp1); } else { free (temp1); goto return0; } free (temp1); set_exit_status (EXECUTION_FAILURE); return ((unbound_vars_is_error && interactive_shell == 0) ? &expand_wdesc_fatal : &expand_wdesc_error); } if (string[zindex]) zindex++; return0: *sindex = zindex; if (ret == 0) { ret = alloc_word_desc (); ret->flags = tflag; /* XXX */ ret->word = temp; } return ret; } void invalidate_cached_quoted_dollar_at () { dispose_words (cached_quoted_dollar_at); cached_quoted_dollar_at = 0; } /* Make a word list which is the result of parameter and variable expansion, command substitution, arithmetic substitution, and quote removal of WORD. Return a pointer to a WORD_LIST which is the result of the expansion. If WORD contains a null word, the word list returned is also null. QUOTED contains flag values defined in shell.h. ISEXP is used to tell expand_word_internal that the word should be treated as the result of an expansion. This has implications for how IFS characters in the word are treated. CONTAINS_DOLLAR_AT and EXPANDED_SOMETHING are return values; when non-null they point to an integer value which receives information about expansion. CONTAINS_DOLLAR_AT gets non-zero if WORD contained "$@", else zero. EXPANDED_SOMETHING get non-zero if WORD contained any parameter expansions, else zero. This only does word splitting in the case of $@ expansion. In that case, we split on ' '. */ /* Values for the local variable quoted_state. */ #define UNQUOTED 0 #define PARTIALLY_QUOTED 1 #define WHOLLY_QUOTED 2 static WORD_LIST * expand_word_internal (word, quoted, isexp, contains_dollar_at, expanded_something) WORD_DESC *word; int quoted, isexp; int *contains_dollar_at; int *expanded_something; { WORD_LIST *list; WORD_DESC *tword; /* The intermediate string that we build while expanding. */ char *istring; /* The current size of the above object. */ size_t istring_size; /* Index into ISTRING. */ int istring_index; /* Temporary string storage. */ char *temp, *temp1; /* The text of WORD. */ register char *string; /* The size of STRING. */ size_t string_size; /* The index into STRING. */ int sindex; /* This gets 1 if we see a $@ while quoted. */ int quoted_dollar_at; /* One of UNQUOTED, PARTIALLY_QUOTED, or WHOLLY_QUOTED, depending on whether WORD contains no quoting characters, a partially quoted string (e.g., "xx"ab), or is fully quoted (e.g., "xxab"). */ int quoted_state; /* State flags */ int had_quoted_null; int has_quoted_ifs; /* did we add a quoted $IFS character here? */ int has_dollar_at, temp_has_dollar_at; int split_on_spaces; int local_expanded; int tflag; int pflags; /* flags passed to param_expand */ int mb_cur_max; int assignoff; /* If assignment, offset of `=' */ register unsigned char c; /* Current character. */ int t_index; /* For calls to string_extract_xxx. */ char twochars[2]; DECLARE_MBSTATE; /* OK, let's see if we can optimize a common idiom: "$@" */ if (STREQ (word->word, "\"$@\"") && (word->flags == (W_HASDOLLAR|W_QUOTED)) && dollar_vars[1]) /* XXX - check IFS here as well? */ { if (contains_dollar_at) *contains_dollar_at = 1; if (expanded_something) *expanded_something = 1; if (cached_quoted_dollar_at) return (copy_word_list (cached_quoted_dollar_at)); list = list_rest_of_args (); list = quote_list (list); cached_quoted_dollar_at = copy_word_list (list); return (list); } istring = (char *)xmalloc (istring_size = DEFAULT_INITIAL_ARRAY_SIZE); istring[istring_index = 0] = '\0'; quoted_dollar_at = had_quoted_null = has_dollar_at = 0; has_quoted_ifs = 0; split_on_spaces = 0; quoted_state = UNQUOTED; string = word->word; if (string == 0) goto finished_with_string; mb_cur_max = MB_CUR_MAX; /* Don't need the string length for the SADD... and COPY_ macros unless multibyte characters are possible, but do need it for bounds checking. */ string_size = (mb_cur_max > 1) ? strlen (string) : 1; if (contains_dollar_at) *contains_dollar_at = 0; assignoff = -1; /* Begin the expansion. */ for (sindex = 0; ;) { c = string[sindex]; /* Case on top-level character. */ switch (c) { case '\0': goto finished_with_string; case CTLESC: sindex++; #if HANDLE_MULTIBYTE if (mb_cur_max > 1 && string[sindex]) { SADD_MBQCHAR_BODY(temp, string, sindex, string_size); } else #endif { temp = (char *)xmalloc (3); temp[0] = CTLESC; temp[1] = c = string[sindex]; temp[2] = '\0'; } dollar_add_string: if (string[sindex]) sindex++; add_string: if (temp) { istring = sub_append_string (temp, istring, &istring_index, &istring_size); temp = (char *)0; } break; #if defined (PROCESS_SUBSTITUTION) /* Process substitution. */ case '<': case '>': { /* XXX - technically this should only be expanded at the start of a word */ if (string[++sindex] != LPAREN || (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (word->flags & (W_DQUOTE|W_NOPROCSUB))) { sindex--; /* add_character: label increments sindex */ goto add_character; } else t_index = sindex + 1; /* skip past both '<' and LPAREN */ temp1 = extract_process_subst (string, (c == '<') ? "<(" : ">(", &t_index, 0); /*))*/ sindex = t_index; /* If the process substitution specification is `<()', we want to open the pipe for writing in the child and produce output; if it is `>()', we want to open the pipe for reading in the child and consume input. */ temp = temp1 ? process_substitute (temp1, (c == '>')) : (char *)0; FREE (temp1); goto dollar_add_string; } #endif /* PROCESS_SUBSTITUTION */ case '=': /* Posix.2 section 3.6.1 says that tildes following `=' in words which are not assignment statements are not expanded. If the shell isn't in posix mode, though, we perform tilde expansion on `likely candidate' unquoted assignment statements (flags include W_ASSIGNMENT but not W_QUOTED). A likely candidate contains an unquoted :~ or =~. Something to think about: we now have a flag that says to perform tilde expansion on arguments to `assignment builtins' like declare and export that look like assignment statements. We now do tilde expansion on such words even in POSIX mode. */ if (word->flags & (W_ASSIGNRHS|W_NOTILDE)) { if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c)) goto add_ifs_character; else goto add_character; } /* If we're not in posix mode or forcing assignment-statement tilde expansion, note where the first `=' appears in the word and prepare to do tilde expansion following the first `='. We have to keep track of the first `=' (using assignoff) to avoid being confused by an `=' in the rhs of the assignment statement. */ if ((word->flags & W_ASSIGNMENT) && (posixly_correct == 0 || (word->flags & W_TILDEEXP)) && assignoff == -1 && sindex > 0) assignoff = sindex; if (sindex == assignoff && string[sindex+1] == '~') /* XXX */ word->flags |= W_ITILDE; if (word->flags & W_ASSIGNARG) word->flags |= W_ASSIGNRHS; /* affects $@ */ if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c)) { has_quoted_ifs++; goto add_ifs_character; } else goto add_character; case ':': if (word->flags & (W_NOTILDE|W_NOASSNTILDE)) { if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c)) goto add_ifs_character; else goto add_character; } if ((word->flags & (W_ASSIGNMENT|W_ASSIGNRHS)) && (posixly_correct == 0 || (word->flags & W_TILDEEXP)) && string[sindex+1] == '~') word->flags |= W_ITILDE; if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c)) goto add_ifs_character; else goto add_character; case '~': /* If the word isn't supposed to be tilde expanded, or we're not at the start of a word or after an unquoted : or = in an assignment statement, we don't do tilde expansion. We don't do tilde expansion if quoted or in an arithmetic context. */ if ((word->flags & (W_NOTILDE|W_DQUOTE)) || (sindex > 0 && ((word->flags & W_ITILDE) == 0)) || (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) { word->flags &= ~W_ITILDE; if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0) goto add_ifs_character; else goto add_character; } if (word->flags & W_ASSIGNRHS) tflag = 2; else if (word->flags & (W_ASSIGNMENT|W_TILDEEXP)) tflag = 1; else tflag = 0; temp = bash_tilde_find_word (string + sindex, tflag, &t_index); word->flags &= ~W_ITILDE; if (temp && *temp && t_index > 0) { temp1 = bash_tilde_expand (temp, tflag); if (temp1 && *temp1 == '~' && STREQ (temp, temp1)) { FREE (temp); FREE (temp1); goto add_character; /* tilde expansion failed */ } free (temp); temp = temp1; sindex += t_index; goto add_quoted_string; /* XXX was add_string */ } else { FREE (temp); goto add_character; } case '$': if (expanded_something) *expanded_something = 1; local_expanded = 1; temp_has_dollar_at = 0; pflags = (word->flags & W_NOCOMSUB) ? PF_NOCOMSUB : 0; if (word->flags & W_NOSPLIT2) pflags |= PF_NOSPLIT2; if (word->flags & W_ASSIGNRHS) pflags |= PF_ASSIGNRHS; if (word->flags & W_COMPLETE) pflags |= PF_COMPLETE; tword = param_expand (string, &sindex, quoted, expanded_something, &temp_has_dollar_at, &quoted_dollar_at, &had_quoted_null, pflags); has_dollar_at += temp_has_dollar_at; split_on_spaces += (tword->flags & W_SPLITSPACE); if (tword == &expand_wdesc_error || tword == &expand_wdesc_fatal) { free (string); free (istring); return ((tword == &expand_wdesc_error) ? &expand_word_error : &expand_word_fatal); } if (contains_dollar_at && has_dollar_at) *contains_dollar_at = 1; if (tword && (tword->flags & W_HASQUOTEDNULL)) had_quoted_null = 1; /* note for later */ if (tword && (tword->flags & W_SAWQUOTEDNULL)) had_quoted_null = 1; /* XXX */ temp = tword ? tword->word : (char *)NULL; dispose_word_desc (tword); /* Kill quoted nulls; we will add them back at the end of expand_word_internal if nothing else in the string */ if (had_quoted_null && temp && QUOTED_NULL (temp)) { FREE (temp); temp = (char *)NULL; } goto add_string; break; case '`': /* Backquoted command substitution. */ { t_index = sindex++; temp = string_extract (string, &sindex, "`", SX_REQMATCH); /* The test of sindex against t_index is to allow bare instances of ` to pass through, for backwards compatibility. */ if (temp == &extract_string_error || temp == &extract_string_fatal) { if (sindex - 1 == t_index) { sindex = t_index; goto add_character; } set_exit_status (EXECUTION_FAILURE); report_error (_("bad substitution: no closing \"`\" in %s") , string+t_index); free (string); free (istring); return ((temp == &extract_string_error) ? &expand_word_error : &expand_word_fatal); } if (expanded_something) *expanded_something = 1; local_expanded = 1; if (word->flags & W_NOCOMSUB) /* sindex + 1 because string[sindex] == '`' */ temp1 = substring (string, t_index, sindex + 1); else { de_backslash (temp); tword = command_substitute (temp, quoted, 0); temp1 = tword ? tword->word : (char *)NULL; if (tword) dispose_word_desc (tword); } FREE (temp); temp = temp1; goto dollar_add_string; } case '\\': if (string[sindex + 1] == '\n') { sindex += 2; continue; } c = string[++sindex]; /* "However, the double-quote character ( '"' ) shall not be treated specially within a here-document, except when the double-quote appears within "$()", "``", or "${}"." */ if ((quoted & Q_HERE_DOCUMENT) && (quoted & Q_DOLBRACE) && c == '"') tflag = CBSDQUOTE; /* special case */ else if (quoted & Q_HERE_DOCUMENT) tflag = CBSHDOC; else if (quoted & Q_DOUBLE_QUOTES) tflag = CBSDQUOTE; else tflag = 0; /* From Posix discussion on austin-group list: Backslash escaping a } in ${...} is removed. Issue 0000221 */ if ((quoted & Q_DOLBRACE) && c == RBRACE) { SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size); } /* This is the fix for " $@\ " */ else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && ((sh_syntaxtab[c] & tflag) == 0) && isexp == 0 && isifs (c)) { RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE); istring[istring_index++] = CTLESC; istring[istring_index++] = '\\'; istring[istring_index] = '\0'; SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size); } else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && c == 0) { RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE); istring[istring_index++] = CTLESC; istring[istring_index++] = '\\'; istring[istring_index] = '\0'; break; } else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && ((sh_syntaxtab[c] & tflag) == 0)) { SCOPY_CHAR_I (twochars, '\\', c, string, sindex, string_size); } else if (c == 0) { c = CTLNUL; sindex--; /* add_character: label increments sindex */ goto add_character; } else { SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size); } sindex++; add_twochars: /* BEFORE jumping here, we need to increment sindex if appropriate */ RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE); istring[istring_index++] = twochars[0]; istring[istring_index++] = twochars[1]; istring[istring_index] = '\0'; break; case '"': if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) && ((quoted & Q_ARITH) == 0)) goto add_character; t_index = ++sindex; temp = string_extract_double_quoted (string, &sindex, (word->flags & W_COMPLETE) ? SX_COMPLETE : 0); /* If the quotes surrounded the entire string, then the whole word was quoted. */ quoted_state = (t_index == 1 && string[sindex] == '\0') ? WHOLLY_QUOTED : PARTIALLY_QUOTED; if (temp && *temp) { tword = alloc_word_desc (); tword->word = temp; if (word->flags & W_ASSIGNARG) tword->flags |= word->flags & (W_ASSIGNARG|W_ASSIGNRHS); /* affects $@ */ if (word->flags & W_COMPLETE) tword->flags |= W_COMPLETE; /* for command substitutions */ if (word->flags & W_NOCOMSUB) tword->flags |= W_NOCOMSUB; if (word->flags & W_NOPROCSUB) tword->flags |= W_NOPROCSUB; if (word->flags & W_ASSIGNRHS) tword->flags |= W_ASSIGNRHS; temp = (char *)NULL; temp_has_dollar_at = 0; /* does this quoted (sub)string include $@? */ /* Need to get W_HASQUOTEDNULL flag through this function. */ list = expand_word_internal (tword, Q_DOUBLE_QUOTES, 0, &temp_has_dollar_at, (int *)NULL); has_dollar_at += temp_has_dollar_at; if (list == &expand_word_error || list == &expand_word_fatal) { free (istring); free (string); /* expand_word_internal has already freed temp_word->word for us because of the way it prints error messages. */ tword->word = (char *)NULL; dispose_word (tword); return list; } dispose_word (tword); /* "$@" (a double-quoted dollar-at) expands into nothing, not even a NULL word, when there are no positional parameters. Posix interp 888 says that other parts of the word that expand to quoted nulls result in quoted nulls, so we can't just throw the entire word away if we have "$@" anywhere in it. We use had_quoted_null to keep track */ if (list == 0 && temp_has_dollar_at) /* XXX - was has_dollar_at */ { quoted_dollar_at++; break; } /* If this list comes back with a quoted null from expansion, we have either "$x" or "$@" with $1 == ''. In either case, we need to make sure we add a quoted null argument and disable the special handling that "$@" gets. */ if (list && list->word && list->next == 0 && (list->word->flags & W_HASQUOTEDNULL)) { if (had_quoted_null && temp_has_dollar_at) quoted_dollar_at++; had_quoted_null = 1; /* XXX */ } /* If we get "$@", we know we have expanded something, so we need to remember it for the final split on $IFS. This is a special case; it's the only case where a quoted string can expand into more than one word. It's going to come back from the above call to expand_word_internal as a list with multiple words. */ if (list) dequote_list (list); if (temp_has_dollar_at) /* XXX - was has_dollar_at */ { quoted_dollar_at++; if (contains_dollar_at) *contains_dollar_at = 1; if (expanded_something) *expanded_something = 1; local_expanded = 1; } } else { /* What we have is "". This is a minor optimization. */ FREE (temp); list = (WORD_LIST *)NULL; had_quoted_null = 1; /* note for later */ } /* The code above *might* return a list (consider the case of "$@", where it returns "$1", "$2", etc.). We can't throw away the rest of the list, and we have to make sure each word gets added as quoted. We test on tresult->next: if it is non-NULL, we quote the whole list, save it to a string with string_list, and add that string. We don't need to quote the results of this (and it would be wrong, since that would quote the separators as well), so we go directly to add_string. */ if (list) { if (list->next) { /* Testing quoted_dollar_at makes sure that "$@" is split correctly when $IFS does not contain a space. */ temp = quoted_dollar_at ? string_list_dollar_at (list, Q_DOUBLE_QUOTES, 0) : string_list (quote_list (list)); dispose_words (list); goto add_string; } else { temp = savestring (list->word->word); tflag = list->word->flags; dispose_words (list); /* If the string is not a quoted null string, we want to remove any embedded unquoted CTLNUL characters. We do not want to turn quoted null strings back into the empty string, though. We do this because we want to remove any quoted nulls from expansions that contain other characters. For example, if we have x"$*"y or "x$*y" and there are no positional parameters, the $* should expand into nothing. */ /* We use the W_HASQUOTEDNULL flag to differentiate the cases: a quoted null character as above and when CTLNUL is contained in the (non-null) expansion of some variable. We use the had_quoted_null flag to pass the value through this function to its caller. */ if ((tflag & W_HASQUOTEDNULL) && QUOTED_NULL (temp) == 0) remove_quoted_nulls (temp); /* XXX */ } } else temp = (char *)NULL; if (temp == 0 && quoted_state == PARTIALLY_QUOTED) had_quoted_null = 1; /* note for later */ /* We do not want to add quoted nulls to strings that are only partially quoted; we can throw them away. The exception to this is when we are going to be performing word splitting, since we have to preserve a null argument if the next character will cause word splitting. */ if (temp == 0 && quoted_state == PARTIALLY_QUOTED && quoted == 0 && (word->flags & (W_NOSPLIT|W_EXPANDRHS|W_ASSIGNRHS)) == W_EXPANDRHS) { c = CTLNUL; sindex--; had_quoted_null = 1; goto add_character; } if (temp == 0 && quoted_state == PARTIALLY_QUOTED && (word->flags & (W_NOSPLIT|W_NOSPLIT2))) continue; add_quoted_string: if (temp) { temp1 = temp; temp = quote_string (temp); free (temp1); goto add_string; } else { /* Add NULL arg. */ c = CTLNUL; sindex--; /* add_character: label increments sindex */ had_quoted_null = 1; /* note for later */ goto add_character; } /* break; */ case '\'': if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))) goto add_character; t_index = ++sindex; temp = string_extract_single_quoted (string, &sindex); /* If the entire STRING was surrounded by single quotes, then the string is wholly quoted. */ quoted_state = (t_index == 1 && string[sindex] == '\0') ? WHOLLY_QUOTED : PARTIALLY_QUOTED; /* If all we had was '', it is a null expansion. */ if (*temp == '\0') { free (temp); temp = (char *)NULL; } else remove_quoted_escapes (temp); /* ??? */ if (temp == 0 && quoted_state == PARTIALLY_QUOTED) had_quoted_null = 1; /* note for later */ /* We do not want to add quoted nulls to strings that are only partially quoted; such nulls are discarded. See above for the exception, which is when the string is going to be split. Posix interp 888/1129 */ if (temp == 0 && quoted_state == PARTIALLY_QUOTED && quoted == 0 && (word->flags & (W_NOSPLIT|W_EXPANDRHS|W_ASSIGNRHS)) == W_EXPANDRHS) { c = CTLNUL; sindex--; goto add_character; } if (temp == 0 && (quoted_state == PARTIALLY_QUOTED) && (word->flags & (W_NOSPLIT|W_NOSPLIT2))) continue; /* If we have a quoted null expansion, add a quoted NULL to istring. */ if (temp == 0) { c = CTLNUL; sindex--; /* add_character: label increments sindex */ goto add_character; } else goto add_quoted_string; /* break; */ case ' ': /* If we are in a context where the word is not going to be split, but we need to account for $@ and $* producing one word for each positional parameter, add quoted spaces so the spaces in the expansion of "$@", if any, behave correctly. We still may need to split if we are expanding the rhs of a word expansion. */ if (ifs_is_null || split_on_spaces || ((word->flags & (W_NOSPLIT|W_NOSPLIT2|W_ASSIGNRHS)) && (word->flags & W_EXPANDRHS) == 0)) { if (string[sindex]) sindex++; twochars[0] = CTLESC; twochars[1] = c; goto add_twochars; } /* FALLTHROUGH */ default: /* This is the fix for " $@ " */ add_ifs_character: if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (isexp == 0 && isifs (c) && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0)) { if ((quoted&(Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0) has_quoted_ifs++; add_quoted_character: if (string[sindex]) /* from old goto dollar_add_string */ sindex++; if (c == 0) { c = CTLNUL; goto add_character; } else { #if HANDLE_MULTIBYTE /* XXX - should make sure that c is actually multibyte, otherwise we can use the twochars branch */ if (mb_cur_max > 1) sindex--; if (mb_cur_max > 1) { SADD_MBQCHAR_BODY(temp, string, sindex, string_size); } else #endif { twochars[0] = CTLESC; twochars[1] = c; goto add_twochars; } } } SADD_MBCHAR (temp, string, sindex, string_size); add_character: RESIZE_MALLOCED_BUFFER (istring, istring_index, 1, istring_size, DEFAULT_ARRAY_SIZE); istring[istring_index++] = c; istring[istring_index] = '\0'; /* Next character. */ sindex++; } } finished_with_string: /* OK, we're ready to return. If we have a quoted string, and quoted_dollar_at is not set, we do no splitting at all; otherwise we split on ' '. The routines that call this will handle what to do if nothing has been expanded. */ /* Partially and wholly quoted strings which expand to the empty string are retained as an empty arguments. Unquoted strings which expand to the empty string are discarded. The single exception is the case of expanding "$@" when there are no positional parameters. In that case, we discard the expansion. */ /* Because of how the code that handles "" and '' in partially quoted strings works, we need to make ISTRING into a QUOTED_NULL if we saw quoting characters, but the expansion was empty. "" and '' are tossed away before we get to this point when processing partially quoted strings. This makes "" and $xxx"" equivalent when xxx is unset. We also look to see whether we saw a quoted null from a ${} expansion and add one back if we need to. */ /* If we expand to nothing and there were no single or double quotes in the word, we throw it away. Otherwise, we return a NULL word. The single exception is for $@ surrounded by double quotes when there are no positional parameters. In that case, we also throw the word away. */ if (*istring == '\0') { if (quoted_dollar_at == 0 && (had_quoted_null || quoted_state == PARTIALLY_QUOTED)) { istring[0] = CTLNUL; istring[1] = '\0'; tword = alloc_word_desc (); tword->word = istring; istring = 0; /* avoid later free() */ tword->flags |= W_HASQUOTEDNULL; /* XXX */ list = make_word_list (tword, (WORD_LIST *)NULL); if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) tword->flags |= W_QUOTED; } /* According to sh, ksh, and Posix.2, if a word expands into nothing and a double-quoted "$@" appears anywhere in it, then the entire word is removed. */ /* XXX - exception appears to be that quoted null strings result in null arguments */ else if (quoted_state == UNQUOTED || quoted_dollar_at) list = (WORD_LIST *)NULL; else list = (WORD_LIST *)NULL; } else if (word->flags & W_NOSPLIT) { tword = alloc_word_desc (); tword->word = istring; if (had_quoted_null && QUOTED_NULL (istring)) tword->flags |= W_HASQUOTEDNULL; istring = 0; /* avoid later free() */ if (word->flags & W_ASSIGNMENT) tword->flags |= W_ASSIGNMENT; /* XXX */ if (word->flags & W_COMPASSIGN) tword->flags |= W_COMPASSIGN; /* XXX */ if (word->flags & W_NOGLOB) tword->flags |= W_NOGLOB; /* XXX */ if (word->flags & W_NOBRACE) tword->flags |= W_NOBRACE; /* XXX */ if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) tword->flags |= W_QUOTED; list = make_word_list (tword, (WORD_LIST *)NULL); } else if (word->flags & W_ASSIGNRHS) { list = list_string (istring, "", quoted); tword = list->word; if (had_quoted_null && QUOTED_NULL (istring)) tword->flags |= W_HASQUOTEDNULL; free (list); free (istring); istring = 0; /* avoid later free() */ goto set_word_flags; } else { char *ifs_chars; ifs_chars = (quoted_dollar_at || has_dollar_at) ? ifs_value : (char *)NULL; /* If we have $@, we need to split the results no matter what. If IFS is unset or NULL, string_list_dollar_at has separated the positional parameters with a space, so we split on space (we have set ifs_chars to " \t\n" above if ifs is unset). If IFS is set, string_list_dollar_at has separated the positional parameters with the first character of $IFS, so we split on $IFS. If SPLIT_ON_SPACES is set, we expanded $* (unquoted) with IFS either unset or null, and we want to make sure that we split on spaces regardless of what else has happened to IFS since the expansion, or we expanded "$@" with IFS null and we need to split the positional parameters into separate words. */ if (split_on_spaces) { /* If IFS is not set, and the word is not quoted, we want to split the individual words on $' \t\n'. We rely on previous steps to quote the portions of the word that should not be split */ if (ifs_is_set == 0) list = list_string (istring, " \t\n", 1); /* XXX quoted == 1? */ else list = list_string (istring, " ", 1); /* XXX quoted == 1? */ } /* If we have $@ (has_dollar_at != 0) and we are in a context where we don't want to split the result (W_NOSPLIT2), and we are not quoted, we have already separated the arguments with the first character of $IFS. In this case, we want to return a list with a single word with the separator possibly replaced with a space (it's what other shells seem to do). quoted_dollar_at is internal to this function and is set if we are passed an argument that is unquoted (quoted == 0) but we encounter a double-quoted $@ while expanding it. */ else if (has_dollar_at && quoted_dollar_at == 0 && ifs_chars && quoted == 0 && (word->flags & W_NOSPLIT2)) { tword = alloc_word_desc (); /* Only split and rejoin if we have to */ if (*ifs_chars && *ifs_chars != ' ') { /* list_string dequotes CTLESCs in the string it's passed, so we need it to get the space separation right if space isn't the first character in IFS (but is present) and to remove the quoting we added back in param_expand(). */ list = list_string (istring, *ifs_chars ? ifs_chars : " ", 1); /* This isn't exactly right in the case where we're expanding the RHS of an expansion like ${var-$@} where IFS=: (for example). The W_NOSPLIT2 means we do the separation with :; the list_string removes the quotes and breaks the string into a list, and the string_list rejoins it on spaces. When we return, we expect to be able to split the results, but the space separation means the right split doesn't happen. */ tword->word = string_list (list); } else tword->word = istring; if (had_quoted_null && QUOTED_NULL (istring)) tword->flags |= W_HASQUOTEDNULL; /* XXX */ if (tword->word != istring) free (istring); istring = 0; /* avoid later free() */ goto set_word_flags; } else if (has_dollar_at && ifs_chars) list = list_string (istring, *ifs_chars ? ifs_chars : " ", 1); else { tword = alloc_word_desc (); if (expanded_something && *expanded_something == 0 && has_quoted_ifs) tword->word = remove_quoted_ifs (istring); else tword->word = istring; if (had_quoted_null && QUOTED_NULL (istring)) /* should check for more than one */ tword->flags |= W_HASQUOTEDNULL; /* XXX */ else if (had_quoted_null) tword->flags |= W_SAWQUOTEDNULL; /* XXX */ if (tword->word != istring) free (istring); istring = 0; /* avoid later free() */ set_word_flags: if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (quoted_state == WHOLLY_QUOTED)) tword->flags |= W_QUOTED; if (word->flags & W_ASSIGNMENT) tword->flags |= W_ASSIGNMENT; if (word->flags & W_COMPASSIGN) tword->flags |= W_COMPASSIGN; if (word->flags & W_NOGLOB) tword->flags |= W_NOGLOB; if (word->flags & W_NOBRACE) tword->flags |= W_NOBRACE; list = make_word_list (tword, (WORD_LIST *)NULL); } } free (istring); return (list); } /* **************************************************************** */ /* */ /* Functions for Quote Removal */ /* */ /* **************************************************************** */ /* Perform quote removal on STRING. If QUOTED > 0, assume we are obeying the backslash quoting rules for within double quotes or a here document. */ char * string_quote_removal (string, quoted) char *string; int quoted; { size_t slen; char *r, *result_string, *temp, *send; int sindex, tindex, dquote; unsigned char c; DECLARE_MBSTATE; /* The result can be no longer than the original string. */ slen = strlen (string); send = string + slen; r = result_string = (char *)xmalloc (slen + 1); for (dquote = sindex = 0; c = string[sindex];) { switch (c) { case '\\': c = string[++sindex]; if (c == 0) { *r++ = '\\'; break; } if (((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote) && (sh_syntaxtab[c] & CBSDQUOTE) == 0) *r++ = '\\'; /* FALLTHROUGH */ default: SCOPY_CHAR_M (r, string, send, sindex); break; case '\'': if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote) { *r++ = c; sindex++; break; } tindex = sindex + 1; temp = string_extract_single_quoted (string, &tindex); if (temp) { strcpy (r, temp); r += strlen (r); free (temp); } sindex = tindex; break; case '"': dquote = 1 - dquote; sindex++; break; } } *r = '\0'; return (result_string); } #if 0 /* UNUSED */ /* Perform quote removal on word WORD. This allocates and returns a new WORD_DESC *. */ WORD_DESC * word_quote_removal (word, quoted) WORD_DESC *word; int quoted; { WORD_DESC *w; char *t; t = string_quote_removal (word->word, quoted); w = alloc_word_desc (); w->word = t ? t : savestring (""); return (w); } /* Perform quote removal on all words in LIST. If QUOTED is non-zero, the members of the list are treated as if they are surrounded by double quotes. Return a new list, or NULL if LIST is NULL. */ WORD_LIST * word_list_quote_removal (list, quoted) WORD_LIST *list; int quoted; { WORD_LIST *result, *t, *tresult, *e; for (t = list, result = (WORD_LIST *)NULL; t; t = t->next) { tresult = make_word_list (word_quote_removal (t->word, quoted), (WORD_LIST *)NULL); #if 0 result = (WORD_LIST *) list_append (result, tresult); #else if (result == 0) result = e = tresult; else { e->next = tresult; while (e->next) e = e->next; } #endif } return (result); } #endif /******************************************* * * * Functions to perform word splitting * * * *******************************************/ void setifs (v) SHELL_VAR *v; { char *t; unsigned char uc; ifs_var = v; ifs_value = (v && value_cell (v)) ? value_cell (v) : " \t\n"; ifs_is_set = ifs_var != 0; ifs_is_null = ifs_is_set && (*ifs_value == 0); /* Should really merge ifs_cmap with sh_syntaxtab. XXX - doesn't yet handle multibyte chars in IFS */ memset (ifs_cmap, '\0', sizeof (ifs_cmap)); for (t = ifs_value ; t && *t; t++) { uc = *t; ifs_cmap[uc] = 1; } #if defined (HANDLE_MULTIBYTE) if (ifs_value == 0) { ifs_firstc[0] = '\0'; /* XXX - ? */ ifs_firstc_len = 1; } else { if (locale_utf8locale && UTF8_SINGLEBYTE (*ifs_value)) ifs_firstc_len = (*ifs_value != 0) ? 1 : 0; else { size_t ifs_len; ifs_len = strnlen (ifs_value, MB_CUR_MAX); ifs_firstc_len = MBLEN (ifs_value, ifs_len); } if (ifs_firstc_len == 1 || ifs_firstc_len == 0 || MB_INVALIDCH (ifs_firstc_len)) { ifs_firstc[0] = ifs_value[0]; ifs_firstc[1] = '\0'; ifs_firstc_len = 1; } else memcpy (ifs_firstc, ifs_value, ifs_firstc_len); } #else ifs_firstc = ifs_value ? *ifs_value : 0; #endif } char * getifs () { return ifs_value; } /* This splits a single word into a WORD LIST on $IFS, but only if the word is not quoted. list_string () performs quote removal for us, even if we don't do any splitting. */ WORD_LIST * word_split (w, ifs_chars) WORD_DESC *w; char *ifs_chars; { WORD_LIST *result; if (w) { char *xifs; xifs = ((w->flags & W_QUOTED) || ifs_chars == 0) ? "" : ifs_chars; result = list_string (w->word, xifs, w->flags & W_QUOTED); } else result = (WORD_LIST *)NULL; return (result); } /* Perform word splitting on LIST and return the RESULT. It is possible to return (WORD_LIST *)NULL. */ static WORD_LIST * word_list_split (list) WORD_LIST *list; { WORD_LIST *result, *t, *tresult, *e; WORD_DESC *w; for (t = list, result = (WORD_LIST *)NULL; t; t = t->next) { tresult = word_split (t->word, ifs_value); /* POSIX 2.6: "If the complete expansion appropriate for a word results in an empty field, that empty field shall be deleted from the list of fields that form the completely expanded command, unless the original word contained single-quote or double-quote characters." This is where we handle these words that contain quoted null strings and other characters that expand to nothing after word splitting. */ if (tresult == 0 && t->word && (t->word->flags & W_SAWQUOTEDNULL)) /* XXX */ { w = alloc_word_desc (); w->word = (char *)xmalloc (1); w->word[0] = '\0'; tresult = make_word_list (w, (WORD_LIST *)NULL); } if (result == 0) result = e = tresult; else { e->next = tresult; while (e->next) e = e->next; } } return (result); } /************************************************** * * * Functions to expand an entire WORD_LIST * * * **************************************************/ /* Do any word-expansion-specific cleanup and jump to top_level */ static void exp_jump_to_top_level (v) int v; { set_pipestatus_from_exit (last_command_exit_value); /* Cleanup code goes here. */ expand_no_split_dollar_star = 0; /* XXX */ if (expanding_redir) undo_partial_redirects (); expanding_redir = 0; assigning_in_environment = 0; if (parse_and_execute_level == 0) top_level_cleanup (); /* from sig.c */ jump_to_top_level (v); } /* Put NLIST (which is a WORD_LIST * of only one element) at the front of ELIST, and set ELIST to the new list. */ #define PREPEND_LIST(nlist, elist) \ do { nlist->next = elist; elist = nlist; } while (0) /* Separate out any initial variable assignments from TLIST. If set -k has been executed, remove all assignment statements from TLIST. Initial variable assignments and other environment assignments are placed on SUBST_ASSIGN_VARLIST. */ static WORD_LIST * separate_out_assignments (tlist) WORD_LIST *tlist; { register WORD_LIST *vp, *lp; if (tlist == 0) return ((WORD_LIST *)NULL); if (subst_assign_varlist) dispose_words (subst_assign_varlist); /* Clean up after previous error */ subst_assign_varlist = (WORD_LIST *)NULL; vp = lp = tlist; /* Separate out variable assignments at the start of the command. Loop invariant: vp->next == lp Loop postcondition: lp = list of words left after assignment statements skipped tlist = original list of words */ while (lp && (lp->word->flags & W_ASSIGNMENT)) { vp = lp; lp = lp->next; } /* If lp != tlist, we have some initial assignment statements. We make SUBST_ASSIGN_VARLIST point to the list of assignment words and TLIST point to the remaining words. */ if (lp != tlist) { subst_assign_varlist = tlist; /* ASSERT(vp->next == lp); */ vp->next = (WORD_LIST *)NULL; /* terminate variable list */ tlist = lp; /* remainder of word list */ } /* vp == end of variable list */ /* tlist == remainder of original word list without variable assignments */ if (!tlist) /* All the words in tlist were assignment statements */ return ((WORD_LIST *)NULL); /* ASSERT(tlist != NULL); */ /* ASSERT((tlist->word->flags & W_ASSIGNMENT) == 0); */ /* If the -k option is in effect, we need to go through the remaining words, separate out the assignment words, and place them on SUBST_ASSIGN_VARLIST. */ if (place_keywords_in_env) { WORD_LIST *tp; /* tp == running pointer into tlist */ tp = tlist; lp = tlist->next; /* Loop Invariant: tp->next == lp */ /* Loop postcondition: tlist == word list without assignment statements */ while (lp) { if (lp->word->flags & W_ASSIGNMENT) { /* Found an assignment statement, add this word to end of subst_assign_varlist (vp). */ if (!subst_assign_varlist) subst_assign_varlist = vp = lp; else { vp->next = lp; vp = lp; } /* Remove the word pointed to by LP from TLIST. */ tp->next = lp->next; /* ASSERT(vp == lp); */ lp->next = (WORD_LIST *)NULL; lp = tp->next; } else { tp = lp; lp = lp->next; } } } return (tlist); } #define WEXP_VARASSIGN 0x001 #define WEXP_BRACEEXP 0x002 #define WEXP_TILDEEXP 0x004 #define WEXP_PARAMEXP 0x008 #define WEXP_PATHEXP 0x010 /* All of the expansions, including variable assignments at the start of the list. */ #define WEXP_ALL (WEXP_VARASSIGN|WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP) /* All of the expansions except variable assignments at the start of the list. */ #define WEXP_NOVARS (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP) /* All of the `shell expansions': brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, word splitting, and quote removal. */ #define WEXP_SHELLEXP (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP) /* Take the list of words in LIST and do the various substitutions. Return a new list of words which is the expanded list, and without things like variable assignments. */ WORD_LIST * expand_words (list) WORD_LIST *list; { return (expand_word_list_internal (list, WEXP_ALL)); } /* Same as expand_words (), but doesn't hack variable or environment variables. */ WORD_LIST * expand_words_no_vars (list) WORD_LIST *list; { return (expand_word_list_internal (list, WEXP_NOVARS)); } WORD_LIST * expand_words_shellexp (list) WORD_LIST *list; { return (expand_word_list_internal (list, WEXP_SHELLEXP)); } static WORD_LIST * glob_expand_word_list (tlist, eflags) WORD_LIST *tlist; int eflags; { char **glob_array, *temp_string; register int glob_index; WORD_LIST *glob_list, *output_list, *disposables, *next; WORD_DESC *tword; int x; output_list = disposables = (WORD_LIST *)NULL; glob_array = (char **)NULL; while (tlist) { /* For each word, either globbing is attempted or the word is added to orig_list. If globbing succeeds, the results are added to orig_list and the word (tlist) is added to the list of disposable words. If globbing fails and failed glob expansions are left unchanged (the shell default), the original word is added to orig_list. If globbing fails and failed glob expansions are removed, the original word is added to the list of disposable words. orig_list ends up in reverse order and requires a call to REVERSE_LIST to be set right. After all words are examined, the disposable words are freed. */ next = tlist->next; /* If the word isn't an assignment and contains an unquoted pattern matching character, then glob it. */ if ((tlist->word->flags & W_NOGLOB) == 0 && unquoted_glob_pattern_p (tlist->word->word)) { glob_array = shell_glob_filename (tlist->word->word, QGLOB_CTLESC); /* XXX */ /* Handle error cases. I don't think we should report errors like "No such file or directory". However, I would like to report errors like "Read failed". */ if (glob_array == 0 || GLOB_FAILED (glob_array)) { glob_array = (char **)xmalloc (sizeof (char *)); glob_array[0] = (char *)NULL; } /* Dequote the current word in case we have to use it. */ if (glob_array[0] == NULL) { temp_string = dequote_string (tlist->word->word); free (tlist->word->word); tlist->word->word = temp_string; } /* Make the array into a word list. */ glob_list = (WORD_LIST *)NULL; for (glob_index = 0; glob_array[glob_index]; glob_index++) { tword = make_bare_word (glob_array[glob_index]); glob_list = make_word_list (tword, glob_list); } if (glob_list) { output_list = (WORD_LIST *)list_append (glob_list, output_list); PREPEND_LIST (tlist, disposables); } else if (fail_glob_expansion != 0) { last_command_exit_value = EXECUTION_FAILURE; report_error (_("no match: %s"), tlist->word->word); exp_jump_to_top_level (DISCARD); } else if (allow_null_glob_expansion == 0) { /* Failed glob expressions are left unchanged. */ PREPEND_LIST (tlist, output_list); } else { /* Failed glob expressions are removed. */ PREPEND_LIST (tlist, disposables); } } else { /* Dequote the string. */ temp_string = dequote_string (tlist->word->word); free (tlist->word->word); tlist->word->word = temp_string; PREPEND_LIST (tlist, output_list); } strvec_dispose (glob_array); glob_array = (char **)NULL; tlist = next; } if (disposables) dispose_words (disposables); if (output_list) output_list = REVERSE_LIST (output_list, WORD_LIST *); return (output_list); } #if defined (BRACE_EXPANSION) static WORD_LIST * brace_expand_word_list (tlist, eflags) WORD_LIST *tlist; int eflags; { register char **expansions; char *temp_string; WORD_LIST *disposables, *output_list, *next; WORD_DESC *w; int eindex; for (disposables = output_list = (WORD_LIST *)NULL; tlist; tlist = next) { next = tlist->next; if (tlist->word->flags & W_NOBRACE) { /*itrace("brace_expand_word_list: %s: W_NOBRACE", tlist->word->word);*/ PREPEND_LIST (tlist, output_list); continue; } if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG)) { /*itrace("brace_expand_word_list: %s: W_COMPASSIGN|W_ASSIGNARG", tlist->word->word);*/ PREPEND_LIST (tlist, output_list); continue; } /* Only do brace expansion if the word has a brace character. If not, just add the word list element to BRACES and continue. In the common case, at least when running shell scripts, this will degenerate to a bunch of calls to `mbschr', and then what is basically a reversal of TLIST into BRACES, which is corrected by a call to REVERSE_LIST () on BRACES when the end of TLIST is reached. */ if (mbschr (tlist->word->word, LBRACE)) { expansions = brace_expand (tlist->word->word); for (eindex = 0; temp_string = expansions[eindex]; eindex++) { w = alloc_word_desc (); w->word = temp_string; /* If brace expansion didn't change the word, preserve the flags. We may want to preserve the flags unconditionally someday -- XXX */ if (STREQ (temp_string, tlist->word->word)) w->flags = tlist->word->flags; else w = make_word_flags (w, temp_string); output_list = make_word_list (w, output_list); } free (expansions); /* Add TLIST to the list of words to be freed after brace expansion has been performed. */ PREPEND_LIST (tlist, disposables); } else PREPEND_LIST (tlist, output_list); } if (disposables) dispose_words (disposables); if (output_list) output_list = REVERSE_LIST (output_list, WORD_LIST *); return (output_list); } #endif #if defined (ARRAY_VARS) /* Take WORD, a compound array assignment, and internally run (for example), 'declare -A w', where W is the variable name portion of WORD. OPTION is the list of options to supply to `declare'. CMD is the declaration command we are expanding right now; it's unused currently. */ static int make_internal_declare (word, option, cmd) char *word; char *option; char *cmd; { int t, r; WORD_LIST *wl; WORD_DESC *w; w = make_word (word); t = assignment (w->word, 0); if (w->word[t] == '=') { w->word[t] = '\0'; if (w->word[t - 1] == '+') /* cut off any append op */ w->word[t - 1] = '\0'; } wl = make_word_list (w, (WORD_LIST *)NULL); wl = make_word_list (make_word (option), wl); r = declare_builtin (wl); dispose_words (wl); return r; } /* Expand VALUE in NAME[+]=( VALUE ) to a list of words. FLAGS is 1 if NAME is an associative array. If we are processing an indexed array, expand_compound_array_assignment will expand all the individual words and quote_compound_array_list will single-quote them. If we are processing an associative array, we use parse_string_to_word_list to split VALUE into a list of words instead of faking up a shell variable and calling expand_compound_array_assignment. expand_and_quote_assoc_word expands and single-quotes each word in VALUE together so we don't have problems finding the end of the subscript when quoting it. Words in VALUE can be individual words, which are expanded and single-quoted, or words of the form [IND]=VALUE, which end up as explained below, as ['expanded-ind']='expanded-value'. */ static WORD_LIST * expand_oneword (value, flags) char *value; int flags; { WORD_LIST *l, *nl; char *t; int kvpair; if (flags == 0) { /* Indexed array */ l = expand_compound_array_assignment ((SHELL_VAR *)NULL, value, flags); /* Now we quote the results of the expansion above to prevent double expansion. */ quote_compound_array_list (l, flags); return l; } else { /* Associative array */ l = parse_string_to_word_list (value, 1, "array assign"); #if ASSOC_KVPAIR_ASSIGNMENT kvpair = kvpair_assignment_p (l); #endif /* For associative arrays, with their arbitrary subscripts, we have to expand and quote in one step so we don't have to search for the closing right bracket more than once. */ for (nl = l; nl; nl = nl->next) { #if ASSOC_KVPAIR_ASSIGNMENT if (kvpair) /* keys and values undergo the same set of expansions */ t = expand_and_quote_kvpair_word (nl->word->word); else #endif if ((nl->word->flags & W_ASSIGNMENT) == 0) t = sh_single_quote (nl->word->word ? nl->word->word : ""); else t = expand_and_quote_assoc_word (nl->word->word, flags); free (nl->word->word); nl->word->word = t; } return l; } } /* Expand a single compound assignment argument to a declaration builtin. This word takes the form NAME[+]=( VALUE ). The NAME[+]= is passed through unchanged. The VALUE is expanded and each word in the result is single- quoted. Words of the form [key]=value end up as ['expanded-key']='expanded-value'. Associative arrays have special handling, see expand_oneword() above. The return value is NAME[+]=( expanded-and-quoted-VALUE ). */ static void expand_compound_assignment_word (tlist, flags) WORD_LIST *tlist; int flags; { WORD_LIST *l; int wlen, oind, t; char *value, *temp; /*itrace("expand_compound_assignment_word: original word = -%s-", tlist->word->word);*/ t = assignment (tlist->word->word, 0); /* value doesn't have the open and close parens */ oind = 1; value = extract_array_assignment_list (tlist->word->word + t + 1, &oind); /* This performs one round of expansion on the index/key and value and single-quotes each word in the result. */ l = expand_oneword (value, flags); free (value); value = string_list (l); dispose_words (l); wlen = STRLEN (value); /* Now, let's rebuild the string */ temp = xmalloc (t + 3 + wlen + 1); /* name[+]=(value) */ memcpy (temp, tlist->word->word, ++t); temp[t++] = '('; if (value) memcpy (temp + t, value, wlen); t += wlen; temp[t++] = ')'; temp[t] = '\0'; /*itrace("expand_compound_assignment_word: reconstructed word = -%s-", temp);*/ free (tlist->word->word); tlist->word->word = temp; free (value); } /* Expand and process an argument to a declaration command. We have already set flags in TLIST->word->flags depending on the declaration command (declare, local, etc.) and the options supplied to it (-a, -A, etc.). TLIST->word->word is of the form NAME[+]=( VALUE ). This does several things, all using pieces of other functions to get the evaluation sequence right. It's called for compound array assignments with the W_ASSIGNMENT flag set (basically, valid identifier names on the lhs). It parses out which flags need to be set for declare to create the variable correctly, then calls declare internally (make_internal_declare) to make sure the variable exists with the correct attributes. Before the variable is created, it calls expand_compound_assignment_word to expand VALUE to a list of words, appropriately quoted for further evaluation. This preserves the semantics of word-expansion-before-calling-builtins. Finally, it calls do_word_assignment to perform the expansion and assignment with the same expansion semantics as a standalone assignment statement (no word splitting, etc.) even though the word is single-quoted so all that needs to happen is quote removal. */ static WORD_LIST * expand_declaration_argument (tlist, wcmd) WORD_LIST *tlist, *wcmd; { char opts[16], omap[128]; int t, opti, oind, skip, inheriting; WORD_LIST *l; inheriting = localvar_inherit; opti = 0; if (tlist->word->flags & (W_ASSIGNASSOC|W_ASSNGLOBAL|W_CHKLOCAL|W_ASSIGNARRAY)) opts[opti++] = '-'; if ((tlist->word->flags & (W_ASSIGNASSOC|W_ASSNGLOBAL)) == (W_ASSIGNASSOC|W_ASSNGLOBAL)) { opts[opti++] = 'g'; opts[opti++] = 'A'; } else if (tlist->word->flags & W_ASSIGNASSOC) { opts[opti++] = 'A'; } else if ((tlist->word->flags & (W_ASSIGNARRAY|W_ASSNGLOBAL)) == (W_ASSIGNARRAY|W_ASSNGLOBAL)) { opts[opti++] = 'g'; opts[opti++] = 'a'; } else if (tlist->word->flags & W_ASSIGNARRAY) { opts[opti++] = 'a'; } else if (tlist->word->flags & W_ASSNGLOBAL) opts[opti++] = 'g'; if (tlist->word->flags & W_CHKLOCAL) opts[opti++] = 'G'; /* If we have special handling note the integer attribute and others that transform the value upon assignment. What we do is take all of the option arguments and scan through them looking for options that cause such transformations, and add them to the `opts' array. */ memset (omap, '\0', sizeof (omap)); for (l = wcmd->next; l != tlist; l = l->next) { if (l->word->word[0] != '-') break; /* non-option argument */ if (l->word->word[0] == '-' && l->word->word[1] == '-' && l->word->word[2] == 0) break; /* -- signals end of options */ for (oind = 1; l->word->word[oind]; oind++) switch (l->word->word[oind]) { case 'I': inheriting = 1; case 'i': case 'l': case 'u': case 'c': omap[l->word->word[oind]] = 1; if (opti == 0) opts[opti++] = '-'; break; default: break; } } for (oind = 0; oind < sizeof (omap); oind++) if (omap[oind]) opts[opti++] = oind; /* If there are no -a/-A options, but we have a compound assignment, we have a choice: we can set opts[0]='-', opts[1]='a', since the default is to create an indexed array, and call make_internal_declare with that, or we can just skip the -a and let declare_builtin deal with it. Once we're here, we're better set up for the latter, since we don't want to deal with looking up any existing variable here -- better to let declare_builtin do it. We need the variable created, though, especially if it's local, so we get the scoping right before we call do_word_assignment. To ensure that make_local_declare gets called, we add `--' if there aren't any options. */ if ((tlist->word->flags & (W_ASSIGNASSOC|W_ASSIGNARRAY)) == 0) { if (opti == 0) { opts[opti++] = '-'; opts[opti++] = '-'; } } opts[opti] = '\0'; /* This isn't perfect, but it's a start. Improvements later. We expand tlist->word->word and single-quote the results to avoid multiple expansions by, say, do_assignment_internal(). We have to weigh the cost of reconstructing the compound assignment string with its single quoting and letting the declare builtin handle it. The single quotes will prevent any unwanted additional expansion or word splitting. */ expand_compound_assignment_word (tlist, (tlist->word->flags & W_ASSIGNASSOC) ? 1 : 0); skip = 0; if (opti > 0) { t = make_internal_declare (tlist->word->word, opts, wcmd ? wcmd->word->word : (char *)0); if (t != EXECUTION_SUCCESS) { last_command_exit_value = t; if (tlist->word->flags & W_FORCELOCAL) /* non-fatal error */ skip = 1; else exp_jump_to_top_level (DISCARD); } } if (skip == 0) { t = do_word_assignment (tlist->word, 0); if (t == 0) { last_command_exit_value = EXECUTION_FAILURE; exp_jump_to_top_level (DISCARD); } } /* Now transform the word as ksh93 appears to do and go on */ t = assignment (tlist->word->word, 0); tlist->word->word[t] = '\0'; if (tlist->word->word[t - 1] == '+') tlist->word->word[t - 1] = '\0'; /* cut off append op */ tlist->word->flags &= ~(W_ASSIGNMENT|W_NOSPLIT|W_COMPASSIGN|W_ASSIGNARG|W_ASSIGNASSOC|W_ASSIGNARRAY); return (tlist); } #endif /* ARRAY_VARS */ static WORD_LIST * shell_expand_word_list (tlist, eflags) WORD_LIST *tlist; int eflags; { WORD_LIST *expanded, *orig_list, *new_list, *next, *temp_list, *wcmd; int expanded_something, has_dollar_at; /* We do tilde expansion all the time. This is what 1003.2 says. */ wcmd = new_list = (WORD_LIST *)NULL; for (orig_list = tlist; tlist; tlist = next) { if (wcmd == 0 && (tlist->word->flags & W_ASSNBLTIN)) wcmd = tlist; next = tlist->next; #if defined (ARRAY_VARS) /* If this is a compound array assignment to a builtin that accepts such assignments (e.g., `declare'), take the assignment and perform it separately, handling the semantics of declarations inside shell functions. This avoids the double-evaluation of such arguments, because `declare' does some evaluation of compound assignments on its own. */ if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG)) expand_declaration_argument (tlist, wcmd); #endif expanded_something = 0; expanded = expand_word_internal (tlist->word, 0, 0, &has_dollar_at, &expanded_something); if (expanded == &expand_word_error || expanded == &expand_word_fatal) { /* By convention, each time this error is returned, tlist->word->word has already been freed. */ tlist->word->word = (char *)NULL; /* Dispose our copy of the original list. */ dispose_words (orig_list); /* Dispose the new list we're building. */ dispose_words (new_list); last_command_exit_value = EXECUTION_FAILURE; if (expanded == &expand_word_error) exp_jump_to_top_level (DISCARD); else exp_jump_to_top_level (FORCE_EOF); } /* Don't split words marked W_NOSPLIT. */ if (expanded_something && (tlist->word->flags & W_NOSPLIT) == 0) { temp_list = word_list_split (expanded); dispose_words (expanded); } else { /* If no parameter expansion, command substitution, process substitution, or arithmetic substitution took place, then do not do word splitting. We still have to remove quoted null characters from the result. */ word_list_remove_quoted_nulls (expanded); temp_list = expanded; } expanded = REVERSE_LIST (temp_list, WORD_LIST *); new_list = (WORD_LIST *)list_append (expanded, new_list); } if (orig_list) dispose_words (orig_list); if (new_list) new_list = REVERSE_LIST (new_list, WORD_LIST *); return (new_list); } /* The workhorse for expand_words () and expand_words_no_vars (). First arg is LIST, a WORD_LIST of words. Second arg EFLAGS is a flags word controlling which expansions are performed. This does all of the substitutions: brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, process substitution, word splitting, and pathname expansion, according to the bits set in EFLAGS. Words with the W_QUOTED or W_NOSPLIT bits set, or for which no expansion is done, do not undergo word splitting. Words with the W_NOGLOB bit set do not undergo pathname expansion; words with W_NOBRACE set do not undergo brace expansion (see brace_expand_word_list above). */ static WORD_LIST * expand_word_list_internal (list, eflags) WORD_LIST *list; int eflags; { WORD_LIST *new_list, *temp_list; int tint; char *savecmd; tempenv_assign_error = 0; if (list == 0) return ((WORD_LIST *)NULL); garglist = new_list = copy_word_list (list); if (eflags & WEXP_VARASSIGN) { garglist = new_list = separate_out_assignments (new_list); if (new_list == 0) { if (subst_assign_varlist) { /* All the words were variable assignments, so they are placed into the shell's environment. */ for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next) { savecmd = this_command_name; this_command_name = (char *)NULL; /* no arithmetic errors */ tint = do_word_assignment (temp_list->word, 0); this_command_name = savecmd; /* Variable assignment errors in non-interactive shells running in Posix.2 mode cause the shell to exit, unless they are being run by the `command' builtin. */ if (tint == 0) { last_command_exit_value = EXECUTION_FAILURE; if (interactive_shell == 0 && posixly_correct && executing_command_builtin == 0) exp_jump_to_top_level (FORCE_EOF); else exp_jump_to_top_level (DISCARD); } } dispose_words (subst_assign_varlist); subst_assign_varlist = (WORD_LIST *)NULL; } return ((WORD_LIST *)NULL); } } /* Begin expanding the words that remain. The expansions take place on things that aren't really variable assignments. */ #if defined (BRACE_EXPANSION) /* Do brace expansion on this word if there are any brace characters in the string. */ if ((eflags & WEXP_BRACEEXP) && brace_expansion && new_list) new_list = brace_expand_word_list (new_list, eflags); #endif /* BRACE_EXPANSION */ /* Perform the `normal' shell expansions: tilde expansion, parameter and variable substitution, command substitution, arithmetic expansion, and word splitting. */ new_list = shell_expand_word_list (new_list, eflags); /* Okay, we're almost done. Now let's just do some filename globbing. */ if (new_list) { if ((eflags & WEXP_PATHEXP) && disallow_filename_globbing == 0) /* Glob expand the word list unless globbing has been disabled. */ new_list = glob_expand_word_list (new_list, eflags); else /* Dequote the words, because we're not performing globbing. */ new_list = dequote_list (new_list); } if ((eflags & WEXP_VARASSIGN) && subst_assign_varlist) { sh_wassign_func_t *assign_func; int is_special_builtin, is_builtin_or_func; /* If the remainder of the words expand to nothing, Posix.2 requires that the variable and environment assignments affect the shell's environment. */ assign_func = new_list ? assign_in_env : do_word_assignment; tempenv_assign_error = 0; is_builtin_or_func = (new_list && new_list->word && (find_shell_builtin (new_list->word->word) || find_function (new_list->word->word))); /* Posix says that special builtins exit if a variable assignment error occurs in an assignment preceding it. */ is_special_builtin = (posixly_correct && new_list && new_list->word && find_special_builtin (new_list->word->word)); for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next) { savecmd = this_command_name; this_command_name = (char *)NULL; assigning_in_environment = (assign_func == assign_in_env); tint = (*assign_func) (temp_list->word, is_builtin_or_func); assigning_in_environment = 0; this_command_name = savecmd; /* Variable assignment errors in non-interactive shells running in Posix.2 mode cause the shell to exit. */ if (tint == 0) { if (assign_func == do_word_assignment) { last_command_exit_value = EXECUTION_FAILURE; if (interactive_shell == 0 && posixly_correct) exp_jump_to_top_level (FORCE_EOF); else exp_jump_to_top_level (DISCARD); } else if (interactive_shell == 0 && is_special_builtin) { last_command_exit_value = EXECUTION_FAILURE; exp_jump_to_top_level (FORCE_EOF); } else tempenv_assign_error++; } } dispose_words (subst_assign_varlist); subst_assign_varlist = (WORD_LIST *)NULL; } return (new_list); }
428572.c
/*++ Copyright (c) 1989 Microsoft Corporation Module Name: tokenopn.c Abstract: This module implements the open thread and process token services. Author: Jim Kelly (JimK) 2-Aug-1990 Environment: Kernel mode only. Revision History: --*/ //#ifndef TOKEN_DEBUG //#define TOKEN_DEBUG //#endif #include "sep.h" #include "seopaque.h" #include "tokenp.h" NTSTATUS SepCreateImpersonationTokenDacl( IN PTOKEN Token, IN PACCESS_TOKEN PrimaryToken, OUT PACL *Acl ); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE,NtOpenProcessToken) #pragma alloc_text(PAGE,NtOpenThreadToken) #pragma alloc_text(PAGE,SepCreateImpersonationTokenDacl) #endif NTSTATUS SepCreateImpersonationTokenDacl( IN PTOKEN Token, IN PACCESS_TOKEN PrimaryToken, OUT PACL *Acl ) /*++ Routine Description: This routine modifies the DACL protecting the passed token to allow the current user (described by the PrimaryToken parameter) full access. This permits callers of NtOpenThreadToken to call with OpenAsSelf==TRUE and succeed. The new DACL placed on the token is as follows: ACE 0 - Server gets TOKEN_ALL_ACCESS ACE 1 - Client gets TOKEN_ALL_ACCESS ACE 2 - Admins gets TOKEN_ALL_ACCESS ACE 3 - System gets TOKEN_ALL_ACCESS ACE 4 - Restricted gets TOKEN_ALL_ACCESS Arguments: Token - The token whose protection is to be modified. PrimaryToken - Token representing the subject to be granted access. Acl - Returns the modified ACL, allocated out of PagedPool. Return Value: --*/ { PSID ServerUserSid; PSID ClientUserSid; NTSTATUS Status = STATUS_SUCCESS; ULONG AclLength; PACL NewDacl; PSECURITY_DESCRIPTOR OldDescriptor; BOOLEAN MemoryAllocated; PACL OldDacl; BOOLEAN DaclPresent; BOOLEAN DaclDefaulted; PAGED_CODE(); ServerUserSid = ((PTOKEN)PrimaryToken)->UserAndGroups[0].Sid; ClientUserSid = Token->UserAndGroups[0].Sid; // // Compute how much space we'll need for the new DACL. // AclLength = 5 * sizeof( ACCESS_ALLOWED_ACE ) - 5 * sizeof( ULONG ) + SeLengthSid( ServerUserSid ) + SeLengthSid( SeLocalSystemSid ) + SeLengthSid( ClientUserSid ) + SeLengthSid( SeAliasAdminsSid ) + SeLengthSid( SeRestrictedSid ) + sizeof( ACL ); NewDacl = ExAllocatePool( PagedPool, AclLength ); if (NewDacl == NULL) { *Acl = NULL; return STATUS_INSUFFICIENT_RESOURCES; } Status = RtlCreateAcl( NewDacl, AclLength, ACL_REVISION2 ); ASSERT(NT_SUCCESS( Status )); Status = RtlAddAccessAllowedAce ( NewDacl, ACL_REVISION2, TOKEN_ALL_ACCESS, ServerUserSid ); ASSERT( NT_SUCCESS( Status )); Status = RtlAddAccessAllowedAce ( NewDacl, ACL_REVISION2, TOKEN_ALL_ACCESS, ClientUserSid ); ASSERT( NT_SUCCESS( Status )); Status = RtlAddAccessAllowedAce ( NewDacl, ACL_REVISION2, TOKEN_ALL_ACCESS, SeAliasAdminsSid ); ASSERT( NT_SUCCESS( Status )); Status = RtlAddAccessAllowedAce ( NewDacl, ACL_REVISION2, TOKEN_ALL_ACCESS, SeLocalSystemSid ); ASSERT( NT_SUCCESS( Status )); if(ARGUMENT_PRESENT(((PTOKEN)PrimaryToken)->RestrictedSids) || ARGUMENT_PRESENT(Token->RestrictedSids)) { Status = RtlAddAccessAllowedAce ( NewDacl, ACL_REVISION2, TOKEN_ALL_ACCESS, SeRestrictedSid ); ASSERT( NT_SUCCESS( Status )); } *Acl = NewDacl; return STATUS_SUCCESS; } NTSTATUS NtOpenProcessToken( IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, OUT PHANDLE TokenHandle ) /*++ Routine Description: Open a token object associated with a process and return a handle that may be used to access that token. Arguments: ProcessHandle - Specifies the process whose token is to be opened. DesiredAccess - Is an access mask indicating which access types are desired to the token. These access types are reconciled with the Discretionary Access Control list of the token to determine whether the accesses will be granted or denied. TokenHandle - Receives the handle of the newly opened token. Return Value: STATUS_SUCCESS - Indicates the operation was successful. --*/ { PVOID Token; KPROCESSOR_MODE PreviousMode; NTSTATUS Status; HANDLE LocalHandle; PAGED_CODE(); PreviousMode = KeGetPreviousMode(); // // Probe parameters // if (PreviousMode != KernelMode) { try { ProbeForWriteHandle(TokenHandle); } except(EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } // end_try } //end_if // // Valdiate access to the process and obtain a pointer to the // process's token. If successful, this will cause the token's // reference count to be incremented. // Status = PsOpenTokenOfProcess( ProcessHandle, ((PACCESS_TOKEN *)&Token)); if (!NT_SUCCESS(Status)) { return Status; } // // Now try to open the token for the specified desired access // Status = ObOpenObjectByPointer( (PVOID)Token, // Object 0, // HandleAttributes NULL, // AccessState DesiredAccess, // DesiredAccess SepTokenObjectType, // ObjectType PreviousMode, // AccessMode &LocalHandle // Handle ); // // And decrement the reference count of the token to counter // the action performed by PsOpenTokenOfProcess(). If the open // was successful, the handle will have caused the token's // reference count to have been incremented. // ObDereferenceObject( Token ); // // Return the new handle // if (NT_SUCCESS(Status)) { try { *TokenHandle = LocalHandle; } except(EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } } return Status; } NTSTATUS SepOpenTokenOfThread( IN HANDLE ThreadHandle, IN BOOLEAN OpenAsSelf, OUT PACCESS_TOKEN *Token, OUT PETHREAD *Thread, OUT PBOOLEAN CopyOnOpen, OUT PBOOLEAN EffectiveOnly, OUT PSECURITY_IMPERSONATION_LEVEL ImpersonationLevel ) /*++ Routine Description: This function does the thread specific processing of an NtOpenThreadToken() service. The service validates that the handle has appropriate access to reference the thread. If so, it goes on to increment the reference count of the token object to prevent it from going away while the rest of the NtOpenThreadToken() request is processed. NOTE: If this call completes successfully, the caller is responsible for decrementing the reference count of the target token. This must be done using PsDereferenceImpersonationToken(). Arguments: ThreadHandle - Supplies a handle to a thread object. OpenAsSelf - Is a boolean value indicating whether the access should be made using the calling thread's current security context, which may be that of a client (if impersonating), or using the caller's process-level security context. A value of FALSE indicates the caller's current context should be used un-modified. A value of TRUE indicates the request should be fulfilled using the process level security context. Token - If successful, receives a pointer to the thread's token object. CopyOnOpen - The current value of the Thread->Client->CopyOnOpen field. EffectiveOnly - The current value of the Thread->Client->EffectiveOnly field. ImpersonationLevel - The current value of the Thread->Client->ImpersonationLevel field. Return Value: STATUS_SUCCESS - Indicates the call completed successfully. STATUS_NO_TOKEN - Indicates the referenced thread is not currently impersonating a client. STATUS_CANT_OPEN_ANONYMOUS - Indicates the client requested anonymous impersonation level. An anonymous token can not be openned. status may also be any value returned by an attemp the reference the thread object for THREAD_QUERY_INFORMATION access. --*/ { NTSTATUS Status; KPROCESSOR_MODE PreviousMode; SE_IMPERSONATION_STATE DisabledImpersonationState; BOOLEAN RestoreImpersonationState = FALSE; PreviousMode = KeGetPreviousMode(); // // Disable impersonation if necessary // if (OpenAsSelf) { RestoreImpersonationState = PsDisableImpersonation( PsGetCurrentThread(), &DisabledImpersonationState ); } // // Make sure the handle grants the appropriate access to the specified // thread. // Status = ObReferenceObjectByHandle( ThreadHandle, THREAD_QUERY_INFORMATION, PsThreadType, PreviousMode, (PVOID *)Thread, NULL ); if (RestoreImpersonationState) { PsRestoreImpersonation( PsGetCurrentThread(), &DisabledImpersonationState ); } if (!NT_SUCCESS(Status)) { return Status; } // // Reference the impersonation token, if there is one // (*Token) = PsReferenceImpersonationToken( *Thread, CopyOnOpen, EffectiveOnly, ImpersonationLevel ); // // Make sure there is a token // if ((*Token) == NULL) { ObDereferenceObject( *Thread ); (*Thread) = NULL; return STATUS_NO_TOKEN; } // // Make sure the ImpersonationLevel is high enough to allow // the token to be openned. // if ((*ImpersonationLevel) <= SecurityAnonymous) { PsDereferenceImpersonationToken( (*Token) ); ObDereferenceObject( *Thread ); (*Thread) = NULL; (*Token) = NULL; return STATUS_CANT_OPEN_ANONYMOUS; } return STATUS_SUCCESS; } NTSTATUS NtOpenThreadToken( IN HANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN BOOLEAN OpenAsSelf, OUT PHANDLE TokenHandle ) /*++ Routine Description: Open a token object associated with a thread and return a handle that may be used to access that token. Arguments: ThreadHandle - Specifies the thread whose token is to be opened. DesiredAccess - Is an access mask indicating which access types are desired to the token. These access types are reconciled with the Discretionary Access Control list of the token to determine whether the accesses will be granted or denied. OpenAsSelf - Is a boolean value indicating whether the access should be made using the calling thread's current security context, which may be that of a client if impersonating, or using the caller's process-level security context. A value of FALSE indicates the caller's current context should be used un-modified. A value of TRUE indicates the request should be fulfilled using the process level security context. This parameter is necessary to allow a server process to open a client's token when the client specified IDENTIFICATION level impersonation. In this case, the caller would not be able to open the client's token using the client's context (because you can't create executive level objects using IDENTIFICATION level impersonation). TokenHandle - Receives the handle of the newly opened token. Return Value: STATUS_SUCCESS - Indicates the operation was successful. STATUS_NO_TOKEN - Indicates an attempt has been made to open a token associated with a thread that is not currently impersonating a client. STATUS_CANT_OPEN_ANONYMOUS - Indicates the client requested anonymous impersonation level. An anonymous token can not be openned. --*/ { KPROCESSOR_MODE PreviousMode; NTSTATUS Status; PVOID Token; PTOKEN NewToken = NULL; BOOLEAN CopyOnOpen; BOOLEAN EffectiveOnly; SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; SE_IMPERSONATION_STATE DisabledImpersonationState; BOOLEAN RestoreImpersonationState = FALSE; HANDLE LocalHandle; SECURITY_DESCRIPTOR SecurityDescriptor; OBJECT_ATTRIBUTES ObjectAttributes; PACL NewAcl = NULL; PETHREAD Thread; PETHREAD OriginalThread = NULL; PACCESS_TOKEN PrimaryToken; SECURITY_SUBJECT_CONTEXT SubjectSecurityContext; PAGED_CODE(); PreviousMode = KeGetPreviousMode(); // // Probe parameters // if (PreviousMode != KernelMode) { try { ProbeForWriteHandle(TokenHandle); } except(EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } // end_try } //end_if // // Valdiate access to the thread and obtain a pointer to the // thread's token (if there is one). If successful, this will // cause the token's reference count to be incremented. // // This routine disabled impersonation as necessary to properly // honor the OpenAsSelf flag. // Status = SepOpenTokenOfThread( ThreadHandle, OpenAsSelf, ((PACCESS_TOKEN *)&Token), &OriginalThread, &CopyOnOpen, &EffectiveOnly, &ImpersonationLevel ); if (!NT_SUCCESS(Status)) { return Status; } // // The token was successfully referenced. // // // We need to create and/or open a token object, so disable impersonation // if necessary. // if (OpenAsSelf) { RestoreImpersonationState = PsDisableImpersonation( PsGetCurrentThread(), &DisabledImpersonationState ); } // // If the CopyOnOpen flag is not set, then the token can be // opened directly. Otherwise, the token must be duplicated, // and a handle to the duplicate returned. // if (CopyOnOpen) { // // Create the new security descriptor for the token. // // We must obtain the correct SID to put into the Dacl. Do this // by finding the process associated with the passed thread // and grabbing the User SID out of that process's token. // If we just use the current SubjectContext, we'll get the // SID of whoever is calling us, which isn't what we want. // Status = ObReferenceObjectByHandle( ThreadHandle, THREAD_ALL_ACCESS, PsThreadType, KernelMode, (PVOID)&Thread, NULL ); // // Verify that the handle is still pointer to the same thread\ // BUGBUG: wrong error code. // if (NT_SUCCESS(Status) && (Thread != OriginalThread)) { Status = STATUS_OBJECT_TYPE_MISMATCH; } if (NT_SUCCESS(Status)) { PrimaryToken = PsReferencePrimaryToken(Thread->ThreadsProcess); Status = SepCreateImpersonationTokenDacl( (PTOKEN)Token, PrimaryToken, &NewAcl ); PsDereferencePrimaryToken( PrimaryToken ); if (NT_SUCCESS( Status )) { if (NewAcl != NULL) { // // There exist tokens that either do not have security descriptors at all, // or have security descriptors, but do not have DACLs. In either case, do // nothing. // Status = RtlCreateSecurityDescriptor ( &SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION ); ASSERT( NT_SUCCESS( Status )); Status = RtlSetDaclSecurityDescriptor ( &SecurityDescriptor, TRUE, NewAcl, FALSE ); ASSERT( NT_SUCCESS( Status )); } InitializeObjectAttributes( &ObjectAttributes, NULL, 0L, NULL, NewAcl == NULL ? NULL : &SecurityDescriptor ); // // Open a copy of the token // Status = SepDuplicateToken( (PTOKEN)Token, // ExistingToken &ObjectAttributes, // ObjectAttributes EffectiveOnly, // EffectiveOnly TokenImpersonation, // TokenType ImpersonationLevel, // ImpersonationLevel KernelMode, // RequestorMode must be kernel mode &NewToken ); if (NT_SUCCESS( Status )) { // // Reference the token so it doesn't go away // ObReferenceObject(NewToken); // // Insert the new token // Status = ObInsertObject( NewToken, NULL, DesiredAccess, 0, (PVOID *)NULL, &LocalHandle ); } } } } else { // // We do not have to modify the security on the token in the static case, // because in all the places in the system where impersonation takes place // over a secure transport (e.g., LPC), CopyOnOpen is set. The only reason // we'be be here is if the impersonation is taking place because someone did // an NtSetInformationThread and passed in a token. // // In that case, we absolutely do not want to give the caller guaranteed // access, because that would allow anyone who has access to a thread to // impersonate any of that thread's clients for any access. // // // Open the existing token // Status = ObOpenObjectByPointer( (PVOID)Token, // Object 0, // HandleAttributes NULL, // AccessState DesiredAccess, // DesiredAccess SepTokenObjectType, // ObjectType PreviousMode, // AccessMode &LocalHandle // Handle ); } if (NewAcl != NULL) { ExFreePool( NewAcl ); } if (RestoreImpersonationState) { PsRestoreImpersonation( PsGetCurrentThread(), &DisabledImpersonationState ); } // // And decrement the reference count of the existing token to counter // the action performed by PsOpenTokenOfThread. If the open // was successful, the handle will have caused the token's // reference count to have been incremented. // ObDereferenceObject( Token ); if (NT_SUCCESS( Status ) && CopyOnOpen) { // // Assign the newly duplicated token to the thread. // PsImpersonateClient( Thread, NewToken, FALSE, // turn off CopyOnOpen flag EffectiveOnly, ImpersonationLevel ); } // // We've impersonated the token so let go of oure reference // if (NewToken != NULL) { ObDereferenceObject( NewToken ); } if (CopyOnOpen && (Thread != NULL)) { ObDereferenceObject( Thread ); } if (OriginalThread != NULL) { ObDereferenceObject(OriginalThread); } // // Return the new handle // if (NT_SUCCESS(Status)) { try { *TokenHandle = LocalHandle; } except(EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } } return Status; }
668720.c
/** * @file ice.c ICE Module * * Copyright (C) 2010 Alfred E. Heggestad */ #include <re.h> #include <baresip.h> /** * @defgroup ice ice * * Interactive Connectivity Establishment (ICE) for media NAT traversal * * This module enables ICE for NAT traversal. You can enable ICE * in your accounts file with the parameter ;medianat=ice. * */ enum { ICE_LAYER = 0 }; struct mnat_sess { struct list medial; struct sa srv; struct stun_dns *dnsq; struct sdp_session *sdp; struct tmr tmr_async; char lufrag[8]; char lpwd[32]; uint64_t tiebrk; bool turn; bool offerer; char *user; char *pass; bool started; bool send_reinvite; mnat_estab_h *estabh; void *arg; }; struct mnat_media { struct comp { struct mnat_media *m; /* pointer to parent */ struct stun_ctrans *ct_gath; struct sa laddr; unsigned id; void *sock; } compv[2]; struct le le; struct mnat_sess *sess; struct sdp_media *sdpm; struct icem *icem; bool gathered; bool complete; bool terminated; int nstun; /**< Number of pending STUN candidates */ mnat_connected_h *connh; void *arg; }; static void gather_handler(int err, uint16_t scode, const char *reason, void *arg); static void call_gather_handler(int err, struct mnat_media *m, uint16_t scode, const char *reason) { /* No more pending requests? */ if (m->nstun != 0) return; debug("ice: all components gathered.\n"); if (err) goto out; /* Eliminate redundant local candidates */ icem_cand_redund_elim(m->icem); err = icem_comps_set_default_cand(m->icem); if (err) { warning("ice: set default cands failed (%m)\n", err); goto out; } out: gather_handler(err, scode, reason, m); } static void stun_resp_handler(int err, uint16_t scode, const char *reason, const struct stun_msg *msg, void *arg) { struct comp *comp = arg; struct mnat_media *m = comp->m; struct stun_attr *attr; struct ice_cand *lcand; if (m->terminated) return; --m->nstun; if (err || scode > 0) { warning("ice: comp %u: STUN Request failed: %m\n", comp->id, err); goto out; } debug("ice: srflx gathering for comp %u complete.\n", comp->id); /* base candidate */ lcand = icem_cand_find(icem_lcandl(m->icem), comp->id, NULL); if (!lcand) goto out; attr = stun_msg_attr(msg, STUN_ATTR_XOR_MAPPED_ADDR); if (!attr) attr = stun_msg_attr(msg, STUN_ATTR_MAPPED_ADDR); if (!attr) { warning("ice: no Mapped Address in Response\n"); err = EPROTO; goto out; } err = icem_lcand_add(m->icem, icem_lcand_base(lcand), ICE_CAND_TYPE_SRFLX, &attr->v.sa); out: call_gather_handler(err, m, scode, reason); } /** Gather Server Reflexive address */ static int send_binding_request(struct mnat_media *m, struct comp *comp) { int err; if (comp->ct_gath) return EALREADY; debug("ice: gathering srflx for comp %u ..\n", comp->id); err = stun_request(&comp->ct_gath, icem_stun(m->icem), IPPROTO_UDP, comp->sock, &m->sess->srv, 0, STUN_METHOD_BINDING, NULL, false, 0, stun_resp_handler, comp, 1, STUN_ATTR_SOFTWARE, stun_software); if (err) return err; ++m->nstun; return 0; } static void turnc_handler(int err, uint16_t scode, const char *reason, const struct sa *relay, const struct sa *mapped, const struct stun_msg *msg, void *arg) { struct comp *comp = arg; struct mnat_media *m = comp->m; struct ice_cand *lcand; (void)msg; --m->nstun; /* TURN failed, so we destroy the client */ if (err || scode) { icem_set_turn_client(m->icem, comp->id, NULL); } if (err) { warning("{%u} TURN Client error: %m\n", comp->id, err); goto out; } if (scode) { warning("{%u} TURN Client error: %u %s\n", comp->id, scode, reason); err = send_binding_request(m, comp); if (err) goto out; return; } debug("ice: relay gathered for comp %u (%u %s)\n", comp->id, scode, reason); lcand = icem_cand_find(icem_lcandl(m->icem), comp->id, NULL); if (!lcand) goto out; if (!sa_cmp(relay, icem_lcand_addr(icem_lcand_base(lcand)), SA_ALL)) { err = icem_lcand_add(m->icem, icem_lcand_base(lcand), ICE_CAND_TYPE_RELAY, relay); } if (mapped) { err |= icem_lcand_add(m->icem, icem_lcand_base(lcand), ICE_CAND_TYPE_SRFLX, mapped); } else { err |= send_binding_request(m, comp); } out: call_gather_handler(err, m, scode, reason); } static int cand_gather_relayed(struct mnat_media *m, struct comp *comp, const char *username, const char *password) { struct turnc *turnc = NULL; const int layer = ICE_LAYER - 10; /* below ICE stack */ int err; err = turnc_alloc(&turnc, stun_conf(icem_stun(m->icem)), IPPROTO_UDP, comp->sock, layer, &m->sess->srv, username, password, 60, turnc_handler, comp); if (err) return err; err = icem_set_turn_client(m->icem, comp->id, turnc); if (err) goto out; ++m->nstun; out: mem_deref(turnc); return err; } static int start_gathering(struct mnat_media *m, const char *username, const char *password) { unsigned i; int err = 0; /* for each component */ for (i=0; i<2; i++) { struct comp *comp = &m->compv[i]; if (!comp->sock) continue; if (m->sess->turn) { err |= cand_gather_relayed(m, comp, username, password); } else err |= send_binding_request(m, comp); } return err; } static int icem_gather_srflx(struct mnat_media *m) { if (!m) return EINVAL; return start_gathering(m, NULL, NULL); } static int icem_gather_relay(struct mnat_media *m, const char *username, const char *password) { if (!m || !username || !password) return EINVAL; return start_gathering(m, username, password); } static void ice_printf(struct mnat_media *m, const char *fmt, ...) { va_list ap; va_start(ap, fmt); debug("%s: %v", m ? sdp_media_name(m->sdpm) : "ICE", fmt, &ap); va_end(ap); } static void session_destructor(void *arg) { struct mnat_sess *sess = arg; tmr_cancel(&sess->tmr_async); list_flush(&sess->medial); mem_deref(sess->dnsq); mem_deref(sess->user); mem_deref(sess->pass); mem_deref(sess->sdp); } static void media_destructor(void *arg) { struct mnat_media *m = arg; unsigned i; m->terminated = true; list_unlink(&m->le); mem_deref(m->sdpm); mem_deref(m->icem); for (i=0; i<2; i++) { mem_deref(m->compv[i].ct_gath); mem_deref(m->compv[i].sock); } } static bool candidate_handler(struct le *le, void *arg) { return 0 != sdp_media_set_lattr(arg, false, ice_attr_cand, "%H", ice_cand_encode, le->data); } /** * Update the local SDP attributes, this can be called multiple times * when the state of the ICE machinery changes */ static int set_media_attributes(struct mnat_media *m) { int err = 0; if (icem_mismatch(m->icem)) { err = sdp_media_set_lattr(m->sdpm, true, ice_attr_mismatch, NULL); return err; } else { sdp_media_del_lattr(m->sdpm, ice_attr_mismatch); } /* Encode all my candidates */ sdp_media_del_lattr(m->sdpm, ice_attr_cand); if (list_apply(icem_lcandl(m->icem), true, candidate_handler, m->sdpm)) return ENOMEM; if (ice_remotecands_avail(m->icem)) { err |= sdp_media_set_lattr(m->sdpm, true, ice_attr_remote_cand, "%H", ice_remotecands_encode, m->icem); } return err; } static bool if_handler(const char *ifname, const struct sa *sa, void *arg) { struct mnat_media *m = arg; uint16_t lprio; unsigned i; int err = 0; /* Skip loopback and link-local addresses */ if (sa_is_loopback(sa) || sa_is_linklocal(sa)) return false; if (!net_af_enabled(baresip_network(), sa_af(sa))) return false; lprio = 0; ice_printf(m, "added interface: %s:%j (local prio %u)\n", ifname, sa, lprio); for (i=0; i<2; i++) { if (m->compv[i].sock) err |= icem_cand_add(m->icem, i+1, lprio, ifname, sa); } if (err) { warning("ice: %s:%j: icem_cand_add: %m\n", ifname, sa, err); } return false; } static int media_start(struct mnat_sess *sess, struct mnat_media *m) { int err = 0; net_if_apply(if_handler, m); if (sess->turn) { err = icem_gather_relay(m, sess->user, sess->pass); } else { err = icem_gather_srflx(m); } return err; } static void dns_handler(int err, const struct sa *srv, void *arg) { struct mnat_sess *sess = arg; struct le *le; if (err) goto out; debug("ice: resolved %s-server to address %J\n", sess->turn ? "TURN" : "STUN", srv); sess->srv = *srv; for (le=sess->medial.head; le; le=le->next) { struct mnat_media *m = le->data; err = media_start(sess, m); if (err) goto out; } return; out: sess->estabh(err, 0, NULL, sess->arg); } static void tmr_async_handler(void *arg) { struct mnat_sess *sess = arg; struct le *le; for (le = sess->medial.head; le; le = le->next) { struct mnat_media *m = le->data; net_if_apply(if_handler, m); call_gather_handler(0, m, 0, ""); } } static int session_alloc(struct mnat_sess **sessp, const struct mnat *mnat, struct dnsc *dnsc, int af, const struct stun_uri *srv, const char *user, const char *pass, struct sdp_session *ss, bool offerer, mnat_estab_h *estabh, void *arg) { struct mnat_sess *sess; const char *usage = NULL; int err = 0; (void)mnat; if (!sessp || !dnsc || !ss || !estabh) return EINVAL; if (srv) { info("ice: new session with %s-server at %s (username=%s)\n", srv->scheme == STUN_SCHEME_TURN ? "TURN" : "STUN", srv->host, user); switch (srv->scheme) { case STUN_SCHEME_STUN: usage = stun_usage_binding; break; case STUN_SCHEME_TURN: usage = stun_usage_relay; break; default: return ENOTSUP; } } sess = mem_zalloc(sizeof(*sess), session_destructor); if (!sess) return ENOMEM; sess->sdp = mem_ref(ss); sess->estabh = estabh; sess->arg = arg; if (user && pass) { err = str_dup(&sess->user, user); err |= str_dup(&sess->pass, pass); if (err) goto out; } rand_str(sess->lufrag, sizeof(sess->lufrag)); rand_str(sess->lpwd, sizeof(sess->lpwd)); sess->tiebrk = rand_u64(); sess->offerer = offerer; err |= sdp_session_set_lattr(ss, true, ice_attr_ufrag, sess->lufrag); err |= sdp_session_set_lattr(ss, true, ice_attr_pwd, sess->lpwd); if (err) goto out; if (srv) { sess->turn = (srv->scheme == STUN_SCHEME_TURN); err = stun_server_discover(&sess->dnsq, dnsc, usage, stun_proto_udp, af, srv->host, srv->port, dns_handler, sess); } else { tmr_start(&sess->tmr_async, 1, tmr_async_handler, sess); } out: if (err) mem_deref(sess); else *sessp = sess; return err; } static bool verify_peer_ice(struct mnat_sess *ms) { struct le *le; for (le = ms->medial.head; le; le = le->next) { struct mnat_media *m = le->data; struct sa raddr[2]; unsigned i; if (!sdp_media_has_media(m->sdpm)) { info("ice: stream '%s' is disabled -- ignore\n", sdp_media_name(m->sdpm)); continue; } raddr[0] = *sdp_media_raddr(m->sdpm); sdp_media_raddr_rtcp(m->sdpm, &raddr[1]); for (i=0; i<2; i++) { if (m->compv[i].sock && sa_isset(&raddr[i], SA_ADDR) && !icem_verify_support(m->icem, i+1, &raddr[i])) { warning("ice: %s.%u: no remote candidates" " found (address = %J)\n", sdp_media_name(m->sdpm), i+1, &raddr[i]); return false; } } } return true; } static bool refresh_comp_laddr(struct mnat_media *m, unsigned id, struct comp *comp, const struct sa *laddr) { bool changed = false; if (!m || !comp || !comp->sock || !laddr) return false; if (!sa_cmp(&comp->laddr, laddr, SA_ALL)) { changed = true; ice_printf(m, "comp%u setting local: %J\n", id, laddr); } sa_cpy(&comp->laddr, laddr); if (id == 1) sdp_media_set_laddr(m->sdpm, &comp->laddr); else if (id == 2) sdp_media_set_laddr_rtcp(m->sdpm, &comp->laddr); return changed; } /* * Update SDP Media with local addresses */ static bool refresh_laddr(struct mnat_media *m, const struct sa *laddr1, const struct sa *laddr2) { bool changed = false; changed |= refresh_comp_laddr(m, 1, &m->compv[0], laddr1); changed |= refresh_comp_laddr(m, 2, &m->compv[1], laddr2); return changed; } static bool all_gathered(const struct mnat_sess *sess) { struct le *le; for (le = sess->medial.head; le; le = le->next) { struct mnat_media *m = le->data; if (!m->gathered) return false; } return true; } static bool all_completed(const struct mnat_sess *sess) { struct le *le; /* Check all conncheck flags */ LIST_FOREACH(&sess->medial, le) { struct mnat_media *mx = le->data; if (!mx->complete) return false; } return true; } static void gather_handler(int err, uint16_t scode, const char *reason, void *arg) { struct mnat_media *m = arg; mnat_estab_h *estabh = m->sess->estabh; if (err || scode) { warning("ice: gather error: %m (%u %s)\n", err, scode, reason); } else { refresh_laddr(m, icem_cand_default(m->icem, 1), icem_cand_default(m->icem, 2)); info("ice: %s: Default local candidates: %J / %J\n", sdp_media_name(m->sdpm), &m->compv[0].laddr, &m->compv[1].laddr); (void)set_media_attributes(m); m->gathered = true; if (!all_gathered(m->sess)) return; } if (err || scode) m->sess->estabh = NULL; if (estabh) estabh(err, scode, reason, m->sess->arg); } static void conncheck_handler(int err, bool update, void *arg) { struct mnat_media *m = arg; struct mnat_sess *sess = m->sess; bool sess_complete = false; info("ice: %s: connectivity check is complete (update=%d)\n", sdp_media_name(m->sdpm), update); ice_printf(m, "Dumping media state: %H\n", icem_debug, m->icem); if (err) { warning("ice: connectivity check failed: %m\n", err); } else { const struct ice_cand *cand1, *cand2; bool changed; m->complete = true; changed = refresh_laddr(m, icem_selected_laddr(m->icem, 1), icem_selected_laddr(m->icem, 2)); if (changed) sess->send_reinvite = true; (void)set_media_attributes(m); cand1 = icem_selected_rcand(m->icem, 1); cand2 = icem_selected_rcand(m->icem, 2); sess_complete = all_completed(sess); if (m->connh) { m->connh(icem_lcand_addr(cand1), icem_lcand_addr(cand2), m->arg); } } /* call estab-handler and send re-invite */ if (sess_complete && sess->send_reinvite && update) { info("ice: %s: sending Re-INVITE with updated" " default candidates\n", sdp_media_name(m->sdpm)); sess->send_reinvite = false; sess->estabh(0, 0, NULL, sess->arg); } } static int ice_start(struct mnat_sess *sess) { struct le *le; int err = 0; /* Update SDP media */ if (sess->started) { LIST_FOREACH(&sess->medial, le) { struct mnat_media *m = le->data; ice_printf(NULL, "ICE Start: %H", icem_debug, m->icem); icem_update(m->icem); refresh_laddr(m, icem_selected_laddr(m->icem, 1), icem_selected_laddr(m->icem, 2)); err |= set_media_attributes(m); } return err; } /* Clear all conncheck flags */ LIST_FOREACH(&sess->medial, le) { struct mnat_media *m = le->data; if (sdp_media_has_media(m->sdpm)) { m->complete = false; /* start ice if we have remote candidates */ if (!list_isempty(icem_rcandl(m->icem))) { err = icem_conncheck_start(m->icem); if (err) return err; } /* set the pair states -- first media stream only */ if (sess->medial.head == le) { ice_candpair_set_states(m->icem); } } else { m->complete = true; } } sess->started = true; return 0; } static int media_alloc(struct mnat_media **mp, struct mnat_sess *sess, struct udp_sock *sock1, struct udp_sock *sock2, struct sdp_media *sdpm, mnat_connected_h *connh, void *arg) { struct mnat_media *m; enum ice_role role; unsigned i; int err = 0; if (!mp || !sess || !sdpm) return EINVAL; m = mem_zalloc(sizeof(*m), media_destructor); if (!m) return ENOMEM; list_append(&sess->medial, &m->le, m); m->sdpm = mem_ref(sdpm); m->sess = sess; m->compv[0].sock = mem_ref(sock1); m->compv[1].sock = mem_ref(sock2); if (sess->offerer) role = ICE_ROLE_CONTROLLING; else role = ICE_ROLE_CONTROLLED; err = icem_alloc(&m->icem, ICE_MODE_FULL, role, IPPROTO_UDP, ICE_LAYER, sess->tiebrk, sess->lufrag, sess->lpwd, conncheck_handler, m); if (err) goto out; icem_conf(m->icem)->debug = LEVEL_DEBUG==log_level_get(); icem_conf(m->icem)->rc = 4; icem_set_conf(m->icem, icem_conf(m->icem)); icem_set_name(m->icem, sdp_media_name(sdpm)); for (i=0; i<2; i++) { m->compv[i].m = m; m->compv[i].id = i+1; if (m->compv[i].sock) err |= icem_comp_add(m->icem, i+1, m->compv[i].sock); } m->connh = connh; m->arg = arg; if (sa_isset(&sess->srv, SA_ALL)) err |= media_start(sess, m); out: if (err) mem_deref(m); else { *mp = m; } return err; } static bool sdp_attr_handler(const char *name, const char *value, void *arg) { struct mnat_sess *sess = arg; struct le *le; for (le = sess->medial.head; le; le = le->next) { struct mnat_media *m = le->data; (void)ice_sdp_decode(m->icem, name, value); } return false; } static bool media_attr_handler(const char *name, const char *value, void *arg) { struct mnat_media *m = arg; return 0 != icem_sdp_decode(m->icem, name, value); } static int enable_turn_channels(struct mnat_sess *sess) { struct le *le; int err = 0; for (le = sess->medial.head; le; le = le->next) { struct mnat_media *m = le->data; struct sa raddr[2]; unsigned i; err |= set_media_attributes(m); raddr[0] = *sdp_media_raddr(m->sdpm); sdp_media_raddr_rtcp(m->sdpm, &raddr[1]); for (i=0; i<2; i++) { if (m->compv[i].sock && sa_isset(&raddr[i], SA_ALL)) err |= icem_add_chan(m->icem, i+1, &raddr[i]); } } return err; } /** This can be called several times */ static int update(struct mnat_sess *sess) { struct le *le; int err = 0; if (!sess) return EINVAL; /* SDP session */ (void)sdp_session_rattr_apply(sess->sdp, NULL, sdp_attr_handler, sess); /* SDP medialines */ for (le = sess->medial.head; le; le = le->next) { struct mnat_media *m = le->data; sdp_media_rattr_apply(m->sdpm, NULL, media_attr_handler, m); } /* 5.1. Verifying ICE Support */ if (verify_peer_ice(sess)) { err = ice_start(sess); } else if (sess->turn) { info("ice: ICE not supported by peer, fallback to TURN\n"); err = enable_turn_channels(sess); } else { info("ice: ICE not supported by peer\n"); LIST_FOREACH(&sess->medial, le) { struct mnat_media *m = le->data; err |= set_media_attributes(m); } } return err; } static void attr_handler(struct mnat_media *mm, const char *name, const char *value) { if (!mm) return; /* NOTE: this must be done before starting conncheck */ sdp_media_rattr_apply(mm->sdpm, NULL, media_attr_handler, mm); icem_sdp_decode(mm->icem, name, value); /* start ice if we have local candidates */ if (!list_isempty(icem_lcandl(mm->icem))) { icem_conncheck_start(mm->icem); } } static struct mnat mnat_ice = { .id = "ice", .ftag = "+sip.ice", .wait_connected = true, .sessh = session_alloc, .mediah = media_alloc, .updateh = update, .attrh = attr_handler, }; static int module_init(void) { mnat_register(baresip_mnatl(), &mnat_ice); return 0; } static int module_close(void) { mnat_unregister(&mnat_ice); return 0; } EXPORT_SYM const struct mod_export DECL_EXPORTS(ice) = { "ice", "mnat", module_init, module_close, };
761755.c
#include <stdio.h> #include <string.h> #include <stdlib.h> int arr[10]={1,2,3,4,5,6,7,8,9,10}; int* foo(int *); int main(){ int (*po)(int *); po=&foo; int *e=po(arr); for(int i=0;i<10;i++) printf("%d\n",(*e+i)); free(e); return 0; } int* foo(int *arr){ int *p=(int *)malloc(sizeof(arr)); memset(p,0,10); memcpy(p,arr,sizeof(arr)); return p; }
746013.c
/* * POSIX library for Lua 5.1, 5.2 & 5.3. * Copyright (C) 2013-2020 Gary V. Vaughan * Copyright (C) 2010-2013 Reuben Thomas <[email protected]> * Copyright (C) 2008-2010 Natanael Copa <[email protected]> * Clean up and bug fixes by Leo Razoumov <[email protected]> 2006-10-11 * Luiz Henrique de Figueiredo <[email protected]> 07 Apr 2006 23:17:49 * Based on original by Claudio Terra for Lua 3.x. * With contributions by Roberto Ierusalimschy. * With documentation from Steve Donovan 2012 */ /*** Sys V Message Queue Operations. Where supported by the underlying system, functions to send and receive interprocess messages. If the module loads successfully, but there is no system support, then `posix.sys.msg.version` will be set, but the unsupported APIs wil be `nil`. @module posix.sys.msg */ #if HAVE_SYS_MSG_H && HAVE_MSGRCV && HAVE_MSGSND # define HAVE_SYSV_MESSAGING 1 #else # define HAVE_SYSV_MESSAGING 0 #endif #include "_helpers.c" #if HAVE_SYSV_MESSAGING #include <sys/ipc.h> #include <sys/msg.h> #include <sys/types.h> /*** Message queue record. @table PosixMsqid @int msg_qnum number of messages on the queue @int msg_qbytes number of bytes allowed on the queue @int msg_lspid process id of last msgsnd @int msg_lrpid process id of last msgrcv @int msg_stime time of last msgsnd @int msg_rtime time of last msgrcv @int msg_ctime time of last change */ static int pushmsqid(lua_State *L, struct msqid_ds *msqid) { if (!msqid) return lua_pushnil(L), 1; lua_createtable(L, 0, 8); setintegerfield(msqid, msg_qnum); setintegerfield(msqid, msg_qbytes); setintegerfield(msqid, msg_lspid); setintegerfield(msqid, msg_lrpid); setintegerfield(msqid, msg_stime); setintegerfield(msqid, msg_rtime); setintegerfield(msqid, msg_ctime); lua_createtable(L, 0, 5); pushintegerfield("uid", msqid->msg_perm.uid); pushintegerfield("gid", msqid->msg_perm.gid); pushintegerfield("cuid", msqid->msg_perm.cuid); pushintegerfield("cgid", msqid->msg_perm.cgid); pushintegerfield("mode", msqid->msg_perm.mode); lua_setfield(L, -2, "msg_perm"); settypemetatable("PosixMsqid"); return 1; } static const char *Smsqid_fields[] = { "msg_qbytes", "msg_perm" }; static const char *Sipcperm_fields[] = { "uid", "gid", "mode" }; static void tomsqid(lua_State *L, int index, struct msqid_ds *msqid) { int subindex; luaL_checktype(L, index, LUA_TTABLE); /* Copy fields to msqid struct */ msqid->msg_qbytes = checkintfield(L, index, "msg_qbytes"); checkfieldtype(L, index, "msg_perm", LUA_TTABLE, "table"); subindex = lua_gettop(L); msqid->msg_perm.uid = checkintfield(L, subindex, "uid"); msqid->msg_perm.gid = checkintfield(L, subindex, "gid"); msqid->msg_perm.mode = checkintfield(L, subindex, "mode"); checkfieldnames(L, index, Smsqid_fields); checkfieldnames(L, subindex, Sipcperm_fields); } /*** @function msgctl @int id message queue identifier returned by @{msgget} @int cmd one of `IPC_STAT`, `IPC_SET` or `IPC_RMID` @PosixMsqid[opt=nil] values to set with `IPC_SET` @treturn[1] PosixMsqid table for *id*, with `IPC_STAT`, if successful @treturn[2] non-nil, with `IPC_SET` or `IPC_RMID`, if successful @treturn[3] nil otherwise @treturn[3] string error message @treturn[3] int errnum @see msgctl(2) @usage local sysvmsg = require 'posix.sys.msg' local msq = sysvmsg.msgget(sysvmsg.IPC_PRIVATE) local msqid, errmsg = sysvmsg.msgctl(msq, sysvmsg.IPC_STAT) assert(msqid, errmsg) assert(sysvmsg.msgctl(msq, sysvmsg.IPC_RMID)) */ static int Pmsgctl(lua_State *L) { int id = checkint(L, 1); int cmd = checkint(L, 2); struct msqid_ds msqid; switch (cmd) { case IPC_RMID: checknargs(L, 2); return pushresult(L, msgctl(id, cmd, NULL), "msgctl"); case IPC_SET: checknargs(L, 3); tomsqid(L, 3, &msqid); return pushresult(L, msgctl(id, cmd, &msqid), "msgctl"); case IPC_STAT: checknargs(L, 2); if (msgctl(id, cmd, &msqid) < 0) return pusherror(L, "msgctl"); return pushmsqid(L, &msqid); default: checknargs(L, 3); return pusherror(L, "unsupported cmd value"); } } /*** Get a message queue identifier @function msgget @int key message queue id, or `IPC_PRIVATE` for a new queue @int[opt=0] flags bitwise OR of zero or more from `IPC_CREAT` and `IPC_EXCL`, and access permissions `S_IRUSR`, `S_IWUSR`, `S_IRGRP`, `S_IWGRP`, `S_IROTH` and `S_IWOTH` (from @{posix.sys.stat}) @treturn[1] int message queue identifier, if successful @return[2] nil @treturn[2] string error message @treturn[2] int errnum @see msgget(2) */ static int Pmsgget(lua_State *L) { checknargs (L, 2); return pushresult(L, msgget(checkint(L, 1), optint(L, 2, 0)), "msgget"); } /*** Send message to a message queue @function msgsnd @int id message queue identifier returned by @{msgget} @int type arbitrary message type @string message content @int[opt=0] flags optionally `IPC_NOWAIT` @treturn int 0, if successful @return[2] nil @treturn[2] string error message @treturn[2] int errnum @see msgsnd(2) */ static int Pmsgsnd(lua_State *L) { void *ud; lua_Alloc lalloc = lua_getallocf(L, &ud); struct { long mtype; char mtext[0]; } *msg; size_t len; size_t msgsz; ssize_t r; int msgid = checkint(L, 1); long msgtype = checklong(L, 2); const char *msgp = luaL_checklstring(L, 3, &len); int msgflg = optint(L, 4, 0); checknargs(L, 4); msgsz = sizeof(long) + len; if ((msg = lalloc(ud, NULL, 0, msgsz)) == NULL) return pusherror(L, "lalloc"); msg->mtype = msgtype; memcpy(msg->mtext, msgp, len); r = msgsnd(msgid, msg, msgsz, msgflg); lua_pushinteger(L, r); lalloc(ud, msg, msgsz, 0); return (r == -1 ? pusherror(L, NULL) : 1); } /*** Receive message from a message queue @function msgrcv @int id message queue identifier returned by @{msgget} @int size maximum message size @int type message type (optional, default - 0) @int[opt=0] flags bitwise OR of zero or more of `IPC_NOWAIT`, `MSG_EXCEPT` and `MSG_NOERROR` @treturn[1] int message type from @{msgsnd} @treturn[1] string message text, if successful @return[2] nil @treturn[2] string error message @treturn[2] int errnum @see msgrcv(2) */ static int Pmsgrcv(lua_State *L) { int msgid = checkint(L, 1); size_t msgsz = checkint(L, 2); long msgtyp = optint(L, 3, 0); int msgflg = optint(L, 4, 0); void *ud; lua_Alloc lalloc; struct { long mtype; char mtext[0]; } *msg; checknargs(L, 4); lalloc = lua_getallocf(L, &ud); if ((msg = lalloc(ud, NULL, 0, msgsz)) == NULL) return pusherror(L, "lalloc"); int res = msgrcv(msgid, msg, msgsz, msgtyp, msgflg); if (res != -1) { lua_pushinteger(L, msg->mtype); lua_pushlstring(L, msg->mtext, res - sizeof(long)); } lalloc(ud, msg, msgsz, 0); return (res == -1) ? pusherror(L, NULL) : 2; } #endif /*!HAVE_SYSV_MESSAGING*/ static const luaL_Reg posix_sys_msg_fns[] = { #if HAVE_SYSV_MESSAGING LPOSIX_FUNC( Pmsgctl ), LPOSIX_FUNC( Pmsgget ), LPOSIX_FUNC( Pmsgsnd ), LPOSIX_FUNC( Pmsgrcv ), #endif {NULL, NULL} }; /*** Constants. @section constants */ /*** Message constants. Any constants not available in the underlying system will be `nil` valued. @table posix.sys.msg @int IPC_STAT return a Msqid table from msgctl @int IPC_SET set the Msqid fields from msgctl @int IPC_RMID remove a message queue with msgctl @int IPC_CREAT create entry if key does not exist @int IPC_EXCL fail if key exists @int IPC_PRIVATE private key @int IPC_NOWAIT error if request must wait @int MSG_EXCEPT read messages with differing type @int MSG_NOERROR truncate received message rather than erroring @usage -- Print msg constants supported on this host. for name, value in pairs (require "posix.sys.msg") do if type (value) == "number" then print (name, value) end end */ LUALIB_API int luaopen_posix_sys_msg(lua_State *L) { luaL_newlib(L, posix_sys_msg_fns); lua_pushstring(L, LPOSIX_VERSION_STRING("sys.msg")); lua_setfield(L, -2, "version"); #if HAVE_SYSV_MESSAGING LPOSIX_CONST( IPC_CREAT ); # ifdef MSG_EXCEPT LPOSIX_CONST( MSG_EXCEPT ); # endif LPOSIX_CONST( IPC_EXCL ); # ifdef MSG_NOERROR LPOSIX_CONST( MSG_NOERROR ); # endif LPOSIX_CONST( IPC_NOWAIT ); LPOSIX_CONST( IPC_PRIVATE ); LPOSIX_CONST( IPC_RMID ); LPOSIX_CONST( IPC_SET ); LPOSIX_CONST( IPC_STAT ); #endif return 1; }
893639.c
#include "random_check_pri.h" static void random_check_free_func(register random_check_s *restrict r) { register random_check_layer_s *restrict layer, *restrict n; n = r->layer; while ((layer = n)) { n = layer->next; refer_free(layer); } if (r->ml) refer_free(r->ml); } random_check_s* random_check_alloc(mlog_s *ml) { register random_check_s *restrict r; r = (random_check_s *) refer_alloc(sizeof(random_check_s)); if (r) { refer_set_free(r, (refer_free_f) random_check_free_func); r->layer = NULL; r->pnext = &r->layer; r->ml = (mlog_s *) refer_save(ml); } return r; } void random_check_check(register random_check_s *restrict rc, register uint32_t random) { register random_check_layer_s *restrict layer; layer = rc->layer; while (layer) { layer->check(layer, random); layer = layer->next; } } void random_check_clear(register random_check_s *restrict rc) { register random_check_layer_s *restrict layer; layer = rc->layer; while (layer) { layer->clear(layer); layer = layer->next; } } void random_check_dump(register random_check_s *restrict rc) { register random_check_layer_s *restrict layer; register mlog_s *ml; layer = rc->layer; ml = rc->ml; while (layer) { layer->dump(layer, ml); layer = layer->next; } } void random_check_dump_statistics(mlog_s *ml, register const uint32_t *restrict data, register uint32_t number) { register double avg, s2v, min, max, v, k; avg = s2v = max = 0; min = (double) ~(uint32_t) 0; k = 1.0 / number; do { v = *data++; avg += v; s2v += v * v; if (v > max) max = v; if (v < min) min = v; } while (--number); avg *= k; s2v *= k; s2v -= avg * avg; s2v = (s2v > 0)?sqrt(s2v):0; if (avg > 0) { s2v /= avg; max /= avg; min /= avg; mlog_printf(ml, "s2v: %g, dm: %g (min: %f, max: %f)\n", s2v, max - min, min, max); } }
71231.c
#include "treap.h" #include <stdlib.h> #include "fatal.h" struct TreapNode { ElementType Element; Treap Left; Treap Right; int Priority; }; Position NullNode = NULL; /* Needs initialization */ /* START: fig12_39.txt */ Treap Initialize (void) { if (NullNode == NULL) { NullNode = malloc (sizeof (struct TreapNode)); if (NullNode == NULL) FatalError ("Out of space!!!"); NullNode->Left = NullNode->Right = NullNode; NullNode->Priority = Infinity; } return NullNode; } /* END */ /* Use ANSI C random number generator for simplicity */ int Random (void) { return rand () - 1; } Treap MakeEmpty (Treap T) { if (T != NullNode) { MakeEmpty (T->Left); MakeEmpty (T->Right); free (T); } return NullNode; } void PrintTree (Treap T) { if (T != NullNode) { PrintTree (T->Left); printf ("%d ", T->Element); PrintTree (T->Right); } } Position Find (ElementType X, Treap T) { if (T == NullNode) return NullNode; if (X < T->Element) return Find (X, T->Left); else if (X > T->Element) return Find (X, T->Right); else return T; } Position FindMin (Treap T) { if (T == NullNode) return NullNode; else if (T->Left == NullNode) return T; else return FindMin (T->Left); } Position FindMax (Treap T) { if (T != NullNode) while (T->Right != NullNode) T = T->Right; return T; } /* This function can be called only if K2 has a left child */ /* Perform a rotate between a node (K2) and its left child */ /* Update heights, then return new root */ static Position SingleRotateWithLeft (Position K2) { Position K1; K1 = K2->Left; K2->Left = K1->Right; K1->Right = K2; return K1; /* New root */ } /* This function can be called only if K1 has a right child */ /* Perform a rotate between a node (K1) and its right child */ /* Update heights, then return new root */ static Position SingleRotateWithRight (Position K1) { Position K2; K2 = K1->Right; K1->Right = K2->Left; K2->Left = K1; return K2; /* New root */ } /* START: fig12_40.txt */ Treap Insert (ElementType Item, Treap T) { if (T == NullNode) { /* Create and return a one-node tree */ T = malloc (sizeof (struct TreapNode)); if (T == NULL) FatalError ("Out of space!!!"); else { T->Element = Item; T->Priority = Random (); T->Left = T->Right = NullNode; } } else if (Item < T->Element) { T->Left = Insert (Item, T->Left); if (T->Left->Priority < T->Priority) T = SingleRotateWithLeft (T); } else if (Item > T->Element) { T->Right = Insert (Item, T->Right); if (T->Right->Priority < T->Priority) T = SingleRotateWithRight (T); } /* Otherwise it's a duplicate; do nothing */ return T; } /* END */ /* START: fig12_41.txt */ Treap Remove (ElementType Item, Treap T) { if (T != NullNode) { if (Item < T->Element) T->Left = Remove (Item, T->Left); else if (Item > T->Element) T->Right = Remove (Item, T->Right); else { /* Match found */ if (T->Left->Priority < T->Right->Priority) T = SingleRotateWithLeft (T); else T = SingleRotateWithRight (T); if (T != NullNode) /* Continue on down */ T = Remove (Item, T); else { /* At a leaf */ free (T->Left); T->Left = NullNode; } } } return T; } /* END */ ElementType Retrieve (Position P) { return P->Element; }
506241.c
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <sys/unistd.h> #include "unity.h" #include "esp_log.h" #include "esp_system.h" #include "esp_vfs.h" #include "esp_vfs_fat.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/sdmmc_host.h" #include "driver/sdmmc_defs.h" #include "sdmmc_cmd.h" #include "diskio.h" #include "ff.h" static const char* hello_str = "Hello, World!\n"; #define HEAP_SIZE_CAPTURE() \ size_t heap_size = esp_get_free_heap_size(); #define HEAP_SIZE_CHECK(tolerance) \ do {\ size_t final_heap_size = esp_get_free_heap_size(); \ if (final_heap_size < heap_size - tolerance) { \ printf("Initial heap size: %d, final: %d, diff=%d\n", heap_size, final_heap_size, heap_size - final_heap_size); \ } \ } while(0) static void create_file_with_text(const char* name, const char* text) { FILE* f = fopen(name, "wb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_TRUE(fputs(text, f) != EOF); TEST_ASSERT_EQUAL(0, fclose(f)); } TEST_CASE("Mount fails cleanly without card inserted", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = false, .max_files = 5 }; for (int i = 0; i < 3; ++i) { printf("Initializing card, attempt %d ", i); esp_err_t err = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL); printf(" err=%d\n", err); TEST_ESP_ERR(ESP_FAIL, err); } HEAP_SIZE_CHECK(0); } TEST_CASE("can create and write file on sd card", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); create_file_with_text("/sdcard/hello.txt", hello_str); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("overwrite and append file on sd card", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); /* Create new file with 'aaaa' */ const char *NAME = "/sdcard/hello.txt"; create_file_with_text(NAME, "aaaa"); /* Append 'bbbb' to file */ FILE *f_a = fopen(NAME, "a"); TEST_ASSERT_NOT_NULL(f_a); TEST_ASSERT_NOT_EQUAL(EOF, fputs("bbbb", f_a)); TEST_ASSERT_EQUAL(0, fclose(f_a)); /* Read back 8 bytes from file, verify it's 'aaaabbbb' */ char buf[10] = { 0 }; FILE *f_r = fopen(NAME, "r"); TEST_ASSERT_NOT_NULL(f_r); TEST_ASSERT_EQUAL(8, fread(buf, 1, 8, f_r)); TEST_ASSERT_EQUAL_STRING_LEN("aaaabbbb", buf, 8); /* Be sure we're at end of file */ TEST_ASSERT_EQUAL(0, fread(buf, 1, 8, f_r)); TEST_ASSERT_EQUAL(0, fclose(f_r)); /* Overwrite file with 'cccc' */ create_file_with_text(NAME, "cccc"); /* Verify file now only contains 'cccc' */ f_r = fopen(NAME, "r"); TEST_ASSERT_NOT_NULL(f_r); bzero(buf, sizeof(buf)); TEST_ASSERT_EQUAL(4, fread(buf, 1, 8, f_r)); // trying to read 8 bytes, only expecting 4 TEST_ASSERT_EQUAL_STRING_LEN("cccc", buf, 4); TEST_ASSERT_EQUAL(0, fclose(f_r)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("can read file on sd card", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = false, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); FILE* f = fopen("/sdcard/hello.txt", "r"); TEST_ASSERT_NOT_NULL(f); char buf[32]; int cb = fread(buf, 1, sizeof(buf), f); TEST_ASSERT_EQUAL(strlen(hello_str), cb); TEST_ASSERT_EQUAL(0, strcmp(hello_str, buf)); TEST_ASSERT_EQUAL(0, fclose(f)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } static void speed_test(void* buf, size_t buf_size, size_t file_size, bool write) { const size_t buf_count = file_size / buf_size; sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = write, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); FILE* f = fopen("/sdcard/4mb.bin", (write) ? "wb" : "rb"); TEST_ASSERT_NOT_NULL(f); struct timeval tv_start; gettimeofday(&tv_start, NULL); for (size_t n = 0; n < buf_count; ++n) { if (write) { TEST_ASSERT_EQUAL(1, fwrite(buf, buf_size, 1, f)); } else { if (fread(buf, buf_size, 1, f) != 1) { printf("reading at n=%d, eof=%d", n, feof(f)); TEST_FAIL(); } } } struct timeval tv_end; gettimeofday(&tv_end, NULL); TEST_ASSERT_EQUAL(0, fclose(f)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); float t_s = tv_end.tv_sec - tv_start.tv_sec + 1e-6f * (tv_end.tv_usec - tv_start.tv_usec); printf("%s %d bytes (block size %d) in %.3fms (%.3f MB/s)\n", (write)?"Wrote":"Read", file_size, buf_size, t_s * 1e3, (file_size / 1024 / 1024) / t_s); } TEST_CASE("read speed test", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); const size_t buf_size = 16 * 1024; uint32_t* buf = (uint32_t*) calloc(1, buf_size); const size_t file_size = 4 * 1024 * 1024; speed_test(buf, 4 * 1024, file_size, false); HEAP_SIZE_CHECK(0); speed_test(buf, 8 * 1024, file_size, false); HEAP_SIZE_CHECK(0); speed_test(buf, 16 * 1024, file_size, false); HEAP_SIZE_CHECK(0); free(buf); HEAP_SIZE_CHECK(0); } TEST_CASE("write speed test", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); const size_t buf_size = 16 * 1024; uint32_t* buf = (uint32_t*) calloc(1, buf_size); for (size_t i = 0; i < buf_size / 4; ++i) { buf[i] = esp_random(); } const size_t file_size = 4 * 1024 * 1024; speed_test(buf, 4 * 1024, file_size, true); speed_test(buf, 8 * 1024, file_size, true); speed_test(buf, 16 * 1024, file_size, true); free(buf); HEAP_SIZE_CHECK(0); } TEST_CASE("can lseek", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); FILE* f = fopen("/sdcard/seek.txt", "wb+"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_EQUAL(11, fprintf(f, "0123456789\n")); TEST_ASSERT_EQUAL(0, fseek(f, -2, SEEK_CUR)); TEST_ASSERT_EQUAL('9', fgetc(f)); TEST_ASSERT_EQUAL(0, fseek(f, 3, SEEK_SET)); TEST_ASSERT_EQUAL('3', fgetc(f)); TEST_ASSERT_EQUAL(0, fseek(f, -3, SEEK_END)); TEST_ASSERT_EQUAL('8', fgetc(f)); TEST_ASSERT_EQUAL(0, fseek(f, 3, SEEK_END)); TEST_ASSERT_EQUAL(14, ftell(f)); TEST_ASSERT_EQUAL(4, fprintf(f, "abc\n")); TEST_ASSERT_EQUAL(0, fseek(f, 0, SEEK_END)); TEST_ASSERT_EQUAL(18, ftell(f)); TEST_ASSERT_EQUAL(0, fseek(f, 0, SEEK_SET)); char buf[20]; TEST_ASSERT_EQUAL(18, fread(buf, 1, sizeof(buf), f)); const char ref_buf[] = "0123456789\n\0\0\0abc\n"; TEST_ASSERT_EQUAL_INT8_ARRAY(ref_buf, buf, sizeof(ref_buf) - 1); TEST_ASSERT_EQUAL(0, fclose(f)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("stat returns correct values", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); struct tm tm; tm.tm_year = 2016 - 1900; tm.tm_mon = 0; tm.tm_mday = 10; tm.tm_hour = 16; tm.tm_min = 30; tm.tm_sec = 0; time_t t = mktime(&tm); printf("Setting time: %s", asctime(&tm)); struct timeval now = { .tv_sec = t }; settimeofday(&now, NULL); create_file_with_text("/sdcard/stat.txt", "foo\n"); struct stat st; TEST_ASSERT_EQUAL(0, stat("/sdcard/stat.txt", &st)); time_t mtime = st.st_mtime; struct tm mtm; localtime_r(&mtime, &mtm); printf("File time: %s", asctime(&mtm)); TEST_ASSERT(abs(mtime - t) < 2); // fatfs library stores time with 2 second precision TEST_ASSERT(st.st_mode & S_IFREG); TEST_ASSERT_FALSE(st.st_mode & S_IFDIR); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("unlink removes a file", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); create_file_with_text("/sdcard/unlink.txt", "unlink\n"); TEST_ASSERT_EQUAL(0, unlink("/sdcard/unlink.txt")); TEST_ASSERT_NULL(fopen("/sdcard/unlink.txt", "r")); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("link copies a file, rename moves a file", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); unlink("/sdcard/linkcopy.txt"); unlink("/sdcard/link_dst.txt"); unlink("/sdcard/link_src.txt"); FILE* f = fopen("/sdcard/link_src.txt", "w+"); TEST_ASSERT_NOT_NULL(f); char* str = "0123456789"; for (int i = 0; i < 4000; ++i) { TEST_ASSERT_NOT_EQUAL(EOF, fputs(str, f)); } TEST_ASSERT_EQUAL(0, fclose(f)); TEST_ASSERT_EQUAL(0, link("/sdcard/link_src.txt", "/sdcard/linkcopy.txt")); FILE* fcopy = fopen("/sdcard/linkcopy.txt", "r"); TEST_ASSERT_NOT_NULL(fcopy); TEST_ASSERT_EQUAL(0, fseek(fcopy, 0, SEEK_END)); TEST_ASSERT_EQUAL(40000, ftell(fcopy)); TEST_ASSERT_EQUAL(0, fclose(fcopy)); TEST_ASSERT_EQUAL(0, rename("/sdcard/linkcopy.txt", "/sdcard/link_dst.txt")); TEST_ASSERT_NULL(fopen("/sdcard/linkcopy.txt", "r")); FILE* fdst = fopen("/sdcard/link_dst.txt", "r"); TEST_ASSERT_NOT_NULL(fdst); TEST_ASSERT_EQUAL(0, fseek(fdst, 0, SEEK_END)); TEST_ASSERT_EQUAL(40000, ftell(fdst)); TEST_ASSERT_EQUAL(0, fclose(fdst)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } typedef struct { const char* filename; bool write; size_t word_count; int seed; SemaphoreHandle_t done; int result; } read_write_test_arg_t; #define READ_WRITE_TEST_ARG_INIT(name, seed_) \ { \ .filename = name, \ .seed = seed_, \ .word_count = 8192, \ .write = true, \ .done = xSemaphoreCreateBinary() \ } static void read_write_task(void* param) { read_write_test_arg_t* args = (read_write_test_arg_t*) param; FILE* f = fopen(args->filename, args->write ? "wb" : "rb"); if (f == NULL) { args->result = ESP_ERR_NOT_FOUND; goto done; } srand(args->seed); for (size_t i = 0; i < args->word_count; ++i) { uint32_t val = rand(); if (args->write) { int cnt = fwrite(&val, sizeof(val), 1, f); if (cnt != 1) { args->result = ESP_FAIL; goto close; } } else { uint32_t rval; int cnt = fread(&rval, sizeof(rval), 1, f); if (cnt != 1 || rval != val) { ets_printf("E: i=%d, cnt=%d rval=%d val=%d\n\n", i, cnt, rval, val); args->result = ESP_FAIL; goto close; } } } args->result = ESP_OK; close: fclose(f); done: xSemaphoreGive(args->done); vTaskDelay(1); vTaskDelete(NULL); } TEST_CASE("multiple tasks can use same volume", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); read_write_test_arg_t args1 = READ_WRITE_TEST_ARG_INIT("/sdcard/f1", 1); read_write_test_arg_t args2 = READ_WRITE_TEST_ARG_INIT("/sdcard/f2", 2); printf("writing f1 and f2\n"); xTaskCreatePinnedToCore(&read_write_task, "rw1", 2048, &args1, 3, NULL, 0); xTaskCreatePinnedToCore(&read_write_task, "rw2", 2048, &args2, 3, NULL, 1); xSemaphoreTake(args1.done, portMAX_DELAY); printf("f1 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args1.result); xSemaphoreTake(args2.done, portMAX_DELAY); printf("f2 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args2.result); args1.write = false; args2.write = false; read_write_test_arg_t args3 = READ_WRITE_TEST_ARG_INIT("/sdcard/f3", 3); read_write_test_arg_t args4 = READ_WRITE_TEST_ARG_INIT("/sdcard/f4", 4); printf("reading f1 and f2, writing f3 and f4\n"); xTaskCreatePinnedToCore(&read_write_task, "rw3", 2048, &args3, 3, NULL, 1); xTaskCreatePinnedToCore(&read_write_task, "rw4", 2048, &args4, 3, NULL, 0); xTaskCreatePinnedToCore(&read_write_task, "rw1", 2048, &args1, 3, NULL, 0); xTaskCreatePinnedToCore(&read_write_task, "rw2", 2048, &args2, 3, NULL, 1); xSemaphoreTake(args1.done, portMAX_DELAY); printf("f1 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args1.result); xSemaphoreTake(args2.done, portMAX_DELAY); printf("f2 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args2.result); xSemaphoreTake(args3.done, portMAX_DELAY); printf("f3 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args3.result); xSemaphoreTake(args4.done, portMAX_DELAY); printf("f4 done\n"); TEST_ASSERT_EQUAL(ESP_OK, args4.result); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); vSemaphoreDelete(args1.done); vSemaphoreDelete(args2.done); vSemaphoreDelete(args3.done); vSemaphoreDelete(args4.done); vTaskDelay(10); HEAP_SIZE_CHECK(0); } TEST_CASE("can create and remove directories", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); TEST_ASSERT_EQUAL(0, mkdir("/sdcard/dir1", 0755)); struct stat st; TEST_ASSERT_EQUAL(0, stat("/sdcard/dir1", &st)); TEST_ASSERT_TRUE(st.st_mode & S_IFDIR); TEST_ASSERT_FALSE(st.st_mode & S_IFREG); TEST_ASSERT_EQUAL(0, rmdir("/sdcard/dir1")); TEST_ASSERT_EQUAL(-1, stat("/sdcard/dir1", &st)); TEST_ASSERT_EQUAL(0, mkdir("/sdcard/dir2", 0755)); create_file_with_text("/sdcard/dir2/1.txt", "foo\n"); TEST_ASSERT_EQUAL(0, stat("/sdcard/dir2", &st)); TEST_ASSERT_TRUE(st.st_mode & S_IFDIR); TEST_ASSERT_FALSE(st.st_mode & S_IFREG); TEST_ASSERT_EQUAL(0, stat("/sdcard/dir2/1.txt", &st)); TEST_ASSERT_FALSE(st.st_mode & S_IFDIR); TEST_ASSERT_TRUE(st.st_mode & S_IFREG); TEST_ASSERT_EQUAL(-1, rmdir("/sdcard/dir2")); TEST_ASSERT_EQUAL(0, unlink("/sdcard/dir2/1.txt")); TEST_ASSERT_EQUAL(0, rmdir("/sdcard/dir2")); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); } TEST_CASE("opendir, readdir, rewinddir, seekdir work as expected", "[fatfs][ignore]") { HEAP_SIZE_CAPTURE(); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = true, .max_files = 5 }; TEST_ESP_OK(esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, NULL)); unlink("/sdcard/dir/inner/3.txt"); rmdir("/sdcard/dir/inner"); unlink("/sdcard/dir/2.txt"); unlink("/sdcard/dir/1.txt"); unlink("/sdcard/dir/boo.bin"); rmdir("/sdcard/dir"); TEST_ASSERT_EQUAL(0, mkdir("/sdcard/dir", 0755)); create_file_with_text("/sdcard/dir/2.txt", "1\n"); create_file_with_text("/sdcard/dir/1.txt", "1\n"); create_file_with_text("/sdcard/dir/boo.bin", "\01\02\03"); TEST_ASSERT_EQUAL(0, mkdir("/sdcard/dir/inner", 0755)); create_file_with_text("/sdcard/dir/inner/3.txt", "3\n"); DIR* dir = opendir("/sdcard/dir"); TEST_ASSERT_NOT_NULL(dir); int count = 0; const char* names[4]; while(count < 4) { struct dirent* de = readdir(dir); if (!de) { break; } printf("found '%s'\n", de->d_name); if (strcasecmp(de->d_name, "1.txt") == 0) { TEST_ASSERT_TRUE(de->d_type == DT_REG); names[count] = "1.txt"; ++count; } else if (strcasecmp(de->d_name, "2.txt") == 0) { TEST_ASSERT_TRUE(de->d_type == DT_REG); names[count] = "2.txt"; ++count; } else if (strcasecmp(de->d_name, "inner") == 0) { TEST_ASSERT_TRUE(de->d_type == DT_DIR); names[count] = "inner"; ++count; } else if (strcasecmp(de->d_name, "boo.bin") == 0) { TEST_ASSERT_TRUE(de->d_type == DT_REG); names[count] = "boo.bin"; ++count; } else { TEST_FAIL_MESSAGE("unexpected directory entry"); } } TEST_ASSERT_EQUAL(count, 4); rewinddir(dir); struct dirent* de = readdir(dir); TEST_ASSERT_NOT_NULL(de); TEST_ASSERT_EQUAL(0, strcasecmp(de->d_name, names[0])); seekdir(dir, 3); de = readdir(dir); TEST_ASSERT_NOT_NULL(de); TEST_ASSERT_EQUAL(0, strcasecmp(de->d_name, names[3])); seekdir(dir, 1); de = readdir(dir); TEST_ASSERT_NOT_NULL(de); TEST_ASSERT_EQUAL(0, strcasecmp(de->d_name, names[1])); seekdir(dir, 2); de = readdir(dir); TEST_ASSERT_NOT_NULL(de); TEST_ASSERT_EQUAL(0, strcasecmp(de->d_name, names[2])); TEST_ASSERT_EQUAL(0, closedir(dir)); TEST_ESP_OK(esp_vfs_fat_sdmmc_unmount()); HEAP_SIZE_CHECK(0); }
521507.c
/* $NetBSD: ipnat.c,v 1.9.2.2 1997/11/17 16:27:10 mrg Exp $ */ /* * Copyright (C) 1993-1997 by Darren Reed. * * Redistribution and use in source and binary forms are permitted * provided that this notice is preserved and due credit is given * to the original author and the contributors. * * Added redirect stuff and a variety of bug fixes. ([email protected]) * * Broken still: * Displaying the nat with redirect entries is way confusing * * Example redirection line: * rdr le1 0.0.0.0/0 port 79 -> 199.165.219.129 port 9901 * * Will redirect all incoming packets on le1 to any machine, port 79 to * host 199.165.219.129, port 9901 */ #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #if !defined(__SVR4) && !defined(__svr4__) #include <strings.h> #else #include <sys/byteorder.h> #endif #include <sys/time.h> #include <sys/param.h> #include <stdlib.h> #include <unistd.h> #include <stddef.h> #include <sys/socket.h> #include <sys/ioctl.h> #if defined(sun) && (defined(__svr4__) || defined(__SVR4)) # include <sys/ioccom.h> # include <sys/sysmacros.h> #endif #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <net/if.h> #include <netdb.h> #include <arpa/nameser.h> #include <arpa/inet.h> #include <resolv.h> #include <ctype.h> #include "netinet/ip_compat.h" #include "netinet/ip_fil.h" #include "netinet/ip_proxy.h" #include "netinet/ip_nat.h" #include "kmem.h" #if !defined(lint) static const char sccsid[] ="@(#)ipnat.c 1.9 6/5/96 (C) 1993 Darren Reed"; static const char rcsid[] = "@(#)Id: ipnat.c,v 2.0.2.21.2.1 1997/11/08 04:55:55 darrenr Exp "; #endif #if SOLARIS #define bzero(a,b) memset(a,0,b) #endif extern char *optarg; ipnat_t *parse __P((char *)); u_long hostnum __P((char *, int *)); u_long hostmask __P((char *)); u_short portnum __P((char *, char *)); void dostats __P((int, int)), flushtable __P((int, int)); void printnat __P((ipnat_t *, int, void *)); void parsefile __P((int, char *, int)); void usage __P((char *)); int countbits __P((u_long)); char *getnattype __P((ipnat_t *)); int main __P((int, char*[])); #define OPT_REM 1 #define OPT_NODO 2 #define OPT_STAT 4 #define OPT_LIST 8 #define OPT_VERBOSE 16 #define OPT_FLUSH 32 #define OPT_CLEAR 64 void usage(name) char *name; { fprintf(stderr, "%s: [-CFlnrsv] [-f filename]\n", name); exit(1); } int main(argc, argv) int argc; char *argv[]; { char *file = NULL; int fd = -1, opts = 1, c; while ((c = getopt(argc, argv, "CFf:lnrsv")) != -1) switch (c) { case 'C' : opts |= OPT_CLEAR; break; case 'f' : file = optarg; break; case 'F' : opts |= OPT_FLUSH; break; case 'l' : opts |= OPT_LIST; break; case 'n' : opts |= OPT_NODO; break; case 'r' : opts &= ~OPT_REM; break; case 's' : opts |= OPT_STAT; break; case 'v' : opts |= OPT_VERBOSE; break; default : usage(argv[0]); } if (!(opts & OPT_NODO) && ((fd = open(IPL_NAT, O_RDWR)) == -1) && ((fd = open(IPL_NAT, O_RDONLY)) == -1)) { perror("open"); exit(-1); } if (opts & (OPT_FLUSH|OPT_CLEAR)) flushtable(fd, opts); if (file) parsefile(fd, file, opts); if (opts & (OPT_LIST|OPT_STAT)) dostats(fd, opts); return 0; } /* * count consecutive 1's in bit mask. If the mask generated by counting * consecutive 1's is different to that passed, return -1, else return # * of bits. */ int countbits(ip) u_long ip; { u_long ipn; int cnt = 0, i, j; ip = ipn = ntohl(ip); for (i = 32; i; i--, ipn *= 2) if (ipn & 0x80000000) cnt++; else break; ipn = 0; for (i = 32, j = cnt; i; i--, j--) { ipn *= 2; if (j > 0) ipn++; } if (ipn == ip) return cnt; return -1; } void printnat(np, verbose, ptr) ipnat_t *np; int verbose; void *ptr; { int bits; struct protoent *pr; switch (np->in_redir) { case NAT_REDIRECT : printf("rdr "); break; case NAT_MAP : printf("map "); break; case NAT_BIMAP : printf("bimap "); break; default : fprintf(stderr, "unknown value for in_redir: %#x\n", np->in_redir); break; } if (np->in_redir == NAT_REDIRECT) { printf("%s %s", np->in_ifname, inet_ntoa(np->in_out[0])); bits = countbits(np->in_out[1].s_addr); if (bits != -1) printf("/%d ", bits); else printf("/%s ", inet_ntoa(np->in_out[1])); if (np->in_pmin) printf("port %d ", ntohs(np->in_pmin)); printf("-> %s", inet_ntoa(np->in_in[0])); if (np->in_pnext) printf(" port %d", ntohs(np->in_pnext)); if ((np->in_flags & IPN_TCPUDP) == IPN_TCPUDP) printf(" tcp/udp"); else if ((np->in_flags & IPN_TCP) == IPN_TCP) printf(" tcp"); else if ((np->in_flags & IPN_UDP) == IPN_UDP) printf(" udp"); printf("\n"); if (verbose) printf("\t%p %u %x %u %p %d\n", np->in_ifp, np->in_space, np->in_flags, np->in_pnext, np, np->in_use); } else { np->in_nextip.s_addr = htonl(np->in_nextip.s_addr); printf("%s %s/", np->in_ifname, inet_ntoa(np->in_in[0])); bits = countbits(np->in_in[1].s_addr); if (bits != -1) printf("%d ", bits); else printf("%s", inet_ntoa(np->in_in[1])); printf(" -> %s/", inet_ntoa(np->in_out[0])); bits = countbits(ntohl(np->in_out[1].s_addr)); if (bits != -1) printf("%d ", bits); else printf("%s", inet_ntoa(np->in_out[1])); if (*np->in_plabel) { printf(" proxy port"); if (np->in_dport) printf(" %hu", ntohs(np->in_dport)); printf(" %.*s/", (int)sizeof(np->in_plabel), np->in_plabel); if ((pr = getprotobynumber(np->in_p))) fputs(pr->p_name, stdout); else printf("%d", np->in_p); } else if (np->in_pmin || np->in_pmax) { printf(" portmap"); if ((np->in_flags & IPN_TCPUDP) == IPN_TCPUDP) printf(" tcp/udp"); else if (np->in_flags & IPN_TCP) printf(" tcp"); else if (np->in_flags & IPN_UDP) printf(" udp"); printf(" %d:%d", ntohs(np->in_pmin), ntohs(np->in_pmax)); } printf("\n"); if (verbose) printf("\t%p %u %s %d %x\n", np->in_ifp, np->in_space, inet_ntoa(np->in_nextip), np->in_pnext, np->in_flags); } } /* * Get a nat filter type given its kernel address. */ char *getnattype(ipnat) ipnat_t *ipnat; { char *which; ipnat_t ipnatbuff; if (ipnat && kmemcpy((char *)&ipnatbuff, (long)ipnat, sizeof(ipnatbuff))) return "???"; switch (ipnatbuff.in_redir) { case NAT_MAP : which = "MAP"; break; case NAT_REDIRECT : which = "RDR"; break; case NAT_BIMAP : which = "BIMAP"; break; default : which = "unknown"; break; } return which; } void dostats(fd, opts) int fd, opts; { natstat_t ns; ipnat_t ipn; nat_t **nt[2], *np, nat; int i = 0; bzero((char *)&ns, sizeof(ns)); if (!(opts & OPT_NODO) && ioctl(fd, SIOCGNATS, &ns) == -1) { perror("ioctl(SIOCGNATS)"); return; } if (opts & OPT_STAT) { printf("mapped\tin\t%lu\tout\t%lu\n", ns.ns_mapped[0], ns.ns_mapped[1]); printf("added\t%lu\texpired\t%lu\n", ns.ns_added, ns.ns_expire); printf("inuse\t%lu\nrules\t%lu\n", ns.ns_inuse, ns.ns_rules); if (opts & OPT_VERBOSE) printf("table %p list %p\n", ns.ns_table, ns.ns_list); } if (opts & OPT_LIST) { printf("List of active MAP/Redirect filters:\n"); while (ns.ns_list) { if (kmemcpy((char *)&ipn, (long)ns.ns_list, sizeof(ipn))) { perror("kmemcpy"); break; } printnat(&ipn, opts & OPT_VERBOSE, (void *)ns.ns_list); ns.ns_list = ipn.in_next; } nt[0] = (nat_t **)malloc(sizeof(*nt) * NAT_SIZE); if (kmemcpy((char *)nt[0], (long)ns.ns_table[0], sizeof(**nt) * NAT_SIZE)) { perror("kmemcpy"); return; } printf("\nList of active sessions:\n"); for (i = 0; i < NAT_SIZE; i++) for (np = nt[0][i]; np; np = nat.nat_hnext[0]) { if (kmemcpy((char *)&nat, (long)np, sizeof(nat))) break; printf("%s %-15s %-5hu <- ->", getnattype(nat.nat_ptr), inet_ntoa(nat.nat_inip), ntohs(nat.nat_inport)); printf(" %-15s %-5hu", inet_ntoa(nat.nat_outip), ntohs(nat.nat_outport)); printf(" [%s %hu]", inet_ntoa(nat.nat_oip), ntohs(nat.nat_oport)); printf(" %ld %hu %lx", nat.nat_age, nat.nat_use, nat.nat_sumd); #if SOLARIS printf(" %lx", nat.nat_ipsumd); #endif putchar('\n'); } free(nt[0]); } } u_short portnum(name, proto) char *name, *proto; { struct servent *sp, *sp2; u_short p1 = 0; if (isdigit(*name)) return htons((u_short)atoi(name)); if (!proto) proto = "tcp/udp"; if (strcasecmp(proto, "tcp/udp")) { sp = getservbyname(name, proto); if (sp) return sp->s_port; (void) fprintf(stderr, "unknown service \"%s\".\n", name); return 0; } sp = getservbyname(name, "tcp"); if (sp) p1 = sp->s_port; sp2 = getservbyname(name, "udp"); if (!sp || !sp2) { (void) fprintf(stderr, "unknown tcp/udp service \"%s\".\n", name); return 0; } if (p1 != sp2->s_port) { (void) fprintf(stderr, "%s %d/tcp is a different port to ", name, p1); (void) fprintf(stderr, "%s %d/udp\n", name, sp->s_port); return 0; } return p1; } u_long hostmask(msk) char *msk; { int bits = -1; u_long mask; if (!isdigit(*msk)) return (u_long)-1; if (strchr(msk, '.')) return inet_addr(msk); if (strchr(msk, 'x')) return (u_long)strtol(msk, NULL, 0); /* * set x most significant bits */ for (mask = 0, bits = atoi(msk); bits; bits--) { mask /= 2; mask |= ntohl(inet_addr("128.0.0.0")); } mask = htonl(mask); return mask; } /* * returns an ip address as a long var as a result of either a DNS lookup or * straight inet_addr() call */ u_long hostnum(host, resolved) char *host; int *resolved; { struct hostent *hp; struct netent *np; *resolved = 0; if (!strcasecmp("any", host)) return 0L; if (isdigit(*host)) return inet_addr(host); if (!(hp = gethostbyname(host))) { if (!(np = getnetbyname(host))) { *resolved = -1; fprintf(stderr, "can't resolve hostname: %s\n", host); return 0; } return np->n_net; } return *(u_32_t *)hp->h_addr; } ipnat_t *parse(line) char *line; { struct protoent *pr; static ipnat_t ipn; char *s, *t; char *shost, *snetm, *dhost, *proto; char *dnetm = NULL, *dport = NULL, *tport = NULL; int resolved; bzero((char *)&ipn, sizeof(ipn)); if ((s = strchr(line, '\n'))) *s = '\0'; if ((s = strchr(line, '#'))) *s = '\0'; if (!*line) return NULL; if (!(s = strtok(line, " \t"))) return NULL; if (!strcasecmp(s, "map")) ipn.in_redir = NAT_MAP; else if (!strcasecmp(s, "rdr")) ipn.in_redir = NAT_REDIRECT; else if (!strcasecmp(s, "bimap")) ipn.in_redir = NAT_BIMAP; else { (void)fprintf(stderr, "expected map/rdr/bimap, got \"%s\"\n", s); return NULL; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (interface)\n"); return NULL; } strncpy(ipn.in_ifname, s, sizeof(ipn.in_ifname) - 1); ipn.in_ifname[sizeof(ipn.in_ifname) - 1] = '\0'; if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (%s)\n", ipn.in_redir ? "destination": "source"); return NULL; } shost = s; if (ipn.in_redir == NAT_REDIRECT) { if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (destination port)\n"); return NULL; } if (strcasecmp(s, "port")) { fprintf(stderr, "missing fields (port)\n"); return NULL; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (destination port)\n"); return NULL; } dport = s; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (->)\n"); return NULL; } if (!strcmp(s, "->")) { snetm = strrchr(shost, '/'); if (!snetm) { fprintf(stderr, "missing fields (%s netmask)\n", ipn.in_redir ? "destination":"source"); return NULL; } } else { if (strcasecmp(s, "netmask")) { fprintf(stderr, "missing fields (netmask)\n"); return NULL; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (%s netmask)\n", ipn.in_redir ? "destination":"source"); return NULL; } snetm = s; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (%s)\n", ipn.in_redir ? "destination":"target"); return NULL; } dhost = s; if (ipn.in_redir & NAT_MAP) { if (!(s = strtok(NULL, " \t"))) { dnetm = strrchr(dhost, '/'); if (!dnetm) { fprintf(stderr, "missing fields (dest netmask)\n"); return NULL; } } if (!s || !strcasecmp(s, "portmap") || !strcasecmp(s, "proxy")) { dnetm = strrchr(dhost, '/'); if (!dnetm) { fprintf(stderr, "missing fields (dest netmask)\n"); return NULL; } } else { if (strcasecmp(s, "netmask")) { fprintf(stderr, "missing fields (dest netmask)\n"); return NULL; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (dest netmask)\n"); return NULL; } dnetm = s; } if (*dnetm == '/') *dnetm++ = '\0'; } else { /* If it's a in_redir, expect target port */ if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (destination port)\n"); return NULL; } if (strcasecmp(s, "port")) { fprintf(stderr, "missing fields (port)\n"); return NULL; } if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing fields (destination port)\n"); return NULL; } tport = s; } if (*snetm == '/') *snetm++ = '\0'; if (ipn.in_redir & NAT_MAP) { ipn.in_inip = hostnum(shost, &resolved); if (resolved == -1) return NULL; ipn.in_inmsk = hostmask(snetm); ipn.in_outip = hostnum(dhost, &resolved); if (resolved == -1) return NULL; ipn.in_outmsk = hostmask(dnetm); } else { ipn.in_inip = hostnum(dhost, &resolved); /* Inside is target */ if (resolved == -1) return NULL; ipn.in_inmsk = hostmask("255.255.255.255"); ipn.in_outip = hostnum(shost, &resolved); if (resolved == -1) return NULL; ipn.in_outmsk = hostmask(snetm); if (!(s = strtok(NULL, " \t"))) { ipn.in_flags = IPN_TCP; /* XXX- TCP only by default */ proto = "tcp"; } else { if (!strcasecmp(s, "tcp")) ipn.in_flags = IPN_TCP; else if (!strcasecmp(s, "udp")) ipn.in_flags = IPN_UDP; else if (!strcasecmp(s, "tcp/udp")) ipn.in_flags = IPN_TCPUDP; else if (!strcasecmp(s, "tcpudp")) ipn.in_flags = IPN_TCPUDP; else { fprintf(stderr, "expected protocol - got \"%s\"\n", s); return NULL; } proto = s; if ((s = strtok(NULL, " \t"))) { fprintf(stderr, "extra junk at the end of rdr: %s\n", s); return NULL; } } ipn.in_pmin = portnum(dport, proto); /* dest port */ ipn.in_pmax = ipn.in_pmin; /* NECESSARY of removing nats */ ipn.in_pnext = portnum(tport, proto); /* target port */ s = NULL; /* That's all she wrote! */ } ipn.in_inip &= ipn.in_inmsk; ipn.in_outip &= ipn.in_outmsk; if (!s) return &ipn; if (ipn.in_redir == NAT_BIMAP) { fprintf(stderr, "extra words at the end of bimap line: %s\n", s); return NULL; } if (!strcasecmp(s, "proxy")) { if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing parameter for \"proxy\"\n"); return NULL; } dport = NULL; if (!strcasecmp(s, "port")) { if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing parameter for \"port\"\n"); return NULL; } dport = s; if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "missing parameter for \"proxy\"\n"); return NULL; } } if ((proto = index(s, '/'))) { *proto++ = '\0'; if ((pr = getprotobyname(proto))) ipn.in_p = pr->p_proto; else ipn.in_p = atoi(proto); if (dport) ipn.in_dport = portnum(dport, proto); } else { ipn.in_p = 0; if (dport) ipn.in_dport = portnum(dport, NULL); } (void) strncpy(ipn.in_plabel, s, sizeof(ipn.in_plabel)); if ((s = strtok(NULL, " \t"))) { fprintf(stderr, "too many parameters for \"proxy\"\n"); return NULL; } return &ipn; } if (strcasecmp(s, "portmap")) { fprintf(stderr, "expected \"portmap\" - got \"%s\"\n", s); return NULL; } if (!(s = strtok(NULL, " \t"))) return NULL; if (!strcasecmp(s, "tcp")) ipn.in_flags = IPN_TCP; else if (!strcasecmp(s, "udp")) ipn.in_flags = IPN_UDP; else if (!strcasecmp(s, "tcpudp")) ipn.in_flags = IPN_TCPUDP; else if (!strcasecmp(s, "tcp/udp")) ipn.in_flags = IPN_TCPUDP; else { fprintf(stderr, "expected protocol name - got \"%s\"\n", s); return NULL; } proto = s; if (!(s = strtok(NULL, " \t"))) { fprintf(stderr, "no port range found\n"); return NULL; } if (!(t = strchr(s, ':'))) { fprintf(stderr, "no port range in \"%s\"\n", s); return NULL; } *t++ = '\0'; ipn.in_pmin = portnum(s, proto); ipn.in_pmax = portnum(t, proto); return &ipn; } void parsefile(fd, file, opts) int fd; char *file; int opts; { char line[512], *s; ipnat_t *np; FILE *fp; int linenum = 1; if (strcmp(file, "-")) { if (!(fp = fopen(file, "r"))) { perror(file); exit(1); } } else fp = stdin; while (fgets(line, sizeof(line) - 1, fp)) { line[sizeof(line) - 1] = '\0'; if ((s = strchr(line, '\n'))) *s = '\0'; if (!(np = parse(line))) { if (*line) fprintf(stderr, "%d: syntax error in \"%s\"\n", linenum, line); } else if (!(opts & OPT_NODO)) { if ((opts & OPT_VERBOSE) && np) printnat(np, opts & OPT_VERBOSE, NULL); if (opts & OPT_REM) { if (ioctl(fd, SIOCADNAT, np) == -1) perror("ioctl(SIOCADNAT)"); } else if (ioctl(fd, SIOCRMNAT, np) == -1) perror("ioctl(SIOCRMNAT)"); } linenum++; } if (fp != stdin) fclose(fp); } void flushtable(fd, opts) int fd, opts; { int n = 0; if (opts & OPT_FLUSH) { n = 0; if (!(opts & OPT_NODO) && ioctl(fd, SIOCFLNAT, &n) == -1) perror("ioctl(SIOCFLNAT)"); else printf("%d entries flushed from NAT table\n", n); } if (opts & OPT_CLEAR) { n = 0; if (!(opts & OPT_NODO) && ioctl(fd, SIOCCNATL, &n) == -1) perror("ioctl(SIOCCNATL)"); else printf("%d entries flushed from NAT list\n", n); } }
56577.c
/* * dim2_hal.c - DIM2 HAL implementation * (MediaLB, Device Interface Macro IP, OS62420) * * Copyright (C) 2015-2016, Microchip Technology Germany II GmbH & Co. KG * * 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. * * This file is licensed under GPLv2. */ /* Author: Andrey Shvetsov <[email protected]> */ #include "dim2_hal.h" #include "dim2_errors.h" #include "dim2_reg.h" #include <stddef.h> /* * Size factor for isochronous DBR buffer. * Minimal value is 3. */ #define ISOC_DBR_FACTOR 3u /* * Number of 32-bit units for DBR map. * * 1: block size is 512, max allocation is 16K * 2: block size is 256, max allocation is 8K * 4: block size is 128, max allocation is 4K * 8: block size is 64, max allocation is 2K * * Min allocated space is block size. * Max possible allocated space is 32 blocks. */ #define DBR_MAP_SIZE 2 /* -------------------------------------------------------------------------- */ /* not configurable area */ #define CDT 0x00 #define ADT 0x40 #define MLB_CAT 0x80 #define AHB_CAT 0x88 #define DBR_SIZE (16 * 1024) /* specified by IP */ #define DBR_BLOCK_SIZE (DBR_SIZE / 32 / DBR_MAP_SIZE) #define ROUND_UP_TO(x, d) (((x) + (d) - 1) / (d) * (d)) /* -------------------------------------------------------------------------- */ /* generic helper functions and macros */ static inline uint32_t bit_mask(uint8_t position) { return (uint32_t)1 << position; } static inline bool dim_on_error(uint8_t error_id, const char *error_message) { dimcb_on_error(error_id, error_message); return false; } /* -------------------------------------------------------------------------- */ /* types and local variables */ struct async_tx_dbr { uint8_t ch_addr; uint16_t rpc; uint16_t wpc; uint16_t rest_size; uint16_t sz_queue[CDT0_RPC_MASK + 1]; }; struct lld_global_vars_t { bool dim_is_initialized; bool mcm_is_initialized; struct dim2_regs *dim2; /* DIM2 core base address */ struct async_tx_dbr atx_dbr; uint32_t fcnt; uint32_t dbr_map[DBR_MAP_SIZE]; }; static struct lld_global_vars_t g = { false }; /* -------------------------------------------------------------------------- */ static int dbr_get_mask_size(uint16_t size) { int i; for (i = 0; i < 6; i++) if (size <= (DBR_BLOCK_SIZE << i)) return 1 << i; return 0; } /** * Allocates DBR memory. * @param size Allocating memory size. * @return Offset in DBR memory by success or DBR_SIZE if out of memory. */ static int alloc_dbr(uint16_t size) { int mask_size; int i, block_idx = 0; if (size <= 0) return DBR_SIZE; /* out of memory */ mask_size = dbr_get_mask_size(size); if (mask_size == 0) return DBR_SIZE; /* out of memory */ for (i = 0; i < DBR_MAP_SIZE; i++) { uint32_t const blocks = (size + DBR_BLOCK_SIZE - 1) / DBR_BLOCK_SIZE; uint32_t mask = ~((~(uint32_t)0) << blocks); do { if ((g.dbr_map[i] & mask) == 0) { g.dbr_map[i] |= mask; return block_idx * DBR_BLOCK_SIZE; } block_idx += mask_size; /* do shift left with 2 steps in case mask_size == 32 */ mask <<= mask_size - 1; } while ((mask <<= 1) != 0); } return DBR_SIZE; /* out of memory */ } static void free_dbr(int offs, int size) { int block_idx = offs / DBR_BLOCK_SIZE; uint32_t const blocks = (size + DBR_BLOCK_SIZE - 1) / DBR_BLOCK_SIZE; uint32_t mask = ~((~(uint32_t)0) << blocks); mask <<= block_idx % 32; g.dbr_map[block_idx / 32] &= ~mask; } /* -------------------------------------------------------------------------- */ static void dim2_transfer_madr(uint32_t val) { dimcb_io_write(&g.dim2->MADR, val); /* wait for transfer completion */ while ((dimcb_io_read(&g.dim2->MCTL) & 1) != 1) continue; dimcb_io_write(&g.dim2->MCTL, 0); /* clear transfer complete */ } static void dim2_clear_dbr(uint16_t addr, uint16_t size) { enum { MADR_TB_BIT = 30, MADR_WNR_BIT = 31 }; uint16_t const end_addr = addr + size; uint32_t const cmd = bit_mask(MADR_WNR_BIT) | bit_mask(MADR_TB_BIT); dimcb_io_write(&g.dim2->MCTL, 0); /* clear transfer complete */ dimcb_io_write(&g.dim2->MDAT0, 0); for (; addr < end_addr; addr++) dim2_transfer_madr(cmd | addr); } static uint32_t dim2_read_ctr(uint32_t ctr_addr, uint16_t mdat_idx) { dim2_transfer_madr(ctr_addr); return dimcb_io_read((&g.dim2->MDAT0) + mdat_idx); } static void dim2_write_ctr_mask(uint32_t ctr_addr, const uint32_t *mask, const uint32_t *value) { enum { MADR_WNR_BIT = 31 }; dimcb_io_write(&g.dim2->MCTL, 0); /* clear transfer complete */ if (mask[0] != 0) dimcb_io_write(&g.dim2->MDAT0, value[0]); if (mask[1] != 0) dimcb_io_write(&g.dim2->MDAT1, value[1]); if (mask[2] != 0) dimcb_io_write(&g.dim2->MDAT2, value[2]); if (mask[3] != 0) dimcb_io_write(&g.dim2->MDAT3, value[3]); dimcb_io_write(&g.dim2->MDWE0, mask[0]); dimcb_io_write(&g.dim2->MDWE1, mask[1]); dimcb_io_write(&g.dim2->MDWE2, mask[2]); dimcb_io_write(&g.dim2->MDWE3, mask[3]); dim2_transfer_madr(bit_mask(MADR_WNR_BIT) | ctr_addr); } static inline void dim2_write_ctr(uint32_t ctr_addr, const uint32_t *value) { uint32_t const mask[4] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; dim2_write_ctr_mask(ctr_addr, mask, value); } static inline void dim2_clear_ctr(uint32_t ctr_addr) { uint32_t const value[4] = { 0, 0, 0, 0 }; dim2_write_ctr(ctr_addr, value); } static void dim2_configure_cat(uint8_t cat_base, uint8_t ch_addr, uint8_t ch_type, bool read_not_write, bool sync_mfe) { uint16_t const cat = (read_not_write << CAT_RNW_BIT) | (ch_type << CAT_CT_SHIFT) | (ch_addr << CAT_CL_SHIFT) | (sync_mfe << CAT_MFE_BIT) | (false << CAT_MT_BIT) | (true << CAT_CE_BIT); uint8_t const ctr_addr = cat_base + ch_addr / 8; uint8_t const idx = (ch_addr % 8) / 2; uint8_t const shift = (ch_addr % 2) * 16; uint32_t mask[4] = { 0, 0, 0, 0 }; uint32_t value[4] = { 0, 0, 0, 0 }; mask[idx] = (uint32_t)0xFFFF << shift; value[idx] = cat << shift; dim2_write_ctr_mask(ctr_addr, mask, value); } static void dim2_clear_cat(uint8_t cat_base, uint8_t ch_addr) { uint8_t const ctr_addr = cat_base + ch_addr / 8; uint8_t const idx = (ch_addr % 8) / 2; uint8_t const shift = (ch_addr % 2) * 16; uint32_t mask[4] = { 0, 0, 0, 0 }; uint32_t value[4] = { 0, 0, 0, 0 }; mask[idx] = (uint32_t)0xFFFF << shift; dim2_write_ctr_mask(ctr_addr, mask, value); } static void dim2_configure_cdt(uint8_t ch_addr, uint16_t dbr_address, uint16_t hw_buffer_size, uint16_t packet_length) { uint32_t cdt[4] = { 0, 0, 0, 0 }; if (packet_length) cdt[1] = ((packet_length - 1) << CDT1_BS_ISOC_SHIFT); cdt[3] = ((hw_buffer_size - 1) << CDT3_BD_SHIFT) | (dbr_address << CDT3_BA_SHIFT); dim2_write_ctr(CDT + ch_addr, cdt); } static uint16_t dim2_rpc(uint8_t ch_addr) { uint32_t cdt0 = dim2_read_ctr(CDT + ch_addr, 0); return (cdt0 >> CDT0_RPC_SHIFT) & CDT0_RPC_MASK; } static void dim2_clear_cdt(uint8_t ch_addr) { uint32_t cdt[4] = { 0, 0, 0, 0 }; dim2_write_ctr(CDT + ch_addr, cdt); } static void dim2_configure_adt(uint8_t ch_addr) { uint32_t adt[4] = { 0, 0, 0, 0 }; adt[0] = (true << ADT0_CE_BIT) | (true << ADT0_LE_BIT) | (0 << ADT0_PG_BIT); dim2_write_ctr(ADT + ch_addr, adt); } static void dim2_clear_adt(uint8_t ch_addr) { uint32_t adt[4] = { 0, 0, 0, 0 }; dim2_write_ctr(ADT + ch_addr, adt); } static void dim2_start_ctrl_async(uint8_t ch_addr, uint8_t idx, uint32_t buf_addr, uint16_t buffer_size) { uint8_t const shift = idx * 16; uint32_t mask[4] = { 0, 0, 0, 0 }; uint32_t adt[4] = { 0, 0, 0, 0 }; mask[1] = bit_mask(ADT1_PS_BIT + shift) | bit_mask(ADT1_RDY_BIT + shift) | (ADT1_CTRL_ASYNC_BD_MASK << (ADT1_BD_SHIFT + shift)); adt[1] = (true << (ADT1_PS_BIT + shift)) | (true << (ADT1_RDY_BIT + shift)) | ((buffer_size - 1) << (ADT1_BD_SHIFT + shift)); mask[idx + 2] = 0xFFFFFFFF; adt[idx + 2] = buf_addr; dim2_write_ctr_mask(ADT + ch_addr, mask, adt); } static void dim2_start_isoc_sync(uint8_t ch_addr, uint8_t idx, uint32_t buf_addr, uint16_t buffer_size) { uint8_t const shift = idx * 16; uint32_t mask[4] = { 0, 0, 0, 0 }; uint32_t adt[4] = { 0, 0, 0, 0 }; mask[1] = bit_mask(ADT1_RDY_BIT + shift) | (ADT1_ISOC_SYNC_BD_MASK << (ADT1_BD_SHIFT + shift)); adt[1] = (true << (ADT1_RDY_BIT + shift)) | ((buffer_size - 1) << (ADT1_BD_SHIFT + shift)); mask[idx + 2] = 0xFFFFFFFF; adt[idx + 2] = buf_addr; dim2_write_ctr_mask(ADT + ch_addr, mask, adt); } static void dim2_clear_ctram(void) { uint32_t ctr_addr; for (ctr_addr = 0; ctr_addr < 0x90; ctr_addr++) dim2_clear_ctr(ctr_addr); } static void dim2_configure_channel( uint8_t ch_addr, uint8_t type, uint8_t is_tx, uint16_t dbr_address, uint16_t hw_buffer_size, uint16_t packet_length, bool sync_mfe) { dim2_configure_cdt(ch_addr, dbr_address, hw_buffer_size, packet_length); dim2_configure_cat(MLB_CAT, ch_addr, type, is_tx ? 1 : 0, sync_mfe); dim2_configure_adt(ch_addr); dim2_configure_cat(AHB_CAT, ch_addr, type, is_tx ? 0 : 1, sync_mfe); /* unmask interrupt for used channel, enable mlb_sys_int[0] interrupt */ dimcb_io_write(&g.dim2->ACMR0, dimcb_io_read(&g.dim2->ACMR0) | bit_mask(ch_addr)); } static void dim2_clear_channel(uint8_t ch_addr) { /* mask interrupt for used channel, disable mlb_sys_int[0] interrupt */ dimcb_io_write(&g.dim2->ACMR0, dimcb_io_read(&g.dim2->ACMR0) & ~bit_mask(ch_addr)); dim2_clear_cat(AHB_CAT, ch_addr); dim2_clear_adt(ch_addr); dim2_clear_cat(MLB_CAT, ch_addr); dim2_clear_cdt(ch_addr); /* clear channel status bit */ dimcb_io_write(&g.dim2->ACSR0, bit_mask(ch_addr)); } /* -------------------------------------------------------------------------- */ /* trace async tx dbr fill state */ static inline uint16_t norm_pc(uint16_t pc) { return pc & CDT0_RPC_MASK; } static void dbrcnt_init(uint8_t ch_addr, uint16_t dbr_size) { g.atx_dbr.rest_size = dbr_size; g.atx_dbr.rpc = dim2_rpc(ch_addr); g.atx_dbr.wpc = g.atx_dbr.rpc; } static void dbrcnt_enq(int buf_sz) { g.atx_dbr.rest_size -= buf_sz; g.atx_dbr.sz_queue[norm_pc(g.atx_dbr.wpc)] = buf_sz; g.atx_dbr.wpc++; } uint16_t dim_dbr_space(struct dim_channel *ch) { uint16_t cur_rpc; struct async_tx_dbr *dbr = &g.atx_dbr; if (ch->addr != dbr->ch_addr) return 0xFFFF; cur_rpc = dim2_rpc(ch->addr); while (norm_pc(dbr->rpc) != cur_rpc) { dbr->rest_size += dbr->sz_queue[norm_pc(dbr->rpc)]; dbr->rpc++; } if ((uint16_t)(dbr->wpc - dbr->rpc) >= CDT0_RPC_MASK) return 0; return dbr->rest_size; } /* -------------------------------------------------------------------------- */ /* channel state helpers */ static void state_init(struct int_ch_state *state) { state->request_counter = 0; state->service_counter = 0; state->idx1 = 0; state->idx2 = 0; state->level = 0; } /* -------------------------------------------------------------------------- */ /* macro helper functions */ static inline bool check_channel_address(uint32_t ch_address) { return ch_address > 0 && (ch_address % 2) == 0 && (ch_address / 2) <= (uint32_t)CAT_CL_MASK; } static inline bool check_packet_length(uint32_t packet_length) { uint16_t const max_size = ((uint16_t)CDT3_BD_ISOC_MASK + 1u) / ISOC_DBR_FACTOR; if (packet_length <= 0) return false; /* too small */ if (packet_length > max_size) return false; /* too big */ if (packet_length - 1u > (uint32_t)CDT1_BS_ISOC_MASK) return false; /* too big */ return true; } static inline bool check_bytes_per_frame(uint32_t bytes_per_frame) { uint16_t const bd_factor = g.fcnt + 2; uint16_t const max_size = ((uint16_t)CDT3_BD_MASK + 1u) >> bd_factor; if (bytes_per_frame <= 0) return false; /* too small */ if (bytes_per_frame > max_size) return false; /* too big */ return true; } static inline uint16_t norm_ctrl_async_buffer_size(uint16_t buf_size) { uint16_t const max_size = (uint16_t)ADT1_CTRL_ASYNC_BD_MASK + 1u; if (buf_size > max_size) return max_size; return buf_size; } static inline uint16_t norm_isoc_buffer_size(uint16_t buf_size, uint16_t packet_length) { uint16_t n; uint16_t const max_size = (uint16_t)ADT1_ISOC_SYNC_BD_MASK + 1u; if (buf_size > max_size) buf_size = max_size; n = buf_size / packet_length; if (n < 2u) return 0; /* too small buffer for given packet_length */ return packet_length * n; } static inline uint16_t norm_sync_buffer_size(uint16_t buf_size, uint16_t bytes_per_frame) { uint16_t n; uint16_t const max_size = (uint16_t)ADT1_ISOC_SYNC_BD_MASK + 1u; uint32_t const unit = bytes_per_frame << g.fcnt; if (buf_size > max_size) buf_size = max_size; n = buf_size / unit; if (n < 1u) return 0; /* too small buffer for given bytes_per_frame */ return unit * n; } static void dim2_cleanup(void) { /* disable MediaLB */ dimcb_io_write(&g.dim2->MLBC0, false << MLBC0_MLBEN_BIT); dim2_clear_ctram(); /* disable mlb_int interrupt */ dimcb_io_write(&g.dim2->MIEN, 0); /* clear status for all dma channels */ dimcb_io_write(&g.dim2->ACSR0, 0xFFFFFFFF); dimcb_io_write(&g.dim2->ACSR1, 0xFFFFFFFF); /* mask interrupts for all channels */ dimcb_io_write(&g.dim2->ACMR0, 0); dimcb_io_write(&g.dim2->ACMR1, 0); } static void dim2_initialize(bool enable_6pin, uint8_t mlb_clock) { dim2_cleanup(); /* configure and enable MediaLB */ dimcb_io_write(&g.dim2->MLBC0, enable_6pin << MLBC0_MLBPEN_BIT | mlb_clock << MLBC0_MLBCLK_SHIFT | g.fcnt << MLBC0_FCNT_SHIFT | true << MLBC0_MLBEN_BIT); /* activate all HBI channels */ dimcb_io_write(&g.dim2->HCMR0, 0xFFFFFFFF); dimcb_io_write(&g.dim2->HCMR1, 0xFFFFFFFF); /* enable HBI */ dimcb_io_write(&g.dim2->HCTL, bit_mask(HCTL_EN_BIT)); /* configure DMA */ dimcb_io_write(&g.dim2->ACTL, ACTL_DMA_MODE_VAL_DMA_MODE_1 << ACTL_DMA_MODE_BIT | true << ACTL_SCE_BIT); } static bool dim2_is_mlb_locked(void) { uint32_t const mask0 = bit_mask(MLBC0_MLBLK_BIT); uint32_t const mask1 = bit_mask(MLBC1_CLKMERR_BIT) | bit_mask(MLBC1_LOCKERR_BIT); uint32_t const c1 = dimcb_io_read(&g.dim2->MLBC1); uint32_t const nda_mask = (uint32_t)MLBC1_NDA_MASK << MLBC1_NDA_SHIFT; dimcb_io_write(&g.dim2->MLBC1, c1 & nda_mask); return (dimcb_io_read(&g.dim2->MLBC1) & mask1) == 0 && (dimcb_io_read(&g.dim2->MLBC0) & mask0) != 0; } /* -------------------------------------------------------------------------- */ /* channel help routines */ static inline bool service_channel(uint8_t ch_addr, uint8_t idx) { uint8_t const shift = idx * 16; uint32_t const adt1 = dim2_read_ctr(ADT + ch_addr, 1); uint32_t mask[4] = { 0, 0, 0, 0 }; uint32_t adt_w[4] = { 0, 0, 0, 0 }; if (((adt1 >> (ADT1_DNE_BIT + shift)) & 1) == 0) return false; mask[1] = bit_mask(ADT1_DNE_BIT + shift) | bit_mask(ADT1_ERR_BIT + shift) | bit_mask(ADT1_RDY_BIT + shift); dim2_write_ctr_mask(ADT + ch_addr, mask, adt_w); /* clear channel status bit */ dimcb_io_write(&g.dim2->ACSR0, bit_mask(ch_addr)); return true; } /* -------------------------------------------------------------------------- */ /* channel init routines */ static void isoc_init(struct dim_channel *ch, uint8_t ch_addr, uint16_t packet_length) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = packet_length; ch->bytes_per_frame = 0; ch->done_sw_buffers_number = 0; } static void sync_init(struct dim_channel *ch, uint8_t ch_addr, uint16_t bytes_per_frame) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = 0; ch->bytes_per_frame = bytes_per_frame; ch->done_sw_buffers_number = 0; } static void channel_init(struct dim_channel *ch, uint8_t ch_addr) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = 0; ch->bytes_per_frame = 0; ch->done_sw_buffers_number = 0; } /* returns true if channel interrupt state is cleared */ static bool channel_service_interrupt(struct dim_channel *ch) { struct int_ch_state *const state = &ch->state; if (!service_channel(ch->addr, state->idx2)) return false; state->idx2 ^= 1; state->request_counter++; return true; } static bool channel_start(struct dim_channel *ch, uint32_t buf_addr, uint16_t buf_size) { struct int_ch_state *const state = &ch->state; if (buf_size <= 0) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad buffer size"); if (ch->packet_length == 0 && ch->bytes_per_frame == 0 && buf_size != norm_ctrl_async_buffer_size(buf_size)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad control/async buffer size"); if (ch->packet_length && buf_size != norm_isoc_buffer_size(buf_size, ch->packet_length)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad isochronous buffer size"); if (ch->bytes_per_frame && buf_size != norm_sync_buffer_size(buf_size, ch->bytes_per_frame)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad synchronous buffer size"); if (state->level >= 2u) return dim_on_error(DIM_ERR_OVERFLOW, "Channel overflow"); ++state->level; if (ch->addr == g.atx_dbr.ch_addr) dbrcnt_enq(buf_size); if (ch->packet_length || ch->bytes_per_frame) dim2_start_isoc_sync(ch->addr, state->idx1, buf_addr, buf_size); else dim2_start_ctrl_async(ch->addr, state->idx1, buf_addr, buf_size); state->idx1 ^= 1; return true; } static uint8_t channel_service(struct dim_channel *ch) { struct int_ch_state *const state = &ch->state; if (state->service_counter != state->request_counter) { state->service_counter++; if (state->level == 0) return DIM_ERR_UNDERFLOW; --state->level; ch->done_sw_buffers_number++; } return DIM_NO_ERROR; } static bool channel_detach_buffers(struct dim_channel *ch, uint16_t buffers_number) { if (buffers_number > ch->done_sw_buffers_number) return dim_on_error(DIM_ERR_UNDERFLOW, "Channel underflow"); ch->done_sw_buffers_number -= buffers_number; return true; } /* -------------------------------------------------------------------------- */ /* API */ uint8_t dim_startup(struct dim2_regs *dim_base_address, uint32_t mlb_clock, uint32_t fcnt) { g.dim_is_initialized = false; if (!dim_base_address) return DIM_INIT_ERR_DIM_ADDR; /* MediaLB clock: 0 - 256 fs, 1 - 512 fs, 2 - 1024 fs, 3 - 2048 fs */ /* MediaLB clock: 4 - 3072 fs, 5 - 4096 fs, 6 - 6144 fs, 7 - 8192 fs */ if (mlb_clock >= 8) return DIM_INIT_ERR_MLB_CLOCK; if (fcnt > MLBC0_FCNT_MAX_VAL) return DIM_INIT_ERR_MLB_CLOCK; g.dim2 = dim_base_address; g.fcnt = fcnt; g.dbr_map[0] = 0; g.dbr_map[1] = 0; dim2_initialize(mlb_clock >= 3, mlb_clock); g.dim_is_initialized = true; return DIM_NO_ERROR; } void dim_shutdown(void) { g.dim_is_initialized = false; dim2_cleanup(); } bool dim_get_lock_state(void) { return dim2_is_mlb_locked(); } static uint8_t init_ctrl_async(struct dim_channel *ch, uint8_t type, uint8_t is_tx, uint16_t ch_address, uint16_t hw_buffer_size) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; ch->dbr_size = ROUND_UP_TO(hw_buffer_size, DBR_BLOCK_SIZE); ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; channel_init(ch, ch_address / 2); dim2_configure_channel(ch->addr, type, is_tx, ch->dbr_addr, ch->dbr_size, 0, false); return DIM_NO_ERROR; } void dim_service_mlb_int_irq(void) { dimcb_io_write(&g.dim2->MS0, 0); dimcb_io_write(&g.dim2->MS1, 0); } uint16_t dim_norm_ctrl_async_buffer_size(uint16_t buf_size) { return norm_ctrl_async_buffer_size(buf_size); } /** * Retrieves maximal possible correct buffer size for isochronous data type * conform to given packet length and not bigger than given buffer size. * * Returns non-zero correct buffer size or zero by error. */ uint16_t dim_norm_isoc_buffer_size(uint16_t buf_size, uint16_t packet_length) { if (!check_packet_length(packet_length)) return 0; return norm_isoc_buffer_size(buf_size, packet_length); } /** * Retrieves maximal possible correct buffer size for synchronous data type * conform to given bytes per frame and not bigger than given buffer size. * * Returns non-zero correct buffer size or zero by error. */ uint16_t dim_norm_sync_buffer_size(uint16_t buf_size, uint16_t bytes_per_frame) { if (!check_bytes_per_frame(bytes_per_frame)) return 0; return norm_sync_buffer_size(buf_size, bytes_per_frame); } uint8_t dim_init_control(struct dim_channel *ch, uint8_t is_tx, uint16_t ch_address, uint16_t max_buffer_size) { return init_ctrl_async(ch, CAT_CT_VAL_CONTROL, is_tx, ch_address, max_buffer_size); } uint8_t dim_init_async(struct dim_channel *ch, uint8_t is_tx, uint16_t ch_address, uint16_t max_buffer_size) { uint8_t ret = init_ctrl_async(ch, CAT_CT_VAL_ASYNC, is_tx, ch_address, max_buffer_size); if (is_tx && !g.atx_dbr.ch_addr) { g.atx_dbr.ch_addr = ch->addr; dbrcnt_init(ch->addr, ch->dbr_size); dimcb_io_write(&g.dim2->MIEN, bit_mask(20)); } return ret; } uint8_t dim_init_isoc(struct dim_channel *ch, uint8_t is_tx, uint16_t ch_address, uint16_t packet_length) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; if (!check_packet_length(packet_length)) return DIM_ERR_BAD_CONFIG; ch->dbr_size = packet_length * ISOC_DBR_FACTOR; ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; isoc_init(ch, ch_address / 2, packet_length); dim2_configure_channel(ch->addr, CAT_CT_VAL_ISOC, is_tx, ch->dbr_addr, ch->dbr_size, packet_length, false); return DIM_NO_ERROR; } uint8_t dim_init_sync(struct dim_channel *ch, uint8_t is_tx, uint16_t ch_address, uint16_t bytes_per_frame) { uint16_t bd_factor = g.fcnt + 2; if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; if (!check_bytes_per_frame(bytes_per_frame)) return DIM_ERR_BAD_CONFIG; ch->dbr_size = bytes_per_frame << bd_factor; ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; sync_init(ch, ch_address / 2, bytes_per_frame); dim2_clear_dbr(ch->dbr_addr, ch->dbr_size); dim2_configure_channel(ch->addr, CAT_CT_VAL_SYNC, is_tx, ch->dbr_addr, ch->dbr_size, 0, true); return DIM_NO_ERROR; } uint8_t dim_destroy_channel(struct dim_channel *ch) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (ch->addr == g.atx_dbr.ch_addr) { dimcb_io_write(&g.dim2->MIEN, 0); g.atx_dbr.ch_addr = 0; } dim2_clear_channel(ch->addr); if (ch->dbr_addr < DBR_SIZE) free_dbr(ch->dbr_addr, ch->dbr_size); ch->dbr_addr = DBR_SIZE; return DIM_NO_ERROR; } void dim_service_ahb_int_irq(struct dim_channel *const *channels) { bool state_changed; if (!g.dim_is_initialized) { dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "DIM is not initialized"); return; } if (!channels) { dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channels"); return; } /* * Use while-loop and a flag to make sure the age is changed back at * least once, otherwise the interrupt may never come if CPU generates * interrupt on changing age. * This cycle runs not more than number of channels, because * channel_service_interrupt() routine doesn't start the channel again. */ do { struct dim_channel *const *ch = channels; state_changed = false; while (*ch) { state_changed |= channel_service_interrupt(*ch); ++ch; } } while (state_changed); } uint8_t dim_service_channel(struct dim_channel *ch) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; return channel_service(ch); } struct dim_ch_state_t *dim_get_channel_state(struct dim_channel *ch, struct dim_ch_state_t *state_ptr) { if (!ch || !state_ptr) return NULL; state_ptr->ready = ch->state.level < 2; state_ptr->done_buffers = ch->done_sw_buffers_number; return state_ptr; } bool dim_enqueue_buffer(struct dim_channel *ch, uint32_t buffer_addr, uint16_t buffer_size) { if (!ch) return dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channel"); return channel_start(ch, buffer_addr, buffer_size); } bool dim_detach_buffers(struct dim_channel *ch, uint16_t buffers_number) { if (!ch) return dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channel"); return channel_detach_buffers(ch, buffers_number); }
467876.c
/* origin: FreeBSD /usr/src/lib/msun/src/s_exp2.c */ /*- * Copyright (c) 2005 David Schultz <[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, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "libm.h" #define TBLSIZE 256 static const double redux = 0x1.8p52 / TBLSIZE, P1 = 0x1.62e42fefa39efp-1, P2 = 0x1.ebfbdff82c575p-3, P3 = 0x1.c6b08d704a0a6p-5, P4 = 0x1.3b2ab88f70400p-7, P5 = 0x1.5d88003875c74p-10; static const double tbl[TBLSIZE * 2] = { /* exp2(z + eps) eps */ 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, 0x1.6b052fa751744p-1, 0x1.8000p-50, 0x1.6c012750bd9fep-1, -0x1.8780p-45, 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, 0x1.6dfb23c651a29p-1, -0x1.8000p-50, 0x1.6ef9298593ae3p-1, -0x1.c000p-52, 0x1.6ff7df9519386p-1, -0x1.fd80p-45, 0x1.70f7466f42da3p-1, -0x1.c880p-45, 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, 0x1.72f8286eacf05p-1, -0x1.8300p-44, 0x1.73f9a48a58152p-1, -0x1.0c00p-47, 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, 0x1.75feb564267f1p-1, 0x1.3e00p-47, 0x1.77024b1ab6d48p-1, -0x1.7d00p-45, 0x1.780694fde5d38p-1, -0x1.d000p-50, 0x1.790b938ac1d00p-1, 0x1.3000p-49, 0x1.7a11473eb0178p-1, -0x1.d000p-49, 0x1.7b17b0976d060p-1, 0x1.0400p-45, 0x1.7c1ed0130c133p-1, 0x1.0000p-53, 0x1.7d26a62ff8636p-1, -0x1.6900p-45, 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47, 0x1.7f3878491c3e8p-1, -0x1.4580p-45, 0x1.80427543e1b4ep-1, 0x1.3000p-44, 0x1.814d2add1071ap-1, 0x1.f000p-47, 0x1.82589994ccd7ep-1, -0x1.1c00p-45, 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, 0x1.8471a4623cab5p-1, 0x1.7100p-43, 0x1.857f4179f5bbcp-1, 0x1.2600p-45, 0x1.868d99b4491afp-1, -0x1.2c40p-44, 0x1.879cad931a395p-1, -0x1.3000p-45, 0x1.88ac7d98a65b8p-1, -0x1.a800p-45, 0x1.89bd0a4785800p-1, -0x1.d000p-49, 0x1.8ace5422aa223p-1, 0x1.3280p-44, 0x1.8be05bad619fap-1, 0x1.2b40p-43, 0x1.8cf3216b54383p-1, -0x1.ed00p-45, 0x1.8e06a5e08664cp-1, -0x1.0500p-45, 0x1.8f1ae99157807p-1, 0x1.8280p-45, 0x1.902fed0282c0ep-1, -0x1.cb00p-46, 0x1.9145b0b91ff96p-1, -0x1.5e00p-47, 0x1.925c353aa2ff9p-1, 0x1.5400p-48, 0x1.93737b0cdc64ap-1, 0x1.7200p-46, 0x1.948b82b5f98aep-1, -0x1.9000p-47, 0x1.95a44cbc852cbp-1, 0x1.5680p-45, 0x1.96bdd9a766f21p-1, -0x1.6d00p-44, 0x1.97d829fde4e2ap-1, -0x1.1000p-47, 0x1.98f33e47a23a3p-1, 0x1.d000p-45, 0x1.9a0f170ca0604p-1, -0x1.8a40p-44, 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, 0x1.9d674194bb8c5p-1, -0x1.c000p-49, 0x1.9e86319e3238ep-1, 0x1.7d00p-46, 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, 0x1.a0c667b5de54dp-1, -0x1.5000p-48, 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, 0x1.a42c980460a5dp-1, -0x1.af00p-46, 0x1.a5503b23e259bp-1, 0x1.b600p-47, 0x1.a674a8af46213p-1, 0x1.8880p-44, 0x1.a799e1330b3a7p-1, 0x1.1200p-46, 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45, 0x1.ab0e521356fb8p-1, 0x1.b700p-45, 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, 0x1.ae89f995ad2a3p-1, -0x1.c900p-45, 0x1.afb4ce622f367p-1, 0x1.6500p-46, 0x1.b0e07298db790p-1, 0x1.fd40p-45, 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, 0x1.b468415b747e7p-1, -0x1.8380p-44, 0x1.b59728de5593ap-1, 0x1.8000p-54, 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, 0x1.b928cf22749b2p-1, -0x1.4c00p-47, 0x1.ba5b030a10603p-1, -0x1.d700p-47, 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46, 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46, 0x1.c06286141b2e9p-1, -0x1.1400p-46, 0x1.c199bdd8552e0p-1, 0x1.be00p-47, 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47, 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47, 0x1.c544778fafd15p-1, 0x1.9660p-44, 0x1.c67f12e57d0cbp-1, -0x1.a100p-46, 0x1.c7ba88988c1b6p-1, -0x1.8458p-42, 0x1.c8f6d9406e733p-1, -0x1.a480p-46, 0x1.ca3405751c4dfp-1, 0x1.b000p-51, 0x1.cb720dcef9094p-1, 0x1.1400p-47, 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, 0x1.cdf0b555dc412p-1, 0x1.3600p-48, 0x1.cf3155b5bab3bp-1, -0x1.6900p-47, 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, 0x1.d1b532b08c8fap-1, -0x1.5e00p-46, 0x1.d2f87080d8a85p-1, 0x1.d280p-46, 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, 0x1.d5818dcfba491p-1, 0x1.f000p-50, 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47, 0x1.d80e316c9834ep-1, -0x1.cd80p-47, 0x1.d955d71ff6090p-1, 0x1.4c00p-48, 0x1.da9e603db32aep-1, 0x1.f900p-48, 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, 0x1.dd321f301b445p-1, -0x1.5200p-48, 0x1.de7d5641c05bfp-1, -0x1.d700p-46, 0x1.dfc97337b9aecp-1, -0x1.6140p-46, 0x1.e11676b197d5ep-1, 0x1.b480p-47, 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, 0x1.e502ee78b3fb4p-1, -0x1.9300p-47, 0x1.e653924676d68p-1, -0x1.5000p-49, 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47, 0x1.e8f7977cdb726p-1, -0x1.3700p-48, 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, 0x1.ecf482d8e680dp-1, 0x1.5500p-48, 0x1.ee4aaa2188514p-1, 0x1.6400p-51, 0x1.efa1bee615a13p-1, -0x1.e800p-49, 0x1.f0f9c1cb64106p-1, -0x1.a880p-48, 0x1.f252b376bb963p-1, -0x1.c900p-45, 0x1.f3ac948dd7275p-1, 0x1.a000p-53, 0x1.f50765b6e4524p-1, -0x1.4f00p-48, 0x1.f6632798844fdp-1, 0x1.a800p-51, 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, 0x1.f91d802243c82p-1, -0x1.4600p-50, 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47, 0x1.fbdba3692d511p-1, -0x1.0e00p-51, 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46, 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, 0x1.0000000000000p+0, 0x0.0000p+0, 0x1.00b1afa5abcbep+0, -0x1.3400p-52, 0x1.0163da9fb3303p+0, -0x1.2170p-46, 0x1.02168143b0282p+0, 0x1.a400p-52, 0x1.02c9a3e77806cp+0, 0x1.f980p-49, 0x1.037d42e11bbcap+0, -0x1.7400p-51, 0x1.04315e86e7f89p+0, 0x1.8300p-50, 0x1.04e5f72f65467p+0, -0x1.a3f0p-46, 0x1.059b0d315855ap+0, -0x1.2840p-47, 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, 0x1.0706b29ddf71ap+0, 0x1.5240p-46, 0x1.07bd42b72a82dp+0, -0x1.9a00p-49, 0x1.0874518759bd0p+0, 0x1.6400p-49, 0x1.092bdf66607c8p+0, -0x1.0780p-47, 0x1.09e3ecac6f383p+0, -0x1.8000p-54, 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, 0x1.0b5586cf988fcp+0, -0x1.ac80p-48, 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, 0x1.0cc922b724816p+0, 0x1.5200p-47, 0x1.0d83b23395dd8p+0, -0x1.ad00p-48, 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47, 0x1.0fb66affed2f0p+0, -0x1.d300p-47, 0x1.1073028d7234bp+0, 0x1.1500p-48, 0x1.11301d0125b5bp+0, 0x1.c000p-49, 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, 0x1.12abdc06c31d5p+0, 0x1.8400p-49, 0x1.136a814f2047dp+0, -0x1.ed00p-47, 0x1.1429aaea92de9p+0, 0x1.8e00p-49, 0x1.14e95934f3138p+0, 0x1.b400p-49, 0x1.15a98c8a58e71p+0, 0x1.5300p-47, 0x1.166a45471c3dfp+0, 0x1.3380p-47, 0x1.172b83c7d5211p+0, 0x1.8d40p-45, 0x1.17ed48695bb9fp+0, -0x1.5d00p-47, 0x1.18af9388c8d93p+0, -0x1.c880p-46, 0x1.1972658375d66p+0, 0x1.1f00p-46, 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, 0x1.1af99f81387e3p+0, -0x1.7390p-43, 0x1.1bbe084045d54p+0, 0x1.4e40p-45, 0x1.1c82f95281c43p+0, -0x1.a200p-47, 0x1.1d4873168b9b2p+0, 0x1.3800p-49, 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, 0x1.1ed5022fcd938p+0, 0x1.1900p-47, 0x1.1f9c18438cdf7p+0, -0x1.b780p-46, 0x1.2063b88628d8fp+0, 0x1.d940p-45, 0x1.212be3578a81ep+0, 0x1.8000p-50, 0x1.21f49917ddd41p+0, 0x1.b340p-45, 0x1.22bdda2791323p+0, 0x1.9f80p-46, 0x1.2387a6e7561e7p+0, -0x1.9c80p-46, 0x1.2451ffb821427p+0, 0x1.2300p-47, 0x1.251ce4fb2a602p+0, -0x1.3480p-46, 0x1.25e85711eceb0p+0, 0x1.2700p-46, 0x1.26b4565e27d16p+0, 0x1.1d00p-46, 0x1.2780e341de00fp+0, 0x1.1ee0p-44, 0x1.284dfe1f5633ep+0, -0x1.4c00p-46, 0x1.291ba7591bb30p+0, -0x1.3d80p-46, 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45, 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, 0x1.2c57e39771af9p+0, -0x1.0800p-46, 0x1.2d285a6e402d9p+0, -0x1.ed00p-47, 0x1.2df961f641579p+0, -0x1.4200p-48, 0x1.2ecafa93e2ecfp+0, -0x1.4980p-45, 0x1.2f9d24abd8822p+0, -0x1.6300p-46, 0x1.306fe0a31b625p+0, -0x1.2360p-44, 0x1.31432edeea50bp+0, -0x1.0df8p-40, 0x1.32170fc4cd7b8p+0, -0x1.2480p-45, 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45, 0x1.33c08b2641766p+0, 0x1.ed00p-46, 0x1.3496266e3fa27p+0, -0x1.c000p-50, 0x1.356c55f929f0fp+0, -0x1.0d80p-44, 0x1.36431a2de88b9p+0, 0x1.2c80p-45, 0x1.371a7373aaa39p+0, 0x1.0600p-45, 0x1.37f26231e74fep+0, -0x1.6600p-46, 0x1.38cae6d05d838p+0, -0x1.ae00p-47, 0x1.39a401b713ec3p+0, -0x1.4720p-43, 0x1.3a7db34e5a020p+0, 0x1.8200p-47, 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, 0x1.3d0e544ede122p+0, -0x1.7a00p-46, 0x1.3dea64c1234bbp+0, 0x1.6300p-45, 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43, 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44, 0x1.40822c367a0bbp+0, 0x1.5b80p-45, 0x1.4160a21f72e95p+0, 0x1.ec00p-46, 0x1.423fb27094646p+0, -0x1.3600p-46, 0x1.431f5d950a920p+0, 0x1.3980p-45, 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, 0x1.44e0860618919p+0, -0x1.6c00p-48, 0x1.45c2042a7d201p+0, -0x1.bc00p-47, 0x1.46a41ed1d0016p+0, -0x1.2800p-46, 0x1.4786d668b3326p+0, 0x1.0e00p-44, 0x1.486a2b5c13c00p+0, -0x1.d400p-45, 0x1.494e1e192af04p+0, 0x1.c200p-47, 0x1.4a32af0d7d372p+0, -0x1.e500p-46, 0x1.4b17dea6db801p+0, 0x1.7800p-47, 0x1.4bfdad53629e1p+0, -0x1.3800p-46, 0x1.4ce41b817c132p+0, 0x1.0800p-47, 0x1.4dcb299fddddbp+0, 0x1.c700p-45, 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46, 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, 0x1.508417f4531c1p+0, -0x1.8c00p-47, 0x1.516daa2cf662ap+0, -0x1.a000p-48, 0x1.5257de83f51eap+0, 0x1.a080p-43, 0x1.5342b569d4edap+0, -0x1.6d80p-45, 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44, 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, 0x1.56070dde9116bp+0, 0x1.4b00p-45, 0x1.56f4736b529dep+0, 0x1.15a0p-43, 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45, 0x1.58d12d497c76fp+0, -0x1.3080p-45, 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, 0x1.5ab07dd485427p+0, -0x1.4000p-51, 0x1.5ba11fba87af4p+0, 0x1.0080p-44, 0x1.5c9268a59460bp+0, -0x1.6c80p-45, 0x1.5d84590998e3fp+0, 0x1.69a0p-43, 0x1.5e76f15ad20e1p+0, -0x1.b400p-46, 0x1.5f6a320dcebcap+0, 0x1.7700p-46, 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, 0x1.6152ae6cdf715p+0, 0x1.1000p-47, 0x1.6247eb03a5531p+0, -0x1.5d00p-46, 0x1.633dd1d1929b5p+0, -0x1.2d00p-46, 0x1.6434634ccc313p+0, -0x1.a800p-49, 0x1.652b9febc8efap+0, -0x1.8600p-45, 0x1.6623882553397p+0, 0x1.1fe0p-40, 0x1.671c1c708328ep+0, -0x1.7200p-44, 0x1.68155d44ca97ep+0, 0x1.6800p-49, 0x1.690f4b19e9471p+0, -0x1.9780p-45, }; /* * exp2(x): compute the base 2 exponential of x * * Accuracy: Peak error < 0.503 ulp for normalized results. * * Method: (accurate tables) * * Reduce x: * x = k + y, for integer k and |y| <= 1/2. * Thus we have exp2(x) = 2**k * exp2(y). * * Reduce y: * y = i/TBLSIZE + z - eps[i] for integer i near y * TBLSIZE. * Thus we have exp2(y) = exp2(i/TBLSIZE) * exp2(z - eps[i]), * with |z - eps[i]| <= 2**-9 + 2**-39 for the table used. * * We compute exp2(i/TBLSIZE) via table lookup and exp2(z - eps[i]) via * a degree-5 minimax polynomial with maximum error under 1.3 * 2**-61. * The values in exp2t[] and eps[] are chosen such that * exp2t[i] = exp2(i/TBLSIZE + eps[i]), and eps[i] is a small offset such * that exp2t[i] is accurate to 2**-64. * * Note that the range of i is +-TBLSIZE/2, so we actually index the tables * by i0 = i + TBLSIZE/2. For cache efficiency, exp2t[] and eps[] are * virtual tables, interleaved in the real table tbl[]. * * This method is due to Gal, with many details due to Gal and Bachelis: * * Gal, S. and Bachelis, B. An Accurate Elementary Mathematical Library * for the IEEE Floating Point Standard. TOMS 17(1), 26-46 (1991). */ double exp2(double x) { double_t r, t, z; uint32_t ix, i0; union {double f; uint64_t i;} u = {x}; union {uint32_t u; int32_t i;} k; /* Filter out exceptional cases. */ ix = u.i>>32 & 0x7fffffff; if (ix >= 0x408ff000) { /* |x| >= 1022 or nan */ if (ix >= 0x40900000 && u.i>>63 == 0) { /* x >= 1024 or nan */ /* overflow */ x *= 0x1p1023; return x; } if (ix >= 0x7ff00000) /* -inf or -nan */ return -1/x; if (u.i>>63) { /* x <= -1022 */ /* underflow */ if (x <= -1075 || x - 0x1p52 + 0x1p52 != x) FORCE_EVAL((float)(-0x1p-149/x)); if (x <= -1075) return 0; } } else if (ix < 0x3c900000) { /* |x| < 0x1p-54 */ return 1.0 + x; } /* Reduce x, computing z, i0, and k. */ u.f = x + redux; i0 = u.i; i0 += TBLSIZE / 2; k.u = i0 / TBLSIZE * TBLSIZE; k.i /= TBLSIZE; i0 %= TBLSIZE; u.f -= redux; z = x - u.f; /* Compute r = exp2(y) = exp2t[i0] * p(z - eps[i]). */ t = tbl[2*i0]; /* exp2t[i0] */ z -= tbl[2*i0 + 1]; /* eps[i0] */ r = t + t * z * (P1 + z * (P2 + z * (P3 + z * (P4 + z * P5)))); return scalbn(r, k.i); }
688266.c
/* * i2c Support for Atmel's AT91 Two-Wire Interface (TWI) * * Copyright (C) 2011 Weinmann Medical GmbH * Author: Nikolaus Voss <[email protected]> * * Evolved from original work by: * Copyright (C) 2004 Rick Bronson * Converted to 2.6 by Andrew Victor <[email protected]> * * Borrowed heavily from original work by: * Copyright (C) 2000 Philip Edelbrock <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/clk.h> #include <linux/completion.h> #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/platform_data/dma-atmel.h> #include <linux/pm_runtime.h> #include <linux/pinctrl/consumer.h> #define DEFAULT_TWI_CLK_HZ 100000 /* max 400 Kbits/s */ #define AT91_I2C_TIMEOUT msecs_to_jiffies(100) /* transfer timeout */ #define AT91_I2C_DMA_THRESHOLD 8 /* enable DMA if transfer size is bigger than this threshold */ #define AUTOSUSPEND_TIMEOUT 2000 /* AT91 TWI register definitions */ #define AT91_TWI_CR 0x0000 /* Control Register */ #define AT91_TWI_START 0x0001 /* Send a Start Condition */ #define AT91_TWI_STOP 0x0002 /* Send a Stop Condition */ #define AT91_TWI_MSEN 0x0004 /* Master Transfer Enable */ #define AT91_TWI_SVDIS 0x0020 /* Slave Transfer Disable */ #define AT91_TWI_QUICK 0x0040 /* SMBus quick command */ #define AT91_TWI_SWRST 0x0080 /* Software Reset */ #define AT91_TWI_MMR 0x0004 /* Master Mode Register */ #define AT91_TWI_IADRSZ_1 0x0100 /* Internal Device Address Size */ #define AT91_TWI_MREAD 0x1000 /* Master Read Direction */ #define AT91_TWI_IADR 0x000c /* Internal Address Register */ #define AT91_TWI_CWGR 0x0010 /* Clock Waveform Generator Reg */ #define AT91_TWI_SR 0x0020 /* Status Register */ #define AT91_TWI_TXCOMP 0x0001 /* Transmission Complete */ #define AT91_TWI_RXRDY 0x0002 /* Receive Holding Register Ready */ #define AT91_TWI_TXRDY 0x0004 /* Transmit Holding Register Ready */ #define AT91_TWI_OVRE 0x0040 /* Overrun Error */ #define AT91_TWI_UNRE 0x0080 /* Underrun Error */ #define AT91_TWI_NACK 0x0100 /* Not Acknowledged */ #define AT91_TWI_INT_MASK \ (AT91_TWI_TXCOMP | AT91_TWI_RXRDY | AT91_TWI_TXRDY | AT91_TWI_NACK) #define AT91_TWI_IER 0x0024 /* Interrupt Enable Register */ #define AT91_TWI_IDR 0x0028 /* Interrupt Disable Register */ #define AT91_TWI_IMR 0x002c /* Interrupt Mask Register */ #define AT91_TWI_RHR 0x0030 /* Receive Holding Register */ #define AT91_TWI_THR 0x0034 /* Transmit Holding Register */ struct at91_twi_pdata { unsigned clk_max_div; unsigned clk_offset; bool has_unre_flag; struct at_dma_slave dma_slave; }; struct at91_twi_dma { struct dma_chan *chan_rx; struct dma_chan *chan_tx; struct scatterlist sg; struct dma_async_tx_descriptor *data_desc; enum dma_data_direction direction; bool buf_mapped; bool xfer_in_progress; }; struct at91_twi_dev { struct device *dev; void __iomem *base; struct completion cmd_complete; struct clk *clk; u8 *buf; size_t buf_len; struct i2c_msg *msg; int irq; unsigned imr; unsigned transfer_status; struct i2c_adapter adapter; unsigned twi_cwgr_reg; struct at91_twi_pdata *pdata; bool use_dma; bool recv_len_abort; struct at91_twi_dma dma; }; static unsigned at91_twi_read(struct at91_twi_dev *dev, unsigned reg) { return readl_relaxed(dev->base + reg); } static void at91_twi_write(struct at91_twi_dev *dev, unsigned reg, unsigned val) { writel_relaxed(val, dev->base + reg); } static void at91_disable_twi_interrupts(struct at91_twi_dev *dev) { at91_twi_write(dev, AT91_TWI_IDR, AT91_TWI_INT_MASK); } static void at91_twi_irq_save(struct at91_twi_dev *dev) { dev->imr = at91_twi_read(dev, AT91_TWI_IMR) & AT91_TWI_INT_MASK; at91_disable_twi_interrupts(dev); } static void at91_twi_irq_restore(struct at91_twi_dev *dev) { at91_twi_write(dev, AT91_TWI_IER, dev->imr); } static void at91_init_twi_bus(struct at91_twi_dev *dev) { at91_disable_twi_interrupts(dev); at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_SWRST); at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_MSEN); at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_SVDIS); at91_twi_write(dev, AT91_TWI_CWGR, dev->twi_cwgr_reg); } /* * Calculate symmetric clock as stated in datasheet: * twi_clk = F_MAIN / (2 * (cdiv * (1 << ckdiv) + offset)) */ static void at91_calc_twi_clock(struct at91_twi_dev *dev, int twi_clk) { int ckdiv, cdiv, div; struct at91_twi_pdata *pdata = dev->pdata; int offset = pdata->clk_offset; int max_ckdiv = pdata->clk_max_div; div = max(0, (int)DIV_ROUND_UP(clk_get_rate(dev->clk), 2 * twi_clk) - offset); ckdiv = fls(div >> 8); cdiv = div >> ckdiv; if (ckdiv > max_ckdiv) { dev_warn(dev->dev, "%d exceeds ckdiv max value which is %d.\n", ckdiv, max_ckdiv); ckdiv = max_ckdiv; cdiv = 255; } dev->twi_cwgr_reg = (ckdiv << 16) | (cdiv << 8) | cdiv; dev_dbg(dev->dev, "cdiv %d ckdiv %d\n", cdiv, ckdiv); } static void at91_twi_dma_cleanup(struct at91_twi_dev *dev) { struct at91_twi_dma *dma = &dev->dma; at91_twi_irq_save(dev); if (dma->xfer_in_progress) { if (dma->direction == DMA_FROM_DEVICE) dmaengine_terminate_all(dma->chan_rx); else dmaengine_terminate_all(dma->chan_tx); dma->xfer_in_progress = false; } if (dma->buf_mapped) { dma_unmap_single(dev->dev, sg_dma_address(&dma->sg), dev->buf_len, dma->direction); dma->buf_mapped = false; } at91_twi_irq_restore(dev); } static void at91_twi_write_next_byte(struct at91_twi_dev *dev) { if (dev->buf_len <= 0) return; at91_twi_write(dev, AT91_TWI_THR, *dev->buf); /* send stop when last byte has been written */ if (--dev->buf_len == 0) at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP); dev_dbg(dev->dev, "wrote 0x%x, to go %d\n", *dev->buf, dev->buf_len); ++dev->buf; } static void at91_twi_write_data_dma_callback(void *data) { struct at91_twi_dev *dev = (struct at91_twi_dev *)data; dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg), dev->buf_len, DMA_TO_DEVICE); /* * When this callback is called, THR/TX FIFO is likely not to be empty * yet. So we have to wait for TXCOMP or NACK bits to be set into the * Status Register to be sure that the STOP bit has been sent and the * transfer is completed. The NACK interrupt has already been enabled, * we just have to enable TXCOMP one. */ at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP); at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP); } static void at91_twi_write_data_dma(struct at91_twi_dev *dev) { dma_addr_t dma_addr; struct dma_async_tx_descriptor *txdesc; struct at91_twi_dma *dma = &dev->dma; struct dma_chan *chan_tx = dma->chan_tx; if (dev->buf_len <= 0) return; dma->direction = DMA_TO_DEVICE; at91_twi_irq_save(dev); dma_addr = dma_map_single(dev->dev, dev->buf, dev->buf_len, DMA_TO_DEVICE); if (dma_mapping_error(dev->dev, dma_addr)) { dev_err(dev->dev, "dma map failed\n"); return; } dma->buf_mapped = true; at91_twi_irq_restore(dev); sg_dma_len(&dma->sg) = dev->buf_len; sg_dma_address(&dma->sg) = dma_addr; txdesc = dmaengine_prep_slave_sg(chan_tx, &dma->sg, 1, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!txdesc) { dev_err(dev->dev, "dma prep slave sg failed\n"); goto error; } txdesc->callback = at91_twi_write_data_dma_callback; txdesc->callback_param = dev; dma->xfer_in_progress = true; dmaengine_submit(txdesc); dma_async_issue_pending(chan_tx); return; error: at91_twi_dma_cleanup(dev); } static void at91_twi_read_next_byte(struct at91_twi_dev *dev) { if (dev->buf_len <= 0) return; *dev->buf = at91_twi_read(dev, AT91_TWI_RHR) & 0xff; --dev->buf_len; /* return if aborting, we only needed to read RHR to clear RXRDY*/ if (dev->recv_len_abort) return; /* handle I2C_SMBUS_BLOCK_DATA */ if (unlikely(dev->msg->flags & I2C_M_RECV_LEN)) { /* ensure length byte is a valid value */ if (*dev->buf <= I2C_SMBUS_BLOCK_MAX && *dev->buf > 0) { dev->msg->flags &= ~I2C_M_RECV_LEN; dev->buf_len += *dev->buf; dev->msg->len = dev->buf_len + 1; dev_dbg(dev->dev, "received block length %d\n", dev->buf_len); } else { /* abort and send the stop by reading one more byte */ dev->recv_len_abort = true; dev->buf_len = 1; } } /* send stop if second but last byte has been read */ if (dev->buf_len == 1) at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP); dev_dbg(dev->dev, "read 0x%x, to go %d\n", *dev->buf, dev->buf_len); ++dev->buf; } static void at91_twi_read_data_dma_callback(void *data) { struct at91_twi_dev *dev = (struct at91_twi_dev *)data; dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg), dev->buf_len, DMA_FROM_DEVICE); /* The last two bytes have to be read without using dma */ dev->buf += dev->buf_len - 2; dev->buf_len = 2; at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_RXRDY | AT91_TWI_TXCOMP); } static void at91_twi_read_data_dma(struct at91_twi_dev *dev) { dma_addr_t dma_addr; struct dma_async_tx_descriptor *rxdesc; struct at91_twi_dma *dma = &dev->dma; struct dma_chan *chan_rx = dma->chan_rx; dma->direction = DMA_FROM_DEVICE; /* Keep in mind that we won't use dma to read the last two bytes */ at91_twi_irq_save(dev); dma_addr = dma_map_single(dev->dev, dev->buf, dev->buf_len - 2, DMA_FROM_DEVICE); if (dma_mapping_error(dev->dev, dma_addr)) { dev_err(dev->dev, "dma map failed\n"); return; } dma->buf_mapped = true; at91_twi_irq_restore(dev); dma->sg.dma_address = dma_addr; sg_dma_len(&dma->sg) = dev->buf_len - 2; rxdesc = dmaengine_prep_slave_sg(chan_rx, &dma->sg, 1, DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!rxdesc) { dev_err(dev->dev, "dma prep slave sg failed\n"); goto error; } rxdesc->callback = at91_twi_read_data_dma_callback; rxdesc->callback_param = dev; dma->xfer_in_progress = true; dmaengine_submit(rxdesc); dma_async_issue_pending(dma->chan_rx); return; error: at91_twi_dma_cleanup(dev); } static irqreturn_t atmel_twi_interrupt(int irq, void *dev_id) { struct at91_twi_dev *dev = dev_id; const unsigned status = at91_twi_read(dev, AT91_TWI_SR); const unsigned irqstatus = status & at91_twi_read(dev, AT91_TWI_IMR); if (!irqstatus) return IRQ_NONE; else if (irqstatus & AT91_TWI_RXRDY) at91_twi_read_next_byte(dev); else if (irqstatus & AT91_TWI_TXRDY) at91_twi_write_next_byte(dev); /* catch error flags */ dev->transfer_status |= status; if (irqstatus & (AT91_TWI_TXCOMP | AT91_TWI_NACK)) { at91_disable_twi_interrupts(dev); complete(&dev->cmd_complete); } return IRQ_HANDLED; } static int at91_do_twi_transfer(struct at91_twi_dev *dev) { int ret; unsigned long time_left; bool has_unre_flag = dev->pdata->has_unre_flag; /* * WARNING: the TXCOMP bit in the Status Register is NOT a clear on * read flag but shows the state of the transmission at the time the * Status Register is read. According to the programmer datasheet, * TXCOMP is set when both holding register and internal shifter are * empty and STOP condition has been sent. * Consequently, we should enable NACK interrupt rather than TXCOMP to * detect transmission failure. * * Besides, the TXCOMP bit is already set before the i2c transaction * has been started. For read transactions, this bit is cleared when * writing the START bit into the Control Register. So the * corresponding interrupt can safely be enabled just after. * However for write transactions managed by the CPU, we first write * into THR, so TXCOMP is cleared. Then we can safely enable TXCOMP * interrupt. If TXCOMP interrupt were enabled before writing into THR, * the interrupt handler would be called immediately and the i2c command * would be reported as completed. * Also when a write transaction is managed by the DMA controller, * enabling the TXCOMP interrupt in this function may lead to a race * condition since we don't know whether the TXCOMP interrupt is enabled * before or after the DMA has started to write into THR. So the TXCOMP * interrupt is enabled later by at91_twi_write_data_dma_callback(). * Immediately after in that DMA callback, we still need to send the * STOP condition manually writing the corresponding bit into the * Control Register. */ dev_dbg(dev->dev, "transfer: %s %d bytes.\n", (dev->msg->flags & I2C_M_RD) ? "read" : "write", dev->buf_len); reinit_completion(&dev->cmd_complete); dev->transfer_status = 0; if (!dev->buf_len) { at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_QUICK); at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP); } else if (dev->msg->flags & I2C_M_RD) { unsigned start_flags = AT91_TWI_START; if (at91_twi_read(dev, AT91_TWI_SR) & AT91_TWI_RXRDY) { dev_err(dev->dev, "RXRDY still set!"); at91_twi_read(dev, AT91_TWI_RHR); } /* if only one byte is to be read, immediately stop transfer */ if (dev->buf_len <= 1 && !(dev->msg->flags & I2C_M_RECV_LEN)) start_flags |= AT91_TWI_STOP; at91_twi_write(dev, AT91_TWI_CR, start_flags); /* * When using dma, the last byte has to be read manually in * order to not send the stop command too late and then * to receive extra data. In practice, there are some issues * if you use the dma to read n-1 bytes because of latency. * Reading n-2 bytes with dma and the two last ones manually * seems to be the best solution. */ if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) { at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK); at91_twi_read_data_dma(dev); } else { at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP | AT91_TWI_NACK | AT91_TWI_RXRDY); } } else { if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) { at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK); at91_twi_write_data_dma(dev); } else { at91_twi_write_next_byte(dev); at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP | AT91_TWI_NACK | AT91_TWI_TXRDY); } } time_left = wait_for_completion_timeout(&dev->cmd_complete, dev->adapter.timeout); if (time_left == 0) { dev_err(dev->dev, "controller timed out\n"); at91_init_twi_bus(dev); ret = -ETIMEDOUT; goto error; } if (dev->transfer_status & AT91_TWI_NACK) { dev_dbg(dev->dev, "received nack\n"); ret = -EREMOTEIO; goto error; } if (dev->transfer_status & AT91_TWI_OVRE) { dev_err(dev->dev, "overrun while reading\n"); ret = -EIO; goto error; } if (has_unre_flag && dev->transfer_status & AT91_TWI_UNRE) { dev_err(dev->dev, "underrun while writing\n"); ret = -EIO; goto error; } if (dev->recv_len_abort) { dev_err(dev->dev, "invalid smbus block length recvd\n"); ret = -EPROTO; goto error; } dev_dbg(dev->dev, "transfer complete\n"); return 0; error: at91_twi_dma_cleanup(dev); return ret; } static int at91_twi_xfer(struct i2c_adapter *adap, struct i2c_msg *msg, int num) { struct at91_twi_dev *dev = i2c_get_adapdata(adap); int ret; unsigned int_addr_flag = 0; struct i2c_msg *m_start = msg; dev_dbg(&adap->dev, "at91_xfer: processing %d messages:\n", num); ret = pm_runtime_get_sync(dev->dev); if (ret < 0) goto out; if (num == 2) { int internal_address = 0; int i; /* 1st msg is put into the internal address, start with 2nd */ m_start = &msg[1]; for (i = 0; i < msg->len; ++i) { const unsigned addr = msg->buf[msg->len - 1 - i]; internal_address |= addr << (8 * i); int_addr_flag += AT91_TWI_IADRSZ_1; } at91_twi_write(dev, AT91_TWI_IADR, internal_address); } at91_twi_write(dev, AT91_TWI_MMR, (m_start->addr << 16) | int_addr_flag | ((m_start->flags & I2C_M_RD) ? AT91_TWI_MREAD : 0)); dev->buf_len = m_start->len; dev->buf = m_start->buf; dev->msg = m_start; dev->recv_len_abort = false; ret = at91_do_twi_transfer(dev); ret = (ret < 0) ? ret : num; out: pm_runtime_mark_last_busy(dev->dev); pm_runtime_put_autosuspend(dev->dev); return ret; } /* * The hardware can handle at most two messages concatenated by a * repeated start via it's internal address feature. */ static struct i2c_adapter_quirks at91_twi_quirks = { .flags = I2C_AQ_COMB | I2C_AQ_COMB_WRITE_FIRST | I2C_AQ_COMB_SAME_ADDR, .max_comb_1st_msg_len = 3, }; static u32 at91_twi_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_SMBUS_READ_BLOCK_DATA; } static struct i2c_algorithm at91_twi_algorithm = { .master_xfer = at91_twi_xfer, .functionality = at91_twi_func, }; static struct at91_twi_pdata at91rm9200_config = { .clk_max_div = 5, .clk_offset = 3, .has_unre_flag = true, }; static struct at91_twi_pdata at91sam9261_config = { .clk_max_div = 5, .clk_offset = 4, .has_unre_flag = false, }; static struct at91_twi_pdata at91sam9260_config = { .clk_max_div = 7, .clk_offset = 4, .has_unre_flag = false, }; static struct at91_twi_pdata at91sam9g20_config = { .clk_max_div = 7, .clk_offset = 4, .has_unre_flag = false, }; static struct at91_twi_pdata at91sam9g10_config = { .clk_max_div = 7, .clk_offset = 4, .has_unre_flag = false, }; static const struct platform_device_id at91_twi_devtypes[] = { { .name = "i2c-at91rm9200", .driver_data = (unsigned long) &at91rm9200_config, }, { .name = "i2c-at91sam9261", .driver_data = (unsigned long) &at91sam9261_config, }, { .name = "i2c-at91sam9260", .driver_data = (unsigned long) &at91sam9260_config, }, { .name = "i2c-at91sam9g20", .driver_data = (unsigned long) &at91sam9g20_config, }, { .name = "i2c-at91sam9g10", .driver_data = (unsigned long) &at91sam9g10_config, }, { /* sentinel */ } }; #if defined(CONFIG_OF) static struct at91_twi_pdata at91sam9x5_config = { .clk_max_div = 7, .clk_offset = 4, .has_unre_flag = false, }; static const struct of_device_id atmel_twi_dt_ids[] = { { .compatible = "atmel,at91rm9200-i2c", .data = &at91rm9200_config, } , { .compatible = "atmel,at91sam9260-i2c", .data = &at91sam9260_config, } , { .compatible = "atmel,at91sam9261-i2c", .data = &at91sam9261_config, } , { .compatible = "atmel,at91sam9g20-i2c", .data = &at91sam9g20_config, } , { .compatible = "atmel,at91sam9g10-i2c", .data = &at91sam9g10_config, }, { .compatible = "atmel,at91sam9x5-i2c", .data = &at91sam9x5_config, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, atmel_twi_dt_ids); #endif static int at91_twi_configure_dma(struct at91_twi_dev *dev, u32 phy_addr) { int ret = 0; struct dma_slave_config slave_config; struct at91_twi_dma *dma = &dev->dma; memset(&slave_config, 0, sizeof(slave_config)); slave_config.src_addr = (dma_addr_t)phy_addr + AT91_TWI_RHR; slave_config.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; slave_config.src_maxburst = 1; slave_config.dst_addr = (dma_addr_t)phy_addr + AT91_TWI_THR; slave_config.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; slave_config.dst_maxburst = 1; slave_config.device_fc = false; dma->chan_tx = dma_request_slave_channel_reason(dev->dev, "tx"); if (IS_ERR(dma->chan_tx)) { ret = PTR_ERR(dma->chan_tx); dma->chan_tx = NULL; goto error; } dma->chan_rx = dma_request_slave_channel_reason(dev->dev, "rx"); if (IS_ERR(dma->chan_rx)) { ret = PTR_ERR(dma->chan_rx); dma->chan_rx = NULL; goto error; } slave_config.direction = DMA_MEM_TO_DEV; if (dmaengine_slave_config(dma->chan_tx, &slave_config)) { dev_err(dev->dev, "failed to configure tx channel\n"); ret = -EINVAL; goto error; } slave_config.direction = DMA_DEV_TO_MEM; if (dmaengine_slave_config(dma->chan_rx, &slave_config)) { dev_err(dev->dev, "failed to configure rx channel\n"); ret = -EINVAL; goto error; } sg_init_table(&dma->sg, 1); dma->buf_mapped = false; dma->xfer_in_progress = false; dev->use_dma = true; dev_info(dev->dev, "using %s (tx) and %s (rx) for DMA transfers\n", dma_chan_name(dma->chan_tx), dma_chan_name(dma->chan_rx)); return ret; error: if (ret != -EPROBE_DEFER) dev_info(dev->dev, "can't use DMA, error %d\n", ret); if (dma->chan_rx) dma_release_channel(dma->chan_rx); if (dma->chan_tx) dma_release_channel(dma->chan_tx); return ret; } static struct at91_twi_pdata *at91_twi_get_driver_data( struct platform_device *pdev) { if (pdev->dev.of_node) { const struct of_device_id *match; match = of_match_node(atmel_twi_dt_ids, pdev->dev.of_node); if (!match) return NULL; return (struct at91_twi_pdata *)match->data; } return (struct at91_twi_pdata *) platform_get_device_id(pdev)->driver_data; } static int at91_twi_probe(struct platform_device *pdev) { struct at91_twi_dev *dev; struct resource *mem; int rc; u32 phy_addr; u32 bus_clk_rate; dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; init_completion(&dev->cmd_complete); dev->dev = &pdev->dev; mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!mem) return -ENODEV; phy_addr = mem->start; dev->pdata = at91_twi_get_driver_data(pdev); if (!dev->pdata) return -ENODEV; dev->base = devm_ioremap_resource(&pdev->dev, mem); if (IS_ERR(dev->base)) return PTR_ERR(dev->base); dev->irq = platform_get_irq(pdev, 0); if (dev->irq < 0) return dev->irq; rc = devm_request_irq(&pdev->dev, dev->irq, atmel_twi_interrupt, 0, dev_name(dev->dev), dev); if (rc) { dev_err(dev->dev, "Cannot get irq %d: %d\n", dev->irq, rc); return rc; } platform_set_drvdata(pdev, dev); dev->clk = devm_clk_get(dev->dev, NULL); if (IS_ERR(dev->clk)) { dev_err(dev->dev, "no clock defined\n"); return -ENODEV; } clk_prepare_enable(dev->clk); if (dev->dev->of_node) { rc = at91_twi_configure_dma(dev, phy_addr); if (rc == -EPROBE_DEFER) return rc; } rc = of_property_read_u32(dev->dev->of_node, "clock-frequency", &bus_clk_rate); if (rc) bus_clk_rate = DEFAULT_TWI_CLK_HZ; at91_calc_twi_clock(dev, bus_clk_rate); at91_init_twi_bus(dev); snprintf(dev->adapter.name, sizeof(dev->adapter.name), "AT91"); i2c_set_adapdata(&dev->adapter, dev); dev->adapter.owner = THIS_MODULE; dev->adapter.class = I2C_CLASS_DEPRECATED; dev->adapter.algo = &at91_twi_algorithm; dev->adapter.quirks = &at91_twi_quirks; dev->adapter.dev.parent = dev->dev; dev->adapter.nr = pdev->id; dev->adapter.timeout = AT91_I2C_TIMEOUT; dev->adapter.dev.of_node = pdev->dev.of_node; pm_runtime_set_autosuspend_delay(dev->dev, AUTOSUSPEND_TIMEOUT); pm_runtime_use_autosuspend(dev->dev); pm_runtime_set_active(dev->dev); pm_runtime_enable(dev->dev); rc = i2c_add_numbered_adapter(&dev->adapter); if (rc) { dev_err(dev->dev, "Adapter %s registration failed\n", dev->adapter.name); clk_disable_unprepare(dev->clk); pm_runtime_disable(dev->dev); pm_runtime_set_suspended(dev->dev); return rc; } dev_info(dev->dev, "AT91 i2c bus driver.\n"); return 0; } static int at91_twi_remove(struct platform_device *pdev) { struct at91_twi_dev *dev = platform_get_drvdata(pdev); i2c_del_adapter(&dev->adapter); clk_disable_unprepare(dev->clk); pm_runtime_disable(dev->dev); pm_runtime_set_suspended(dev->dev); return 0; } #ifdef CONFIG_PM static int at91_twi_runtime_suspend(struct device *dev) { struct at91_twi_dev *twi_dev = dev_get_drvdata(dev); clk_disable_unprepare(twi_dev->clk); pinctrl_pm_select_sleep_state(dev); return 0; } static int at91_twi_runtime_resume(struct device *dev) { struct at91_twi_dev *twi_dev = dev_get_drvdata(dev); pinctrl_pm_select_default_state(dev); return clk_prepare_enable(twi_dev->clk); } static int at91_twi_suspend_noirq(struct device *dev) { if (!pm_runtime_status_suspended(dev)) at91_twi_runtime_suspend(dev); return 0; } static int at91_twi_resume_noirq(struct device *dev) { int ret; if (!pm_runtime_status_suspended(dev)) { ret = at91_twi_runtime_resume(dev); if (ret) return ret; } pm_runtime_mark_last_busy(dev); pm_request_autosuspend(dev); return 0; } static const struct dev_pm_ops at91_twi_pm = { .suspend_noirq = at91_twi_suspend_noirq, .resume_noirq = at91_twi_resume_noirq, .runtime_suspend = at91_twi_runtime_suspend, .runtime_resume = at91_twi_runtime_resume, }; #define at91_twi_pm_ops (&at91_twi_pm) #else #define at91_twi_pm_ops NULL #endif static struct platform_driver at91_twi_driver = { .probe = at91_twi_probe, .remove = at91_twi_remove, .id_table = at91_twi_devtypes, .driver = { .name = "at91_i2c", .of_match_table = of_match_ptr(atmel_twi_dt_ids), .pm = at91_twi_pm_ops, }, }; static int __init at91_twi_init(void) { return platform_driver_register(&at91_twi_driver); } static void __exit at91_twi_exit(void) { platform_driver_unregister(&at91_twi_driver); } subsys_initcall(at91_twi_init); module_exit(at91_twi_exit); MODULE_AUTHOR("Nikolaus Voss <[email protected]>"); MODULE_DESCRIPTION("I2C (TWI) driver for Atmel AT91"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:at91_i2c");
781213.c
/* Test of bind_textdomain_codeset. Copyright (C) 2001 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Bruno Haible <[email protected]>, 2001. 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; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <libintl.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { char *s; int result = 0; unsetenv ("LANGUAGE"); unsetenv ("OUTPUT_CHARSET"); setlocale (LC_ALL, "de_DE.ISO-8859-1"); textdomain ("codeset"); bindtextdomain ("codeset", OBJPFX "domaindir"); /* Here we expect output in ISO-8859-1. */ s = gettext ("cheese"); if (strcmp (s, "K\344se")) { printf ("call 1 returned: %s\n", s); result = 1; } bind_textdomain_codeset ("codeset", "UTF-8"); /* Here we expect output in UTF-8. */ s = gettext ("cheese"); if (strcmp (s, "K\303\244se")) { printf ("call 2 returned: %s\n", s); result = 1; } return result; }
91777.c
/* * Copyright 2008-2019, Marvell International Ltd. * All Rights Reserved. * * Derived from: * http://www.kernel.org/pub/linux/libs/klibc/ */ /* * lrand48.c */ #include <stdlib.h> #include <stdint.h> unsigned short __rand48_seed[3]; /* Common with mrand48.c, srand48.c */ extern long jrand48(unsigned short *); long lrand48(void) { return (uint32_t) jrand48(__rand48_seed) >> 1; } int rand(void) { return (int)lrand48(); } long random(void) { return lrand48(); }
19873.c
/* T R A N S F O R M . C * BRL-CAD * * Copyright (c) 2006-2016 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This 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 file; see the file named COPYING for more * information. */ #include "common.h" #include "vmath.h" #include "raytrace.h" int rt_matrix_transform(struct rt_db_internal *output, const mat_t matrix, struct rt_db_internal *input, int freeflag, struct db_i *dbip, struct resource *resource) { int ret; RT_CK_DB_INTERNAL(output); RT_CK_DB_INTERNAL(input); RT_CK_DBI(dbip); RT_CK_RESOURCE(resource); ret = -1; if (OBJ[input->idb_type].ft_xform) { ret = OBJ[input->idb_type].ft_xform(output, matrix, input, freeflag, dbip, resource); } return ret; } /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
854439.c
#include <stdio.h> int a[100005]; int main() { int n,k,t,i; scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&t); a[t]++; } scanf("%d",&k); for(i=100000;i>=1;i--){ if(a[i])k--; if(k==0) { printf("%d %d\n",i,a[i]); break; } } return 0; }
406785.c
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECC cipher suite support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ #include <stdio.h> #include "e_os.h" #ifndef NO_SYS_TYPES_H # include <sys/types.h> #endif #include "internal/o_dir.h" #include <openssl/lhash.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/dh.h> #include <openssl/bn.h> #include <openssl/crypto.h> #include "ssl_locl.h" #include "internal/thread_once.h" static int ssl_security_default_callback(const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex); static CRYPTO_ONCE ssl_x509_store_ctx_once = CRYPTO_ONCE_STATIC_INIT; static volatile int ssl_x509_store_ctx_idx = -1; DEFINE_RUN_ONCE_STATIC(ssl_x509_store_ctx_init) { ssl_x509_store_ctx_idx = X509_STORE_CTX_get_ex_new_index(0, "SSL for verify callback", NULL, NULL, NULL); return ssl_x509_store_ctx_idx >= 0; } int SSL_get_ex_data_X509_STORE_CTX_idx(void) { if (!RUN_ONCE(&ssl_x509_store_ctx_once, ssl_x509_store_ctx_init)) return -1; return ssl_x509_store_ctx_idx; } CERT *ssl_cert_new(void) { CERT *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE); return NULL; } ret->key = &(ret->pkeys[SSL_PKEY_RSA_ENC]); ret->references = 1; ret->sec_cb = ssl_security_default_callback; ret->sec_level = OPENSSL_TLS_SECURITY_LEVEL; ret->sec_ex = NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE); OPENSSL_free(ret); return NULL; } return ret; } CERT *ssl_cert_dup(CERT *cert) { CERT *ret = OPENSSL_zalloc(sizeof(*ret)); int i; if (ret == NULL) { SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE); return NULL; } ret->references = 1; ret->key = &ret->pkeys[cert->key - cert->pkeys]; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE); OPENSSL_free(ret); return NULL; } #ifndef OPENSSL_NO_DH if (cert->dh_tmp != NULL) { ret->dh_tmp = cert->dh_tmp; EVP_PKEY_up_ref(ret->dh_tmp); } ret->dh_tmp_cb = cert->dh_tmp_cb; ret->dh_tmp_auto = cert->dh_tmp_auto; #endif for (i = 0; i < SSL_PKEY_NUM; i++) { CERT_PKEY *cpk = cert->pkeys + i; CERT_PKEY *rpk = ret->pkeys + i; if (cpk->x509 != NULL) { rpk->x509 = cpk->x509; X509_up_ref(rpk->x509); } if (cpk->privatekey != NULL) { rpk->privatekey = cpk->privatekey; EVP_PKEY_up_ref(cpk->privatekey); } if (cpk->chain) { rpk->chain = X509_chain_up_ref(cpk->chain); if (!rpk->chain) { SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE); goto err; } } if (cert->pkeys[i].serverinfo != NULL) { /* Just copy everything. */ ret->pkeys[i].serverinfo = OPENSSL_malloc(cert->pkeys[i].serverinfo_length); if (ret->pkeys[i].serverinfo == NULL) { SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE); goto err; } ret->pkeys[i].serverinfo_length = cert->pkeys[i].serverinfo_length; memcpy(ret->pkeys[i].serverinfo, cert->pkeys[i].serverinfo, cert->pkeys[i].serverinfo_length); } } /* Configured sigalgs copied across */ if (cert->conf_sigalgs) { ret->conf_sigalgs = OPENSSL_malloc(cert->conf_sigalgslen); if (ret->conf_sigalgs == NULL) goto err; memcpy(ret->conf_sigalgs, cert->conf_sigalgs, cert->conf_sigalgslen); ret->conf_sigalgslen = cert->conf_sigalgslen; } else ret->conf_sigalgs = NULL; if (cert->client_sigalgs) { ret->client_sigalgs = OPENSSL_malloc(cert->client_sigalgslen); if (ret->client_sigalgs == NULL) goto err; memcpy(ret->client_sigalgs, cert->client_sigalgs, cert->client_sigalgslen); ret->client_sigalgslen = cert->client_sigalgslen; } else ret->client_sigalgs = NULL; /* Shared sigalgs also NULL */ ret->shared_sigalgs = NULL; /* Copy any custom client certificate types */ if (cert->ctypes) { ret->ctypes = OPENSSL_malloc(cert->ctype_num); if (ret->ctypes == NULL) goto err; memcpy(ret->ctypes, cert->ctypes, cert->ctype_num); ret->ctype_num = cert->ctype_num; } ret->cert_flags = cert->cert_flags; ret->cert_cb = cert->cert_cb; ret->cert_cb_arg = cert->cert_cb_arg; if (cert->verify_store) { X509_STORE_up_ref(cert->verify_store); ret->verify_store = cert->verify_store; } if (cert->chain_store) { X509_STORE_up_ref(cert->chain_store); ret->chain_store = cert->chain_store; } ret->sec_cb = cert->sec_cb; ret->sec_level = cert->sec_level; ret->sec_ex = cert->sec_ex; if (!custom_exts_copy(&ret->cli_ext, &cert->cli_ext)) goto err; if (!custom_exts_copy(&ret->srv_ext, &cert->srv_ext)) goto err; #ifndef OPENSSL_NO_PSK if (cert->psk_identity_hint) { ret->psk_identity_hint = OPENSSL_strdup(cert->psk_identity_hint); if (ret->psk_identity_hint == NULL) goto err; } #endif return ret; err: ssl_cert_free(ret); return NULL; } /* Free up and clear all certificates and chains */ void ssl_cert_clear_certs(CERT *c) { int i; if (c == NULL) return; for (i = 0; i < SSL_PKEY_NUM; i++) { CERT_PKEY *cpk = c->pkeys + i; X509_free(cpk->x509); cpk->x509 = NULL; EVP_PKEY_free(cpk->privatekey); cpk->privatekey = NULL; sk_X509_pop_free(cpk->chain, X509_free); cpk->chain = NULL; OPENSSL_free(cpk->serverinfo); cpk->serverinfo = NULL; cpk->serverinfo_length = 0; } } void ssl_cert_free(CERT *c) { int i; if (c == NULL) return; CRYPTO_DOWN_REF(&c->references, &i, c->lock); REF_PRINT_COUNT("CERT", c); if (i > 0) return; REF_ASSERT_ISNT(i < 0); #ifndef OPENSSL_NO_DH EVP_PKEY_free(c->dh_tmp); #endif ssl_cert_clear_certs(c); OPENSSL_free(c->conf_sigalgs); OPENSSL_free(c->client_sigalgs); OPENSSL_free(c->shared_sigalgs); OPENSSL_free(c->ctypes); X509_STORE_free(c->verify_store); X509_STORE_free(c->chain_store); custom_exts_free(&c->cli_ext); custom_exts_free(&c->srv_ext); #ifndef OPENSSL_NO_PSK OPENSSL_free(c->psk_identity_hint); #endif CRYPTO_THREAD_lock_free(c->lock); OPENSSL_free(c); } int ssl_cert_set0_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain) { int i, r; CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key; if (!cpk) return 0; for (i = 0; i < sk_X509_num(chain); i++) { r = ssl_security_cert(s, ctx, sk_X509_value(chain, i), 0, 0); if (r != 1) { SSLerr(SSL_F_SSL_CERT_SET0_CHAIN, r); return 0; } } sk_X509_pop_free(cpk->chain, X509_free); cpk->chain = chain; return 1; } int ssl_cert_set1_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain) { STACK_OF(X509) *dchain; if (!chain) return ssl_cert_set0_chain(s, ctx, NULL); dchain = X509_chain_up_ref(chain); if (!dchain) return 0; if (!ssl_cert_set0_chain(s, ctx, dchain)) { sk_X509_pop_free(dchain, X509_free); return 0; } return 1; } int ssl_cert_add0_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x) { int r; CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key; if (!cpk) return 0; r = ssl_security_cert(s, ctx, x, 0, 0); if (r != 1) { SSLerr(SSL_F_SSL_CERT_ADD0_CHAIN_CERT, r); return 0; } if (!cpk->chain) cpk->chain = sk_X509_new_null(); if (!cpk->chain || !sk_X509_push(cpk->chain, x)) return 0; return 1; } int ssl_cert_add1_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x) { if (!ssl_cert_add0_chain_cert(s, ctx, x)) return 0; X509_up_ref(x); return 1; } int ssl_cert_select_current(CERT *c, X509 *x) { int i; if (x == NULL) return 0; for (i = 0; i < SSL_PKEY_NUM; i++) { CERT_PKEY *cpk = c->pkeys + i; if (cpk->x509 == x && cpk->privatekey) { c->key = cpk; return 1; } } for (i = 0; i < SSL_PKEY_NUM; i++) { CERT_PKEY *cpk = c->pkeys + i; if (cpk->privatekey && cpk->x509 && !X509_cmp(cpk->x509, x)) { c->key = cpk; return 1; } } return 0; } int ssl_cert_set_current(CERT *c, long op) { int i, idx; if (!c) return 0; if (op == SSL_CERT_SET_FIRST) idx = 0; else if (op == SSL_CERT_SET_NEXT) { idx = (int)(c->key - c->pkeys + 1); if (idx >= SSL_PKEY_NUM) return 0; } else return 0; for (i = idx; i < SSL_PKEY_NUM; i++) { CERT_PKEY *cpk = c->pkeys + i; if (cpk->x509 && cpk->privatekey) { c->key = cpk; return 1; } } return 0; } void ssl_cert_set_cert_cb(CERT *c, int (*cb) (SSL *ssl, void *arg), void *arg) { c->cert_cb = cb; c->cert_cb_arg = arg; } int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk) { X509 *x; int i = 0; X509_STORE *verify_store; X509_STORE_CTX *ctx = NULL; X509_VERIFY_PARAM *param; if ((sk == NULL) || (sk_X509_num(sk) == 0)) return 0; if (s->cert->verify_store) verify_store = s->cert->verify_store; else verify_store = s->ctx->cert_store; ctx = X509_STORE_CTX_new(); if (ctx == NULL) { SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_MALLOC_FAILURE); return 0; } x = sk_X509_value(sk, 0); if (!X509_STORE_CTX_init(ctx, verify_store, x, sk)) { SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_X509_LIB); goto end; } param = X509_STORE_CTX_get0_param(ctx); /* * XXX: Separate @AUTHSECLEVEL and @TLSSECLEVEL would be useful at some * point, for now a single @SECLEVEL sets the same policy for TLS crypto * and PKI authentication. */ X509_VERIFY_PARAM_set_auth_level(param, SSL_get_security_level(s)); /* Set suite B flags if needed */ X509_STORE_CTX_set_flags(ctx, tls1_suiteb(s)); if (!X509_STORE_CTX_set_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s)) { goto end; } /* Verify via DANE if enabled */ if (DANETLS_ENABLED(&s->dane)) X509_STORE_CTX_set0_dane(ctx, &s->dane); /* * We need to inherit the verify parameters. These can be determined by * the context: if its a server it will verify SSL client certificates or * vice versa. */ X509_STORE_CTX_set_default(ctx, s->server ? "ssl_client" : "ssl_server"); /* * Anything non-default in "s->param" should overwrite anything in the ctx. */ X509_VERIFY_PARAM_set1(param, s->param); if (s->verify_callback) X509_STORE_CTX_set_verify_cb(ctx, s->verify_callback); if (s->ctx->app_verify_callback != NULL) i = s->ctx->app_verify_callback(ctx, s->ctx->app_verify_arg); else i = X509_verify_cert(ctx); s->verify_result = X509_STORE_CTX_get_error(ctx); sk_X509_pop_free(s->verified_chain, X509_free); s->verified_chain = NULL; if (X509_STORE_CTX_get0_chain(ctx) != NULL) { s->verified_chain = X509_STORE_CTX_get1_chain(ctx); if (s->verified_chain == NULL) { SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_MALLOC_FAILURE); i = 0; } } /* Move peername from the store context params to the SSL handle's */ X509_VERIFY_PARAM_move_peername(s->param, param); end: X509_STORE_CTX_free(ctx); return i; } static void set_client_CA_list(STACK_OF(X509_NAME) **ca_list, STACK_OF(X509_NAME) *name_list) { sk_X509_NAME_pop_free(*ca_list, X509_NAME_free); *ca_list = name_list; } STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk) { int i; STACK_OF(X509_NAME) *ret; X509_NAME *name; ret = sk_X509_NAME_new_null(); if (ret == NULL) { SSLerr(SSL_F_SSL_DUP_CA_LIST, ERR_R_MALLOC_FAILURE); return NULL; } for (i = 0; i < sk_X509_NAME_num(sk); i++) { name = X509_NAME_dup(sk_X509_NAME_value(sk, i)); if (name == NULL || !sk_X509_NAME_push(ret, name)) { sk_X509_NAME_pop_free(ret, X509_NAME_free); X509_NAME_free(name); return NULL; } } return (ret); } void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list) { set_client_CA_list(&(s->client_CA), name_list); } void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list) { set_client_CA_list(&(ctx->client_CA), name_list); } STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx) { return (ctx->client_CA); } STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s) { if (!s->server) { /* we are in the client */ if (((s->version >> 8) == SSL3_VERSION_MAJOR) && (s->s3 != NULL)) return (s->s3->tmp.ca_names); else return (NULL); } else { if (s->client_CA != NULL) return (s->client_CA); else return (s->ctx->client_CA); } } static int add_client_CA(STACK_OF(X509_NAME) **sk, X509 *x) { X509_NAME *name; if (x == NULL) return (0); if ((*sk == NULL) && ((*sk = sk_X509_NAME_new_null()) == NULL)) return (0); if ((name = X509_NAME_dup(X509_get_subject_name(x))) == NULL) return (0); if (!sk_X509_NAME_push(*sk, name)) { X509_NAME_free(name); return (0); } return (1); } int SSL_add_client_CA(SSL *ssl, X509 *x) { return (add_client_CA(&(ssl->client_CA), x)); } int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x) { return (add_client_CA(&(ctx->client_CA), x)); } static int xname_sk_cmp(const X509_NAME *const *a, const X509_NAME *const *b) { return (X509_NAME_cmp(*a, *b)); } static int xname_cmp(const X509_NAME *a, const X509_NAME *b) { return X509_NAME_cmp(a, b); } static unsigned long xname_hash(const X509_NAME *a) { return X509_NAME_hash((X509_NAME *)a); } /** * Load CA certs from a file into a ::STACK. Note that it is somewhat misnamed; * it doesn't really have anything to do with clients (except that a common use * for a stack of CAs is to send it to the client). Actually, it doesn't have * much to do with CAs, either, since it will load any old cert. * \param file the file containing one or more certs. * \return a ::STACK containing the certs. */ STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file) { BIO *in = BIO_new(BIO_s_file()); X509 *x = NULL; X509_NAME *xn = NULL; STACK_OF(X509_NAME) *ret = NULL; LHASH_OF(X509_NAME) *name_hash = lh_X509_NAME_new(xname_hash, xname_cmp); if ((name_hash == NULL) || (in == NULL)) { SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE); goto err; } if (!BIO_read_filename(in, file)) goto err; for (;;) { if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL) break; if (ret == NULL) { ret = sk_X509_NAME_new_null(); if (ret == NULL) { SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE); goto err; } } if ((xn = X509_get_subject_name(x)) == NULL) goto err; /* check for duplicates */ xn = X509_NAME_dup(xn); if (xn == NULL) goto err; if (lh_X509_NAME_retrieve(name_hash, xn) != NULL) { /* Duplicate. */ X509_NAME_free(xn); xn = NULL; } else { lh_X509_NAME_insert(name_hash, xn); if (!sk_X509_NAME_push(ret, xn)) goto err; } } goto done; err: X509_NAME_free(xn); sk_X509_NAME_pop_free(ret, X509_NAME_free); ret = NULL; done: BIO_free(in); X509_free(x); lh_X509_NAME_free(name_hash); if (ret != NULL) ERR_clear_error(); return (ret); } /** * Add a file of certs to a stack. * \param stack the stack to add to. * \param file the file to add from. All certs in this file that are not * already in the stack will be added. * \return 1 for success, 0 for failure. Note that in the case of failure some * certs may have been added to \c stack. */ int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack, const char *file) { BIO *in; X509 *x = NULL; X509_NAME *xn = NULL; int ret = 1; int (*oldcmp) (const X509_NAME *const *a, const X509_NAME *const *b); oldcmp = sk_X509_NAME_set_cmp_func(stack, xname_sk_cmp); in = BIO_new(BIO_s_file()); if (in == NULL) { SSLerr(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK, ERR_R_MALLOC_FAILURE); goto err; } if (!BIO_read_filename(in, file)) goto err; for (;;) { if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL) break; if ((xn = X509_get_subject_name(x)) == NULL) goto err; xn = X509_NAME_dup(xn); if (xn == NULL) goto err; if (sk_X509_NAME_find(stack, xn) >= 0) { /* Duplicate. */ X509_NAME_free(xn); } else if (!sk_X509_NAME_push(stack, xn)) { X509_NAME_free(xn); goto err; } } ERR_clear_error(); goto done; err: ret = 0; done: BIO_free(in); X509_free(x); (void)sk_X509_NAME_set_cmp_func(stack, oldcmp); return ret; } /** * Add a directory of certs to a stack. * \param stack the stack to append to. * \param dir the directory to append from. All files in this directory will be * examined as potential certs. Any that are acceptable to * SSL_add_dir_cert_subjects_to_stack() that are not already in the stack will be * included. * \return 1 for success, 0 for failure. Note that in the case of failure some * certs may have been added to \c stack. */ int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack, const char *dir) { OPENSSL_DIR_CTX *d = NULL; const char *filename; int ret = 0; /* Note that a side effect is that the CAs will be sorted by name */ while ((filename = OPENSSL_DIR_read(&d, dir))) { char buf[1024]; int r; if (strlen(dir) + strlen(filename) + 2 > sizeof buf) { SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, SSL_R_PATH_TOO_LONG); goto err; } #ifdef OPENSSL_SYS_VMS r = BIO_snprintf(buf, sizeof buf, "%s%s", dir, filename); #else r = BIO_snprintf(buf, sizeof buf, "%s/%s", dir, filename); #endif if (r <= 0 || r >= (int)sizeof(buf)) goto err; if (!SSL_add_file_cert_subjects_to_stack(stack, buf)) goto err; } if (errno) { SYSerr(SYS_F_OPENDIR, get_last_sys_error()); ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')"); SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, ERR_R_SYS_LIB); goto err; } ret = 1; err: if (d) OPENSSL_DIR_end(&d); return ret; } /* Add a certificate to the WPACKET */ static int ssl_add_cert_to_buf(WPACKET *pkt, X509 *x) { int len; unsigned char *outbytes; len = i2d_X509(x, NULL); if (len < 0) { SSLerr(SSL_F_SSL_ADD_CERT_TO_BUF, ERR_R_BUF_LIB); return 0; } if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes) || i2d_X509(x, &outbytes) != len) { SSLerr(SSL_F_SSL_ADD_CERT_TO_BUF, ERR_R_INTERNAL_ERROR); return 0; } return 1; } /* Add certificate chain to internal SSL BUF_MEM structure */ int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk) { int i, chain_count; X509 *x; STACK_OF(X509) *extra_certs; STACK_OF(X509) *chain = NULL; X509_STORE *chain_store; if (cpk == NULL || cpk->x509 == NULL) return 1; x = cpk->x509; /* * If we have a certificate specific chain use it, else use parent ctx. */ if (cpk->chain) extra_certs = cpk->chain; else extra_certs = s->ctx->extra_certs; if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs) chain_store = NULL; else if (s->cert->chain_store) chain_store = s->cert->chain_store; else chain_store = s->ctx->cert_store; if (chain_store) { X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new(); if (xs_ctx == NULL) { SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE); return (0); } if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) { X509_STORE_CTX_free(xs_ctx); SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB); return (0); } /* * It is valid for the chain not to be complete (because normally we * don't include the root cert in the chain). Therefore we deliberately * ignore the error return from this call. We're not actually verifying * the cert - we're just building as much of the chain as we can */ (void)X509_verify_cert(xs_ctx); /* Don't leave errors in the queue */ ERR_clear_error(); chain = X509_STORE_CTX_get0_chain(xs_ctx); i = ssl_security_cert_chain(s, chain, NULL, 0); if (i != 1) { #if 0 /* Dummy error calls so mkerr generates them */ SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL); SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL); SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK); #endif X509_STORE_CTX_free(xs_ctx); SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i); return 0; } chain_count = sk_X509_num(chain); for (i = 0; i < chain_count; i++) { x = sk_X509_value(chain, i); if (!ssl_add_cert_to_buf(pkt, x)) { X509_STORE_CTX_free(xs_ctx); return 0; } } X509_STORE_CTX_free(xs_ctx); } else { i = ssl_security_cert_chain(s, extra_certs, x, 0); if (i != 1) { SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i); return 0; } if (!ssl_add_cert_to_buf(pkt, x)) return 0; for (i = 0; i < sk_X509_num(extra_certs); i++) { x = sk_X509_value(extra_certs, i); if (!ssl_add_cert_to_buf(pkt, x)) return 0; } } return 1; } /* Build a certificate chain for current certificate */ int ssl_build_cert_chain(SSL *s, SSL_CTX *ctx, int flags) { CERT *c = s ? s->cert : ctx->cert; CERT_PKEY *cpk = c->key; X509_STORE *chain_store = NULL; X509_STORE_CTX *xs_ctx = NULL; STACK_OF(X509) *chain = NULL, *untrusted = NULL; X509 *x; int i, rv = 0; unsigned long error; if (!cpk->x509) { SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_NO_CERTIFICATE_SET); goto err; } /* Rearranging and check the chain: add everything to a store */ if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) { chain_store = X509_STORE_new(); if (chain_store == NULL) goto err; for (i = 0; i < sk_X509_num(cpk->chain); i++) { x = sk_X509_value(cpk->chain, i); if (!X509_STORE_add_cert(chain_store, x)) { error = ERR_peek_last_error(); if (ERR_GET_LIB(error) != ERR_LIB_X509 || ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) goto err; ERR_clear_error(); } } /* Add EE cert too: it might be self signed */ if (!X509_STORE_add_cert(chain_store, cpk->x509)) { error = ERR_peek_last_error(); if (ERR_GET_LIB(error) != ERR_LIB_X509 || ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) goto err; ERR_clear_error(); } } else { if (c->chain_store) chain_store = c->chain_store; else if (s) chain_store = s->ctx->cert_store; else chain_store = ctx->cert_store; if (flags & SSL_BUILD_CHAIN_FLAG_UNTRUSTED) untrusted = cpk->chain; } xs_ctx = X509_STORE_CTX_new(); if (xs_ctx == NULL) { SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_MALLOC_FAILURE); goto err; } if (!X509_STORE_CTX_init(xs_ctx, chain_store, cpk->x509, untrusted)) { SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_X509_LIB); goto err; } /* Set suite B flags if needed */ X509_STORE_CTX_set_flags(xs_ctx, c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS); i = X509_verify_cert(xs_ctx); if (i <= 0 && flags & SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR) { if (flags & SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR) ERR_clear_error(); i = 1; rv = 2; } if (i > 0) chain = X509_STORE_CTX_get1_chain(xs_ctx); if (i <= 0) { SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_CERTIFICATE_VERIFY_FAILED); i = X509_STORE_CTX_get_error(xs_ctx); ERR_add_error_data(2, "Verify error:", X509_verify_cert_error_string(i)); goto err; } /* Remove EE certificate from chain */ x = sk_X509_shift(chain); X509_free(x); if (flags & SSL_BUILD_CHAIN_FLAG_NO_ROOT) { if (sk_X509_num(chain) > 0) { /* See if last cert is self signed */ x = sk_X509_value(chain, sk_X509_num(chain) - 1); if (X509_get_extension_flags(x) & EXFLAG_SS) { x = sk_X509_pop(chain); X509_free(x); } } } /* * Check security level of all CA certificates: EE will have been checked * already. */ for (i = 0; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); rv = ssl_security_cert(s, ctx, x, 0, 0); if (rv != 1) { SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, rv); sk_X509_pop_free(chain, X509_free); rv = 0; goto err; } } sk_X509_pop_free(cpk->chain, X509_free); cpk->chain = chain; if (rv == 0) rv = 1; err: if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) X509_STORE_free(chain_store); X509_STORE_CTX_free(xs_ctx); return rv; } int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain, int ref) { X509_STORE **pstore; if (chain) pstore = &c->chain_store; else pstore = &c->verify_store; X509_STORE_free(*pstore); *pstore = store; if (ref && store) X509_STORE_up_ref(store); return 1; } static int ssl_security_default_callback(const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex) { int level, minbits; static const int minbits_table[5] = { 80, 112, 128, 192, 256 }; if (ctx) level = SSL_CTX_get_security_level(ctx); else level = SSL_get_security_level(s); if (level <= 0) { /* * No EDH keys weaker than 1024-bits even at level 0, otherwise, * anything goes. */ if (op == SSL_SECOP_TMP_DH && bits < 80) return 0; return 1; } if (level > 5) level = 5; minbits = minbits_table[level - 1]; switch (op) { case SSL_SECOP_CIPHER_SUPPORTED: case SSL_SECOP_CIPHER_SHARED: case SSL_SECOP_CIPHER_CHECK: { const SSL_CIPHER *c = other; /* No ciphers below security level */ if (bits < minbits) return 0; /* No unauthenticated ciphersuites */ if (c->algorithm_auth & SSL_aNULL) return 0; /* No MD5 mac ciphersuites */ if (c->algorithm_mac & SSL_MD5) return 0; /* SHA1 HMAC is 160 bits of security */ if (minbits > 160 && c->algorithm_mac & SSL_SHA1) return 0; /* Level 2: no RC4 */ if (level >= 2 && c->algorithm_enc == SSL_RC4) return 0; /* Level 3: forward secure ciphersuites only */ if (level >= 3 && !(c->algorithm_mkey & (SSL_kEDH | SSL_kEECDH))) return 0; break; } case SSL_SECOP_VERSION: if (!SSL_IS_DTLS(s)) { /* SSLv3 not allowed at level 2 */ if (nid <= SSL3_VERSION && level >= 2) return 0; /* TLS v1.1 and above only for level 3 */ if (nid <= TLS1_VERSION && level >= 3) return 0; /* TLS v1.2 only for level 4 and above */ if (nid <= TLS1_1_VERSION && level >= 4) return 0; } else { /* DTLS v1.2 only for level 4 and above */ if (DTLS_VERSION_LT(nid, DTLS1_2_VERSION) && level >= 4) return 0; } break; case SSL_SECOP_COMPRESSION: if (level >= 2) return 0; break; case SSL_SECOP_TICKET: if (level >= 3) return 0; break; default: if (bits < minbits) return 0; } return 1; } int ssl_security(const SSL *s, int op, int bits, int nid, void *other) { return s->cert->sec_cb(s, NULL, op, bits, nid, other, s->cert->sec_ex); } int ssl_ctx_security(const SSL_CTX *ctx, int op, int bits, int nid, void *other) { return ctx->cert->sec_cb(NULL, ctx, op, bits, nid, other, ctx->cert->sec_ex); }
661291.c
/* Polygonet Commanders (Konami, 1993) Poly-Net Warriors (Konami, 1993) Preliminary driver by R. Belmont Additional work by Andrew Gardner This is Konami's first 3D game! Hardware: 68EC020 @ 16 MHz Motorola XC56156-40 DSP @ 40 MHz Z80 + K054539 for sound Network to connect up to 4 PCBs. Video hardware: TTL text plane similar to Run and Gun. Konami K054009(x2) + K054010(x2) (polygon rasterizers) Konami K053936 "PSAC2" (3d roz plane, used for backgrounds) 24.0 MHz crystal to drive the video hardware Driver includes: - 68020 memory map - Z80 + sound system - EEPROM - service switch - TTL text plane Driver needs: - Handle network at 580800 so game starts - Polygon rasterization (K054009 + K054010) - Hook up PSAC2 (gfx decode for it is already present and correct) - Palettes - Controls - Priorities. From the original board it appears they're fixed, in front to back order: (all the way in front) TTL text layer -> polygons -> PSAC2 (all the way in back) Tech info by Phil Bennett, from the schematics: 68000 address map ================= 400000-43ffff = PSAC 440000-47ffff = PSVR 480000-4bffff = IO 4c0000-4fffff = SYS 500000-53ffff = DSP 540000-57ffff = FIX 580000-5bffff = OP1 5c0000-5fffff = UNUSED SYS (Write only?) ================= D28 = /FIXKILL - Disable 'FIX' layer? D27 = MUTE D26 = EEPROM CLK D25 = EEPROM CS D24 = EEPROM DATA D23 = BRMAS - 68k bus error mask D22 = L7MAS - L7 interrupt mask (unusued - should always be '1') D21 = /L5MAS - L5 interrupt mask/acknowledge D20 = L3MAS - L3 interrupt mask D19 = VFLIP - Flip video vertically D18 = HFLIP - Flip video horizontally D17 = COIN2 - Coin counter 2 D16 = COIN1 - Coin counter 1 DSP === 500000-503fff = HCOM - 16kB common RAM 504000-504fff = CONTROL - DSP/Host Control D10? = COMBNK - Switch between 68k and DSP access to common RAM D08? = RESN - Reset DSP 506000-506fff = HEN - DSP/Host interface */ #include "driver.h" #include "video/konamiic.h" #include "cpu/m68000/m68000.h" #include "cpu/z80/z80.h" #include "cpu/dsp56k/dsp56k.h" #include "sound/k054539.h" #include "machine/eeprom.h" VIDEO_START( polygonet ); VIDEO_UPDATE( polygonet ); READ32_HANDLER( polygonet_ttl_ram_r ); WRITE32_HANDLER( polygonet_ttl_ram_w ); READ32_HANDLER( polygonet_roz_ram_r ); WRITE32_HANDLER( polygonet_roz_ram_w ); static int init_eeprom_count; /* 68k-side shared ram */ static UINT32* shared_ram; static UINT16* dsp56k_p_mirror; static UINT16* dsp56k_p_8000; static const UINT16 dsp56k_bank00_size = 0x1000; static UINT16* dsp56k_bank00_ram; static const UINT16 dsp56k_bank01_size = 0x1000; static UINT16* dsp56k_bank01_ram; static const UINT16 dsp56k_bank02_size = 0x4000; static UINT16* dsp56k_bank02_ram; static const UINT16 dsp56k_shared_ram_16_size = 0x2000; static UINT16* dsp56k_shared_ram_16; static const UINT16 dsp56k_bank04_size = 0x1fc0; static UINT16* dsp56k_bank04_ram; static direct_update_func dsp56k_update_handler = NULL; static const eeprom_interface eeprom_intf = { 7, /* address bits */ 8, /* data bits */ "011000", /* read command */ "010100", /* write command */ "0100100000000",/* erase command */ "0100000000000",/* lock command */ "0100110000000" /* unlock command */ }; static NVRAM_HANDLER( polygonet ) { if (read_or_write) eeprom_save(file); else { eeprom_init(machine, &eeprom_intf); if (file) { init_eeprom_count = 0; eeprom_load(file); } else init_eeprom_count = 10; } } static READ32_HANDLER( polygonet_eeprom_r ) { if (ACCESSING_BITS_0_15) { return 0x0200 | (eeprom_read_bit()<<8); } else { UINT8 lowInputBits = input_port_read(space->machine, "IN1"); UINT8 highInputBits = input_port_read(space->machine, "IN0"); return ((highInputBits << 24) | (lowInputBits << 16)); } logerror("unk access to eeprom port (mask %x)\n", mem_mask); return 0; } static WRITE32_HANDLER( polygonet_eeprom_w ) { if (ACCESSING_BITS_24_31) { eeprom_write_bit((data & 0x01000000) ? ASSERT_LINE : CLEAR_LINE); eeprom_set_cs_line((data & 0x02000000) ? CLEAR_LINE : ASSERT_LINE); eeprom_set_clock_line((data & 0x04000000) ? ASSERT_LINE : CLEAR_LINE); return; } logerror("unknown write %x (mask %x) to eeprom\n", data, mem_mask); } /* TTL tile readback for ROM test */ static READ32_HANDLER( ttl_rom_r ) { UINT32 *ROM; ROM = (UINT32 *)memory_region(space->machine, "gfx1"); return ROM[offset]; } /* PSAC2 tile readback for ROM test */ static READ32_HANDLER( psac_rom_r ) { UINT32 *ROM; ROM = (UINT32 *)memory_region(space->machine, "gfx2"); return ROM[offset]; } /* irqs 3, 5, and 7 have valid vectors */ /* irq 3 is network. don't generate if you don't emulate the network h/w! */ /* irq 5 is vblank */ /* irq 7 does nothing (it jsrs to a rts and then rte) */ static INTERRUPT_GEN(polygonet_interrupt) { cpu_set_input_line(device, M68K_IRQ_5, HOLD_LINE); } /* sound CPU communications */ static READ32_HANDLER( sound_r ) { int latch = soundlatch3_r(space, 0); if ((latch == 0xd) || (latch == 0xe)) latch = 0xf; /* hack: until 54539 NMI disable found */ return latch<<8; } static WRITE32_HANDLER( sound_w ) { if (ACCESSING_BITS_8_15) { soundlatch_w(space, 0, (data>>8)&0xff); } else { soundlatch2_w(space, 0, data&0xff); } } static WRITE32_HANDLER( sound_irq_w ) { cputag_set_input_line(space->machine, "soundcpu", 0, HOLD_LINE); } /* DSP communications */ static READ32_HANDLER( dsp_host_interface_r ) { UINT32 value; UINT8 hi_addr = offset << 1; if (mem_mask == 0x0000ff00) { hi_addr++; } /* Low byte */ if (mem_mask == 0xff000000) {} /* High byte */ value = dsp56k_host_interface_read(cputag_get_cpu(space->machine, "dsp"), hi_addr); if (mem_mask == 0x0000ff00) { value <<= 8; } if (mem_mask == 0xff000000) { value <<= 24; } logerror("Dsp HI Read (host-side) %08x (HI %04x) = %08x (@%x)\n", mem_mask, hi_addr, value, cpu_get_pc(space->cpu)); return value; } static WRITE32_HANDLER( shared_ram_write ) { COMBINE_DATA(&shared_ram[offset]) ; if (mem_mask == 0xffff0000) { logerror("68k WRITING %04x to shared ram %x (@%x)\n", (shared_ram[offset] & 0xffff0000) >> 16, 0xc000 + (offset<<1), cpu_get_pc(space->cpu)); } else if (mem_mask == 0x0000ffff) { logerror("68k WRITING %04x to shared ram %x (@%x)\n", (shared_ram[offset] & 0x0000ffff), 0xc000 +((offset<<1)+1), cpu_get_pc(space->cpu)); } else { logerror("68k WRITING %04x & %04x to shared ram %x & %x [%08x] (@%x)\n", (shared_ram[offset] & 0xffff0000) >> 16, (shared_ram[offset] & 0x0000ffff), 0xc000 + (offset<<1), 0xc000 +((offset<<1)+1), mem_mask, cpu_get_pc(space->cpu)); } /* write to the current dsp56k word */ if (mem_mask | (0xffff0000)) { dsp56k_shared_ram_16[(offset<<1)] = (shared_ram[offset] & 0xffff0000) >> 16 ; } /* write to the next dsp56k word */ if (mem_mask | (0x0000ffff)) { dsp56k_shared_ram_16[(offset<<1)+1] = (shared_ram[offset] & 0x0000ffff) ; } } static WRITE32_HANDLER( dsp_w_lines ) { logerror("2w %08x %08x %08x\n", offset, mem_mask, data); /* 0x01000000 is the reset line - 0 is high, 1 is low */ if ((data >> 24) & 0x01) { // logerror("RESET CLEARED\n"); cputag_set_input_line(space->machine, "dsp", DSP56K_IRQ_RESET, CLEAR_LINE); } else { // logerror("RESET ASSERTED\n"); cputag_set_input_line(space->machine, "dsp", DSP56K_IRQ_RESET, ASSERT_LINE); /* A little hacky - I can't seem to set these lines anywhere else where reset is asserted, so i do it here */ cputag_set_input_line(space->machine, "dsp", DSP56K_IRQ_MODA, ASSERT_LINE); cputag_set_input_line(space->machine, "dsp", DSP56K_IRQ_MODB, CLEAR_LINE); } /* 0x04000000 is the COMBNK line - it switches who has access to the shared RAM - the dsp or the 68020 */ } static WRITE32_HANDLER( dsp_host_interface_w ) { UINT8 hi_data = 0x00; UINT8 hi_addr = offset << 1; if (mem_mask == 0x0000ff00) { hi_addr++; } /* Low byte */ if (mem_mask == 0xff000000) {} /* High byte */ if (mem_mask == 0x0000ff00) { hi_data = (data & 0x0000ff00) >> 8; } if (mem_mask == 0xff000000) { hi_data = (data & 0xff000000) >> 24; } logerror("write (host-side) %08x %08x %08x (HI %04x)\n", offset, mem_mask, data, hi_addr); dsp56k_host_interface_write(cputag_get_cpu(space->machine, "dsp"), hi_addr, hi_data); } static READ32_HANDLER( network_r ) { return 0x08000000; } static WRITE32_HANDLER( plygonet_palette_w ) { int r,g,b; COMBINE_DATA(&paletteram32[offset]); r = (paletteram32[offset] >>16) & 0xff; g = (paletteram32[offset] >> 8) & 0xff; b = (paletteram32[offset] >> 0) & 0xff; palette_set_color(space->machine,offset,MAKE_RGB(r,g,b)); } /**********************************************************************************/ /******* DSP56k maps *******/ /**********************************************************************************/ /* It's believed this is hard-wired to return (at least) bit 15 as 0 - causes a host interface bootup */ static READ16_HANDLER( dsp56k_bootload_r ) { return 0x7fff; } static DIRECT_UPDATE_HANDLER( plygonet_dsp56k_direct_handler ) { /* Call the dsp's update handler first */ if (dsp56k_update_handler != NULL) { if ((*dsp56k_update_handler)(space, address, direct) == ~0) return ~0; } /* If the requested region wasn't in there, see if it needs to be caught driver-side */ if (address >= (0x7000<<1) && address <= (0x7fff<<1)) { direct->raw = direct->decrypted = (UINT8*)(dsp56k_p_mirror) - (0x7000<<1); return ~0; } else if (address >= (0x8000<<1) && address <= (0x87ff<<1)) { direct->raw = direct->decrypted = (UINT8*)(dsp56k_p_8000) - (0x8000<<1); return ~0; } return address; } /* The dsp56k's Port C Data register (0xffe3) : Program code (function 4e) configures it as general purpose output I/O pins (ffc1 = 0000 & ffc3 = 0fff). XXXX ---- ---- ---- . Reserved bits ---- ???- -?-- ---- . unknown ---- ---- --x- ---- . [Bank Group A] Enable bit for "001c banking"? ---- ---- ---x xx-- . [Group A bank control] Believed to bank memory from 0x8000-0xbfff ---- ---- ---- --x- . [Bank Group B] Enable bit for "0181 banking"? ---- ---x x--- ---x . [Group B bank control] Believed to bank various other memory regions 001c banking is fairly easy - it happens in a loop and writes from 8000 to bfff 0181 banking is very weird - it happens in a nested loop and writes from 6000-6fff, 7000-7fff, and 8000-ffbf bit 0002 turns on *just* before this happens. */ enum { BANK_GROUP_A, BANK_GROUP_B, INVALID_BANK_GROUP }; static UINT8 dsp56k_bank_group(const device_config* cpu) { UINT16 portC = dsp56k_get_peripheral_memory(cpu, 0xffe3); /* If bank group B is on, it overrides bank group A */ if (portC & 0x0002) return BANK_GROUP_B; else if (portC & 0x0020) return BANK_GROUP_A; return INVALID_BANK_GROUP; } static UINT8 dsp56k_bank_num(const device_config* cpu, UINT8 bank_group) { UINT16 portC = dsp56k_get_peripheral_memory(cpu, 0xffe3); if (bank_group == BANK_GROUP_A) { const UINT16 bit3 = (portC & 0x0010) >> 2; const UINT16 bits21 = (portC & 0x000c) >> 2; return (bit3 | bits21); } else if (bank_group == BANK_GROUP_B) { const UINT16 bits32 = (portC & 0x0180) >> 6; const UINT16 bit1 = (portC & 0x0001) >> 0; return (bits32 | bit1); } else if (bank_group == INVALID_BANK_GROUP) { fatalerror("Plygonet: dsp56k bank num invalid.\n"); } return 0; } /* BANK HANDLERS */ static READ16_HANDLER( dsp56k_ram_bank00_read ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank00_size * 8) + (bank_num * dsp56k_bank00_size); return dsp56k_bank00_ram[driver_bank_offset + offset]; } static WRITE16_HANDLER( dsp56k_ram_bank00_write ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank00_size * 8) + (bank_num * dsp56k_bank00_size); COMBINE_DATA(&dsp56k_bank00_ram[driver_bank_offset + offset]); } static READ16_HANDLER( dsp56k_ram_bank01_read ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank01_size * 8) + (bank_num * dsp56k_bank01_size); return dsp56k_bank01_ram[driver_bank_offset + offset]; } static WRITE16_HANDLER( dsp56k_ram_bank01_write ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank01_size * 8) + (bank_num * dsp56k_bank01_size); COMBINE_DATA(&dsp56k_bank01_ram[driver_bank_offset + offset]); /* For now, *always* combine P:0x7000-0x7fff with bank01 with no regard to the banking hardware. */ dsp56k_p_mirror[offset] = data; } static READ16_HANDLER( dsp56k_ram_bank02_read ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank02_size * 8) + (bank_num * dsp56k_bank02_size); return dsp56k_bank02_ram[driver_bank_offset + offset]; } static WRITE16_HANDLER( dsp56k_ram_bank02_write ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank02_size * 8) + (bank_num * dsp56k_bank02_size); COMBINE_DATA(&dsp56k_bank02_ram[driver_bank_offset + offset]); } static READ16_HANDLER( dsp56k_shared_ram_read ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_shared_ram_16_size * 8) + (bank_num * dsp56k_shared_ram_16_size); return dsp56k_shared_ram_16[driver_bank_offset + offset]; } static WRITE16_HANDLER( dsp56k_shared_ram_write ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_shared_ram_16_size * 8) + (bank_num * dsp56k_shared_ram_16_size); COMBINE_DATA(&dsp56k_shared_ram_16[driver_bank_offset + offset]); /* Bank group A with offset 0 is believed to be the shared region */ if (en_group == BANK_GROUP_A && bank_num == 0) { if (offset % 2) shared_ram[offset>>1] = ((dsp56k_shared_ram_16[offset-1]) << 16) | dsp56k_shared_ram_16[offset] ; else shared_ram[offset>>1] = ((dsp56k_shared_ram_16[offset]) << 16) | dsp56k_shared_ram_16[offset+1] ; } } static READ16_HANDLER( dsp56k_ram_bank04_read ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank04_size * 8) + (bank_num * dsp56k_bank04_size); return dsp56k_bank04_ram[driver_bank_offset + offset]; } static WRITE16_HANDLER( dsp56k_ram_bank04_write ) { UINT8 en_group = dsp56k_bank_group(space->cpu); UINT8 bank_num = dsp56k_bank_num(space->cpu, en_group); UINT32 driver_bank_offset = (en_group * dsp56k_bank04_size * 8) + (bank_num * dsp56k_bank04_size); COMBINE_DATA(&dsp56k_bank04_ram[driver_bank_offset + offset]); } /**********************************************************************************/ static ADDRESS_MAP_START( main_map, ADDRESS_SPACE_PROGRAM, 32 ) AM_RANGE(0x000000, 0x1fffff) AM_ROM AM_RANGE(0x200000, 0x21ffff) AM_RAM_WRITE(plygonet_palette_w) AM_BASE(&paletteram32) AM_RANGE(0x400000, 0x40001f) AM_RAM AM_BASE((UINT32**)&K053936_0_ctrl) AM_RANGE(0x440000, 0x440fff) AM_READWRITE(polygonet_roz_ram_r, polygonet_roz_ram_w) AM_RANGE(0x480000, 0x4bffff) AM_READ(polygonet_eeprom_r) AM_RANGE(0x4C0000, 0x4fffff) AM_WRITE(polygonet_eeprom_w) AM_RANGE(0x500000, 0x503fff) AM_RAM_WRITE(shared_ram_write) AM_BASE(&shared_ram) AM_RANGE(0x504000, 0x504003) AM_WRITE(dsp_w_lines) AM_RANGE(0x506000, 0x50600f) AM_READWRITE(dsp_host_interface_r, dsp_host_interface_w) AM_RANGE(0x540000, 0x540fff) AM_READWRITE(polygonet_ttl_ram_r, polygonet_ttl_ram_w) AM_RANGE(0x541000, 0x54101f) AM_RAM AM_RANGE(0x580000, 0x5807ff) AM_RAM AM_RANGE(0x580800, 0x580803) AM_READ(network_r) AM_WRITENOP /* network RAM | registers? */ AM_RANGE(0x600004, 0x600007) AM_WRITE(sound_w) AM_RANGE(0x600008, 0x60000b) AM_READ(sound_r) AM_RANGE(0x640000, 0x640003) AM_WRITE(sound_irq_w) AM_RANGE(0x680000, 0x680003) AM_WRITE(watchdog_reset32_w) AM_RANGE(0x700000, 0x73ffff) AM_READ(psac_rom_r) AM_RANGE(0x780000, 0x79ffff) AM_READ(ttl_rom_r) AM_RANGE(0xff8000, 0xffffff) AM_RAM ADDRESS_MAP_END /**********************************************************************************/ static ADDRESS_MAP_START( dsp_program_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x7000, 0x7fff) AM_RAM AM_BASE(&dsp56k_p_mirror) /* Unsure of size, but 0x1000 matches bank01 */ AM_RANGE(0x8000, 0x87ff) AM_RAM AM_BASE(&dsp56k_p_8000) AM_RANGE(0xc000, 0xc000) AM_READ(dsp56k_bootload_r) ADDRESS_MAP_END static ADDRESS_MAP_START( dsp_data_map, ADDRESS_SPACE_DATA, 16 ) AM_RANGE(0x0800, 0x5fff) AM_RAM /* Appears to not be affected by banking? */ AM_RANGE(0x6000, 0x6fff) AM_READWRITE(dsp56k_ram_bank00_read, dsp56k_ram_bank00_write) AM_RANGE(0x7000, 0x7fff) AM_READWRITE(dsp56k_ram_bank01_read, dsp56k_ram_bank01_write) /* Mirrored in program space @ 0x7000 */ AM_RANGE(0x8000, 0xbfff) AM_READWRITE(dsp56k_ram_bank02_read, dsp56k_ram_bank02_write) AM_RANGE(0xc000, 0xdfff) AM_READWRITE(dsp56k_shared_ram_read, dsp56k_shared_ram_write) AM_RANGE(0xe000, 0xffbf) AM_READWRITE(dsp56k_ram_bank04_read, dsp56k_ram_bank04_write) ADDRESS_MAP_END /**********************************************************************************/ static int cur_sound_region; static void reset_sound_region(running_machine *machine) { memory_set_bankptr(machine, 2, memory_region(machine, "soundcpu") + 0x10000 + cur_sound_region*0x4000); } static WRITE8_HANDLER( sound_bankswitch_w ) { cur_sound_region = (data & 0x1f); reset_sound_region(space->machine); } static INTERRUPT_GEN(audio_interrupt) { cpu_set_input_line(device, INPUT_LINE_NMI, PULSE_LINE); } static ADDRESS_MAP_START( sound_map, ADDRESS_SPACE_PROGRAM, 8 ) AM_RANGE(0x0000, 0x7fff) AM_READ(SMH_ROM) AM_RANGE(0x8000, 0xbfff) AM_READ(SMH_BANK(2)) AM_RANGE(0x0000, 0xbfff) AM_WRITENOP AM_RANGE(0xc000, 0xdfff) AM_RAM AM_RANGE(0xe000, 0xe22f) AM_DEVREADWRITE("konami1", k054539_r, k054539_w) AM_RANGE(0xe230, 0xe3ff) AM_RAM AM_RANGE(0xe400, 0xe62f) AM_DEVREADWRITE("konami2", k054539_r, k054539_w) AM_RANGE(0xe630, 0xe7ff) AM_RAM AM_RANGE(0xf000, 0xf000) AM_WRITE(soundlatch3_w) AM_RANGE(0xf002, 0xf002) AM_READ(soundlatch_r) AM_RANGE(0xf003, 0xf003) AM_READ(soundlatch2_r) AM_RANGE(0xf800, 0xf800) AM_WRITE(sound_bankswitch_w) AM_RANGE(0xfff1, 0xfff3) AM_WRITENOP ADDRESS_MAP_END static const k054539_interface k054539_config = { "shared" }; /**********************************************************************************/ static const gfx_layout bglayout = { 16,16, 1024, 4, { 0, 1, 2, 3 }, { 0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 }, { 0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 8*4, 9*4, 10*4, 11*4, 12*4, 13*4, 14*4, 15*4 }, 128*8 }; static GFXDECODE_START( plygonet ) GFXDECODE_ENTRY( "gfx2", 0, bglayout, 0x0000, 64 ) GFXDECODE_END static MACHINE_START(polygonet) { logerror("Polygonet machine start\n"); /* Set the dsp56k lines */ /* It's presumed the hardware has hard-wired operating mode 1 (MODA = 1, MODB = 0) */ /* TODO: This should work, but the MAME core appears to do something funny. Not a big deal - it's hacked in dsp_w_lines. */ //cputag_set_input_line(machine, "dsp", INPUT_LINE_RESET, ASSERT_LINE); //cputag_set_input_line(machine, "dsp", DSP56K_IRQ_MODA, ASSERT_LINE); //cputag_set_input_line(machine, "dsp", DSP56K_IRQ_MODB, CLEAR_LINE); } static MACHINE_DRIVER_START( plygonet ) MDRV_CPU_ADD("maincpu", M68EC020, 16000000) /* 16 MHz (xtal is 32.0 MHz) */ MDRV_CPU_PROGRAM_MAP(main_map) MDRV_CPU_VBLANK_INT("screen", polygonet_interrupt) MDRV_CPU_ADD("dsp", DSP56156, 40000000) /* xtal is 40.0 MHz, DSP has an internal divide-by-2 */ MDRV_CPU_PROGRAM_MAP(dsp_program_map) MDRV_CPU_DATA_MAP(dsp_data_map) MDRV_CPU_ADD("soundcpu", Z80, 8000000) MDRV_CPU_PROGRAM_MAP(sound_map) MDRV_CPU_PERIODIC_INT(audio_interrupt, 480) MDRV_MACHINE_START(polygonet) MDRV_GFXDECODE(plygonet) MDRV_NVRAM_HANDLER(polygonet) /* TODO: TEMPORARY! UNTIL A MORE LOCALIZED SYNC CAN BE MADE */ MDRV_QUANTUM_TIME(HZ(1200000)) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(60) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 32*8) MDRV_SCREEN_VISIBLE_AREA(64, 64+368-1, 0, 32*8-1) MDRV_PALETTE_LENGTH(32768) MDRV_VIDEO_START(polygonet) MDRV_VIDEO_UPDATE(polygonet) /* sound hardware */ MDRV_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker") MDRV_SOUND_ADD("konami1", K054539, 48000) MDRV_SOUND_CONFIG(k054539_config) MDRV_SOUND_ROUTE(0, "lspeaker", 0.75) MDRV_SOUND_ROUTE(1, "rspeaker", 0.75) MDRV_SOUND_ADD("konami2", K054539, 48000) MDRV_SOUND_CONFIG(k054539_config) MDRV_SOUND_ROUTE(0, "lspeaker", 0.75) MDRV_SOUND_ROUTE(1, "rspeaker", 0.75) MACHINE_DRIVER_END /**********************************************************************************/ static INPUT_PORTS_START( polygonet ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_SERVICE_NO_TOGGLE( 0x02, IP_ACTIVE_LOW ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON3 ) /* SW1 (changes player color). It's mapped on the JAMMA connector and plugs into an external switch mech. */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON4 ) /* SW2 (changes player color). It's mapped on the JAMMA connector and plugs into an external switch mech. */ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP ) PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP ) PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) INPUT_PORTS_END static INPUT_PORTS_START( polynetw ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_SERVICE_NO_TOGGLE( 0x02, IP_ACTIVE_LOW ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 ) /* SW1 (changes player color). It's mapped on the JAMMA connector and plugs into an external switch mech. */ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 ) /* SW2 (changes player color). It's mapped on the JAMMA connector and plugs into an external switch mech. */ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) INPUT_PORTS_END /**********************************************************************************/ static DRIVER_INIT(polygonet) { /* Set default bankswitch */ cur_sound_region = 2; reset_sound_region(machine); /* Allocate space for the dsp56k banking */ dsp56k_bank00_ram = auto_alloc_array_clear(machine, UINT16, 2 * 8 * dsp56k_bank00_size); /* 2 bank sets, 8 potential banks each */ dsp56k_bank01_ram = auto_alloc_array_clear(machine, UINT16, 2 * 8 * dsp56k_bank01_size); dsp56k_bank02_ram = auto_alloc_array_clear(machine, UINT16, 2 * 8 * dsp56k_bank02_size); dsp56k_shared_ram_16 = auto_alloc_array_clear(machine, UINT16, 2 * 8 * dsp56k_shared_ram_16_size); dsp56k_bank04_ram = auto_alloc_array_clear(machine, UINT16, 2 * 8 * dsp56k_bank04_size); /* The dsp56k occasionally executes out of mapped memory */ dsp56k_update_handler = memory_set_direct_update_handler(cputag_get_address_space(machine, "dsp", ADDRESS_SPACE_PROGRAM), plygonet_dsp56k_direct_handler); } /**********************************************************************************/ ROM_START( plygonet ) /* main program */ ROM_REGION( 0x200000, "maincpu", 0) ROM_LOAD32_BYTE( "305uaa01.4k", 0x000003, 512*1024, CRC(8bdb6c95) SHA1(e981833842f8fd89b9726901fbe2058444204792) ) /* Boards exist without the "UA" in the label IE: 305a01, ect... */ ROM_LOAD32_BYTE( "305uaa02.2k", 0x000002, 512*1024, CRC(4d7e32b3) SHA1(25731526535036972577637d186f02ae467296bd) ) ROM_LOAD32_BYTE( "305uaa03.2h", 0x000001, 512*1024, CRC(36e4e3fe) SHA1(e8fcad4f196c9b225a0fbe70791493ff07c648a9) ) ROM_LOAD32_BYTE( "305uaa04.4h", 0x000000, 512*1024, CRC(d8394e72) SHA1(eb6bcf8aedb9ba5843204ab8aacb735cbaafb74d) ) /* Z80 sound program */ ROM_REGION( 0x30000, "soundcpu", 0 ) ROM_LOAD("305b05.7b", 0x000000, 0x20000, CRC(2d3d9654) SHA1(784a409df47cee877e507b8bbd3610d161d63753) ) ROM_RELOAD( 0x10000, 0x20000) /* TTL text plane tiles */ ROM_REGION( 0x20000, "gfx1", 0 ) ROM_LOAD( "305b06.18g", 0x000000, 0x20000, CRC(decd6e42) SHA1(4c23dcb1d68132d3381007096e014ee4b6007086) ) /* '936 tiles */ ROM_REGION( 0x40000, "gfx2", 0 ) ROM_LOAD( "305b07.20d", 0x000000, 0x40000, CRC(e4320bc3) SHA1(b0bb2dac40d42f97da94516d4ebe29b1c3d77c37) ) /* sound data */ ROM_REGION( 0x200000, "shared", 0 ) ROM_LOAD( "305b08.2e", 0x000000, 0x200000, CRC(874607df) SHA1(763b44a80abfbc355bcb9be8bf44373254976019) ) ROM_END ROM_START( polynetw ) /* main program */ ROM_REGION( 0x200000, "maincpu", 0) ROM_LOAD32_BYTE( "305jaa01.4k", 0x000003, 0x080000, CRC(ea889bd9) SHA1(102e7c0f0c064662c0f6137ad5da97a9ccd49a97) ) ROM_LOAD32_BYTE( "305jaa02.2k", 0x000002, 0x080000, CRC(d0710379) SHA1(cf0970d63e8d021edf2d404838c658a5b7cb8fb8) ) ROM_LOAD32_BYTE( "305jaa03.2h", 0x000001, 0x080000, CRC(278b5928) SHA1(2ea96054e2ef637731cd64f2bef0b5b2bbe7e24f) ) ROM_LOAD32_BYTE( "305jaa04.4h", 0x000000, 0x080000, CRC(b069353b) SHA1(12fbe2df09328bb7193e89a49d84a61eab5bfdcb) ) /* Z80 sound program */ ROM_REGION( 0x30000, "soundcpu", 0 ) ROM_LOAD( "305jaa05.7b", 0x000000, 0x020000, CRC(06053db6) SHA1(c7d43c2650d949ee552a49db93dece842c17e68d) ) ROM_RELOAD( 0x10000, 0x20000) /* TTL text plane tiles */ ROM_REGION( 0x20000, "gfx1", 0 ) ROM_LOAD( "305a06.18g", 0x000000, 0x020000, CRC(4b9b7e9c) SHA1(8c3c0f1ec7e26fd9552f6da1e6bdd7ff4453ba57) ) /* '936 tiles */ ROM_REGION( 0x40000, "gfx2", 0 ) ROM_LOAD( "305a07.20d", 0x000000, 0x020000, CRC(0959283b) SHA1(482caf96e8e430b87810508b1a1420cd3b58f203) ) /* sound data */ ROM_REGION( 0x400000, "shared", 0 ) ROM_LOAD( "305a08.2e", 0x000000, 0x200000, CRC(7ddb8a52) SHA1(3199b347fc433ffe0de8521001df77672d40771e) ) ROM_LOAD( "305a09.3e", 0x200000, 0x200000, CRC(6da1be58) SHA1(d63ac16ac551193ff8a6036724fb59e1d702e06b) ) ROM_END /* ROM parent machine inp init */ GAME( 1993, plygonet, 0, plygonet, polygonet, polygonet, ROT90, "Konami", "Polygonet Commanders (ver UAA)", GAME_NOT_WORKING | GAME_NO_SOUND ) GAME( 1993, polynetw, 0, plygonet, polynetw, polygonet, ROT90, "Konami", "Poly-Net Warriors (ver JAA)", GAME_NOT_WORKING | GAME_NO_SOUND )
360944.c
#include <strings.h> #include <z80e/debugger/commands.h> #include <z80e/debugger/debugger.h> #include <z80e/ti/hardware/keyboard.h> #include <z80e/debugger/keys.h> int command_release_key(debugger_state_t *state, int argc, char **argv) { if (argc != 2) { state->print(state, "%s - Release the specified key code, in hex or by name.\n", argv[0]); return 0; } uint8_t key; int i, found = 0; for (i = 0; i < sizeof(key_strings) / sizeof(key_string_t); ++i) { if (strcasecmp(key_strings[i].key, argv[1]) == 0) { key = key_strings[i].value; found = 1; break; } } if (!found) { key = parse_expression(state, argv[1]); } release_key(state->asic->cpu->devices[0x01].device, key); return 0; }
955275.c
/* * Copyright (c) 2018 IOTA Stiftung * https:github.com/iotaledger/entangled * * MAM is based on an original implementation & specification by apmi.bsu.by * [ITSec Lab] * * Refer to the LICENSE file for licensing information */ #include <stdio.h> #include "mam/examples/send-common.h" int main(int ac, char **av) { mam_api_t api; bundle_transactions_t *bundle = NULL; tryte_t channel_id[MAM_CHANNEL_ID_TRYTE_SIZE]; retcode_t ret = RC_OK; if (ac != 6) { fprintf(stderr, "usage: send-msg <host> <port> <seed> <payload> <last_packet>\n"); return EXIT_FAILURE; } if (strcmp(av[5], "yes") && strcmp(av[5], "no")) { fprintf(stderr, "Arg <last_packet> should be \"yes\" or \"no\" only\n"); return EXIT_FAILURE; } // Loading or creating MAM API if ((ret = mam_api_load(MAM_FILE, &api, NULL, 0)) == RC_UTILS_FAILED_TO_OPEN_FILE) { if ((ret = mam_api_init(&api, (tryte_t *)av[3])) != RC_OK) { fprintf(stderr, "mam_api_init failed with err %d\n", ret); return EXIT_FAILURE; } } else if (ret != RC_OK) { fprintf(stderr, "mam_api_load failed with err %d\n", ret); return EXIT_FAILURE; } // Creating channel memset(channel_id, 0, MAM_CHANNEL_ID_TRYTE_SIZE+1); if ((ret = mam_example_channel_create(&api, channel_id)) != RC_OK) { fprintf(stderr, "mam_example_channel_create failed with err %d\n", ret); return EXIT_FAILURE; } bundle_transactions_new(&bundle); { trit_t msg_id[MAM_MSG_ID_SIZE]; // Writing header to bundle if ((ret = mam_example_write_header_on_channel(&api, channel_id, bundle, msg_id)) != RC_OK) { fprintf(stderr, "mam_example_write_header failed with err %d\n", ret); return EXIT_FAILURE; } // Writing packet to bundle bool last_packet = strcmp(av[5], "yes") == 0; // if (mam_channel_num_remaining_sks(channel) == 0) { // TODO // - remove old ch // - create new ch // - add ch via `mam_api_add_channel` // return RC_OK; // } if ((ret = mam_example_write_packet(&api, bundle, av[4], msg_id, last_packet)) != RC_OK) { fprintf(stderr, "mam_example_write_packet failed with err %d\n", ret); return EXIT_FAILURE; } } // Sending bundle if ((ret = send_bundle(av[1], atoi(av[2]), bundle)) != RC_OK) { fprintf(stderr, "send_bundle failed with err %d\n", ret); return EXIT_FAILURE; } // Saving and destroying MAM API if ((ret = mam_api_save(&api, MAM_FILE, NULL, 0)) != RC_OK) { fprintf(stderr, "mam_api_save failed with err %d\n", ret); } if ((ret = mam_api_destroy(&api)) != RC_OK) { fprintf(stderr, "mam_api_destroy failed with err %d\n", ret); return EXIT_FAILURE; } // Cleanup { bundle_transactions_free(&bundle); } return EXIT_SUCCESS; }
448909.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: resther <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/22 14:48:23 by ksinistr #+# #+# */ /* Updated: 2021/05/09 17:03:50 by resther ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" int cut_buf(char *buf, size_t buf_size, size_t n_index) { buf_size = buf_size - n_index; ft_memmove(buf, &buf[n_index + 1], buf_size); buf[buf_size] = '\0'; return (1); } int fill_buf(int fd, char *buf, size_t *buf_size) { int buf_readed; buf_readed = read(fd, buf, BUFFER_SIZE); if (buf_readed <= 0) return (buf_readed); buf[buf_readed] = '\0'; *buf_size = ft_strlen2(buf); return (buf_readed); } int fill_line(size_t *n_index, char *buf, size_t buf_size, char **line) { size_t new_line_size; char *tmp; int line_len; tmp = NULL; *n_index = 0; line_len = ft_strlen2(*line); while (buf[*n_index] != '\n' && *n_index < buf_size) (*n_index)++; new_line_size = line_len + *n_index + 1; if (!(tmp = (char *)ft_calloc2(new_line_size, sizeof(char)))) return (-1); ft_memcpy2(tmp, *line, line_len); ft_memcpy2(&tmp[line_len], buf, *n_index); free(*line); *line = tmp; return (1); } int read_line(int fd, char **line, char *buf, size_t buf_size) { static int buf_readed; size_t n_index; n_index = 0; while (n_index == buf_size) { buf_size = ft_strlen2(buf); if (n_index == buf_size || buf_readed <= 0) { buf_readed = fill_buf(fd, buf, &buf_size); if (buf_readed <= 0) return (buf_readed); } if (fill_line(&n_index, buf, buf_size, line) == -1) return (-1); if (buf_readed < BUFFER_SIZE && n_index == buf_size) { buf_readed = 0; return (0); } } return (cut_buf(buf, buf_size, n_index)); } int get_next_line(int fd, char **line) { static char *buf = NULL; int ret; if (BUFFER_SIZE == 0 || line == NULL) return (-1); if (buf == NULL) { if (!(buf = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char)))) return (-1); buf[0] = '\0'; } if (!(*line = (char *)malloc(sizeof(char)))) return (-1); (*line)[0] = '\0'; ret = read_line(fd, line, buf, 0); if (ret <= 0) { free(buf); buf = NULL; } return (ret); }
972533.c
/*------------------------------------------------------------------------- * * parse_type.c * handle type operations for parser * * Portions Copyright (c) 2006-2008, Greenplum inc * Portions Copyright (c) 2012-Present Pivotal Software, Inc. * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/parser/parse_type.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/htup_details.h" #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "lib/stringinfo.h" #include "nodes/makefuncs.h" #include "parser/parser.h" #include "parser/parse_type.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/datum.h" #include "utils/lsyscache.h" #include "utils/syscache.h" static int32 typenameTypeMod(ParseState *pstate, const TypeName *typeName, Type typ); /* * LookupTypeName * Wrapper for typical case. */ Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok) { return LookupTypeNameExtended(pstate, typeName, typmod_p, true, missing_ok); } /* * LookupTypeNameExtended * Given a TypeName object, lookup the pg_type syscache entry of the type. * Returns NULL if no such type can be found. If the type is found, * the typmod value represented in the TypeName struct is computed and * stored into *typmod_p. * * NB: on success, the caller must ReleaseSysCache the type tuple when done * with it. * * NB: direct callers of this function MUST check typisdefined before assuming * that the type is fully valid. Most code should go through typenameType * or typenameTypeId instead. * * typmod_p can be passed as NULL if the caller does not care to know the * typmod value, but the typmod decoration (if any) will be validated anyway, * except in the case where the type is not found. Note that if the type is * found but is a shell, and there is typmod decoration, an error will be * thrown --- this is intentional. * * If temp_ok is false, ignore types in the temporary namespace. Pass false * when the caller will decide, using goodness of fit criteria, whether the * typeName is actually a type or something else. If typeName always denotes * a type (or denotes nothing), pass true. * * pstate is only used for error location info, and may be NULL. */ Type LookupTypeNameExtended(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool temp_ok, bool missing_ok) { Oid typoid; HeapTuple tup; int32 typmod; if (typeName->names == NIL) { /* We have the OID already if it's an internally generated TypeName */ typoid = typeName->typeOid; } else if (typeName->pct_type) { /* Handle %TYPE reference to type of an existing field */ RangeVar *rel = makeRangeVar(NULL, NULL, typeName->location); char *field = NULL; Oid relid; AttrNumber attnum; /* deconstruct the name list */ switch (list_length(typeName->names)) { case 1: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("improper %%TYPE reference (too few dotted names): %s", NameListToString(typeName->names)), parser_errposition(pstate, typeName->location))); break; case 2: rel->relname = strVal(linitial(typeName->names)); field = strVal(lsecond(typeName->names)); break; case 3: rel->schemaname = strVal(linitial(typeName->names)); rel->relname = strVal(lsecond(typeName->names)); field = strVal(lthird(typeName->names)); break; case 4: rel->catalogname = strVal(linitial(typeName->names)); rel->schemaname = strVal(lsecond(typeName->names)); rel->relname = strVal(lthird(typeName->names)); field = strVal(lfourth(typeName->names)); break; default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("improper %%TYPE reference (too many dotted names): %s", NameListToString(typeName->names)), parser_errposition(pstate, typeName->location))); break; } /* * Look up the field. * * XXX: As no lock is taken here, this might fail in the presence of * concurrent DDL. But taking a lock would carry a performance * penalty and would also require a permissions check. */ relid = RangeVarGetRelid(rel, NoLock, missing_ok); attnum = get_attnum(relid, field); if (attnum == InvalidAttrNumber) { if (missing_ok) typoid = InvalidOid; else ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" of relation \"%s\" does not exist", field, rel->relname), parser_errposition(pstate, typeName->location))); } else { typoid = get_atttype(relid, attnum); /* this construct should never have an array indicator */ Assert(typeName->arrayBounds == NIL); /* emit nuisance notice (intentionally not errposition'd) */ ereport(NOTICE, (errmsg("type reference %s converted to %s", TypeNameToString(typeName), format_type_be(typoid)))); } } else { /* Normal reference to a type name */ char *schemaname; char *typname; /* deconstruct the name list */ DeconstructQualifiedName(typeName->names, &schemaname, &typname); if (schemaname) { /* Look in specific schema only */ Oid namespaceId; namespaceId = LookupExplicitNamespace(schemaname, missing_ok); if (OidIsValid(namespaceId)) typoid = GetSysCacheOid2(TYPENAMENSP, PointerGetDatum(typname), ObjectIdGetDatum(namespaceId)); else typoid = InvalidOid; } else { /* Unqualified type name, so search the search path */ typoid = TypenameGetTypidExtended(typname, temp_ok); } /* If an array reference, return the array type instead */ if (typeName->arrayBounds != NIL) typoid = get_array_type(typoid); } if (!OidIsValid(typoid)) { if (typmod_p) *typmod_p = -1; return NULL; } tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid)); if (!HeapTupleIsValid(tup)) /* should not happen */ elog(ERROR, "cache lookup failed for type %u", typoid); typmod = typenameTypeMod(pstate, typeName, (Type) tup); if (typmod_p) *typmod_p = typmod; return (Type) tup; } /* * LookupTypeNameOid * Given a TypeName object, lookup the pg_type syscache entry of the type. * Returns InvalidOid if no such type can be found. If the type is found, * return its Oid. * * NB: direct callers of this function need to be aware that the type OID * returned may correspond to a shell type. Most code should go through * typenameTypeId instead. * * pstate is only used for error location info, and may be NULL. */ Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok) { Oid typoid; Type tup; tup = LookupTypeName(pstate, typeName, NULL, missing_ok); if (tup == NULL) { if (!missing_ok) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" does not exist", TypeNameToString(typeName)), parser_errposition(pstate, typeName->location))); return InvalidOid; } typoid = HeapTupleGetOid(tup); ReleaseSysCache(tup); return typoid; } /* * typenameType - given a TypeName, return a Type structure and typmod * * This is equivalent to LookupTypeName, except that this will report * a suitable error message if the type cannot be found or is not defined. * Callers of this can therefore assume the result is a fully valid type. */ Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p) { Type tup; tup = LookupTypeName(pstate, typeName, typmod_p, false); if (tup == NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" does not exist", TypeNameToString(typeName)), parser_errposition(pstate, typeName->location))); if (!((Form_pg_type) GETSTRUCT(tup))->typisdefined) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" is only a shell", TypeNameToString(typeName)), parser_errposition(pstate, typeName->location))); return tup; } /* * typenameTypeId - given a TypeName, return the type's OID * * This is similar to typenameType, but we only hand back the type OID * not the syscache entry. */ Oid typenameTypeId(ParseState *pstate, const TypeName *typeName) { Oid typoid; Type tup; tup = typenameType(pstate, typeName, NULL); typoid = HeapTupleGetOid(tup); ReleaseSysCache(tup); return typoid; } /* * typenameTypeIdAndMod - given a TypeName, return the type's OID and typmod * * This is equivalent to typenameType, but we only hand back the type OID * and typmod, not the syscache entry. */ void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p) { Type tup; tup = typenameType(pstate, typeName, typmod_p); *typeid_p = HeapTupleGetOid(tup); ReleaseSysCache(tup); } /* * typenameTypeMod - given a TypeName, return the internal typmod value * * This will throw an error if the TypeName includes type modifiers that are * illegal for the data type. * * The actual type OID represented by the TypeName must already have been * looked up, and is passed as "typ". * * pstate is only used for error location info, and may be NULL. */ static int32 typenameTypeMod(ParseState *pstate, const TypeName *typeName, Type typ) { int32 result; Oid typmodin; Datum *datums; int n; ListCell *l; ArrayType *arrtypmod; ParseCallbackState pcbstate; /* Return prespecified typmod if no typmod expressions */ if (typeName->typmods == NIL) return typeName->typemod; /* * Else, type had better accept typmods. We give a special error message * for the shell-type case, since a shell couldn't possibly have a * typmodin function. */ if (!((Form_pg_type) GETSTRUCT(typ))->typisdefined) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("type modifier cannot be specified for shell type \"%s\"", TypeNameToString(typeName)), parser_errposition(pstate, typeName->location))); typmodin = ((Form_pg_type) GETSTRUCT(typ))->typmodin; if (typmodin == InvalidOid) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("type modifier is not allowed for type \"%s\"", TypeNameToString(typeName)), parser_errposition(pstate, typeName->location))); /* * Convert the list of raw-grammar-output expressions to a cstring array. * Currently, we allow simple numeric constants, string literals, and * identifiers; possibly this list could be extended. */ datums = (Datum *) palloc(list_length(typeName->typmods) * sizeof(Datum)); n = 0; foreach(l, typeName->typmods) { Node *tm = (Node *) lfirst(l); char *cstr = NULL; if (IsA(tm, A_Const)) { A_Const *ac = (A_Const *) tm; if (IsA(&ac->val, Integer)) { cstr = psprintf("%ld", (long) ac->val.val.ival); } else if (IsA(&ac->val, Float) || IsA(&ac->val, String)) { /* we can just use the str field directly. */ cstr = ac->val.val.str; } } else if (IsA(tm, ColumnRef)) { ColumnRef *cr = (ColumnRef *) tm; if (list_length(cr->fields) == 1 && IsA(linitial(cr->fields), String)) cstr = strVal(linitial(cr->fields)); } if (!cstr) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("type modifiers must be simple constants or identifiers"), parser_errposition(pstate, typeName->location))); datums[n++] = CStringGetDatum(cstr); } /* hardwired knowledge about cstring's representation details here */ arrtypmod = construct_array(datums, n, CSTRINGOID, -2, false, 'c'); /* arrange to report location if type's typmodin function fails */ setup_parser_errposition_callback(&pcbstate, pstate, typeName->location); result = DatumGetInt32(OidFunctionCall1(typmodin, PointerGetDatum(arrtypmod))); cancel_parser_errposition_callback(&pcbstate); pfree(datums); pfree(arrtypmod); return result; } /* * appendTypeNameToBuffer * Append a string representing the name of a TypeName to a StringInfo. * This is the shared guts of TypeNameToString and TypeNameListToString. * * NB: this must work on TypeNames that do not describe any actual type; * it is mostly used for reporting lookup errors. */ static void appendTypeNameToBuffer(const TypeName *typeName, StringInfo string) { if (typeName->names != NIL) { /* Emit possibly-qualified name as-is */ ListCell *l; foreach(l, typeName->names) { if (l != list_head(typeName->names)) appendStringInfoChar(string, '.'); appendStringInfoString(string, strVal(lfirst(l))); } } else { /* Look up internally-specified type */ appendStringInfoString(string, format_type_be(typeName->typeOid)); } /* * Add decoration as needed, but only for fields considered by * LookupTypeName */ if (typeName->pct_type) appendStringInfoString(string, "%TYPE"); if (typeName->arrayBounds != NIL) appendStringInfoString(string, "[]"); } /* * TypeNameToString * Produce a string representing the name of a TypeName. * * NB: this must work on TypeNames that do not describe any actual type; * it is mostly used for reporting lookup errors. */ char * TypeNameToString(const TypeName *typeName) { StringInfoData string; initStringInfo(&string); appendTypeNameToBuffer(typeName, &string); return string.data; } /* * TypeNameListToString * Produce a string representing the name(s) of a List of TypeNames */ char * TypeNameListToString(List *typenames) { StringInfoData string; ListCell *l; initStringInfo(&string); foreach(l, typenames) { TypeName *typeName = (TypeName *) lfirst(l); Assert(IsA(typeName, TypeName)); if (l != list_head(typenames)) appendStringInfoChar(&string, ','); appendTypeNameToBuffer(typeName, &string); } return string.data; } /* * LookupCollation * * Look up collation by name, return OID, with support for error location. */ Oid LookupCollation(ParseState *pstate, List *collnames, int location) { Oid colloid; ParseCallbackState pcbstate; if (pstate) setup_parser_errposition_callback(&pcbstate, pstate, location); colloid = get_collation_oid(collnames, false); if (pstate) cancel_parser_errposition_callback(&pcbstate); return colloid; } /* * GetColumnDefCollation * * Get the collation to be used for a column being defined, given the * ColumnDef node and the previously-determined column type OID. * * pstate is only used for error location purposes, and can be NULL. */ Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid) { Oid result; Oid typcollation = get_typcollation(typeOid); int location = coldef->location; if (coldef->collClause) { /* We have a raw COLLATE clause, so look up the collation */ location = coldef->collClause->location; result = LookupCollation(pstate, coldef->collClause->collname, location); } else if (OidIsValid(coldef->collOid)) { /* Precooked collation spec, use that */ result = coldef->collOid; } else { /* Use the type's default collation if any */ result = typcollation; } /* Complain if COLLATE is applied to an uncollatable type */ if (OidIsValid(result) && !OidIsValid(typcollation)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("collations are not supported by type %s", format_type_be(typeOid)), parser_errposition(pstate, location))); return result; } /* return a Type structure, given a type id */ /* NB: caller must ReleaseSysCache the type tuple when done with it */ Type typeidType(Oid id) { HeapTuple tup; tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(id)); if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for type %u", id); return (Type) tup; } /* given type (as type struct), return the type OID */ Oid typeTypeId(Type tp) { if (tp == NULL) /* probably useless */ elog(ERROR, "typeTypeId() called with NULL type struct"); return HeapTupleGetOid(tp); } /* given type (as type struct), return the length of type */ int16 typeLen(Type t) { Form_pg_type typ; typ = (Form_pg_type) GETSTRUCT(t); return typ->typlen; } /* given type (as type struct), return its 'byval' attribute */ bool typeByVal(Type t) { Form_pg_type typ; typ = (Form_pg_type) GETSTRUCT(t); return typ->typbyval; } /* given type (as type struct), return the type's name */ char * typeTypeName(Type t) { Form_pg_type typ; typ = (Form_pg_type) GETSTRUCT(t); /* pstrdup here because result may need to outlive the syscache entry */ return pstrdup(NameStr(typ->typname)); } /* given type (as type struct), return its 'typrelid' attribute */ Oid typeTypeRelid(Type typ) { Form_pg_type typtup; typtup = (Form_pg_type) GETSTRUCT(typ); return typtup->typrelid; } /* given type (as type struct), return its 'typcollation' attribute */ Oid typeTypeCollation(Type typ) { Form_pg_type typtup; typtup = (Form_pg_type) GETSTRUCT(typ); return typtup->typcollation; } /* * Given a type structure and a string, returns the internal representation * of that string. The "string" can be NULL to perform conversion of a NULL * (which might result in failure, if the input function rejects NULLs). */ Datum stringTypeDatum(Type tp, char *string, int32 atttypmod) { Form_pg_type typform = (Form_pg_type) GETSTRUCT(tp); Oid typinput = typform->typinput; Oid typioparam = getTypeIOParam(tp); Datum result; result = OidInputFunctionCall(typinput, string, typioparam, atttypmod); #ifdef RANDOMIZE_ALLOCATED_MEMORY /* * For pass-by-reference data types, repeat the conversion to see if the * input function leaves any uninitialized bytes in the result. We can * only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is enabled, so * we don't bother testing otherwise. The reason we don't want any * instability in the input function is that comparison of Const nodes * relies on bytewise comparison of the datums, so if the input function * leaves garbage then subexpressions that should be identical may not get * recognized as such. See pgsql-hackers discussion of 2008-04-04. */ if (string && !typform->typbyval) { Datum result2; result2 = OidInputFunctionCall(typinput, string, typioparam, atttypmod); if (!datumIsEqual(result, result2, typform->typbyval, typform->typlen)) elog(WARNING, "type %s has unstable input conversion for \"%s\"", NameStr(typform->typname), string); } #endif return result; } /* given a typeid, return the type's typrelid (associated relation, if any) */ Oid typeidTypeRelid(Oid type_id) { HeapTuple typeTuple; Form_pg_type type; Oid result; typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_id)); if (!HeapTupleIsValid(typeTuple)) elog(ERROR, "cache lookup failed for type %u", type_id); type = (Form_pg_type) GETSTRUCT(typeTuple); result = type->typrelid; ReleaseSysCache(typeTuple); return result; } /* * error context callback for parse failure during parseTypeString() */ static void pts_error_callback(void *arg) { const char *str = (const char *) arg; errcontext("invalid type name \"%s\"", str); /* * Currently we just suppress any syntax error position report, rather * than transforming to an "internal query" error. It's unlikely that a * type name is complex enough to need positioning. */ errposition(0); } /* * Given a string that is supposed to be a SQL-compatible type declaration, * such as "int4" or "integer" or "character varying(32)", parse * the string and convert it to a type OID and type modifier. * If missing_ok is true, InvalidOid is returned rather than raising an error * when the type name is not found. */ void parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p, bool missing_ok) { StringInfoData buf; List *raw_parsetree_list; SelectStmt *stmt; ResTarget *restarget; TypeCast *typecast; TypeName *typeName; ErrorContextCallback ptserrcontext; Type tup; /* make sure we give useful error for empty input */ if (strspn(str, " \t\n\r\f") == strlen(str)) goto fail; initStringInfo(&buf); appendStringInfo(&buf, "SELECT NULL::%s", str); /* * Setup error traceback support in case of ereport() during parse */ ptserrcontext.callback = pts_error_callback; ptserrcontext.arg = (void *) str; ptserrcontext.previous = error_context_stack; error_context_stack = &ptserrcontext; raw_parsetree_list = raw_parser(buf.data); error_context_stack = ptserrcontext.previous; /* * Make sure we got back exactly what we expected and no more; paranoia is * justified since the string might contain anything. */ if (list_length(raw_parsetree_list) != 1) goto fail; stmt = (SelectStmt *) linitial(raw_parsetree_list); if (stmt == NULL || !IsA(stmt, SelectStmt) || stmt->distinctClause != NIL || stmt->intoClause != NULL || stmt->fromClause != NIL || stmt->whereClause != NULL || stmt->groupClause != NIL || stmt->havingClause != NULL || stmt->windowClause != NIL || stmt->valuesLists != NIL || stmt->sortClause != NIL || stmt->limitOffset != NULL || stmt->limitCount != NULL || stmt->lockingClause != NIL || stmt->withClause != NULL || stmt->op != SETOP_NONE) goto fail; if (list_length(stmt->targetList) != 1) goto fail; restarget = (ResTarget *) linitial(stmt->targetList); if (restarget == NULL || !IsA(restarget, ResTarget) || restarget->name != NULL || restarget->indirection != NIL) goto fail; typecast = (TypeCast *) restarget->val; if (typecast == NULL || !IsA(typecast, TypeCast) || typecast->arg == NULL || !IsA(typecast->arg, A_Const)) goto fail; typeName = typecast->typeName; if (typeName == NULL || !IsA(typeName, TypeName)) goto fail; if (typeName->setof) goto fail; tup = LookupTypeName(NULL, typeName, typmod_p, missing_ok); if (tup == NULL) { if (!missing_ok) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" does not exist", TypeNameToString(typeName)), parser_errposition(NULL, typeName->location))); *typeid_p = InvalidOid; } else { if (!((Form_pg_type) GETSTRUCT(tup))->typisdefined) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" is only a shell", TypeNameToString(typeName)), parser_errposition(NULL, typeName->location))); *typeid_p = HeapTupleGetOid(tup); ReleaseSysCache(tup); } pfree(buf.data); return; fail: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("invalid type name \"%s\"", str))); }
269931.c
/* ******************************************************************************* * Copyright (c) 2020, STMicroelectronics * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* * Automatically generated from STM32L476R(C-E-G)Tx.xml */ #include "Arduino.h" #include "PeripheralPins.h" /* ===== * Note: Commented lines are alternative possibilities which are not used per default. * If you change them, you will have to know what you do * ===== */ //*** ADC *** #ifdef HAL_ADC_MODULE_ENABLED WEAK const PinMap PinMap_ADC[] = { {PA_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 // {PA_0, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 {PA_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 // {PA_1, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 // {PA_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 - STLink Tx // {PA_2, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 - STLink Tx // {PA_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 - STLink Rx // {PA_3, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // ADC2_IN8 - STLink Rx {PA_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 // {PA_4, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 9, 0)}, // ADC2_IN9 // {PA_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10 - LED // {PA_5, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 10, 0)}, // ADC2_IN10 {PA_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 11, 0)}, // ADC1_IN11 // {PA_6, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 11, 0)}, // ADC2_IN11 {PA_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12 // {PA_7, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 12, 0)}, // ADC2_IN12 {PB_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 // {PB_0, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 15, 0)}, // ADC2_IN15 // {PB_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16 // {PB_1, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 16, 0)}, // ADC2_IN16 {PC_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 // {PC_0, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 1, 0)}, // ADC2_IN1 // {PC_0, ADC3, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 1, 0)}, // ADC3_IN1 {PC_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 // {PC_1, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 2, 0)}, // ADC2_IN2 // {PC_1, ADC3, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 2, 0)}, // ADC3_IN2 {PC_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // {PC_2, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 3, 0)}, // ADC2_IN3 // {PC_2, ADC3, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 3, 0)}, // ADC3_IN3 {PC_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 // {PC_3, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // ADC2_IN4 // {PC_3, ADC3, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // ADC3_IN4 {PC_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 // {PC_4, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 13, 0)}, // ADC2_IN13 {PC_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 // {PC_5, ADC2, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 14, 0)}, // ADC2_IN14 {NC, NP, 0} }; #endif //*** DAC *** #ifdef HAL_DAC_MODULE_ENABLED WEAK const PinMap PinMap_DAC[] = { {PA_4, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC1_OUT1 {PA_5, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC1_OUT2 - LED {NC, NP, 0} }; #endif //*** I2C *** #ifdef HAL_I2C_MODULE_ENABLED WEAK const PinMap PinMap_I2C_SDA[] = { {PB_7, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_9, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_11, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PB_14, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PC_1, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {NC, NP, 0} }; #endif #ifdef HAL_I2C_MODULE_ENABLED WEAK const PinMap PinMap_I2C_SCL[] = { {PB_6, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_8, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_10, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PB_13, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PC_0, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {NC, NP, 0} }; #endif //*** PWM *** #ifdef HAL_TIM_MODULE_ENABLED WEAK const PinMap PinMap_PWM[] = { {PA_0, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // {PA_0, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 - (used by us_ticker) {PA_1, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 - (used by us_ticker) // {PA_1, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N // {PA_2, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 - STLink Tx // {PA_2, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 - (used by us_ticker) // {PA_2, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 - STLink Tx // {PA_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 - STLink Rx // {PA_3, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 - (used by us_ticker) // {PA_3, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 - STLink Rx {PA_5, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // {PA_5, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // {PA_6, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 // {PA_7, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N {PA_7, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 // {PA_7, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N // {PA_7, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1 {PA_8, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 {PA_9, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 {PA_10, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 {PA_11, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 4, 0)}, // TIM1_CH4 {PA_15, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // {PB_0, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N {PB_0, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 // {PB_0, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N // {PB_1, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N // {PB_1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 // {PB_1, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PB_5, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_6, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 1)}, // TIM16_CH1N {PB_7, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 // {PB_7, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 1)}, // TIM17_CH1N {PB_8, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 // {PB_8, TIM16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM16, 1, 0)}, // TIM16_CH1 {PB_9, TIM4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4 // {PB_9, TIM17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM17, 1, 0)}, // TIM17_CH1 {PB_10, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 {PB_11, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 {PB_13, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N // {PB_13, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)}, // TIM15_CH1N {PB_14, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N // {PB_14, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N // {PB_14, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)}, // TIM15_CH1 {PB_15, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 1)}, // TIM1_CH3N // {PB_15, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N // {PB_15, TIM15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)}, // TIM15_CH2 // {PC_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PC_6, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 0)}, // TIM8_CH1 // {PC_7, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PC_7, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 0)}, // TIM8_CH2 // {PC_8, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 {PC_8, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 0)}, // TIM8_CH3 // {PC_9, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 {PC_9, TIM8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 4, 0)}, // TIM8_CH4 {NC, NP, 0} }; #endif //*** SERIAL *** #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_TX[] = { {PA_0, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, {PA_2, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PB_11, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_1, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_4, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_10, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, // {PC_10, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_12, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_RX[] = { {PA_1, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, {PA_3, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_7, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PB_11, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_0, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_5, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_11, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, // {PC_11, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PD_2, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_RTS[] = { {PA_1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_12, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // {PA_15, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, // {PB_1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // {PB_3, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // {PB_4, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, // {PB_12, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // {PB_14, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // {PD_2, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_CTS[] = { {PA_0, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // {PA_6, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PA_11, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // {PB_4, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, // {PB_5, UART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART5)}, // {PB_7, UART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, // {PB_13, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // {PB_13, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {NC, NP, 0} }; #endif //*** SPI *** #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_MOSI[] = { {PA_7, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, {PB_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_5, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_15, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_12, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_MISO[] = { {PA_6, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, {PB_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_4, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_14, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_2, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_11, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_SCLK[] = { {PA_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // LED {PB_3, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_3, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_10, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PB_13, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_10, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_SSEL[] = { {PA_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PA_4, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PA_15, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PA_15, SPI3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_9, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PB_12, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {NC, NP, 0} }; #endif //*** CAN *** #ifdef HAL_CAN_MODULE_ENABLED WEAK const PinMap PinMap_CAN_RD[] = { {PA_11, CAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_8, CAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NP, 0} }; #endif #ifdef HAL_CAN_MODULE_ENABLED WEAK const PinMap PinMap_CAN_TD[] = { {PA_12, CAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_9, CAN1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NP, 0} }; #endif //*** No ETHERNET *** //*** QUADSPI *** #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_DATA0[] = { {PB_1, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO0 {NC, NP, 0} }; #endif #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_DATA1[] = { {PB_0, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO1 {NC, NP, 0} }; #endif #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_DATA2[] = { {PA_7, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO2 {NC, NP, 0} }; #endif #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_DATA3[] = { {PA_6, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_BK1_IO3 {NC, NP, 0} }; #endif #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_SCLK[] = { {PB_10, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_CLK {NC, NP, 0} }; #endif #ifdef HAL_QSPI_MODULE_ENABLED WEAK const PinMap PinMap_QUADSPI_SSEL[] = { {PB_11, QUADSPI, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_QUADSPI)}, // QUADSPI_NCS {NC, NP, 0} }; #endif //*** USB *** #ifdef HAL_PCD_MODULE_ENABLED WEAK const PinMap PinMap_USB_OTG_FS[] = { {PA_8, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_SOF {PA_9, USB_OTG_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_OTG_FS_VBUS {PA_10, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_ID {PA_11, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_DM {PA_12, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_DP // {PA_13, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_NOE {PC_9, USB_OTG_FS, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_OTG_FS)}, // USB_OTG_FS_NOE {NC, NP, 0} }; #endif //*** No USB_OTG_HS *** //*** SD *** #ifdef HAL_SD_MODULE_ENABLED WEAK const PinMap PinMap_SD[] = { {PB_8, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D4 {PB_9, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D5 {PC_6, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D6 {PC_7, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D7 {PC_8, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D0 {PC_9, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D1 {PC_10, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D2 {PC_11, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF12_SDMMC1)}, // SDMMC1_D3 {PC_12, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC1)}, // SDMMC1_CK {PD_2, SDMMC1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_SDMMC1)}, // SDMMC1_CMD {NC, NP, 0} }; #endif
78780.c
#include "Fecha.h" #include <stdio.h> Fecha initFecha(int dia, int mes, int ano) { Fecha fecha; fecha.dia = dia; fecha.mes = mes; fecha.ano = ano; return fecha; } // devuelve -1 si f1 es mayor que f2 // devuelve 1 si f2 es mayor que f1 // devuelve 0 si f1 es igual a f2 int Fecha_Cmp(Fecha f1, Fecha f2) { if (f1.ano < f2.ano) return 1; else if (f1.ano > f2.ano) return -1; else { if (f1.mes < f2.mes) return 1; else if (f1.mes > f2.mes) return -1; else { if (f1.dia < f2.dia) return 1; else if (f1.dia > f2.dia) return -1; else return 0; } } } void Fecha_Print(Fecha fecha) { printf("%d/%d/%d", fecha.dia, fecha.mes, fecha.ano); }
148154.c
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <stdint.h> #include <sys/param.h> #include "error/s2n_errno.h" #include "tls/s2n_tls_parameters.h" #include "tls/s2n_connection.h" #include "tls/s2n_record.h" #include "tls/s2n_resume.h" #include "tls/s2n_alerts.h" #include "utils/s2n_safety.h" #include "utils/s2n_blob.h" #define S2N_TLS_ALERT_CLOSE_NOTIFY 0 #define S2N_TLS_ALERT_UNEXPECTED_MSG 10 #define S2N_TLS_ALERT_BAD_RECORD_MAC 20 #define S2N_TLS_ALERT_DECRYPT_FAILED 21 #define S2N_TLS_ALERT_RECORD_OVERFLOW 22 #define S2N_TLS_ALERT_DECOMP_FAILED 30 #define S2N_TLS_ALERT_HANDSHAKE_FAILURE 40 #define S2N_TLS_ALERT_NO_CERTIFICATE 41 #define S2N_TLS_ALERT_BAD_CERTIFICATE 42 #define S2N_TLS_ALERT_UNSUPPORTED_CERT 43 #define S2N_TLS_ALERT_CERT_REVOKED 44 #define S2N_TLS_ALERT_CERT_EXPIRED 45 #define S2N_TLS_ALERT_CERT_UNKNOWN 46 #define S2N_TLS_ALERT_ILLEGAL_PARAMETER 47 #define S2N_TLS_ALERT_UNKNOWN_CA 48 #define S2N_TLS_ALERT_ACCESS_DENIED 49 #define S2N_TLS_ALERT_DECODE_ERROR 50 #define S2N_TLS_ALERT_DECRYPT_ERROR 51 #define S2N_TLS_ALERT_EXPORT_RESTRICTED 60 #define S2N_TLS_ALERT_PROTOCOL_VERSION 70 #define S2N_TLS_ALERT_INSUFFICIENT_SECURITY 71 #define S2N_TLS_ALERT_INTERNAL_ERROR 80 #define S2N_TLS_ALERT_USER_CANCELED 90 #define S2N_TLS_ALERT_NO_RENEGOTIATION 100 #define S2N_TLS_ALERT_UNSUPPORTED_EXTENSION 110 #define S2N_TLS_ALERT_LEVEL_WARNING 1 #define S2N_TLS_ALERT_LEVEL_FATAL 2 static bool s2n_alerts_supported(struct s2n_connection *conn) { /* If running in QUIC mode, QUIC handles alerting. * S2N should not send or receive alerts. */ return conn && conn->config && !conn->config->quic_enabled; } static bool s2n_handle_as_warning(struct s2n_connection *conn, uint8_t level, uint8_t type) { /* Only TLS1.2 considers the alert level. The alert level field is * considered deprecated in TLS1.3. */ if (s2n_connection_get_protocol_version(conn) < S2N_TLS13) { return level == S2N_TLS_ALERT_LEVEL_WARNING && conn->config->alert_behavior == S2N_ALERT_IGNORE_WARNINGS; } /* user_canceled is the only alert currently treated as a warning in TLS1.3. * We need to treat it as a warning regardless of alert_behavior to avoid marking * correctly-closed connections as failed. */ return type == S2N_TLS_ALERT_USER_CANCELED; } int s2n_process_alert_fragment(struct s2n_connection *conn) { POSIX_ENSURE_REF(conn); S2N_ERROR_IF(s2n_stuffer_data_available(&conn->in) == 0, S2N_ERR_BAD_MESSAGE); S2N_ERROR_IF(s2n_stuffer_data_available(&conn->alert_in) == 2, S2N_ERR_ALERT_PRESENT); POSIX_ENSURE(s2n_alerts_supported(conn), S2N_ERR_BAD_MESSAGE); while (s2n_stuffer_data_available(&conn->in)) { uint8_t bytes_required = 2; /* Alerts are two bytes long, but can still be fragmented or coalesced */ if (s2n_stuffer_data_available(&conn->alert_in) == 1) { bytes_required = 1; } int bytes_to_read = MIN(bytes_required, s2n_stuffer_data_available(&conn->in)); POSIX_GUARD(s2n_stuffer_copy(&conn->in, &conn->alert_in, bytes_to_read)); if (s2n_stuffer_data_available(&conn->alert_in) == 2) { /* Close notifications are handled as shutdowns */ if (conn->alert_in_data[1] == S2N_TLS_ALERT_CLOSE_NOTIFY) { conn->closed = 1; conn->close_notify_received = true; return 0; } /* Ignore warning-level alerts if we're in warning-tolerant mode */ if (s2n_handle_as_warning(conn, conn->alert_in_data[0], conn->alert_in_data[1])) { POSIX_GUARD(s2n_stuffer_wipe(&conn->alert_in)); return 0; } /* RFC 5077 5.1 - Expire any cached session on an error alert */ if (s2n_allowed_to_cache_connection(conn) && conn->session_id_len) { conn->config->cache_delete(conn, conn->config->cache_delete_data, conn->session_id, conn->session_id_len); } /* All other alerts are treated as fatal errors */ conn->closed = 1; POSIX_BAIL(S2N_ERR_ALERT); } } return 0; } int s2n_queue_writer_close_alert_warning(struct s2n_connection *conn) { POSIX_ENSURE_REF(conn); uint8_t alert[2]; alert[0] = S2N_TLS_ALERT_LEVEL_WARNING; alert[1] = S2N_TLS_ALERT_CLOSE_NOTIFY; struct s2n_blob out = {.data = alert,.size = sizeof(alert) }; /* If there is an alert pending or we've already sent a close_notify, do nothing */ if (s2n_stuffer_data_available(&conn->writer_alert_out) || conn->close_notify_queued) { return S2N_SUCCESS; } if (!s2n_alerts_supported(conn)) { return S2N_SUCCESS; } POSIX_GUARD(s2n_stuffer_write(&conn->writer_alert_out, &out)); conn->close_notify_queued = 1; return S2N_SUCCESS; } static int s2n_queue_reader_alert(struct s2n_connection *conn, uint8_t level, uint8_t error_code) { POSIX_ENSURE_REF(conn); uint8_t alert[2]; alert[0] = level; alert[1] = error_code; struct s2n_blob out = {.data = alert,.size = sizeof(alert) }; /* If there is an alert pending, do nothing */ if (s2n_stuffer_data_available(&conn->reader_alert_out)) { return S2N_SUCCESS; } if (!s2n_alerts_supported(conn)) { return S2N_SUCCESS; } POSIX_GUARD(s2n_stuffer_write(&conn->reader_alert_out, &out)); return S2N_SUCCESS; } int s2n_queue_reader_unsupported_protocol_version_alert(struct s2n_connection *conn) { return s2n_queue_reader_alert(conn, S2N_TLS_ALERT_LEVEL_FATAL, S2N_TLS_ALERT_PROTOCOL_VERSION); } int s2n_queue_reader_handshake_failure_alert(struct s2n_connection *conn) { return s2n_queue_reader_alert(conn, S2N_TLS_ALERT_LEVEL_FATAL, S2N_TLS_ALERT_HANDSHAKE_FAILURE); }
660119.c
/* Fontname: -FreeType-FreeUniversal-Medium-R-Normal--34-340-72-72-P-161-ISO10646-1 Copyright: (FreeUniversal) Copyright (c) Stephen Wilson 2009 a modification of: Original Font (SIL Sophia) Copyright (c) SIL International, 1994-2008. Glyphs: 189/243 BBX Build Mode: 0 */ const uint8_t u8g2_font_fur25_tf[7403] U8G2_FONT_SECTION("u8g2_font_fur25_tf") = "\275\0\4\3\5\6\5\6\7!-\377\367\31\371\32\373\4f\11\211\34\316 \6\0\200\240\22!\13#" "\243 \23\376\7\221\7\2\42\33K\221\357\23h(\206&\206&\206&\206&\206&\206&\244D\244D" "\244$\0#=\66\223`\66\207\206\207\206\245\204\207\206\207\206\245\244\245\344\16\16L\16\16\12\245\204\207" "\206\207\244\245\204\207\346\16\16j\16\16\352\206\206\207\206\245\244\245\204\207\206\207\206\245\204\207\206\207F\1" "$B\60\214\234\364\304\265=\210;\230:\250!\21!\231\221\31\231\221\31\231\221\31\231\21\234\21$\221" "<=\20<\230<\10\24\251\223\241\23\62\22\62\22\62\22\272\21\232 \221\241\70\270\71(;\210\25\327" "\16\0%V|\223 \370\241\346A%M%\17\42\5I\350\4\211\310\4\307\246$\307\206&\307\206D" "\307fF\251f\204\207f\246\17d\344\1\214\204\354!d\16\302eH\250E\210he\306Fg\306F" "\205\306&\207\306&\245\306\6\247\306\6\305\210\350\4I\10%\17\2em\0&A\67\223\240\326\354\1" "\16\206i\210\307f\307f\307f\247\206i\250\17\344\1\354!\354\306\16\302\246(\310\206h\250f\250\210" "f\346h\26R\14M\36\215\32\221\222QV\225\35D\35\134P\35\320\224\235\25'\14D\241o\23(" "\366\205\210\12\0(\27\346\233\33\223dfd\326\310\354\204df\377\206fG\63C\252\4)\30\346\233" "\33\23\244\204\204f\206f\266\241\331\377\311\314\66\62kdf\0*\37\256\241\254u\204\304F\306F\346" "D$\251HD\16\236\220LQ\212\310\215L\221\214\11\311\0+.\264\272\240\70\345a\344a\344a\344" "a\344a\344a\344a\344a$\17~P)\17#\17#\17#\17#\17#\17#\17#\17#\17#" "\11,\17&\221\134R(HHfFf\326\10\1-\10h\210\247\22>\30.\10\203\230`\22\16\12" "/ \212\223^\23\345\346\4\345\346\4\325\315\11\312\315\11\312\255\23\224\233\23\224['(\67'(\10" "\60%/\223\340\264\12\17\244\16h\250H\346F\346&\350.\375/\17'\346(\346F\310f\210h\16" "\250\16\4\253\0\61\21)\243\340\264\210jL\16*N\212\306\366\377\37\62\37/\223\340\264\354\16\244\16" "h\212H\310(\6\17\207\327\222\322\316\222\362\264\262)\267\7\37\10\63&\60\223\340\264\14\17\246hj" "\310H\6G\6\247\27\317R\232\32\227SOSO_>\34!\243)\251:\30\264\2\64&\61\213\340" "T\211\333\232\236NL\216L\216\14\316\314\15\315\15\215M-\233\32\33\232\233\31\234\71\370\7\262\343{" "\3\65'/\223\340\64\16L\16L\16L\206\367\304\350\240\246\210\204ld\216Brx\307\206\7q#" "c$\65D\7sV\0\66\60\60\213\340\264\14\17\246\210h\310H\6G\6'\210\247\327\30\215\34\210" "L\34\214XQ\324M\20\36D~\71\61\71A\67\63\67SCv h\5\67\35/\223\340\24~ " "<K;<K;<K;\313v\226\355,\355,\333Y\266\203\0\70/\60\213\340\264\14\17\246\210h" "\310H\6G\6G\6G\6g\306\206\230\35\4\36\204\325L\215\315\14N\214\372\364\220\202n\206\210\352" "`\320\12\0\71,\60\223\340\224\16\17\210\330\314Q\20NL\376 \220b\220\202\312\344`b\350dz" "c\212\301\221\301\221\71\222\61\42\32\262\3\301+\0:\13C\232`\22\16\352\21\34\24;\22\306\212\134" "Rf\266\307\230df\311\314\32\231\31\0<%u\272\241\370\241\342a\346\1\252\255\253\255\233\327C\310" "\3\325\303\324\3\325\303\330\303\324\3\325\303\330\303\314C\5=\15\24\271\246\30\376\240\36\257\16~P>" "\42\65\272\242\30\346a\354a\352a\354a\352\201\352a\352\201\352a\346!\252\253\255\253\255\333C\314\303" "\0\77\32/\213\240\224\354\16\206\16L\306(\6\211\267\235\245\35\345\355\360\356\21o\7@b\336\223\233" "x\17\344a\16\16\242\17\16h\15\17\253\313\350A\210\350\201\226\225\14\221\214]L\215L\221XMP" "MQ]\61\263\232\33\263\232\33\263\232\33\263\232\33\263\232\33\263\232\233\232 \32\243\32\231\232\42\42\231" "\242\271\240\241:\210\70\210\32+\62\243\7\246\7\256\207\265\7=\70\210\7\71\260\207:\20\5AA\70" "\213\240V\351\201\352\201\354A\356A&\346A&\350\1H\346\1f\250\211\246\247h\251h\347f\347(" "\11''\351\16\16\346\16\16\346\16\16\250\210\247\246i\310g\346\1H\346\1(\350!\326\203\20B\70" "\62\233\340\25\16\254\16\16b\16\16D&+F)f'f'f'F)&I\16\16b\16\216\16" "\16b&If'f\217\275==\210\254\70\70\20\71\70\210\71\260\2C\67\63\223\340\365N\17\310\252" "\210(gF)h'\206'\346\1\350\1\346!\346!\346!\346!\346!\346!\346!\346A\346!\206" "'\206GFI(\207\252\310\16J\257\0D.\64\233`\26\16\12\17\16\242\16\16\204\6mFKf" "I\206)\246'\246\237\373\365\353\211a\212Y\222\321\222A\233\203\3\241\203\263\203B\0E \60\233`" "\25\36D\34\34D\34\34DL\357\327\7\7\21\7\7\21\7\7\21\323\373\365\301\37\30F\25/\233 " "\25\376\201\361~|pqpqp\61\274\377\30\0G:\65\223\240\26\217\17\352\16\16\242\314jhI" "\246'\350A\346A\350A\346a\346a&\17*\17*\17\352\1\316\317'\306'\250G\210Gjg\354" "\212\16\16\246\16\16\42\17\204\0H\20\62\233 \26\206\375\37\37\374\7\304\376\217\7I\11#\233`\22" "\376\37\24J\25.\223\340t\367\377o\15\15\317(\210H\16\210\16\344\214\0K\67\62\233\340\25F)" "&I\6i\346\210\306\250\246\310\206\350f\10G('Ho\17B'*G(G\12g\352\206\312\246" "\252\306\250\346\210\346j\6K&+F\17b\11L\16/\233\340\24\206\367\377\377\370\340\17\6MI\71" "\233\340\27\352\1\16\250\17\252\17\252\17$f',f',()L&GL&GL\350Hl\346" "fl\346f\214\246\206\214\246\206\214\246\206\254f\246\254f\246\254(\250\314&\306\314&\306\314\316\354\352" "\354\352\14\7\15\27N\67\63\233`\26j\17b\17D\17&\17&-\10-\10M\350L\350l\310l" "\310\214\250\254\246\254\210\314h\314h\354H\354H\14)\14),\17&\17F\17d\17b\13O\70\66" "\223\240\366\16\202\17*\17\356\312\252Hi\210I\306G\306'\310\357!\354!\354!\354!\354!\354!" "\354\1(\306G\306G\210i\206\207H\251\312\352\16.\17\252\15\1P \60\233`\25\16\250\16N\16" "\16\42\6)&O}yHqp\20qpr@\65\275\377\32\0QB\70\223\340\366\16\302\17j\17" ".\313\352H\251\210\211\306\207\306g\310I\346!F\346!F\346!F\346!F\346!F\346!F\346" "\1h\306i\306\207\210\251\206\307H\351\312*\17.\252\16\16\12\17\16\4R\71\61\233`\25\16\252\16" "n\16\16B\6+&)F'F'F'&)\6I\16n\16\252\16n\346h\6I&G&G" "&G&)F'F'F'F'F'F\11S\60\62\223\240\325.\17\310\16\214\310h\10IF" "GFG\346\1\310\313\217\17F\17\206\17\302\351\1\350\1\214\215o'F)\312j\16\256\16\12\317\0" "T\65\63\213`\25\376\7\201\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363" "\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\363\20\203\0U\32\63\233`\26\246\375\377\327\307" "\267\24\263#\224\64e\65\7\7Q\7\226g\0V\67\65\213\240\25\250\17\202)\210IhIHiH" "\211(\247\10\251\10\311\6\347\310\10\307\10\307&\211H\207H\207fI\210G\210G\246\17\302\317\355\1" "\354!\352!(\1WW\77\213`\30FK/K/+)&+)\6'\6G\350&\346H\350&" "\346h\346&\310\206\306f\306\206\250f\246\250\326LQ\15\21-\33\232\32\32\243\231\232\241\233\231\232\31" "\34\231\33\31\34\231\33\231\234\230\233\30\235\230\233\30\265\64\265\264\255,.%\246\245\236\235\3X\67\66" "\213 \66jiH\251\10\311\352\230Q\22\221\22\321\222PS\214\37\304\3\330\203\320\203\330C\330\3L" "P\223\20\317\320\22Q\222\21\316\61\244\242,\232\245!\246\240.Y\66\65\213\340\25\250)\210Ghi" "(\251\10\251\350\230\15RQ\22\315\316\320\222L\237\337\3\324\203\320\203\314\303\314\303\314\303\314\303\314\303" "\314\303\314\303\314\303\314\303L\2Z!\62\223\240\65\16\16&\16\16&\16\16\306\251\251\213\253Y\27W" "\263.nM]\334\232\371\301\77([\16\7\244\231\23\36\14\355\377\377\177tp\134\32\212\223^\23\4" "\5\347\6\25\16*\234\33T\70\250pP\303A\205\203\32\16]\16\7\234\231\23\36\355\377\377\177tp" "\60^,\262\302\240\30\345\1\310Y\213\10\213\10\7\305\12\211\12I\212\11\212\11\212\311\11\212\11\212\11" "J\211\12\211\312\314\212\10\213\10K\210\13_\10Q\200[\24~``\13\306\200\65\22f\206\26I\11" "a%O\222\340\224\16\242\16j\210H\310(\6\207\27\35\220\34X\224M\14Z\32>\10\253\240\231\30" "\71\220\30\252\31b%\60\223 \25\246\367\33\243\211\3\231\211\221f\24\204\23\204\247~y\20\70A\70" "Q\66rR\62q \63S\5c\36N\222\240\224\256\16fjH\306(\346\356l\367\226nbnb" "\214\204\206\350@\354\6\0d%\60\223 \265\367#\233\231\3\211\21\232\13\262\212\271\212\301\313S\237N" "\14R\14\222\214\225\324\30\35DL\325\14e&P\222\340\264\14\17\246hj\310H\6'\10'&'" "\16\16\42\16\16\252\227\17\216\14\216\220\321\224T\35\14Z\1f\24+\213 \263\214nJb\6\267:" "x\20\63\270\377_\1g.\60\223\31\265Lf\16$Fh.\310*\6\17\2O\375\364\220b\220\202" "\254\244\344\346@b\310fz\230bp\204\214\206\210\352`\320\12\0h\26/\223\340\24\206\367\33\233\211" "\3\21\233\212\262\11\272K\377_\16i\14#\223\340\21\16\204\17\376A\1j\21\6\214Yr\266\7\236" "\331\377\377\233\203\10\22\0k).\223`\24f\367\63\212)\222!\232\241\65D#T\23dww\23" "d#T#T\63DC\64C\64S$c\24s\4l\11#\223 \22\376\37\24m\62Z\222\240\27" "f\312l&\16b\16Dl(f*\252\314&\350\350\16'\15'\15'\15'\15'\15'\15'\15" "'\15'\15'\15'\15'\15'\7n\24O\222\340\24fl&\16Dl*\312\16\342.\375\177\71" "o!Q\222`\265\16\17\250jj\350H&'(\17\42o\275\275<\210\244\230\34\241\243iu@x" "\5p%\60\223\31\25f\214F\16bnH\312(\10'\10O\375\364\360 p\242\214\342\244d\342@" "f\306hz_\3q#\60\223Y\265jf\16$Fj,\310*\6\17\2O\375\364\220b\220\202\254" "\244\344\346@b\252fz\77r\21J\222 \23F\16\42\16l\252\310\346\366\177\7s!N\222\240t" "\256\16hh*\310&\346&fi-\17\344\16DKi\15\317(hj\16\246\216\0t\22\312\212!" "s\346\66:\70\260\231\333\377\35\235U\1u\24O\222\340\24&\375\177yw\20VQcr \61c" "\63v#P\212\240\24F/\17)\6G\350f\306h\306\206\250\26\215\321\314\315\314\215\14RL\232\332" "\326\22\223\1w:Z\212 \27\6\11\355\352\356\314F\306\314F\246&\306F\246F\244\206\226\14m\62" "\264f\63\231\241\221\261\221\241\221\261\211\251\221\261\211\61\211A\63\303:\303BRBRB*\0x$" "Q\212\340\64&G\350\206\250\30\215\321\14R\214\336\26S\327\232\36D\216\320\15QQ\15\221\321\14R" "P\22y)\60\213\231\24F/'\6)\6G\350f\306h\250vDE\63\67\63G\61\71\61yi" "\333xzxz\230xz\230\20\0z\30M\222`\64\16*\16*)'\11Y\22\62,\344\222\220\362" "\340A\1{\34k\234X\364\310\252\310\350\6\367wtsTet\205\204\203\204\373\227\203\204u\4|" "\11\242\254\27\23\376\37\20}\36k\234X\24\350\12\11'\7\367\207\204\203\204udUtst\203\373" "\273\71\252\62:\0~\20\222\200\247t\352F\16D\230\34\210\314\325\0\240\6\0\200\240\22\241\14#\253" "Y\23\16$\17\376\203\0\242\63N\223\334T\205\205\203\345\256\16fJJ\206$\26\205\334\210\30I\15" "\205\15\205\315\210\315\304\315\304Q\10ML\10M\24\221\320\320\34\214\331\11\13\7\213\2\243 \61\213\340" "\324\16\17\250jj\350H&G\306\67> ; \34\337\377\370\340@\342\340@\2\0\244/r\212&" "\65\302#\206'fhf\16\256J\312\226\11J\211\12\211\12\211\12\211\12\211J\11\212-+\251\222\70" "\210\220\231!\222\30\236\10\217\0\245\66\62\213 \25h'F)(g\6i\350\246\306\250\250f\256\16" "n\256f&)f'f\315\16~\20\70\17\60\17\60\17\60\17\60\17\60\17\60\17\60\17\60\17\60\7" "\246\12\42\254\31\23~z\360\1\247-\14\224\31\224\254\16bHF\10'W\262,,;\10\251 \31" ":\210\62\63;\232(!\71\20\62\64lH\271\341\210L\311\201\220\21\0\250\11j\200\266\22\206\34\15" "\251TZ\223\240\67\17\342!\16\212\253,I\351\306\247\206\256\324\34L\311\310\324\20\215\310\214\21I\310" "\320\15I\310\314C\320\314C\320\314C\320\314C\320\314C\320\314C\320\14\16\211\310\214\21\211\310\20\21" "\315\310\34L\11\15]\211\215\317\221RV\31\37\324C\34D\2\252 \14\212\251\263\344\16b\206F\244" "F\245n\16D\246D\304D\244F\244f,\204H\344A\17\12\253\31\315\231\342\224f\26\215\14\315l" "\64\263\15\315\14\321\314\320\66SB\273\31\254\25\23\211g\25\376`\36D\36D\36D\36D\36D\36" "D\0\256UZ\223\240\67\17\342!\16\212\253,I\351F\16d\246f\16f\244\204\244hT\311\311\214" "H\311\11I\210\311\11I\210)#;\220#;\220#\223\32#SF\246\214LlHDJNHD" "JNfFHNFh\36Bl|\216\224\262\312\370\240\36\342 \22\0\257\10J\200\266\22\36\30\260" "\17\347\220\362RFd\42\242T\315\204T\0\261&\264\272\240\70\345a\344a\344a\344a\344a$\17" "~P)\17#\17#\17#\17#\17#\17#\217\347\7\77(\262\24\252\211,sj\16Bf\214\346" "\226\255\32\233\42;\70\60\263\27\252\221lSl\16\42f&\244\346\244\310(\7\311\212\16jj\0\264" "\13\306\220\65rFH\326(\2\266M\360\223\32\265\16hl\204nd\16bD\16dD\16dD\16" "dD\16dD\16dd\16bd\16b\244l\344h$e$e$e$e$e$e$e$" "e$e$e$e$e$e$e$e$e$e$eD\0\267\10\203\230j\22\16\12\270" "\17(\221WR\342\342\246\312\26\35\34\214\0\271\14\246\211\254rF\16J\204\364\17\272\31\354\211\252S" "\16b\206F\304$\306\12\71,\233\30\232\71\210\262\7>(\273\31\315\231\342\24f\206\66\222\232\31\332" "fh\15\315\216f\66\222\31\232Y\4\274Gx\213\337vf\345H\247L\305&$G%e\5g\5" "\205\345\206\345\244\305\304\305\304\245\344\1\204\346\1\204\304\206\247\210\305h\247$d\245DD\247DD\245" "d$\207TJ\35PM\35P\11\313I\313I\213\311\3\1\275Ex\213\337vf\307H\247L\305D" "$G%e\5g\5\205\345\206\345\244\305\246\305\304\245\344\1\204\206\312\204d\16BgV\312L\11\316" "\12\312\316\315\12\212\16\212NJN\12R\316\221\12\36\314\14\36\314\310\3\1\276JX\223\337VLg" "\16$\205f\350f\347d\347&\351F\351\244\211\346\1\204\4\305d\6\207f$\17d\246d\216\244\246" "\245\210\207\212\205&d\207Dd\205dDg\204De\244$g\16\350\204\16\310\204\345\206\345\244\305\346" "A\0\277\34/\223\231\364\206\327c\274[R\226M\331\16\257\14!\234\240\242\71(:\20\64\2\300N" "x\214\240\366\346\301\350\301\346\341\346\341\344\1\345\361cz\240z {\220{\220\211y\220\11z\0\222" "y\200\31j\242\351)Z*\332\271\331\71J\302\311I\272\203\203\271\203\203\271\203\3*\342\251i\32\362" "\231y\0\222y\0\12z\210\365 \4\301Nx\214\240\266\351\241\346\241\346\301\344\301\346\301\344\361cz" "\240z {\220{\220\211y\220\11z\0\222y\200\31j\242\351)Z*\332\271\331\71J\302\311I\272" "\203\203\271\203\203\271\203\3*\342\251i\32\362\231y\0\222y\0\12z\210\365 \4\302Rx\214\240V" "\351\201\352\201$\346AF\344A\204\344\1\244\344\361Kz\240z {\220{\220\211y\220\11z\0\222" "y\200\31j\242\351)Z*\332\271\331\71J\302\311I\272\203\203\271\203\203\271\203\3*\342\251i\32\362" "\231y\0\222y\0\12z\210\365 \4\303J\70\214\240\26i\304\17\344\1D\352\361o\350\201\352\201\354" "A\356A&\346A&\350\1H\346\1f\250\211\246\247h\251h\347f\347(\11''\351\16\16\346\16" "\16\346\16\16\250\210\247\246i\310g\346\1H\346\1(\350!\326\203\20\304L\71\204`\26\207\346\1\206" "\346\1\206\346\361\357\352\241\352\241\352\201\356a&\346A(\350!f\346!f\310i\310\247\246\251\210\347" "f\351H'G''\17\16\6\17\16\346\16\16\312\246\307\246\211\310\207\346\1f\350\1H\346A&\350" "A\10\305T\230\214`V\347\241b\342a\242\342A\242\342A\242\342Ad\342\201\352\361[z\240z " "{\220{\220\211y\220\11z\0\222y\200\31j\242\351\251a*Z\262\331\71J\302\311I\272\203\203\271" "\203\203\271\203\3*\342\251i\32j\32\362\231y\0\12z\210\365 \4\306T\77\213\240\270\17\16\246\17" "\16\250\17\16\210\357!'\346\1)\346\1G\346\341H\346\301h\346\301h\346\241\210\346\241\210\16\16\342" "\250\16\16\342\250\16\16\302\310\346a\16\354A\16\356A\16\356!\10\347!&\347\1(\347\1F\307I" "\17\16$f\17\16l\17\16\4\307F\63\224\330\365N\17\310\252\210(gF)h'\206'\346\1\350" "\1\346!\346!\346!\346!\346!\346!\346!\346A\346!\206'\206GFI(\207\252\310\16*\17" "\302\343a\350\1\352!\350A\344Ad\17b\257\0\310(p\234`u\306W\217\217\313\343\366\340 \342" "\340 \342\340 bz\277>\70\210\70\70\210\70\70\210\230\336\257\17\376\300\0\311'p\234`\65\207\211" "W\253\307\361\301A\304\301A\304\301A\304\364~}p\20qp\20qp\20\61\275_\37\374\201\1\312" ",p\234`\265jK'&e\4g\346\244\344qxp\20qp\20qp\20\61\275_\37\34D\34" "\34D\34\34DL\357\327\7\177`\313(\60\234`u\326\315\314\315\314\343\345\301A\304\301A\304\301A" "\304\364~}p\20qp\20qp\20\61\275_\37\374\201\1\314\22f\204`\22h\206\206\204\206\344\201" "g\366\377\377\7\315\23f\234`rFfdFf\344\241g\366\377\377\67\0\316\25i\204`r\210\212" "$FF\324T\311\243\34\333\377\377\337\0\317\20*\204\240\22\206\34\315c\70\267\377\377\77\2\320>\66" "\203 v\16h\17\16\17\16\342\346\314F\251f\211f\211\206i\206i\246g\246\17\16\342\16\16\342\16" "\16\342f\246g\246g\206i\206\207f\211f\211F\251\346\314\16\16\342\16\16\17\10\1\321\77\63\234`" "\326HD\17$'\352\361m\355A\354\201\350\301\344\301\244\5\241\5\241\11\235\11\235\15\231\15\231\21\225" "\325\224\25\221\31\215\31\215\35\211\35\211!\205!\205\345\301\344\301\350\201\354Al\1\322G\226\224\240\326" "\350\201\346\241\346\241\344\241\346\241\346\241\344\361\371A\360A\345\301]Y\25)\15\61\311\370\310\370\4\371" "=\204=\204=\204=\204=\204=\204=\0\305\370\310\370\10\61\315\360\20)UY\335\301\345A\265!" "\0\323G\226\224\240\226\351a\346a\346\201\344\201\346a\346\201\344\361\213\203\340\203\312\203\273\262*R\32" "b\222\361\221\361\11\362{\10{\10{\10{\10{\10{\10{\0\212\361\221\361\21b\232\341!R\252" "\262\272\203\313\203jC\0\324H\226\224\240\66\351a\350A\354!D\306G\246\207\206\305\344\361\355A\360" "A\345\301]Y\25)\15\61\311\370\310\370\4\371=\204=\204=\204=\204=\204=\204=\0\305\370\310" "\370\10\61\315\360\20)UY\335\301\345A\265!\0\325@\66\224\240\366J\204\17\206e\350\361G\7\301" "\7\225\7weU\244\64\304$\343#\343\23\344\367\20\366\20\366\20\366\20\366\20\366\20\366\0\24\343#" "\343#\304\64\303C\244Teu\7\227\7\325\206\0\326@\66\224\240\366\206\206\207\206\207\346\361'\7\301" "\7\225\7weU\244\64\304$\343#\343\23\344\367\20\366\20\366\20\366\20\366\20\366\20\366\0\24\343#" "\343#\304\64\303C\244Teu\7\227\7\325\206\0\327,r\302\241\70\302#\206'Fg\6\247\4\345" "\304$\205dE\244\351\1\344\1\250Ed\205$\305\344\4\245De\204%\206'\302#\0\330O\366\223" "\235\366\201\342\301\346a\350\16b\306\16\16\244\16\16\244\312\252(k(O&)F&)&\10I\16" "\211\354\250\354\250\314\310\254\350\254\350\214\350\16B\10GV\216\34\4\322X\16UR\225U\35\34\210\35" "\34\204\221\34\322\303\314\203\305\3\1\331(\223\234`\266\346A\346!\346A\346A\346A\344a\344\361p" "\332\377\177}|K\61;BISVsp\20u`y\6\332(\223\234`v\347\1\350\1\346\1\346" "!\344!\344!\346\361t\332\377\177}|K\61;BISVsp\20u`y\6\333'\223\234`" "\26\347\1\312\253'\206eF\245D\245\346\361j\332\377\177}|K\61;BISVsp\20u`" "y\6\334\42\63\234`\266\206&\207&\207\346\361\345\264\377\377\372\370\226bv\204\222\246\254\346\340 \352" "\300\362\14\0\335Cu\214\340\225\347A\350A\346A\346a\344a\344\361\21\65\5\361\10-\15%\25!" "\25\35\263A*J\242\331\31Z\222\351\363{\200z\20z\220y\230y\230y\230y\230y\230y\230y" "\230y\230y\230I\0\336!\60\233`\25\246\267>\240:\70\71\70\210\230\253\230<\365\313\273\212\203\203" "\210\203\223\3\252\351\275\6\337\65\61\223\340\264,\17\246L\212\306h\350f\6g\6g\346\206\246\212\206" "\310\206\346\206\346\206\310\206\252\246l\346,&)Fo\235\214\331L\331\224\34\35H\214\325\0\340,o" "\223\340\224\246\27OO\313cy\20uPCDBF\61\70\274\350\200\344\300\242lb\320\322\360AX" "\5\315\304\310\201\304P\315\0\341,\217\223\340\64g\207g\27\253\307\370 \352\240\206\210\204\214bpx" "\321\1\311\201E\331\304\240\245\341\203\260\12\232\211\221\3\211\241\232\1\342\61\217\223\340\324HK\15'\6" "e\306\206\304\324cv\20uPCDBF\61\70\274\350\200\344\300\242lb\320\322\360AX\5\315\304" "\310\201\304P\315\0\343,/\223\340\224J\244\16\304D\350qx\20uPCDBF\61\70\274\350\200" "\344\300\242\354\320\322\360AX\5\315\304\310\201\304P\315\0\344-/\223\340t\206\246\206\246\206\346qv" "\20uPCDBF\61\70\274\350\200\344\300\242lb\320\322\360AX\5\315\304\310\201\304P\315\0\345" "\63\257\223\340\324Fe\42\243\2\243\2\243\2eB\351qz\20uPCSBF\61G\313\350\200\344" "\300\242lb\320\322\360AX\5\315\304\310\201\304P\315\0\346:\134\222 \230\316\36\314\34\14\325\220\14" "\321\314\331\215\14\22N\23\22\217\16\35<\30\71xPQ\66M\70=\71=Xx(!\70A\66\61" "FB\64\303\350@\352@\354\320\10\0\347$N\223\230\224\256\16h\230\214Q\314\335\331\356-\335\304\334" "\304\30\11\15\321\201\234i\64i-\261\262;\33\0\350/\220\223\340t\306\247\307\227\313\3\310cnx" "\60ESCF\62\70A\70\61\71qp\20qpP\275|pdp\204\214\246\244\352`\320\12\0\351" ".\220\223\340\64i\211WKO\313\343\302\360`\212\246\206\214dp\202pbr\342\340 \342\340\240z" "\371\340\310\340\10\31MI\325\301\240\25\0\352\62\220\223\340\324hk-'&e\346\244\344\304\344\261\65" "<\230\242\251!#\31\234 \234\230\234\70\70\210\70\70\250^>\70\62\70BFSRu\60h\5\353" ".\60\223\340t\206\306\206\306\206\346qlx\60EDC\67\62\70A\70\61*qp\20qpP\275" "|pdp\204\214\246\206\352`\320\12\0\354\21f{ \22h\206\206\204\206\344\301f\366\377\17\355\21" "f\223 rF\326\214\314\310\303\315\354\377\337\0\356\25i{ R\212j&FF$f\252\344\21\214" "\355\377\337\0\357\17*{ \22f\336\320\243\236\333\377\77\2\360/Q\223`u\42\243\306\306(*k" "-I\310\246\310\11\17\304\16\212jL\350H&'(\17Bm}z\20\71\62\71BG\323\352\200\360" "\12\0\361\34/\223\340\224H\304\16\304$\352q\64c\63q bSQv\20w\351\377\313\1\362." "\221\223`\225\306\311\347\1\346\1\344!\344\1\346qrx@USCG\62\71Ay\20y\353\355\345" "A$\305\344\10\35M\253\3\302+\0\363'\221\223`U\247\251\227k\217\253\303\3\252\232\32:\222\311" "\11\312\203\310[o/\17\42)&G\350hZ\35\20^\1\364.\221\223`\365\246\213k'&g\6" "\245\344\246\346\61\77<\240\252\251\241#\231\234\240<\210\274\365\366\362 \222br\204\216\246\325\1\341\25" "\0\365)\61\223`\265H\4\17\4E\350\361\346\360\200\252\246\206\216dr\202\362 \362\326\333\313\203H" "\212\311\21:\232V\7\204W\0\366)\61\223`u\206\346\206\346\206\346\361\344\360\200\252\246\206\216dr" "\202\362 \362\326\333\313\203H\212\311\21:\232V\7\204W\0\367\33\364\271\243\70\345A\350!\350A\344" "qy\360\203z\214\344A\350!\350A$\1\370\63\361\222^\365\1\342!\304\247.\206\16\212jj\310" "J\306,\250&\16\242&\256f\214\206l\246l\246.\246\16\310(\352F\312h\332\34\30\211\134\215\313" "\3\371\35\217\223\340t\206\211\247\247\305\245\345\61\233\364\377\345\335AXE\215\311\201\304\214\315\0\372\33" "\217\223\340\64gi\27+\236\307n\322\377\227w\7a\25\65&\7\22\63\66\3\373!\217\223\340\324f" "K+'\6e\344\244\304\244\344\261\231\364\377\345\335AXE\215\311\201\304\214\315\0\374\34/\223\340T" "\206\246\206\246\206\346q\63\351\377\313\273\203\260\212\32\223\3\211\31\233\1\375\65P\214\231T\207\247\245\207" "\247\345\61\35\275\234\30\244\30\34\241\233\31\243\241\32\242ZDE\63\67\63G\61H\61\71\61i\333\226" "zxzPf\216b\362\264\22\0\376'\20\224\31\25\246\367\33\243\221\203\230\33\222\62\12\302\11\302S" "\77=<\10\234(\243\70)\231\70\220\231\61\232\336\327\0\377\61\20\214\231t\206\306\206\306\206\346q\67" "jzH\61\70B\67\63FC\65D\265h\214fn\204\216b\220b\362\322\266\226\230\361\364\60\361\364" "\60!\0\0\0\0\4\377\377\0";
992075.c
/****************************************************************************** * Code generated with sympy 0.7.6 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'project' * ******************************************************************************/ #include "ring_inter_middle_inter_bend_3.h" #include <math.h> double ring_inter_middle_inter_bend_3() { double ring_inter_middle_inter_bend_3_result; ring_inter_middle_inter_bend_3_result = 0; return ring_inter_middle_inter_bend_3_result; }
308306.c
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-IEs" * found in "/home/oai/Downloads/LWA/openair3/S1AP/MESSAGES/ASN1/R10.5/S1AP-IEs.asn" * `asn1c -gen-PER` */ #include "S1ap-ManagementBasedMDTAllowed.h" int S1ap_ManagementBasedMDTAllowed_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { /* Replace with underlying type checker */ td->check_constraints = asn_DEF_NativeEnumerated.check_constraints; return td->check_constraints(td, sptr, ctfailcb, app_key); } /* * This type is implemented using NativeEnumerated, * so here we adjust the DEF accordingly. */ static void S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_NativeEnumerated.free_struct; td->print_struct = asn_DEF_NativeEnumerated.print_struct; td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder; td->der_encoder = asn_DEF_NativeEnumerated.der_encoder; td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder; td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder; td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder; td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder; td->aper_decoder = asn_DEF_NativeEnumerated.aper_decoder; td->aper_encoder = asn_DEF_NativeEnumerated.aper_encoder; td->compare = asn_DEF_NativeEnumerated.compare; if(!td->per_constraints) td->per_constraints = asn_DEF_NativeEnumerated.per_constraints; td->elements = asn_DEF_NativeEnumerated.elements; td->elements_count = asn_DEF_NativeEnumerated.elements_count; /* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */ } void S1ap_ManagementBasedMDTAllowed_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int S1ap_ManagementBasedMDTAllowed_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t S1ap_ManagementBasedMDTAllowed_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t S1ap_ManagementBasedMDTAllowed_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t S1ap_ManagementBasedMDTAllowed_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t S1ap_ManagementBasedMDTAllowed_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } asn_dec_rval_t S1ap_ManagementBasedMDTAllowed_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } asn_enc_rval_t S1ap_ManagementBasedMDTAllowed_encode_uper(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *structure, asn_per_outp_t *per_out) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->uper_encoder(td, constraints, structure, per_out); } asn_enc_rval_t S1ap_ManagementBasedMDTAllowed_encode_aper(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *structure, asn_per_outp_t *per_out) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->aper_encoder(td, constraints, structure, per_out); } asn_comp_rval_t * S1ap_ManagementBasedMDTAllowed_compare(asn_TYPE_descriptor_t *td1, const void *structure1, asn_TYPE_descriptor_t *td2, const void *structure2) { asn_comp_rval_t * res = NULL; S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td1); S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td2); res = td1->compare(td1, structure1, td2, structure2); return res; } asn_dec_rval_t S1ap_ManagementBasedMDTAllowed_decode_aper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { S1ap_ManagementBasedMDTAllowed_1_inherit_TYPE_descriptor(td); return td->aper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } static asn_per_constraints_t asn_PER_type_S1ap_ManagementBasedMDTAllowed_constr_1 GCC_NOTUSED = { { APC_CONSTRAINED | APC_EXTENSIBLE, 0, 0, 0, 0 } /* (0..0,...) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_INTEGER_enum_map_t asn_MAP_S1ap_ManagementBasedMDTAllowed_value2enum_1[] = { { 0, 7, "allowed" } /* This list is extensible */ }; static unsigned int asn_MAP_S1ap_ManagementBasedMDTAllowed_enum2value_1[] = { 0 /* allowed(0) */ /* This list is extensible */ }; static asn_INTEGER_specifics_t asn_SPC_S1ap_ManagementBasedMDTAllowed_specs_1 = { asn_MAP_S1ap_ManagementBasedMDTAllowed_value2enum_1, /* "tag" => N; sorted by tag */ asn_MAP_S1ap_ManagementBasedMDTAllowed_enum2value_1, /* N => "tag"; sorted by N */ 1, /* Number of elements in the maps */ 2, /* Extensions before this member */ 1, /* Strict enumeration */ 0, /* Native long size */ 0 }; static ber_tlv_tag_t asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) }; asn_TYPE_descriptor_t asn_DEF_S1ap_ManagementBasedMDTAllowed = { "S1ap-ManagementBasedMDTAllowed", "S1ap-ManagementBasedMDTAllowed", S1ap_ManagementBasedMDTAllowed_free, S1ap_ManagementBasedMDTAllowed_print, S1ap_ManagementBasedMDTAllowed_constraint, S1ap_ManagementBasedMDTAllowed_decode_ber, S1ap_ManagementBasedMDTAllowed_encode_der, S1ap_ManagementBasedMDTAllowed_decode_xer, S1ap_ManagementBasedMDTAllowed_encode_xer, S1ap_ManagementBasedMDTAllowed_decode_uper, S1ap_ManagementBasedMDTAllowed_encode_uper, S1ap_ManagementBasedMDTAllowed_decode_aper, S1ap_ManagementBasedMDTAllowed_encode_aper, S1ap_ManagementBasedMDTAllowed_compare, 0, /* Use generic outmost tag fetcher */ asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1, sizeof(asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1) /sizeof(asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1[0]), /* 1 */ asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1, /* Same as above */ sizeof(asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1) /sizeof(asn_DEF_S1ap_ManagementBasedMDTAllowed_tags_1[0]), /* 1 */ &asn_PER_type_S1ap_ManagementBasedMDTAllowed_constr_1, 0, 0, /* Defined elsewhere */ &asn_SPC_S1ap_ManagementBasedMDTAllowed_specs_1 /* Additional specs */ };
226435.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" int16_t x12 = -1; uint16_t x18 = UINT16_MAX; volatile int16_t x20 = -15501; static uint32_t x21 = 0U; volatile uint32_t x22 = 8853U; uint16_t x25 = 87U; uint32_t x28 = UINT32_MAX; static int64_t x33 = 6462901LL; volatile int32_t t7 = 90666562; uint64_t x40 = 1LLU; static int8_t x41 = INT8_MIN; int16_t x44 = INT16_MIN; uint16_t x46 = UINT16_MAX; int8_t x53 = INT8_MIN; int16_t x57 = 0; uint32_t x60 = UINT32_MAX; static volatile int32_t t14 = 3828; volatile int32_t t15 = 1150; int64_t x71 = -15729876LL; int8_t x77 = INT8_MAX; int64_t x79 = INT64_MIN; uint8_t x80 = 31U; uint8_t x81 = 43U; int64_t x82 = INT64_MIN; volatile int32_t t19 = 12; uint64_t x91 = 34224276LLU; uint64_t x92 = 2559300LLU; static int16_t x94 = 654; static volatile int32_t t22 = -1371; uint64_t x102 = 6287429LLU; int64_t x103 = -27496924900436LL; uint16_t x104 = UINT16_MAX; int32_t t23 = 11; uint32_t x106 = 313765564U; int8_t x107 = -1; uint32_t x112 = UINT32_MAX; int8_t x113 = INT8_MIN; static int32_t t26 = 3147; uint32_t x123 = 25U; uint16_t x129 = 31U; uint16_t x131 = UINT16_MAX; volatile int64_t x138 = -1LL; int16_t x143 = INT16_MIN; volatile int32_t t33 = -422; uint16_t x146 = UINT16_MAX; static int32_t t34 = -168436; uint64_t x160 = UINT64_MAX; int8_t x195 = INT8_MIN; int32_t t44 = -56294; volatile int64_t x210 = INT64_MAX; int64_t x216 = 930917448466743322LL; int8_t x217 = -1; static uint64_t x220 = UINT64_MAX; uint16_t x229 = UINT16_MAX; static int32_t x231 = -105; uint8_t x236 = UINT8_MAX; int64_t x237 = INT64_MIN; int64_t x245 = INT64_MIN; uint8_t x267 = UINT8_MAX; static volatile int8_t x271 = 0; int32_t t62 = -1001839100; static int8_t x275 = -2; static volatile int64_t x276 = 68186587871LL; int32_t t63 = -188; volatile int32_t t64 = -1889136; int8_t x289 = -1; static uint32_t x290 = 29U; volatile int64_t x294 = 2818166646874721LL; static uint8_t x297 = UINT8_MAX; int16_t x299 = INT16_MAX; volatile uint64_t x302 = 285LLU; static uint64_t x303 = UINT64_MAX; static uint16_t x308 = 5551U; volatile uint64_t x315 = 1LLU; uint8_t x316 = 2U; int8_t x321 = -1; static int8_t x324 = -1; int64_t x329 = -83805976964409LL; int8_t x332 = 4; int64_t x335 = INT64_MAX; int32_t t77 = -57158299; volatile int32_t t78 = 19183; int32_t x341 = INT32_MAX; volatile int32_t t79 = -207468; int16_t x347 = 1; volatile int32_t t80 = -672; uint16_t x349 = UINT16_MAX; static uint8_t x361 = UINT8_MAX; int32_t x362 = -1; uint16_t x363 = 247U; static uint64_t x364 = 3322110617452LLU; uint8_t x371 = UINT8_MAX; int32_t t86 = -40147; uint64_t x377 = 28900940697829LLU; volatile int32_t t87 = 2167; int8_t x405 = INT8_MAX; int8_t x406 = INT8_MAX; volatile int32_t x410 = 659; static int8_t x416 = -1; int64_t x418 = -220923516619883LL; volatile int16_t x422 = INT16_MIN; volatile int16_t x425 = INT16_MIN; volatile uint16_t x429 = UINT16_MAX; int64_t x430 = 633390179371706LL; static volatile int32_t t99 = -372425497; static volatile int32_t x433 = 62219; static int32_t x438 = INT32_MIN; int32_t t101 = 12; volatile int64_t x442 = INT64_MIN; uint8_t x449 = 12U; static volatile int32_t t107 = -739524; uint64_t x469 = UINT64_MAX; int16_t x470 = INT16_MIN; int16_t x472 = 141; volatile int32_t t108 = -27; volatile int32_t t109 = -6713; volatile int64_t x478 = -97LL; volatile int32_t t111 = -21; volatile uint64_t x492 = 12531483367181LLU; int32_t x497 = 0; volatile int32_t t115 = -352; uint16_t x516 = UINT16_MAX; static volatile uint16_t x529 = 16U; int16_t x534 = INT16_MIN; uint32_t x540 = 2453U; static volatile uint32_t x546 = 4508448U; volatile int16_t x560 = INT16_MIN; static uint16_t x569 = 2809U; uint64_t x570 = 2986216567LLU; static int32_t t131 = -160541; static int32_t x575 = -4037617; static volatile int64_t x580 = 4LL; int32_t t133 = 0; volatile int16_t x589 = 7; int32_t x600 = INT32_MAX; int8_t x601 = 0; int32_t t138 = -6; int8_t x628 = 1; int64_t x632 = 12944336LL; static int64_t x643 = 27029190436807022LL; uint64_t x650 = 1353559208LLU; uint32_t x651 = 107449254U; int32_t x654 = -1; volatile int32_t t149 = -4; volatile uint64_t x661 = 9212681644579158058LLU; static uint16_t x670 = 3U; uint64_t x671 = UINT64_MAX; int32_t t152 = -5222; int64_t x673 = INT64_MIN; uint8_t x675 = UINT8_MAX; int8_t x691 = -6; int32_t x694 = 58254761; int16_t x697 = INT16_MIN; int64_t x702 = INT64_MIN; int8_t x704 = INT8_MAX; uint16_t x705 = 15665U; static volatile int16_t x712 = INT16_MIN; int32_t t162 = 60; uint32_t x713 = 120214817U; static int32_t x717 = 69248; static volatile uint32_t x735 = 46476827U; volatile uint32_t x748 = UINT32_MAX; int32_t t170 = -4459270; uint64_t x749 = UINT64_MAX; uint64_t x756 = 735939756091LLU; uint16_t x767 = 28559U; int8_t x773 = -2; volatile int32_t t178 = 6917; int32_t t179 = 1013894524; volatile uint8_t x802 = 52U; volatile int32_t x803 = -1; int64_t x804 = INT64_MAX; uint16_t x814 = 31U; static int8_t x815 = INT8_MIN; static uint64_t x816 = 483LLU; int16_t x826 = INT16_MAX; int64_t x833 = -1LL; volatile int8_t x834 = -25; volatile int16_t x835 = INT16_MIN; volatile int32_t t193 = -1; volatile int16_t x843 = INT16_MIN; volatile int32_t x858 = INT32_MIN; int16_t x860 = INT16_MIN; volatile uint32_t x863 = 1937733U; uint32_t x871 = 131311414U; static uint8_t x872 = 116U; void f0(void) { uint32_t x1 = UINT32_MAX; volatile uint32_t x2 = UINT32_MAX; int8_t x3 = INT8_MIN; int16_t x4 = INT16_MIN; int32_t t0 = 297123; t0 = ((x1+x2)<=(x3^x4)); if (t0 != 0) { NG(); } else { ; } } void f1(void) { uint16_t x9 = 825U; int16_t x10 = -1; int16_t x11 = INT16_MAX; volatile int32_t t1 = -84; t1 = ((x9+x10)<=(x11^x12)); if (t1 != 0) { NG(); } else { ; } } void f2(void) { uint64_t x13 = 69121981648LLU; volatile int16_t x14 = INT16_MIN; uint64_t x15 = 18280694867261LLU; int32_t x16 = -1; static int32_t t2 = 248767; t2 = ((x13+x14)<=(x15^x16)); if (t2 != 1) { NG(); } else { ; } } void f3(void) { volatile int64_t x17 = -1LL; int16_t x19 = INT16_MAX; volatile int32_t t3 = 33258; t3 = ((x17+x18)<=(x19^x20)); if (t3 != 0) { NG(); } else { ; } } void f4(void) { uint16_t x23 = 11870U; int64_t x24 = INT64_MAX; volatile int32_t t4 = 750283; t4 = ((x21+x22)<=(x23^x24)); if (t4 != 1) { NG(); } else { ; } } void f5(void) { int32_t x26 = INT32_MIN; int64_t x27 = INT64_MIN; volatile int32_t t5 = 483921981; t5 = ((x25+x26)<=(x27^x28)); if (t5 != 0) { NG(); } else { ; } } void f6(void) { int32_t x29 = INT32_MAX; volatile int32_t x30 = INT32_MIN; int8_t x31 = -10; static volatile int8_t x32 = INT8_MIN; volatile int32_t t6 = -1517250; t6 = ((x29+x30)<=(x31^x32)); if (t6 != 1) { NG(); } else { ; } } void f7(void) { volatile int64_t x34 = INT64_MIN; uint64_t x35 = 52397LLU; int64_t x36 = -7391112LL; t7 = ((x33+x34)<=(x35^x36)); if (t7 != 1) { NG(); } else { ; } } void f8(void) { volatile int64_t x37 = 2117637LL; int64_t x38 = INT64_MIN; static int64_t x39 = -1LL; volatile int32_t t8 = -7; t8 = ((x37+x38)<=(x39^x40)); if (t8 != 1) { NG(); } else { ; } } void f9(void) { int8_t x42 = 5; int32_t x43 = -7201; volatile int32_t t9 = 398; t9 = ((x41+x42)<=(x43^x44)); if (t9 != 1) { NG(); } else { ; } } void f10(void) { volatile int8_t x45 = INT8_MIN; uint8_t x47 = 120U; int32_t x48 = INT32_MAX; volatile int32_t t10 = 7; t10 = ((x45+x46)<=(x47^x48)); if (t10 != 1) { NG(); } else { ; } } void f11(void) { uint32_t x49 = UINT32_MAX; int32_t x50 = INT32_MAX; int32_t x51 = 2061; int32_t x52 = -1; volatile int32_t t11 = -49; t11 = ((x49+x50)<=(x51^x52)); if (t11 != 1) { NG(); } else { ; } } void f12(void) { static int16_t x54 = -83; int8_t x55 = 0; static int8_t x56 = -1; volatile int32_t t12 = 5; t12 = ((x53+x54)<=(x55^x56)); if (t12 != 1) { NG(); } else { ; } } void f13(void) { int64_t x58 = INT64_MIN; volatile int32_t x59 = 498190661; static int32_t t13 = 32; t13 = ((x57+x58)<=(x59^x60)); if (t13 != 1) { NG(); } else { ; } } void f14(void) { uint32_t x61 = 235505262U; int16_t x62 = -1; int64_t x63 = INT64_MIN; volatile int32_t x64 = 221700644; t14 = ((x61+x62)<=(x63^x64)); if (t14 != 0) { NG(); } else { ; } } void f15(void) { int32_t x65 = 1; int8_t x66 = 2; int64_t x67 = 10668576338611156LL; volatile int16_t x68 = -5455; t15 = ((x65+x66)<=(x67^x68)); if (t15 != 0) { NG(); } else { ; } } void f16(void) { int32_t x69 = -394238486; volatile int16_t x70 = INT16_MIN; static uint64_t x72 = 525248496173LLU; int32_t t16 = -12345568; t16 = ((x69+x70)<=(x71^x72)); if (t16 != 0) { NG(); } else { ; } } void f17(void) { uint8_t x78 = UINT8_MAX; int32_t t17 = -3302256; t17 = ((x77+x78)<=(x79^x80)); if (t17 != 0) { NG(); } else { ; } } void f18(void) { int32_t x83 = INT32_MAX; volatile int64_t x84 = INT64_MIN; int32_t t18 = 877907886; t18 = ((x81+x82)<=(x83^x84)); if (t18 != 1) { NG(); } else { ; } } void f19(void) { uint8_t x85 = 0U; volatile uint32_t x86 = 5222U; int32_t x87 = INT32_MIN; uint16_t x88 = UINT16_MAX; t19 = ((x85+x86)<=(x87^x88)); if (t19 != 1) { NG(); } else { ; } } void f20(void) { static int16_t x89 = INT16_MIN; uint64_t x90 = 7921745665LLU; volatile int32_t t20 = -65518988; t20 = ((x89+x90)<=(x91^x92)); if (t20 != 0) { NG(); } else { ; } } void f21(void) { int64_t x93 = INT64_MIN; uint16_t x95 = 28499U; int16_t x96 = INT16_MIN; volatile int32_t t21 = 7348024; t21 = ((x93+x94)<=(x95^x96)); if (t21 != 1) { NG(); } else { ; } } void f22(void) { uint32_t x97 = 55212U; uint8_t x98 = UINT8_MAX; uint8_t x99 = UINT8_MAX; volatile uint8_t x100 = 14U; t22 = ((x97+x98)<=(x99^x100)); if (t22 != 0) { NG(); } else { ; } } void f23(void) { uint8_t x101 = UINT8_MAX; t23 = ((x101+x102)<=(x103^x104)); if (t23 != 1) { NG(); } else { ; } } void f24(void) { static int16_t x105 = -1; int64_t x108 = INT64_MAX; int32_t t24 = -16120563; t24 = ((x105+x106)<=(x107^x108)); if (t24 != 0) { NG(); } else { ; } } void f25(void) { int8_t x109 = INT8_MIN; int64_t x110 = -1LL; int16_t x111 = INT16_MIN; int32_t t25 = -183923; t25 = ((x109+x110)<=(x111^x112)); if (t25 != 1) { NG(); } else { ; } } void f26(void) { int64_t x114 = 935583361584LL; static int16_t x115 = 1; int32_t x116 = -1; t26 = ((x113+x114)<=(x115^x116)); if (t26 != 0) { NG(); } else { ; } } void f27(void) { uint16_t x117 = 4U; int32_t x118 = 0; static int64_t x119 = 17617735385023LL; uint32_t x120 = 220U; volatile int32_t t27 = 324819; t27 = ((x117+x118)<=(x119^x120)); if (t27 != 1) { NG(); } else { ; } } void f28(void) { volatile int8_t x121 = -1; uint64_t x122 = 363076LLU; static int32_t x124 = 7381; int32_t t28 = -1007; t28 = ((x121+x122)<=(x123^x124)); if (t28 != 0) { NG(); } else { ; } } void f29(void) { static volatile int16_t x125 = 6; uint16_t x126 = 2210U; volatile int16_t x127 = INT16_MIN; static int32_t x128 = -36522066; int32_t t29 = 448; t29 = ((x125+x126)<=(x127^x128)); if (t29 != 1) { NG(); } else { ; } } void f30(void) { volatile int32_t x130 = -399531; int32_t x132 = INT32_MIN; int32_t t30 = -155; t30 = ((x129+x130)<=(x131^x132)); if (t30 != 0) { NG(); } else { ; } } void f31(void) { volatile int16_t x133 = INT16_MAX; static uint16_t x134 = UINT16_MAX; int32_t x135 = -1; static int32_t x136 = 8; int32_t t31 = -3794098; t31 = ((x133+x134)<=(x135^x136)); if (t31 != 0) { NG(); } else { ; } } void f32(void) { int32_t x137 = -1; int16_t x139 = -1; static uint32_t x140 = 748U; volatile int32_t t32 = 10; t32 = ((x137+x138)<=(x139^x140)); if (t32 != 1) { NG(); } else { ; } } void f33(void) { int16_t x141 = -1; int64_t x142 = -1LL; int64_t x144 = -1LL; t33 = ((x141+x142)<=(x143^x144)); if (t33 != 1) { NG(); } else { ; } } void f34(void) { static int32_t x145 = INT32_MIN; static uint8_t x147 = 0U; int64_t x148 = 27076LL; t34 = ((x145+x146)<=(x147^x148)); if (t34 != 1) { NG(); } else { ; } } void f35(void) { uint8_t x149 = 15U; static int64_t x150 = 86367952589LL; int64_t x151 = 784300LL; static uint32_t x152 = UINT32_MAX; static int32_t t35 = -11; t35 = ((x149+x150)<=(x151^x152)); if (t35 != 0) { NG(); } else { ; } } void f36(void) { int8_t x153 = INT8_MIN; int8_t x154 = INT8_MAX; uint8_t x155 = 60U; int32_t x156 = INT32_MIN; int32_t t36 = -102618328; t36 = ((x153+x154)<=(x155^x156)); if (t36 != 0) { NG(); } else { ; } } void f37(void) { int64_t x157 = -160104566LL; int64_t x158 = -32655849248LL; static uint32_t x159 = UINT32_MAX; static int32_t t37 = -320968902; t37 = ((x157+x158)<=(x159^x160)); if (t37 != 1) { NG(); } else { ; } } void f38(void) { int16_t x161 = -27; uint8_t x162 = UINT8_MAX; int64_t x163 = INT64_MIN; volatile uint16_t x164 = 0U; int32_t t38 = 75645; t38 = ((x161+x162)<=(x163^x164)); if (t38 != 0) { NG(); } else { ; } } void f39(void) { uint8_t x165 = UINT8_MAX; uint64_t x166 = UINT64_MAX; int32_t x167 = -1; volatile int8_t x168 = -1; volatile int32_t t39 = 0; t39 = ((x165+x166)<=(x167^x168)); if (t39 != 0) { NG(); } else { ; } } void f40(void) { int8_t x173 = 12; int8_t x174 = INT8_MIN; static uint16_t x175 = 31471U; uint32_t x176 = 9674U; int32_t t40 = 4704; t40 = ((x173+x174)<=(x175^x176)); if (t40 != 0) { NG(); } else { ; } } void f41(void) { int64_t x177 = 5LL; volatile uint16_t x178 = 9U; int8_t x179 = INT8_MIN; static uint16_t x180 = 905U; volatile int32_t t41 = 168152; t41 = ((x177+x178)<=(x179^x180)); if (t41 != 0) { NG(); } else { ; } } void f42(void) { uint32_t x181 = 1354U; uint64_t x182 = UINT64_MAX; static int8_t x183 = INT8_MIN; static volatile int32_t x184 = INT32_MAX; static volatile int32_t t42 = 1102; t42 = ((x181+x182)<=(x183^x184)); if (t42 != 1) { NG(); } else { ; } } void f43(void) { volatile int64_t x189 = -1LL; volatile int32_t x190 = INT32_MIN; int32_t x191 = INT32_MAX; int16_t x192 = -1; volatile int32_t t43 = -27619; t43 = ((x189+x190)<=(x191^x192)); if (t43 != 1) { NG(); } else { ; } } void f44(void) { int32_t x193 = INT32_MIN; int16_t x194 = 17; static volatile int16_t x196 = INT16_MAX; t44 = ((x193+x194)<=(x195^x196)); if (t44 != 1) { NG(); } else { ; } } void f45(void) { uint8_t x197 = 2U; int32_t x198 = 421; int8_t x199 = -48; static uint64_t x200 = 34792900413179569LLU; volatile int32_t t45 = 5030; t45 = ((x197+x198)<=(x199^x200)); if (t45 != 1) { NG(); } else { ; } } void f46(void) { uint64_t x201 = UINT64_MAX; static int16_t x202 = INT16_MIN; static volatile int32_t x203 = INT32_MIN; uint64_t x204 = 13766LLU; volatile int32_t t46 = 1; t46 = ((x201+x202)<=(x203^x204)); if (t46 != 0) { NG(); } else { ; } } void f47(void) { static volatile uint32_t x205 = UINT32_MAX; int64_t x206 = -86071608472710184LL; int32_t x207 = INT32_MAX; volatile int16_t x208 = -11; static volatile int32_t t47 = 3279425; t47 = ((x205+x206)<=(x207^x208)); if (t47 != 1) { NG(); } else { ; } } void f48(void) { int32_t x209 = INT32_MIN; int16_t x211 = 993; static uint8_t x212 = 1U; volatile int32_t t48 = -207; t48 = ((x209+x210)<=(x211^x212)); if (t48 != 0) { NG(); } else { ; } } void f49(void) { static volatile int32_t x213 = 14; int64_t x214 = -233053867LL; uint64_t x215 = 30952944792LLU; volatile int32_t t49 = 448905701; t49 = ((x213+x214)<=(x215^x216)); if (t49 != 0) { NG(); } else { ; } } void f50(void) { volatile uint16_t x218 = 6U; uint32_t x219 = UINT32_MAX; static volatile int32_t t50 = 564549245; t50 = ((x217+x218)<=(x219^x220)); if (t50 != 1) { NG(); } else { ; } } void f51(void) { uint32_t x221 = UINT32_MAX; int8_t x222 = -1; int16_t x223 = 1; int32_t x224 = INT32_MAX; volatile int32_t t51 = -245963163; t51 = ((x221+x222)<=(x223^x224)); if (t51 != 0) { NG(); } else { ; } } void f52(void) { volatile int8_t x225 = INT8_MIN; static int64_t x226 = -1LL; volatile uint8_t x227 = UINT8_MAX; uint16_t x228 = 1551U; static int32_t t52 = -8; t52 = ((x225+x226)<=(x227^x228)); if (t52 != 1) { NG(); } else { ; } } void f53(void) { volatile int64_t x230 = INT64_MIN; int8_t x232 = INT8_MIN; int32_t t53 = 182; t53 = ((x229+x230)<=(x231^x232)); if (t53 != 1) { NG(); } else { ; } } void f54(void) { int64_t x233 = 11922072LL; volatile int8_t x234 = -1; int32_t x235 = INT32_MIN; volatile int32_t t54 = -5; t54 = ((x233+x234)<=(x235^x236)); if (t54 != 0) { NG(); } else { ; } } void f55(void) { volatile int16_t x238 = INT16_MAX; uint64_t x239 = UINT64_MAX; int32_t x240 = -1; volatile int32_t t55 = 173; t55 = ((x237+x238)<=(x239^x240)); if (t55 != 0) { NG(); } else { ; } } void f56(void) { uint16_t x241 = 3U; int32_t x242 = INT32_MIN; int8_t x243 = -1; uint16_t x244 = 26309U; static volatile int32_t t56 = -13; t56 = ((x241+x242)<=(x243^x244)); if (t56 != 1) { NG(); } else { ; } } void f57(void) { int32_t x246 = INT32_MAX; uint16_t x247 = 112U; uint64_t x248 = UINT64_MAX; int32_t t57 = 1570526; t57 = ((x245+x246)<=(x247^x248)); if (t57 != 1) { NG(); } else { ; } } void f58(void) { int16_t x249 = INT16_MAX; volatile uint32_t x250 = 6139092U; int8_t x251 = -1; static volatile uint8_t x252 = UINT8_MAX; int32_t t58 = -691558640; t58 = ((x249+x250)<=(x251^x252)); if (t58 != 1) { NG(); } else { ; } } void f59(void) { int32_t x253 = 1755151; uint16_t x254 = 18U; int16_t x255 = INT16_MIN; int32_t x256 = -1; volatile int32_t t59 = 27790496; t59 = ((x253+x254)<=(x255^x256)); if (t59 != 0) { NG(); } else { ; } } void f60(void) { int8_t x261 = 63; volatile uint64_t x262 = 6920LLU; int16_t x263 = INT16_MIN; uint16_t x264 = UINT16_MAX; volatile int32_t t60 = -8879487; t60 = ((x261+x262)<=(x263^x264)); if (t60 != 1) { NG(); } else { ; } } void f61(void) { int8_t x265 = -1; uint64_t x266 = 0LLU; volatile int8_t x268 = INT8_MAX; int32_t t61 = -1; t61 = ((x265+x266)<=(x267^x268)); if (t61 != 0) { NG(); } else { ; } } void f62(void) { int16_t x269 = -1; uint32_t x270 = 6042499U; static int8_t x272 = -1; t62 = ((x269+x270)<=(x271^x272)); if (t62 != 1) { NG(); } else { ; } } void f63(void) { static uint64_t x273 = 2LLU; int16_t x274 = INT16_MIN; t63 = ((x273+x274)<=(x275^x276)); if (t63 != 0) { NG(); } else { ; } } void f64(void) { volatile int32_t x277 = -4; static int64_t x278 = 0LL; volatile int16_t x279 = 8; int32_t x280 = 6; t64 = ((x277+x278)<=(x279^x280)); if (t64 != 1) { NG(); } else { ; } } void f65(void) { uint64_t x281 = 37846925934503LLU; int32_t x282 = INT32_MAX; uint16_t x283 = 7U; int64_t x284 = INT64_MAX; int32_t t65 = -89; t65 = ((x281+x282)<=(x283^x284)); if (t65 != 1) { NG(); } else { ; } } void f66(void) { uint64_t x285 = UINT64_MAX; uint8_t x286 = UINT8_MAX; int32_t x287 = INT32_MIN; int32_t x288 = INT32_MIN; static int32_t t66 = 3; t66 = ((x285+x286)<=(x287^x288)); if (t66 != 0) { NG(); } else { ; } } void f67(void) { static uint8_t x291 = 0U; int8_t x292 = INT8_MIN; int32_t t67 = 4; t67 = ((x289+x290)<=(x291^x292)); if (t67 != 1) { NG(); } else { ; } } void f68(void) { static uint16_t x293 = 17U; static int32_t x295 = -5258; static int64_t x296 = -1LL; int32_t t68 = 1488; t68 = ((x293+x294)<=(x295^x296)); if (t68 != 0) { NG(); } else { ; } } void f69(void) { uint32_t x298 = 15U; uint32_t x300 = 3U; volatile int32_t t69 = 14936123; t69 = ((x297+x298)<=(x299^x300)); if (t69 != 1) { NG(); } else { ; } } void f70(void) { int16_t x301 = INT16_MAX; uint8_t x304 = 1U; int32_t t70 = 297; t70 = ((x301+x302)<=(x303^x304)); if (t70 != 1) { NG(); } else { ; } } void f71(void) { uint64_t x305 = 517751LLU; int32_t x306 = 234; uint16_t x307 = 25543U; int32_t t71 = -5470115; t71 = ((x305+x306)<=(x307^x308)); if (t71 != 0) { NG(); } else { ; } } void f72(void) { int8_t x313 = INT8_MIN; uint16_t x314 = UINT16_MAX; volatile int32_t t72 = -2985; t72 = ((x313+x314)<=(x315^x316)); if (t72 != 0) { NG(); } else { ; } } void f73(void) { int16_t x317 = -1; static uint64_t x318 = 3134573482534LLU; int32_t x319 = INT32_MIN; static int16_t x320 = INT16_MAX; volatile int32_t t73 = -450; t73 = ((x317+x318)<=(x319^x320)); if (t73 != 1) { NG(); } else { ; } } void f74(void) { int16_t x322 = -2939; uint8_t x323 = 3U; int32_t t74 = 32894; t74 = ((x321+x322)<=(x323^x324)); if (t74 != 1) { NG(); } else { ; } } void f75(void) { int16_t x325 = -2; int16_t x326 = INT16_MAX; uint64_t x327 = UINT64_MAX; int8_t x328 = -1; volatile int32_t t75 = 1042; t75 = ((x325+x326)<=(x327^x328)); if (t75 != 0) { NG(); } else { ; } } void f76(void) { int32_t x330 = INT32_MIN; uint16_t x331 = UINT16_MAX; static int32_t t76 = -25182; t76 = ((x329+x330)<=(x331^x332)); if (t76 != 1) { NG(); } else { ; } } void f77(void) { int8_t x333 = INT8_MAX; int8_t x334 = INT8_MIN; int64_t x336 = -25LL; t77 = ((x333+x334)<=(x335^x336)); if (t77 != 0) { NG(); } else { ; } } void f78(void) { int32_t x337 = 17; int64_t x338 = -384586608755361686LL; uint64_t x339 = UINT64_MAX; volatile int32_t x340 = -1; t78 = ((x337+x338)<=(x339^x340)); if (t78 != 0) { NG(); } else { ; } } void f79(void) { static int32_t x342 = INT32_MIN; int64_t x343 = INT64_MAX; uint16_t x344 = 0U; t79 = ((x341+x342)<=(x343^x344)); if (t79 != 1) { NG(); } else { ; } } void f80(void) { volatile uint16_t x345 = UINT16_MAX; static int8_t x346 = INT8_MAX; int32_t x348 = INT32_MIN; t80 = ((x345+x346)<=(x347^x348)); if (t80 != 0) { NG(); } else { ; } } void f81(void) { int64_t x350 = INT64_MIN; int32_t x351 = -194; int8_t x352 = -3; volatile int32_t t81 = -1246181; t81 = ((x349+x350)<=(x351^x352)); if (t81 != 1) { NG(); } else { ; } } void f82(void) { volatile int16_t x353 = -3; uint16_t x354 = 826U; uint32_t x355 = 62U; static int32_t x356 = INT32_MIN; volatile int32_t t82 = 119306869; t82 = ((x353+x354)<=(x355^x356)); if (t82 != 1) { NG(); } else { ; } } void f83(void) { volatile int8_t x357 = 0; static int8_t x358 = 1; int16_t x359 = -15; static int32_t x360 = INT32_MIN; volatile int32_t t83 = 30011; t83 = ((x357+x358)<=(x359^x360)); if (t83 != 1) { NG(); } else { ; } } void f84(void) { int32_t t84 = 1334277; t84 = ((x361+x362)<=(x363^x364)); if (t84 != 1) { NG(); } else { ; } } void f85(void) { int8_t x365 = 7; volatile uint8_t x366 = UINT8_MAX; volatile int32_t x367 = -1; volatile int32_t x368 = INT32_MIN; volatile int32_t t85 = -14358; t85 = ((x365+x366)<=(x367^x368)); if (t85 != 1) { NG(); } else { ; } } void f86(void) { static volatile uint8_t x369 = UINT8_MAX; static uint64_t x370 = UINT64_MAX; volatile int64_t x372 = INT64_MIN; t86 = ((x369+x370)<=(x371^x372)); if (t86 != 1) { NG(); } else { ; } } void f87(void) { static int32_t x378 = -61602; static volatile int8_t x379 = 58; static volatile int8_t x380 = INT8_MIN; t87 = ((x377+x378)<=(x379^x380)); if (t87 != 1) { NG(); } else { ; } } void f88(void) { int16_t x381 = -1; volatile int8_t x382 = INT8_MIN; static uint8_t x383 = 14U; int8_t x384 = INT8_MIN; static int32_t t88 = -11; t88 = ((x381+x382)<=(x383^x384)); if (t88 != 1) { NG(); } else { ; } } void f89(void) { int32_t x389 = 17609496; static uint32_t x390 = 25813U; int16_t x391 = INT16_MIN; int64_t x392 = -1LL; volatile int32_t t89 = 0; t89 = ((x389+x390)<=(x391^x392)); if (t89 != 0) { NG(); } else { ; } } void f90(void) { volatile uint32_t x393 = UINT32_MAX; int64_t x394 = -7714410084667556LL; int64_t x395 = -483571198318276212LL; int16_t x396 = -1; volatile int32_t t90 = -3847; t90 = ((x393+x394)<=(x395^x396)); if (t90 != 1) { NG(); } else { ; } } void f91(void) { volatile uint16_t x397 = 13645U; uint16_t x398 = UINT16_MAX; int8_t x399 = -1; uint64_t x400 = 0LLU; static volatile int32_t t91 = 314; t91 = ((x397+x398)<=(x399^x400)); if (t91 != 1) { NG(); } else { ; } } void f92(void) { static volatile int32_t x401 = INT32_MAX; int32_t x402 = INT32_MIN; volatile int64_t x403 = INT64_MIN; uint8_t x404 = UINT8_MAX; int32_t t92 = 74684; t92 = ((x401+x402)<=(x403^x404)); if (t92 != 0) { NG(); } else { ; } } void f93(void) { uint16_t x407 = 4U; uint8_t x408 = 56U; volatile int32_t t93 = 7746; t93 = ((x405+x406)<=(x407^x408)); if (t93 != 0) { NG(); } else { ; } } void f94(void) { static int8_t x409 = -1; static int8_t x411 = INT8_MIN; int64_t x412 = INT64_MIN; static volatile int32_t t94 = 7126; t94 = ((x409+x410)<=(x411^x412)); if (t94 != 1) { NG(); } else { ; } } void f95(void) { uint8_t x413 = 2U; int16_t x414 = INT16_MAX; uint16_t x415 = UINT16_MAX; int32_t t95 = 12; t95 = ((x413+x414)<=(x415^x416)); if (t95 != 0) { NG(); } else { ; } } void f96(void) { int16_t x417 = 12280; volatile int16_t x419 = -44; static int16_t x420 = 1; static volatile int32_t t96 = 2; t96 = ((x417+x418)<=(x419^x420)); if (t96 != 1) { NG(); } else { ; } } void f97(void) { int64_t x421 = INT64_MAX; uint32_t x423 = 1487956607U; volatile int64_t x424 = -8270249617819249LL; volatile int32_t t97 = -440; t97 = ((x421+x422)<=(x423^x424)); if (t97 != 0) { NG(); } else { ; } } void f98(void) { int32_t x426 = -1; int64_t x427 = -2178199366384452235LL; static int8_t x428 = INT8_MIN; int32_t t98 = 13224841; t98 = ((x425+x426)<=(x427^x428)); if (t98 != 1) { NG(); } else { ; } } void f99(void) { volatile uint64_t x431 = UINT64_MAX; uint8_t x432 = 4U; t99 = ((x429+x430)<=(x431^x432)); if (t99 != 1) { NG(); } else { ; } } void f100(void) { volatile int64_t x434 = INT64_MIN; int64_t x435 = INT64_MAX; volatile uint32_t x436 = 1031U; int32_t t100 = -16690516; t100 = ((x433+x434)<=(x435^x436)); if (t100 != 1) { NG(); } else { ; } } void f101(void) { uint16_t x437 = 8U; static int64_t x439 = -1LL; uint16_t x440 = UINT16_MAX; t101 = ((x437+x438)<=(x439^x440)); if (t101 != 1) { NG(); } else { ; } } void f102(void) { volatile int8_t x441 = INT8_MAX; int32_t x443 = INT32_MIN; uint32_t x444 = 1U; int32_t t102 = 14; t102 = ((x441+x442)<=(x443^x444)); if (t102 != 1) { NG(); } else { ; } } void f103(void) { uint16_t x445 = UINT16_MAX; volatile int16_t x446 = -1; int8_t x447 = -21; int32_t x448 = INT32_MAX; int32_t t103 = 314069956; t103 = ((x445+x446)<=(x447^x448)); if (t103 != 0) { NG(); } else { ; } } void f104(void) { int8_t x450 = INT8_MIN; uint16_t x451 = 17U; int8_t x452 = 1; volatile int32_t t104 = -3589147; t104 = ((x449+x450)<=(x451^x452)); if (t104 != 1) { NG(); } else { ; } } void f105(void) { int64_t x453 = -1LL; int32_t x454 = INT32_MIN; volatile int32_t x455 = -23; int64_t x456 = -1LL; volatile int32_t t105 = 0; t105 = ((x453+x454)<=(x455^x456)); if (t105 != 1) { NG(); } else { ; } } void f106(void) { int64_t x457 = INT64_MAX; volatile int16_t x458 = INT16_MIN; uint16_t x459 = 1U; int64_t x460 = 505610LL; static int32_t t106 = 859884; t106 = ((x457+x458)<=(x459^x460)); if (t106 != 0) { NG(); } else { ; } } void f107(void) { uint64_t x461 = UINT64_MAX; uint32_t x462 = UINT32_MAX; volatile uint64_t x463 = UINT64_MAX; int32_t x464 = INT32_MIN; t107 = ((x461+x462)<=(x463^x464)); if (t107 != 0) { NG(); } else { ; } } void f108(void) { static volatile uint64_t x471 = 6119752608LLU; t108 = ((x469+x470)<=(x471^x472)); if (t108 != 0) { NG(); } else { ; } } void f109(void) { int8_t x473 = INT8_MIN; int64_t x474 = INT64_MAX; int8_t x475 = INT8_MIN; uint32_t x476 = UINT32_MAX; t109 = ((x473+x474)<=(x475^x476)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { uint32_t x477 = 208689407U; int64_t x479 = INT64_MIN; int16_t x480 = INT16_MIN; int32_t t110 = -81406265; t110 = ((x477+x478)<=(x479^x480)); if (t110 != 1) { NG(); } else { ; } } void f111(void) { int16_t x481 = INT16_MAX; uint8_t x482 = 6U; uint64_t x483 = 3532LLU; int64_t x484 = INT64_MIN; t111 = ((x481+x482)<=(x483^x484)); if (t111 != 1) { NG(); } else { ; } } void f112(void) { static uint64_t x485 = 14956073LLU; uint8_t x486 = UINT8_MAX; volatile uint32_t x487 = 18U; uint32_t x488 = 1U; volatile int32_t t112 = -13; t112 = ((x485+x486)<=(x487^x488)); if (t112 != 0) { NG(); } else { ; } } void f113(void) { volatile int32_t x489 = INT32_MIN; int64_t x490 = INT64_MAX; uint32_t x491 = 168035691U; static volatile int32_t t113 = 13132456; t113 = ((x489+x490)<=(x491^x492)); if (t113 != 0) { NG(); } else { ; } } void f114(void) { int32_t x493 = -1; uint16_t x494 = 5U; int64_t x495 = -1649LL; int16_t x496 = INT16_MIN; volatile int32_t t114 = -2; t114 = ((x493+x494)<=(x495^x496)); if (t114 != 1) { NG(); } else { ; } } void f115(void) { int16_t x498 = -1; int16_t x499 = INT16_MIN; int16_t x500 = INT16_MIN; t115 = ((x497+x498)<=(x499^x500)); if (t115 != 1) { NG(); } else { ; } } void f116(void) { static uint8_t x501 = 1U; uint8_t x502 = 0U; uint16_t x503 = 1569U; int32_t x504 = -1; static int32_t t116 = 1064; t116 = ((x501+x502)<=(x503^x504)); if (t116 != 0) { NG(); } else { ; } } void f117(void) { static uint32_t x505 = 1U; static volatile int16_t x506 = -6; int32_t x507 = INT32_MAX; int64_t x508 = -1151854974401716LL; static volatile int32_t t117 = -2; t117 = ((x505+x506)<=(x507^x508)); if (t117 != 0) { NG(); } else { ; } } void f118(void) { int16_t x513 = INT16_MIN; int16_t x514 = INT16_MAX; uint8_t x515 = 54U; volatile int32_t t118 = -206084034; t118 = ((x513+x514)<=(x515^x516)); if (t118 != 1) { NG(); } else { ; } } void f119(void) { int8_t x517 = INT8_MIN; static int8_t x518 = -1; int16_t x519 = INT16_MAX; static int64_t x520 = INT64_MIN; volatile int32_t t119 = -8669; t119 = ((x517+x518)<=(x519^x520)); if (t119 != 0) { NG(); } else { ; } } void f120(void) { int16_t x521 = -3; uint32_t x522 = UINT32_MAX; int32_t x523 = -9920142; int16_t x524 = INT16_MIN; volatile int32_t t120 = -1; t120 = ((x521+x522)<=(x523^x524)); if (t120 != 0) { NG(); } else { ; } } void f121(void) { int32_t x530 = INT32_MIN; int64_t x531 = -42566743360LL; volatile int64_t x532 = INT64_MIN; int32_t t121 = 377276; t121 = ((x529+x530)<=(x531^x532)); if (t121 != 1) { NG(); } else { ; } } void f122(void) { uint32_t x533 = 18525200U; int64_t x535 = INT64_MAX; uint64_t x536 = UINT64_MAX; int32_t t122 = -6519241; t122 = ((x533+x534)<=(x535^x536)); if (t122 != 1) { NG(); } else { ; } } void f123(void) { int16_t x537 = INT16_MIN; uint64_t x538 = UINT64_MAX; int16_t x539 = INT16_MIN; int32_t t123 = -1; t123 = ((x537+x538)<=(x539^x540)); if (t123 != 0) { NG(); } else { ; } } void f124(void) { static int8_t x541 = INT8_MIN; int16_t x542 = 8146; uint32_t x543 = 2823U; uint16_t x544 = UINT16_MAX; int32_t t124 = 7902; t124 = ((x541+x542)<=(x543^x544)); if (t124 != 1) { NG(); } else { ; } } void f125(void) { int32_t x545 = INT32_MIN; uint64_t x547 = 948564713LLU; int64_t x548 = INT64_MIN; volatile int32_t t125 = -705744; t125 = ((x545+x546)<=(x547^x548)); if (t125 != 1) { NG(); } else { ; } } void f126(void) { uint32_t x549 = 190367U; int32_t x550 = -211057; uint16_t x551 = 22170U; volatile uint8_t x552 = UINT8_MAX; volatile int32_t t126 = -2615; t126 = ((x549+x550)<=(x551^x552)); if (t126 != 0) { NG(); } else { ; } } void f127(void) { int16_t x553 = -26; static volatile int16_t x554 = 0; uint8_t x555 = 12U; int32_t x556 = INT32_MIN; int32_t t127 = 4537; t127 = ((x553+x554)<=(x555^x556)); if (t127 != 0) { NG(); } else { ; } } void f128(void) { volatile uint16_t x557 = 4U; volatile int16_t x558 = INT16_MAX; int16_t x559 = INT16_MIN; int32_t t128 = -540080; t128 = ((x557+x558)<=(x559^x560)); if (t128 != 0) { NG(); } else { ; } } void f129(void) { uint32_t x561 = UINT32_MAX; static int8_t x562 = INT8_MIN; int8_t x563 = INT8_MIN; static volatile int8_t x564 = INT8_MAX; int32_t t129 = 82256; t129 = ((x561+x562)<=(x563^x564)); if (t129 != 1) { NG(); } else { ; } } void f130(void) { static uint32_t x565 = UINT32_MAX; int64_t x566 = 2LL; volatile int16_t x567 = 5493; static int16_t x568 = INT16_MIN; volatile int32_t t130 = 5070912; t130 = ((x565+x566)<=(x567^x568)); if (t130 != 0) { NG(); } else { ; } } void f131(void) { uint8_t x571 = 2U; int32_t x572 = INT32_MAX; t131 = ((x569+x570)<=(x571^x572)); if (t131 != 0) { NG(); } else { ; } } void f132(void) { static int64_t x573 = INT64_MIN; int8_t x574 = 59; volatile int16_t x576 = -1; volatile int32_t t132 = -1724201; t132 = ((x573+x574)<=(x575^x576)); if (t132 != 1) { NG(); } else { ; } } void f133(void) { volatile int32_t x577 = -1; static int16_t x578 = INT16_MAX; int32_t x579 = -610449; t133 = ((x577+x578)<=(x579^x580)); if (t133 != 0) { NG(); } else { ; } } void f134(void) { int32_t x581 = 320975065; uint32_t x582 = 478U; uint8_t x583 = 1U; int32_t x584 = INT32_MIN; volatile int32_t t134 = -5155765; t134 = ((x581+x582)<=(x583^x584)); if (t134 != 1) { NG(); } else { ; } } void f135(void) { uint8_t x585 = 4U; uint32_t x586 = UINT32_MAX; uint8_t x587 = 4U; uint64_t x588 = 231906811443848LLU; static int32_t t135 = 1848; t135 = ((x585+x586)<=(x587^x588)); if (t135 != 1) { NG(); } else { ; } } void f136(void) { int8_t x590 = INT8_MIN; int64_t x591 = -5669144LL; static uint64_t x592 = UINT64_MAX; int32_t t136 = 5; t136 = ((x589+x590)<=(x591^x592)); if (t136 != 0) { NG(); } else { ; } } void f137(void) { static int8_t x597 = 30; volatile int16_t x598 = INT16_MAX; int8_t x599 = -1; int32_t t137 = -43930; t137 = ((x597+x598)<=(x599^x600)); if (t137 != 0) { NG(); } else { ; } } void f138(void) { int16_t x602 = 135; int32_t x603 = -1; static uint16_t x604 = 11271U; t138 = ((x601+x602)<=(x603^x604)); if (t138 != 0) { NG(); } else { ; } } void f139(void) { int64_t x605 = -1LL; uint64_t x606 = 15162545876LLU; static int16_t x607 = -1; int16_t x608 = 1; volatile int32_t t139 = 15447; t139 = ((x605+x606)<=(x607^x608)); if (t139 != 1) { NG(); } else { ; } } void f140(void) { uint16_t x609 = 15U; uint32_t x610 = 53110U; int64_t x611 = -57LL; static uint8_t x612 = UINT8_MAX; int32_t t140 = 1061087; t140 = ((x609+x610)<=(x611^x612)); if (t140 != 0) { NG(); } else { ; } } void f141(void) { uint32_t x613 = 1065U; int8_t x614 = -6; int16_t x615 = -1; uint32_t x616 = UINT32_MAX; static volatile int32_t t141 = -32932; t141 = ((x613+x614)<=(x615^x616)); if (t141 != 0) { NG(); } else { ; } } void f142(void) { static uint16_t x617 = 643U; volatile int8_t x618 = INT8_MIN; uint64_t x619 = 180830698LLU; uint64_t x620 = 8727361601LLU; static volatile int32_t t142 = -1827944; t142 = ((x617+x618)<=(x619^x620)); if (t142 != 1) { NG(); } else { ; } } void f143(void) { static uint32_t x625 = UINT32_MAX; uint16_t x626 = 5U; uint32_t x627 = 1884U; volatile int32_t t143 = -151176; t143 = ((x625+x626)<=(x627^x628)); if (t143 != 1) { NG(); } else { ; } } void f144(void) { static int16_t x629 = 224; uint32_t x630 = 4645597U; volatile uint16_t x631 = 13469U; volatile int32_t t144 = 13162; t144 = ((x629+x630)<=(x631^x632)); if (t144 != 1) { NG(); } else { ; } } void f145(void) { uint64_t x641 = UINT64_MAX; static int16_t x642 = 272; uint8_t x644 = UINT8_MAX; volatile int32_t t145 = -3625739; t145 = ((x641+x642)<=(x643^x644)); if (t145 != 1) { NG(); } else { ; } } void f146(void) { volatile int8_t x645 = INT8_MAX; int16_t x646 = -1; int32_t x647 = 33554; int64_t x648 = -1LL; volatile int32_t t146 = 1445829; t146 = ((x645+x646)<=(x647^x648)); if (t146 != 0) { NG(); } else { ; } } void f147(void) { volatile int32_t x649 = INT32_MAX; uint16_t x652 = 431U; volatile int32_t t147 = 115905208; t147 = ((x649+x650)<=(x651^x652)); if (t147 != 0) { NG(); } else { ; } } void f148(void) { static int64_t x653 = 916633264662054086LL; int64_t x655 = INT64_MIN; static int32_t x656 = 42245830; static int32_t t148 = 872409; t148 = ((x653+x654)<=(x655^x656)); if (t148 != 0) { NG(); } else { ; } } void f149(void) { int64_t x657 = 1990206656520LL; volatile int16_t x658 = -1; int64_t x659 = -1LL; int8_t x660 = INT8_MIN; t149 = ((x657+x658)<=(x659^x660)); if (t149 != 0) { NG(); } else { ; } } void f150(void) { int64_t x662 = 0LL; static int16_t x663 = INT16_MAX; volatile int64_t x664 = INT64_MIN; static volatile int32_t t150 = -517693361; t150 = ((x661+x662)<=(x663^x664)); if (t150 != 1) { NG(); } else { ; } } void f151(void) { int32_t x665 = -297078030; static uint8_t x666 = UINT8_MAX; int32_t x667 = -1; int8_t x668 = 11; static volatile int32_t t151 = 4625; t151 = ((x665+x666)<=(x667^x668)); if (t151 != 1) { NG(); } else { ; } } void f152(void) { uint64_t x669 = UINT64_MAX; int64_t x672 = -24598039700135775LL; t152 = ((x669+x670)<=(x671^x672)); if (t152 != 1) { NG(); } else { ; } } void f153(void) { int8_t x674 = INT8_MAX; volatile uint64_t x676 = 322400LLU; volatile int32_t t153 = 46480; t153 = ((x673+x674)<=(x675^x676)); if (t153 != 0) { NG(); } else { ; } } void f154(void) { uint64_t x677 = 49062LLU; int16_t x678 = INT16_MIN; int32_t x679 = -1; int32_t x680 = INT32_MIN; int32_t t154 = 0; t154 = ((x677+x678)<=(x679^x680)); if (t154 != 1) { NG(); } else { ; } } void f155(void) { static volatile int16_t x681 = INT16_MIN; int16_t x682 = 346; int64_t x683 = INT64_MIN; static int64_t x684 = INT64_MAX; int32_t t155 = -15622; t155 = ((x681+x682)<=(x683^x684)); if (t155 != 1) { NG(); } else { ; } } void f156(void) { volatile int8_t x685 = -1; uint64_t x686 = 2983806218005697456LLU; volatile int16_t x687 = INT16_MAX; volatile int64_t x688 = INT64_MIN; volatile int32_t t156 = 13745517; t156 = ((x685+x686)<=(x687^x688)); if (t156 != 1) { NG(); } else { ; } } void f157(void) { int64_t x689 = INT64_MIN; uint8_t x690 = 5U; int32_t x692 = INT32_MIN; volatile int32_t t157 = -247329375; t157 = ((x689+x690)<=(x691^x692)); if (t157 != 1) { NG(); } else { ; } } void f158(void) { int32_t x693 = INT32_MIN; uint8_t x695 = UINT8_MAX; static int64_t x696 = -11340627191452LL; volatile int32_t t158 = 993; t158 = ((x693+x694)<=(x695^x696)); if (t158 != 0) { NG(); } else { ; } } void f159(void) { int16_t x698 = 15760; uint16_t x699 = 12U; uint64_t x700 = UINT64_MAX; volatile int32_t t159 = -1221; t159 = ((x697+x698)<=(x699^x700)); if (t159 != 1) { NG(); } else { ; } } void f160(void) { int32_t x701 = INT32_MAX; int16_t x703 = INT16_MIN; int32_t t160 = -38; t160 = ((x701+x702)<=(x703^x704)); if (t160 != 1) { NG(); } else { ; } } void f161(void) { int32_t x706 = -1; static uint8_t x707 = 98U; int64_t x708 = INT64_MIN; int32_t t161 = 50; t161 = ((x705+x706)<=(x707^x708)); if (t161 != 0) { NG(); } else { ; } } void f162(void) { int8_t x709 = 0; uint8_t x710 = 0U; uint16_t x711 = 1058U; t162 = ((x709+x710)<=(x711^x712)); if (t162 != 0) { NG(); } else { ; } } void f163(void) { int64_t x714 = -99LL; uint16_t x715 = UINT16_MAX; uint32_t x716 = UINT32_MAX; volatile int32_t t163 = -327469412; t163 = ((x713+x714)<=(x715^x716)); if (t163 != 1) { NG(); } else { ; } } void f164(void) { int32_t x718 = -1; uint64_t x719 = 1494890780LLU; int32_t x720 = INT32_MAX; volatile int32_t t164 = -130919931; t164 = ((x717+x718)<=(x719^x720)); if (t164 != 1) { NG(); } else { ; } } void f165(void) { static volatile uint16_t x721 = 0U; uint16_t x722 = UINT16_MAX; volatile int64_t x723 = 218481LL; int64_t x724 = INT64_MAX; int32_t t165 = -76397; t165 = ((x721+x722)<=(x723^x724)); if (t165 != 1) { NG(); } else { ; } } void f166(void) { int16_t x725 = -440; uint64_t x726 = UINT64_MAX; volatile int32_t x727 = 930253; uint8_t x728 = 0U; int32_t t166 = -461373897; t166 = ((x725+x726)<=(x727^x728)); if (t166 != 0) { NG(); } else { ; } } void f167(void) { uint16_t x729 = 18648U; volatile int8_t x730 = INT8_MAX; uint16_t x731 = UINT16_MAX; uint16_t x732 = 0U; volatile int32_t t167 = -63; t167 = ((x729+x730)<=(x731^x732)); if (t167 != 1) { NG(); } else { ; } } void f168(void) { uint16_t x733 = 288U; uint32_t x734 = UINT32_MAX; int64_t x736 = INT64_MIN; volatile int32_t t168 = 720108575; t168 = ((x733+x734)<=(x735^x736)); if (t168 != 0) { NG(); } else { ; } } void f169(void) { int8_t x737 = INT8_MIN; uint16_t x738 = 9U; uint64_t x739 = 5041393035235LLU; int64_t x740 = -1LL; int32_t t169 = -417933; t169 = ((x737+x738)<=(x739^x740)); if (t169 != 0) { NG(); } else { ; } } void f170(void) { int16_t x745 = INT16_MIN; int16_t x746 = INT16_MIN; static volatile int32_t x747 = INT32_MIN; t170 = ((x745+x746)<=(x747^x748)); if (t170 != 0) { NG(); } else { ; } } void f171(void) { int16_t x750 = -1; static int64_t x751 = INT64_MAX; volatile uint8_t x752 = UINT8_MAX; volatile int32_t t171 = -1; t171 = ((x749+x750)<=(x751^x752)); if (t171 != 0) { NG(); } else { ; } } void f172(void) { uint64_t x753 = UINT64_MAX; uint16_t x754 = 0U; volatile int32_t x755 = 453793; static volatile int32_t t172 = 265075424; t172 = ((x753+x754)<=(x755^x756)); if (t172 != 0) { NG(); } else { ; } } void f173(void) { static volatile uint8_t x757 = UINT8_MAX; uint16_t x758 = UINT16_MAX; int64_t x759 = INT64_MIN; int32_t x760 = -57609661; int32_t t173 = -4613; t173 = ((x757+x758)<=(x759^x760)); if (t173 != 1) { NG(); } else { ; } } void f174(void) { volatile int8_t x761 = INT8_MIN; volatile int16_t x762 = -1; uint32_t x763 = 61082089U; int32_t x764 = INT32_MAX; volatile int32_t t174 = -732155550; t174 = ((x761+x762)<=(x763^x764)); if (t174 != 0) { NG(); } else { ; } } void f175(void) { int8_t x765 = INT8_MAX; int32_t x766 = INT32_MIN; static volatile int8_t x768 = 3; volatile int32_t t175 = -5228; t175 = ((x765+x766)<=(x767^x768)); if (t175 != 1) { NG(); } else { ; } } void f176(void) { static int8_t x769 = INT8_MAX; static volatile int8_t x770 = -1; volatile uint64_t x771 = UINT64_MAX; int8_t x772 = -1; static volatile int32_t t176 = 1469652; t176 = ((x769+x770)<=(x771^x772)); if (t176 != 0) { NG(); } else { ; } } void f177(void) { uint64_t x774 = 22431298834076859LLU; int16_t x775 = INT16_MIN; int16_t x776 = INT16_MIN; volatile int32_t t177 = -957234947; t177 = ((x773+x774)<=(x775^x776)); if (t177 != 0) { NG(); } else { ; } } void f178(void) { uint16_t x777 = 1U; int16_t x778 = -1; static int64_t x779 = -1LL; uint8_t x780 = 31U; t178 = ((x777+x778)<=(x779^x780)); if (t178 != 0) { NG(); } else { ; } } void f179(void) { int32_t x781 = -1; int16_t x782 = -1; uint8_t x783 = UINT8_MAX; volatile int16_t x784 = -1; t179 = ((x781+x782)<=(x783^x784)); if (t179 != 0) { NG(); } else { ; } } void f180(void) { int8_t x785 = INT8_MIN; volatile int32_t x786 = -9202873; int8_t x787 = INT8_MIN; uint64_t x788 = 83996503814LLU; static volatile int32_t t180 = -1; t180 = ((x785+x786)<=(x787^x788)); if (t180 != 0) { NG(); } else { ; } } void f181(void) { volatile int16_t x789 = 7; volatile int32_t x790 = -103060; static int8_t x791 = INT8_MIN; static uint8_t x792 = 13U; int32_t t181 = 320; t181 = ((x789+x790)<=(x791^x792)); if (t181 != 1) { NG(); } else { ; } } void f182(void) { int64_t x793 = -2807765026704LL; int8_t x794 = -5; int8_t x795 = -39; static int16_t x796 = 7; static int32_t t182 = 2; t182 = ((x793+x794)<=(x795^x796)); if (t182 != 1) { NG(); } else { ; } } void f183(void) { int8_t x797 = INT8_MIN; uint64_t x798 = 74494LLU; int16_t x799 = INT16_MAX; volatile int32_t x800 = -1; int32_t t183 = 552280; t183 = ((x797+x798)<=(x799^x800)); if (t183 != 1) { NG(); } else { ; } } void f184(void) { int16_t x801 = -1; volatile int32_t t184 = -53187; t184 = ((x801+x802)<=(x803^x804)); if (t184 != 0) { NG(); } else { ; } } void f185(void) { static int8_t x805 = -5; static uint16_t x806 = 1U; int32_t x807 = 319; uint8_t x808 = UINT8_MAX; int32_t t185 = 82882; t185 = ((x805+x806)<=(x807^x808)); if (t185 != 1) { NG(); } else { ; } } void f186(void) { uint32_t x809 = 34U; int32_t x810 = INT32_MIN; int32_t x811 = -1; static int16_t x812 = INT16_MAX; int32_t t186 = 53909742; t186 = ((x809+x810)<=(x811^x812)); if (t186 != 1) { NG(); } else { ; } } void f187(void) { int8_t x813 = INT8_MIN; int32_t t187 = 1; t187 = ((x813+x814)<=(x815^x816)); if (t187 != 0) { NG(); } else { ; } } void f188(void) { int16_t x817 = INT16_MAX; uint64_t x818 = UINT64_MAX; int8_t x819 = INT8_MIN; int8_t x820 = 9; volatile int32_t t188 = 29384604; t188 = ((x817+x818)<=(x819^x820)); if (t188 != 1) { NG(); } else { ; } } void f189(void) { int16_t x821 = INT16_MIN; uint64_t x822 = UINT64_MAX; int64_t x823 = INT64_MAX; uint64_t x824 = 2962714120518LLU; int32_t t189 = -53; t189 = ((x821+x822)<=(x823^x824)); if (t189 != 0) { NG(); } else { ; } } void f190(void) { volatile uint64_t x825 = 143459591LLU; volatile int64_t x827 = INT64_MIN; int32_t x828 = -2024; static int32_t t190 = -30725; t190 = ((x825+x826)<=(x827^x828)); if (t190 != 1) { NG(); } else { ; } } void f191(void) { volatile uint8_t x829 = 15U; static uint8_t x830 = 1U; uint16_t x831 = UINT16_MAX; static volatile int16_t x832 = INT16_MIN; static volatile int32_t t191 = 310; t191 = ((x829+x830)<=(x831^x832)); if (t191 != 0) { NG(); } else { ; } } void f192(void) { int8_t x836 = 1; int32_t t192 = -1; t192 = ((x833+x834)<=(x835^x836)); if (t192 != 0) { NG(); } else { ; } } void f193(void) { uint8_t x837 = 14U; int16_t x838 = INT16_MAX; uint32_t x839 = 675U; static volatile uint16_t x840 = 2883U; t193 = ((x837+x838)<=(x839^x840)); if (t193 != 0) { NG(); } else { ; } } void f194(void) { int64_t x841 = -47130700370LL; static int16_t x842 = INT16_MIN; uint16_t x844 = UINT16_MAX; int32_t t194 = 123446; t194 = ((x841+x842)<=(x843^x844)); if (t194 != 1) { NG(); } else { ; } } void f195(void) { int64_t x849 = INT64_MAX; int8_t x850 = -1; int64_t x851 = INT64_MIN; int8_t x852 = INT8_MIN; int32_t t195 = -536531736; t195 = ((x849+x850)<=(x851^x852)); if (t195 != 0) { NG(); } else { ; } } void f196(void) { static uint64_t x857 = 1LLU; static uint32_t x859 = 4U; volatile int32_t t196 = -145237707; t196 = ((x857+x858)<=(x859^x860)); if (t196 != 0) { NG(); } else { ; } } void f197(void) { static int16_t x861 = INT16_MIN; uint32_t x862 = 4385U; int16_t x864 = INT16_MIN; volatile int32_t t197 = -203528383; t197 = ((x861+x862)<=(x863^x864)); if (t197 != 0) { NG(); } else { ; } } void f198(void) { volatile int8_t x865 = -13; int16_t x866 = INT16_MAX; volatile int64_t x867 = 1368357556207LL; int16_t x868 = INT16_MIN; volatile int32_t t198 = 1; t198 = ((x865+x866)<=(x867^x868)); if (t198 != 0) { NG(); } else { ; } } void f199(void) { volatile int32_t x869 = -1; uint32_t x870 = UINT32_MAX; volatile int32_t t199 = -28696; t199 = ((x869+x870)<=(x871^x872)); if (t199 != 0) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
79408.c
/** * @file game.c * @author Letter * @brief game * @version 0.1 * @date 2021-07-18 * * @copyright (c) 2021 Letter * */ #include "shell_cmd_group.h" extern int main_2048(int argc, char *argv[]); extern int main_pushbox(int argc, char* argv[]); ShellCommand gameGroup[] = { SHELL_CMD_GROUP_ITEM(SHELL_TYPE_CMD_MAIN, 2048, main_2048, game 2048\n2048 [param]\nParam: blackwhite bluered or null), SHELL_CMD_GROUP_ITEM(SHELL_TYPE_CMD_MAIN, pushbox, main_pushbox, game pushbox), SHELL_CMD_GROUP_END() }; SHELL_EXPORT_CMD_GROUP( SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, game, gameGroup, games);
834842.c
// RUN: %check -e %s #define NULL (void *)0 int a = -NULL; // CHECK: error: - requires an arithmetic type (not "void *") int b = NULL+NULL; // CHECK: error: operation between two pointers must be relational or subtraction int c = NULL+.0f; // CHECK: error: implicit cast from pointer to floating type int d[NULL+1]; // CHECK: error: array size isn't integral (void *) int e = 0?NULL:1; int x = +NULL; // CHECK: error: + requires an arithmetic type (not "void *") int y = ~NULL; // CHECK: error: ~ requires an integral type (not "void *") int z = -NULL; // CHECK: error: - requires an arithmetic type (not "void *")
201373.c
/* * * Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 * <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 "stat.h" #include <string.h> #include <rmean.h> #include <lua.h> #include <lauxlib.h> #include <lualib.h> #include "lua/utils.h" extern struct rmean *rmean_box; extern struct rmean *rmean_error; /** network statistics (iproto & cbus) */ extern struct rmean *rmean_net; extern struct rmean *rmean_tx_wal_bus; static void fill_stat_item(struct lua_State *L, int rps, int64_t total) { lua_pushstring(L, "rps"); lua_pushnumber(L, rps); lua_settable(L, -3); lua_pushstring(L, "total"); lua_pushnumber(L, total); lua_settable(L, -3); } static int set_stat_item(const char *name, int rps, int64_t total, void *cb_ctx) { struct lua_State *L = (struct lua_State *) cb_ctx; lua_pushstring(L, name); lua_newtable(L); fill_stat_item(L, rps, total); lua_settable(L, -3); return 0; } /** * A stat_foreach() callback used to handle access to e.g. * box.stats.DELETE. */ static int seek_stat_item(const char *name, int rps, int64_t total, void *cb_ctx) { struct lua_State *L = (struct lua_State *) cb_ctx; if (strcmp(name, lua_tostring(L, -1)) != 0) return 0; lua_newtable(L); fill_stat_item(L, rps, total); return 1; } static int lbox_stat_index(struct lua_State *L) { luaL_checkstring(L, -1); int res = rmean_foreach(rmean_box, seek_stat_item, L); if (res) return res; return rmean_foreach(rmean_error, seek_stat_item, L); } static int lbox_stat_call(struct lua_State *L) { lua_newtable(L); rmean_foreach(rmean_box, set_stat_item, L); rmean_foreach(rmean_error, set_stat_item, L); return 1; } static int lbox_stat_net_index(struct lua_State *L) { luaL_checkstring(L, -1); return rmean_foreach(rmean_net, seek_stat_item, L); } static int lbox_stat_net_call(struct lua_State *L) { lua_newtable(L); rmean_foreach(rmean_net, set_stat_item, L); return 1; } static const struct luaL_Reg lbox_stat_meta [] = { {"__index", lbox_stat_index}, {"__call", lbox_stat_call}, {NULL, NULL} }; static const struct luaL_Reg lbox_stat_net_meta [] = { {"__index", lbox_stat_net_index}, {"__call", lbox_stat_net_call}, {NULL, NULL} }; /** Initialize box.stat package. */ void box_lua_stat_init(struct lua_State *L) { static const struct luaL_Reg statlib [] = { {NULL, NULL} }; luaL_register_module(L, "box.stat", statlib); lua_newtable(L); luaL_register(L, NULL, lbox_stat_meta); lua_setmetatable(L, -2); lua_pop(L, 1); /* stat module */ luaL_register_module(L, "box.stat.net", statlib); lua_newtable(L); luaL_register(L, NULL, lbox_stat_net_meta); lua_setmetatable(L, -2); lua_pop(L, 1); /* stat net module */ }
6514.c
#include <stdio.h> #include "api.h" #include "crypto_aead.h" typedef unsigned char u8; typedef unsigned long long u64; typedef long long i64; #define LITTLE_ENDIAN //#define BIG_ENDIAN #define RATE (64 / 8) #define PA_ROUNDS 12 #define PB_ROUNDS 6 #define ROTR(x,n) (((x)>>(n))|((x)<<(64-(n)))) #ifdef BIG_ENDIAN #define EXT_BYTE(x,n) ((u8)((u64)(x)>>(8*(n)))) #define INS_BYTE(x,n) ((u64)(x)<<(8*(n))) #define U64BIG(x) (x) #endif #ifdef LITTLE_ENDIAN #define EXT_BYTE(x,n) ((u8)((u64)(x)>>(8*(7-(n))))) #define INS_BYTE(x,n) ((u64)(x)<<(8*(7-(n)))) #define U64BIG(x) \ ((ROTR(x, 8) & (0xFF000000FF000000ULL)) | \ (ROTR(x,24) & (0x00FF000000FF0000ULL)) | \ (ROTR(x,40) & (0x0000FF000000FF00ULL)) | \ (ROTR(x,56) & (0x000000FF000000FFULL))) #endif static const int R[5][2] = { {19, 28}, {39, 61}, {1, 6}, {10, 17}, {7, 41} }; #define ROUND(C) ({\ x2 ^= C;\ x0 ^= x4;\ x4 ^= x3;\ x2 ^= x1;\ t0 = x0;\ t4 = x4;\ t3 = x3;\ t1 = x1;\ t2 = x2;\ x0 = t0 ^ ((~t1) & t2);\ x2 = t2 ^ ((~t3) & t4);\ x4 = t4 ^ ((~t0) & t1);\ x1 = t1 ^ ((~t2) & t3);\ x3 = t3 ^ ((~t4) & t0);\ x1 ^= x0;\ t1 = x1;\ x1 = ROTR(x1, R[1][0]);\ x3 ^= x2;\ t2 = x2;\ x2 = ROTR(x2, R[2][0]);\ t4 = x4;\ t2 ^= x2;\ x2 = ROTR(x2, R[2][1] - R[2][0]);\ t3 = x3;\ t1 ^= x1;\ x3 = ROTR(x3, R[3][0]);\ x0 ^= x4;\ x4 = ROTR(x4, R[4][0]);\ t3 ^= x3;\ x2 ^= t2;\ x1 = ROTR(x1, R[1][1] - R[1][0]);\ t0 = x0;\ x2 = ~x2;\ x3 = ROTR(x3, R[3][1] - R[3][0]);\ t4 ^= x4;\ x4 = ROTR(x4, R[4][1] - R[4][0]);\ x3 ^= t3;\ x1 ^= t1;\ x0 = ROTR(x0, R[0][0]);\ x4 ^= t4;\ t0 ^= x0;\ x0 = ROTR(x0, R[0][1] - R[0][0]);\ x0 ^= t0;\ }) #define P12 ({\ ROUND(0xf0);\ ROUND(0xe1);\ ROUND(0xd2);\ ROUND(0xc3);\ ROUND(0xb4);\ ROUND(0xa5);\ ROUND(0x96);\ ROUND(0x87);\ ROUND(0x78);\ ROUND(0x69);\ ROUND(0x5a);\ ROUND(0x4b);\ }) #define P6 ({\ ROUND(0x96);\ ROUND(0x87);\ ROUND(0x78);\ ROUND(0x69);\ ROUND(0x5a);\ ROUND(0x4b);\ }) int crypto_aead_encrypt( unsigned char *c, unsigned long long *clen, const unsigned char *m, unsigned long long mlen, const unsigned char *ad, unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k) { u64 K0 = U64BIG(((u64*)k)[0]); u64 K1 = U64BIG(((u64*)k)[1]); u64 N0 = U64BIG(((u64*)npub)[0]); u64 N1 = U64BIG(((u64*)npub)[1]); u64 x0, x1, x2, x3, x4; u64 t0, t1, t2, t3, t4; u64 rlen; int i; // initialization x0 = (u64)((CRYPTO_KEYBYTES * 8) << 24 | (RATE * 8) << 16 | PA_ROUNDS << 8 | PB_ROUNDS << 0) << 32; x1 = K0; x2 = K1; x3 = N0; x4 = N1; P12; x3 ^= K0; x4 ^= K1; // process associated data if (adlen) { rlen = adlen; while (rlen >= RATE) { x0 ^= U64BIG(*(u64*)ad); P6; rlen -= RATE; ad += RATE; } for (i = 0; i < rlen; ++i, ++ad) x0 ^= INS_BYTE(*ad, i); x0 ^= INS_BYTE(0x80, rlen); P6; } x4 ^= 1; // process plaintext rlen = mlen; while (rlen >= RATE) { x0 ^= U64BIG(*(u64*)m); *(u64*)c = U64BIG(x0); P6; rlen -= RATE; m += RATE; c += RATE; } for (i = 0; i < rlen; ++i, ++m, ++c) { x0 ^= INS_BYTE(*m, i); *c = EXT_BYTE(x0, i); } x0 ^= INS_BYTE(0x80, rlen); // finalization x1 ^= K0; x2 ^= K1; P12; x3 ^= K0; x4 ^= K1; // return tag ((u64*)c)[0] = U64BIG(x3); ((u64*)c)[1] = U64BIG(x4); *clen = mlen + CRYPTO_KEYBYTES; return 0; } int crypto_aead_decrypt( unsigned char *m, unsigned long long *mlen, unsigned char *nsec, const unsigned char *c, unsigned long long clen, const unsigned char *ad, unsigned long long adlen, const unsigned char *npub, const unsigned char *k) { *mlen = 0; if (clen < CRYPTO_KEYBYTES) return -1; u64 K0 = U64BIG(((u64*)k)[0]); u64 K1 = U64BIG(((u64*)k)[1]); u64 N0 = U64BIG(((u64*)npub)[0]); u64 N1 = U64BIG(((u64*)npub)[1]); u64 x0, x1, x2, x3, x4; u64 t0, t1, t2, t3, t4; u64 rlen; int i; // initialization x0 = (u64)((CRYPTO_KEYBYTES * 8) << 24 | (RATE * 8) << 16 | PA_ROUNDS << 8 | PB_ROUNDS << 0) << 32; x1 = K0; x2 = K1; x3 = N0; x4 = N1; P12; x3 ^= K0; x4 ^= K1; // process associated data if (adlen) { rlen = adlen; while (rlen >= RATE) { x0 ^= U64BIG(*(u64*)ad); P6; rlen -= RATE; ad += RATE; } for (i = 0; i < rlen; ++i, ++ad) x0 ^= INS_BYTE(*ad, i); x0 ^= INS_BYTE(0x80, rlen); P6; } x4 ^= 1; // process plaintext rlen = clen - CRYPTO_KEYBYTES; while (rlen >= RATE) { *(u64*)m = U64BIG(x0) ^ *(u64*)c; x0 = U64BIG(*((u64*)c)); P6; rlen -= RATE; m += RATE; c += RATE; } for (i = 0; i < rlen; ++i, ++m, ++c) { *m = EXT_BYTE(x0, i) ^ *c; x0 &= ~INS_BYTE(0xff, i); x0 |= INS_BYTE(*c, i); } x0 ^= INS_BYTE(0x80, rlen); // finalization x1 ^= K0; x2 ^= K1; P12; x3 ^= K0; x4 ^= K1; // return -1 if verification fails if (((u64*)c)[0] != U64BIG(x3) || ((u64*)c)[1] != U64BIG(x4)) return -1; // return plaintext *mlen = clen - CRYPTO_KEYBYTES; return 0; }
331684.c
/* * infinity.c */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/i386/gen/infinity.c,v 1.10 2003/02/08 20:37:52 mike Exp $"); #include <math.h> /* bytes for +Infinity on a 387 */ const union __infinity_un __infinity = { { 0, 0, 0, 0, 0, 0, 0xf0, 0x7f } }; /* bytes for NaN */ const union __nan_un __nan = { { 0, 0, 0xc0, 0xff } };
190218.c
#include "all.h" #define MASK(w) (BIT(8*(w)-1)*2-1) /* must work when w==8 */ typedef struct Loc Loc; typedef struct Slice Slice; typedef struct Insert Insert; struct Loc { enum { LRoot, /* right above the original load */ LLoad, /* inserting a load is allowed */ LNoLoad, /* only scalar operations allowed */ } type; uint off; Blk *blk; }; struct Slice { Ref ref; short sz; short cls; /* load class */ }; struct Insert { uint isphi:1; uint num:31; uint bid; uint off; union { Ins ins; struct { Slice m; Phi *p; } phi; } new; }; static Fn *curf; static uint inum; /* current insertion number */ static Insert *ilog; /* global insertion log */ static uint nlog; /* number of entries in the log */ int loadsz(Ins *l) { switch (l->op) { case Oloadsb: case Oloadub: return 1; case Oloadsh: case Oloaduh: return 2; case Oloadsw: case Oloaduw: return 4; case Oload: return KWIDE(l->cls) ? 8 : 4; } die("unreachable"); } int storesz(Ins *s) { switch (s->op) { case Ostoreb: return 1; case Ostoreh: return 2; case Ostorew: case Ostores: return 4; case Ostorel: case Ostored: return 8; } die("unreachable"); } static Ref iins(int cls, int op, Ref a0, Ref a1, Loc *l) { Insert *ist; vgrow(&ilog, ++nlog); ist = &ilog[nlog-1]; ist->isphi = 0; ist->num = inum++; ist->bid = l->blk->id; ist->off = l->off; ist->new.ins = (Ins){op, R, {a0, a1}, cls}; return ist->new.ins.to = newtmp("ld", cls, curf); } static void cast(Ref *r, int cls, Loc *l) { int cls0; if (rtype(*r) == RCon) return; assert(rtype(*r) == RTmp); cls0 = curf->tmp[r->val].cls; if (cls0 == cls || (cls == Kw && cls0 == Kl)) return; assert(!KWIDE(cls0) || KWIDE(cls)); if (KWIDE(cls) == KWIDE(cls0)) *r = iins(cls, Ocast, *r, R, l); else { assert(cls == Kl); if (cls0 == Ks) *r = iins(Kw, Ocast, *r, R, l); *r = iins(Kl, Oextuw, *r, R, l); } } static inline void mask(int cls, Ref *r, bits msk, Loc *l) { cast(r, cls, l); *r = iins(cls, Oand, *r, getcon(msk, curf), l); } static Ref load(Slice sl, bits msk, Loc *l) { Alias *a; Ref r, r1; int ld, cls, all, c; ld = (int[]){ [1] = Oloadub, [2] = Oloaduh, [4] = Oloaduw, [8] = Oload }[sl.sz]; all = msk == MASK(sl.sz); if (all) cls = sl.cls; else cls = sl.sz > 4 ? Kl : Kw; r = sl.ref; /* sl.ref might not be live here, * but its alias base ref will be * (see killsl() below) */ if (rtype(r) == RTmp) { a = &curf->tmp[r.val].alias; switch (a->type) { default: die("unreachable"); case ALoc: case AEsc: case AUnk: r = a->base; if (!a->offset) break; r1 = getcon(a->offset, curf); r = iins(Kl, Oadd, r, r1, l); break; case ACon: case ASym: c = curf->ncon++; vgrow(&curf->con, curf->ncon); curf->con[c].type = CAddr; curf->con[c].label = a->label; curf->con[c].bits.i = a->offset; curf->con[c].local = 0; r = CON(c); break; } } r = iins(cls, ld, r, R, l); if (!all) mask(cls, &r, msk, l); return r; } static int killsl(Ref r, Slice sl) { Alias *a; if (rtype(sl.ref) != RTmp) return 0; a = &curf->tmp[sl.ref.val].alias; switch (a->type) { default: die("unreachable"); case ALoc: case AEsc: case AUnk: return req(a->base, r); case ACon: case ASym: return 0; } } /* returns a ref containing the contents of the slice * passed as argument, all the bits set to 0 in the * mask argument are zeroed in the result; * the returned ref has an integer class when the * mask does not cover all the bits of the slice, * otherwise, it has class sl.cls * the procedure returns R when it fails */ static Ref def(Slice sl, bits msk, Blk *b, Ins *i, Loc *il) { Blk *bp; bits msk1, msks; int off, cls, cls1, op, sz, ld; uint np, oldl, oldt; Ref r, r1; Phi *p; Insert *ist; Loc l; /* invariants: * -1- b dominates il->blk; so we can use * temporaries of b in il->blk * -2- if il->type != LNoLoad, then il->blk * postdominates the original load; so it * is safe to load in il->blk * -3- if il->type != LNoLoad, then b * postdominates il->blk (and by 2, the * original load) */ assert(dom(b, il->blk)); oldl = nlog; oldt = curf->ntmp; if (0) { Load: curf->ntmp = oldt; nlog = oldl; if (il->type != LLoad) return R; return load(sl, msk, il); } if (!i) i = &b->ins[b->nins]; cls = sl.sz > 4 ? Kl : Kw; msks = MASK(sl.sz); while (i > b->ins) { --i; if (killsl(i->to, sl) || (i->op == Ocall && escapes(sl.ref, curf))) goto Load; ld = isload(i->op); if (ld) { sz = loadsz(i); r1 = i->arg[0]; r = i->to; } else if (isstore(i->op)) { sz = storesz(i); r1 = i->arg[1]; r = i->arg[0]; } else continue; switch (alias(sl.ref, sl.sz, r1, sz, &off, curf)) { case MustAlias: if (off < 0) { off = -off; msk1 = (MASK(sz) << 8*off) & msks; op = Oshl; } else { msk1 = (MASK(sz) >> 8*off) & msks; op = Oshr; } if ((msk1 & msk) == 0) break; if (off) { cls1 = cls; if (op == Oshr && off + sl.sz > 4) cls1 = Kl; cast(&r, cls1, il); r1 = getcon(8*off, curf); r = iins(cls1, op, r, r1, il); } if ((msk1 & msk) != msk1 || off + sz < sl.sz) mask(cls, &r, msk1 & msk, il); if ((msk & ~msk1) != 0) { r1 = def(sl, msk & ~msk1, b, i, il); if (req(r1, R)) goto Load; r = iins(cls, Oor, r, r1, il); } if (msk == msks) cast(&r, sl.cls, il); return r; case MayAlias: if (ld) break; else goto Load; case NoAlias: break; default: die("unreachable"); } } for (ist=ilog; ist<&ilog[nlog]; ++ist) if (ist->isphi && ist->bid == b->id) if (req(ist->new.phi.m.ref, sl.ref)) if (ist->new.phi.m.sz == sl.sz) { r = ist->new.phi.p->to; if (msk != msks) mask(cls, &r, msk, il); else cast(&r, sl.cls, il); return r; } for (p=b->phi; p; p=p->link) if (killsl(p->to, sl)) /* scanning predecessors in that * case would be unsafe */ goto Load; if (b->npred == 0) goto Load; if (b->npred == 1) { bp = b->pred[0]; assert(bp->loop >= il->blk->loop); l = *il; if (bp->s2) l.type = LNoLoad; r1 = def(sl, msk, bp, 0, &l); if (req(r1, R)) goto Load; return r1; } r = newtmp("ld", sl.cls, curf); p = alloc(sizeof *p); vgrow(&ilog, ++nlog); ist = &ilog[nlog-1]; ist->isphi = 1; ist->bid = b->id; ist->new.phi.m = sl; ist->new.phi.p = p; p->to = r; p->cls = sl.cls; p->narg = b->npred; for (np=0; np<b->npred; ++np) { bp = b->pred[np]; if (!bp->s2 && il->type != LNoLoad && bp->loop < il->blk->loop) l.type = LLoad; else l.type = LNoLoad; l.blk = bp; l.off = bp->nins; r1 = def(sl, msks, bp, 0, &l); if (req(r1, R)) goto Load; p->arg[np] = r1; p->blk[np] = bp; } if (msk != msks) mask(cls, &r, msk, il); return r; } static int icmp(const void *pa, const void *pb) { Insert *a, *b; int c; a = (Insert *)pa; b = (Insert *)pb; if ((c = a->bid - b->bid)) return c; if (a->isphi && b->isphi) return 0; if (a->isphi) return -1; if (b->isphi) return +1; if ((c = a->off - b->off)) return c; return a->num - b->num; } /* require rpo ssa alias */ void loadopt(Fn *fn) { Ins *i, *ib; Blk *b; int sz; uint n, ni, ext, nt; Insert *ist; Slice sl; Loc l; curf = fn; ilog = vnew(0, sizeof ilog[0], Pheap); nlog = 0; inum = 0; for (b=fn->start; b; b=b->link) for (i=b->ins; i<&b->ins[b->nins]; ++i) { if (!isload(i->op)) continue; sz = loadsz(i); sl = (Slice){i->arg[0], sz, i->cls}; l = (Loc){LRoot, i-b->ins, b}; i->arg[1] = def(sl, MASK(sz), b, i, &l); } qsort(ilog, nlog, sizeof ilog[0], icmp); vgrow(&ilog, nlog+1); ilog[nlog].bid = fn->nblk; /* add a sentinel */ ib = vnew(0, sizeof(Ins), Pheap); for (ist=ilog, n=0; n<fn->nblk; ++n) { b = fn->rpo[n]; for (; ist->bid == n && ist->isphi; ++ist) { ist->new.phi.p->link = b->phi; b->phi = ist->new.phi.p; } ni = 0; nt = 0; for (;;) { if (ist->bid == n && ist->off == ni) i = &ist++->new.ins; else { if (ni == b->nins) break; i = &b->ins[ni++]; if (isload(i->op) && !req(i->arg[1], R)) { ext = Oextsb + i->op - Oloadsb; switch (i->op) { default: die("unreachable"); case Oloadsb: case Oloadub: case Oloadsh: case Oloaduh: i->op = ext; break; case Oloadsw: case Oloaduw: if (i->cls == Kl) { i->op = ext; break; } case Oload: i->op = Ocopy; break; } i->arg[0] = i->arg[1]; i->arg[1] = R; } } vgrow(&ib, ++nt); ib[nt-1] = *i; } b->nins = nt; idup(&b->ins, ib, nt); } vfree(ib); vfree(ilog); if (debug['M']) { fprintf(stderr, "\n> After load elimination:\n"); printfn(fn, stderr); } }
457845.c
#include <stdio.h> #include <conio.h> int main() { int n, value, pos, m = 0, arr[100], choice; printf("Enter the total elements in the array: "); scanf("%d", &n); printf("Enter the array elements\n"); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("Enter the element to search: "); scanf("%d", &value); printf("Choose the type of search,\n 1 for Linear Search, \n 2 for Binary Search\n"); printf("choice = "); scanf("%d", &choice); if (choice == 1) { pos = linearSearch(arr, value, 0, n); if (pos != 0) { printf("Element found at pos %d ", pos); } else { printf("Element not found"); } } else { bubbleSort(arr, n); printf("\n"); binarySearch(arr, 0, n, value); } return 0; } int linearSearch(int arr[], int value, int index, int n) { int pos = 0; if(index >= n) { return 0; } else if (arr[index] == value) { pos = index + 1; return pos; } else { return linearSearch(arr, value, index+1, n); } return pos; } void bubbleSort(int arr[], int n) { int temp, i, j; for (i = 0; i < n; i++) { for (j = i; j < n; j++) { if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(i=0; i<n; i++) { printf("%d ",arr[i]); } printf("\n"); } void binarySearch(int arr[], int l, int h, int value) { int mid; if (l > h) { printf("Element not found\n"); return; } mid = (l + h) / 2; if (arr[mid] == value) { printf("Element found at pos %d",mid+1); } else if (arr[mid] > value) { binarySearch(arr, l, mid - 1, value); } else if (arr[mid] < value) { binarySearch(arr, mid + 1, h, value); } }
156390.c
/***************************************************************************//** * \file CapSense_Sensing.c * \version 2.0 * * \brief * This file contains the source of functions common for * different sensing methods. * * \see CapSense v2.0 Datasheet * *//***************************************************************************** * Copyright (2016-2017), Cypress Semiconductor Corporation. ******************************************************************************** * This software is owned by Cypress Semiconductor Corporation (Cypress) and is * protected by and subject to worldwide patent protection (United States and * foreign), United States copyright laws and international treaty provisions. * Cypress hereby grants to licensee a personal, non-exclusive, non-transferable * license to copy, use, modify, create derivative works of, and compile the * Cypress Source Code and derivative works for the sole purpose of creating * custom software in support of licensee product to be used only in conjunction * with a Cypress integrated circuit as specified in the applicable agreement. * Any reproduction, modification, translation, compilation, or representation of * this software except as specified above is prohibited without the express * written permission of Cypress. * * Disclaimer: CYPRESS MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH * REGARD TO THIS MATERIAL, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * Cypress reserves the right to make changes without further notice to the * materials described herein. Cypress does not assume any liability arising out * of the application or use of any product or circuit described herein. Cypress * does not authorize its products for use as critical components in life-support * systems where a malfunction or failure may reasonably be expected to result in * significant injury to the user. The inclusion of Cypress' product in a life- * support systems application implies that the manufacturer assumes all risk of * such use and in doing so indemnifies Cypress against all charges. Use may be * limited by and subject to the applicable Cypress software license agreement. *******************************************************************************/ #include <stdlib.h> #include "cyfitter.h" #include "gpio/cy_gpio.h" #include "cyfitter_sysint_cfg.h" #include "CapSense_ModClk.h" #include "CapSense_Configuration.h" #include "CapSense_Structure.h" #include "CapSense_Sensing.h" #if (CapSense_ENABLE == CapSense_CSX_EN) #include "CapSense_SensingCSX_LL.h" #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ #if (CapSense_ENABLE == CapSense_CSD_EN) #include "CapSense_SensingCSD_LL.h" #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_CSD_SS_DIS != CapSense_CSD_AUTOTUNE) #include "CapSense_SmartSense_LL.h" #endif /* (CapSense_CSD_SS_DIS != CapSense_CSD_AUTOTUNE) */ #if (CapSense_ENABLE == CapSense_ADC_EN) #include "CapSense_Adc.h" #endif /* (CapSense_ENABLE == CapSense_ADC_EN) */ #if (CapSense_ENABLE == CapSense_SELF_TEST_EN) #include "CapSense_SelfTest.h" #endif /*************************************** * API Constants ***************************************/ #define CapSense_CALIBRATION_RESOLUTION (12u) #define CapSense_CALIBRATION_FREQ_KHZ (1500u) #define CapSense_CSD_AUTOTUNE_CAL_LEVEL (CapSense_CSD_RAWCOUNT_CAL_LEVEL) #define CapSense_CSD_AUTOTUNE_CAL_UNITS (1000u) #define CapSense_CP_MIN (0u) #define CapSense_CP_MAX (65000Lu) #define CapSense_CP_ERROR (4000Lu) #define CapSense_CLK_SOURCE_LFSR_SCALE_OFFSET (4u) #define CapSense_CSD_SNS_FREQ_KHZ_MAX (6000u) #define CapSense_MOD_CSD_CLK_12000KHZ (12000uL) #define CapSense_MOD_CSD_CLK_24000KHZ (24000uL) #define CapSense_MOD_CSD_CLK_48000KHZ (48000uL) #define CapSense_EXT_CAP_DISCHARGE_TIME (1u) /*****************************************************************************/ /* Enumeration types definition */ /*****************************************************************************/ typedef enum { CapSense_RES_PULLUP_E = 0x02u, CapSense_RES_PULLDOWN_E = 0x03u } CapSense_PORT_TEST_DM; typedef enum { CapSense_STS_RESET = 0x01u, CapSense_STS_NO_RESET = 0x02u } CapSense_TEST_TYPE; /******************************************************************************* * Static Function Prototypes *******************************************************************************/ /** * \cond SECTION_CYSENSE_INTERNAL * \addtogroup group_cysense_internal * \{ */ #if ((CapSense_ENABLE == CapSense_CSD_CSX_EN) || \ (CapSense_ENABLE == CapSense_SELF_TEST_EN) || \ (CapSense_ENABLE == CapSense_ADC_EN)) #if (CapSense_ENABLE == CapSense_CSD_EN) static void CapSense_SsCSDDisableMode(void); #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_ENABLE == CapSense_CSX_EN) static void CapSense_SsDisableCSXMode(void); #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ #endif #if(((CapSense_ENABLE == CapSense_CSX_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) && \ (CapSense_DISABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES)) ||\ ((CapSense_ENABLE == CapSense_CSD_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE))) static uint8 CapSense_SsCalcLfsrSize(uint32 snsClkDivider, uint32 conversionsNum); static uint8 CapSense_SsCalcLfsrScale(uint32 snsClkDivider, uint8 lfsrSize); #endif #if (CapSense_ENABLE == CapSense_CSD_EN) static void CapSense_SsSetWidgetSenseClkSrc(uint32 wdgtIndex, CapSense_RAM_WD_BASE_STRUCT * ptrWdgt); #endif #if (CapSense_ENABLE == CapSense_CSX_EN) __STATIC_INLINE void CapSense_SsSetWidgetTxClkSrc(uint32 wdgtIndex, CapSense_RAM_WD_BASE_STRUCT * ptrWdgt); #endif /** \} * \endcond */ /******************************************************************************* * Defines module variables *******************************************************************************/ #if ((CapSense_ENABLE == CapSense_CSD_CSX_EN) || \ (CapSense_ENABLE == CapSense_SELF_TEST_EN) || \ (CapSense_ENABLE == CapSense_ADC_EN)) CapSense_SENSE_METHOD_ENUM CapSense_currentSenseMethod = CapSense_UNDEFINED_E; #endif #if(CapSense_ENABLE == CapSense_MULTI_FREQ_SCAN_EN) /* Module variable keep track of multi-frequency scan channel index */ uint8 CapSense_scanFreqIndex = 0u; #else /* const allows C-compiler to do optimization */ const uint8 CapSense_scanFreqIndex = 0u; #endif /* Global software variables */ volatile uint8 CapSense_widgetIndex = 0u; /* Index of the scanning widget */ volatile uint8 CapSense_sensorIndex = 0u; /* Index of the scanning sensor */ uint8 CapSense_requestScanAllWidget = 0u; /* Pointer to RAM_SNS_STRUCT structure */ CapSense_RAM_SNS_STRUCT *CapSense_curRamSnsPtr; #if ((CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) || \ (CapSense_ENABLE == CapSense_CSX_EN)) /* Pointer to Flash structure holding configuration of widget to be scanned */ CapSense_FLASH_WD_STRUCT const *CapSense_curFlashWdgtPtr = 0u; #endif #if (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) /* Pointer to Flash structure holding info of sensor to be scanned */ CapSense_FLASH_SNS_STRUCT const *CapSense_curFlashSnsPtr = 0u; #endif /* Pointer to Flash structure to hold Sns electrode that was connected previously */ CapSense_FLASH_IO_STRUCT const *CapSense_curSnsIOPtr; /******************************************************************************* * Function Name: CapSense_IsBusy ****************************************************************************//** * * \brief * Returns the current status of the Component (Scan is completed or Scan is in * progress). * * \details * This function returns a status of the hardware block whether a scan is * currently in progress or not. If the Component is busy, no new scan or setup * widgets is made. The critical section (i.e. disable global interrupt) * is recommended for the application when the device transitions from * the active mode to sleep or deep sleep modes. * * \return * Returns the current status of the Component: * - CapSense_NOT_BUSY - No scan is in progress and a next scan * can be initiated. * - CapSense_SW_STS_BUSY - The previous scanning is not completed * and the hardware block is busy. * *******************************************************************************/ uint32 CapSense_IsBusy(void) { return (CapSense_dsRam.status & CapSense_SW_STS_BUSY); } /******************************************************************************* * Function Name: CapSense_SetupWidget ****************************************************************************//** * * \brief * Performs the initialization required to scan the specified widget. * * \details * This function prepares the Component to scan all the sensors in the specified * widget by executing the following tasks: * 1. Re-initialize the hardware if it is not configured to perform the * sensing method used by the specified widget, this happens only if the * CSD and CSX methods are used in the Component. * 2. Initialize the hardware with specific sensing configuration (e.g. * sensor clock, scan resolution) used by the widget. * 3. Disconnect all previously connected electrodes, if the electrodes * connected by the CapSense_CSDSetupWidgetExt(), * CapSense_CSXSetupWidgetExt() or CapSense_CSDConnectSns() * functions and not disconnected. * * This function does not start sensor scanning, the CapSense_Scan() * function must be called to start the scan sensors in the widget. If this * function is called more than once, it does not break the Component operation, * but only the last initialized widget is in effect. * * \param widgetId * Specifies the ID number of the widget to be initialized for scanning. * A macro for the widget ID can be found in the * CapSense Configuration header file defined as * CapSense_<WidgetName>_WDGT_ID. * * \return * Returns the status of the widget setting up operation: * - CY_RET_SUCCESS - The operation is successfully completed. * - CY_RET_BAD_PARAM - The widget is invalid or if the specified widget is * disabled * - CY_RET_INVALID_STATE - The previous scanning is not completed and the * hardware block is busy. * - CY_RET_UNKNOWN - An unknown sensing method is used by the widget or any * other spurious error occurred. * **********************************************************************************/ cy_status CapSense_SetupWidget(uint32 widgetId) { cy_status widgetStatus; if (CapSense_WDGT_SW_STS_BUSY == (CapSense_dsRam.status & CapSense_WDGT_SW_STS_BUSY)) { /* Previous widget is being scanned. Return error. */ widgetStatus = CY_RET_INVALID_STATE; } /* * Check if widget id is valid, specified widget is enabled and widget did not * detect any fault conditions if BIST is enabled. If all conditions are met, * set widgetStatus as good, if not, set widgetStatus as bad. */ else if ((CapSense_TOTAL_WIDGETS > widgetId) && (0uL != CapSense_GET_WIDGET_EN_STATUS(widgetId))) { widgetStatus = CY_RET_SUCCESS; } else { widgetStatus = CY_RET_BAD_PARAM; } /* * Check widgetStatus flag that is set earlier, if flag is good, then set up only * widget */ if (CY_RET_SUCCESS == widgetStatus) { #if (CapSense_ENABLE == CapSense_CSD_CSX_EN) /* Check widget sensing method is CSX and call CSX APIs */ if (CapSense_SENSE_METHOD_CSX_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[widgetId])) { /* Set up widget for CSX scan */ CapSense_CSXSetupWidget(widgetId); } /* Check widget sensing method is CSD and call appropriate API */ else if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[widgetId])) { /* Set up widget for CSD scan */ CapSense_CSDSetupWidget(widgetId); } else { /* Sensing method is invalid, return error to caller */ widgetStatus = CY_RET_UNKNOWN; } #elif (CapSense_ENABLE == CapSense_CSD_EN) /* Set up widget for scan */ CapSense_CSDSetupWidget(widgetId); #elif (CapSense_ENABLE == CapSense_CSX_EN) /* Set up widgets for scan */ CapSense_CSXSetupWidget(widgetId); #else widgetStatus = CY_RET_UNKNOWN; #error "No sensing method enabled, Component cannot work in this mode" #endif } return (widgetStatus); } /******************************************************************************* * Function Name: CapSense_Scan ****************************************************************************//** * * \brief * Initiates scanning of all the sensors in the widget initialized by * CapSense_SetupWidget(), if no scan is in progress. * * \details * This function is called only after the CapSense_SetupWidget() * function is called to start the scanning of the sensors in the widget. The * status of a sensor scan must be checked using the CapSense_IsBusy() * API prior to starting a next scan or setting up another widget. * * \return * Returns the status of the scan initiation operation: * - CY_RET_SUCCESS - Scanning is successfully started. * - CY_RET_INVALID_STATE - The previous scanning is not completed and the * hardware block is busy. * - CY_RET_UNKNOWN - An unknown sensing method is used by the widget. * ********************************************************************************/ cy_status CapSense_Scan(void) { cy_status scanStatus = CY_RET_SUCCESS; if (CapSense_WDGT_SW_STS_BUSY == (CapSense_dsRam.status & CapSense_WDGT_SW_STS_BUSY)) { /* Previous widget is being scanned. Return error. */ scanStatus = CY_RET_INVALID_STATE; } else { /* If both CSD and CSX are enabled, call scan API based on widget sensing method */ #if (CapSense_ENABLE == CapSense_CSD_CSX_EN) /* Check widget sensing method and call appropriate APIs */ switch (CapSense_currentSenseMethod) { case CapSense_SENSE_METHOD_CSX_E: CapSense_CSXScan(); break; case CapSense_SENSE_METHOD_CSD_E: CapSense_CSDScan(); break; default: scanStatus = CY_RET_UNKNOWN; break; } /* If only CSD is enabled, call CSD scan */ #elif (CapSense_ENABLE == CapSense_CSD_EN) CapSense_CSDScan(); /* If only CSX is enabled, call CSX scan */ #elif (CapSense_ENABLE == CapSense_CSX_EN) CapSense_CSXScan(); #else scanStatus = CY_RET_UNKNOWN; #error "No sensing method enabled, Component cannot work in this mode" #endif /* (CapSense_ENABLE == CapSense_CSD_CSX_EN) */ } return (scanStatus); } /******************************************************************************* * Function Name: CapSense_ScanAllWidgets ****************************************************************************//** * * \brief * Initializes the first enabled widget and scanning of all the sensors in the * widget, then the same process is repeated for all the widgets in the Component, * i.e. scanning of all the widgets in the Component. * * \details * This function initializes a widget and scans all the sensors in the widget, * and then repeats the same for all the widgets in the Component. The tasks of * the CapSense_SetupWidget() and CapSense_Scan() functions are * executed by these functions. The status of a sensor scan must be checked * using the CapSense_IsBusy() API prior to starting a next scan * or setting up another widget. * * \return * Returns the status of the operation: * - CY_RET_SUCCESS - Scanning is successfully started. * - CY_RET_BAD_PARAM - All the widgets are disabled. * - CY_RET_INVALID_STATE - The previous scanning is not completed and the HW block is busy. * - CY_RET_UNKNOWN - There are unknown errors. * *******************************************************************************/ cy_status CapSense_ScanAllWidgets(void) { cy_status scanStatus = CY_RET_UNKNOWN; uint32 wdgtIndex; if (CapSense_SW_STS_BUSY == (CapSense_dsRam.status & CapSense_SW_STS_BUSY)) { /* Previous widget is being scanned. Return error. */ scanStatus = CY_RET_INVALID_STATE; } else { /* * Set up widget first widget. * If widget returned error, set up next, continue same until widget does not return error. */ for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { scanStatus = CapSense_SetupWidget(wdgtIndex); if (CY_RET_SUCCESS == scanStatus) { #if (0u != (CapSense_TOTAL_WIDGETS - 1u)) /* If there are more than one widget to be scanned, request callback to scan next widget */ if ((CapSense_TOTAL_WIDGETS - 1u) > wdgtIndex) { /* Request callback to scan next widget in ISR */ CapSense_requestScanAllWidget = CapSense_ENABLE; } else { /* Request to exit in ISR (Do not scan the next widgets) */ CapSense_requestScanAllWidget = CapSense_DISABLE; } #else { /* Request to exit in ISR (We have only one widget) */ CapSense_requestScanAllWidget = CapSense_DISABLE; } #endif /* (0u != (CapSense_TOTAL_WIDGETS - 1u)) */ /* Initiate scan and quit loop */ scanStatus = CapSense_Scan(); break; } } } return (scanStatus); } /******************************************************************************* * Function Name: CapSense_SsInitialize ****************************************************************************//** * * \brief * Performs hardware and firmware initialization required for proper operation * of the CapSense Component. This function is called from * the CapSense_Start() API prior to calling any other APIs of the Component. * * \details * Performs hardware and firmware initialization required for proper operation * of the CapSense Component. This function is called from * the CapSense_Start() API prior to calling any other APIs of the Component. * 1. Depending on the configuration, the function initializes the CSD block * for the corresponding sensing mode. * 2. The function updates the dsRam.wdgtWorking variable with 1 when Self-test * is enabled. * * Calling the CapSense_Start API is the recommended method to initialize * the CapSense Component at power-up. The CapSense_SsInitialize() * API should not be used for initialization, resume, or wake-up operations. * The dsRam.wdgtWorking variable is updated. * * \return status * Returns status of operation: * - Zero - Indicates successful initialization. * - Non-zero - One or more errors occurred in the initialization process. * *******************************************************************************/ cy_status CapSense_SsInitialize(void) { cy_status initStatus = CY_RET_SUCCESS; #if((CapSense_ENABLE == CapSense_CSD_EN) ||\ (CapSense_ENABLE == CapSense_CSX_EN)) CapSense_SsInitializeSourceSenseClk(); #endif /* ((CapSense_ENABLE == CapSense_CSD_EN) ||\ (CapSense_ENABLE == CapSense_CSX_EN)) */ /* Set all IO states to default state */ CapSense_SsSetIOsInDefaultState(); #if ((CapSense_ENABLE == CapSense_CSD_CSX_EN) || \ (CapSense_ENABLE == CapSense_SELF_TEST_EN) || \ (CapSense_ENABLE == CapSense_ADC_EN)) /* * CSD hardware block is initialized in the Setup Widget based * on widget sensing method. Release previously captured HW resources * if it is second call of CapSense_Start() function. */ CapSense_SsSwitchSensingMode(CapSense_UNDEFINED_E); #elif (CapSense_ENABLE == CapSense_CSD_EN) /* Initialize CSD block for CSD scanning */ CapSense_SsCSDInitialize(); #elif (CapSense_ENABLE == CapSense_CSX_EN) /* Initialize CSD block for CSX scanning */ CapSense_CSXInitialize(); #else #error "No sensing method enabled, Component cannot work in this mode" initStatus = CY_RET_UNKNOWN; #endif /* (CapSense_ENABLE == CapSense_CSD_CSX_EN) */ return (initStatus); } /******************************************************************************* * Function Name: CapSense_SetPinState ****************************************************************************//** * * \brief * Sets the state (drive mode and output state) of the port pin used by a sensor. * The possible states are GND, Shield, High-Z, Tx or Rx, Sensor. If the sensor * specified in the input parameter is a ganged sensor, then the state of all pins * associated with the ganged sensor is updated. * * \details * This function sets a specified state for a specified sensor element. For the * CSD widgets, sensor element is a sensor ID, for the CSX widgets, it is either * an Rx or Tx electrode ID. If the specified sensor is a ganged sensor, then * the specified state is set for all the electrodes belong to the sensor. * This function must not be called while the Component is in the busy state. * * This function accepts the CapSense_SHIELD and * CapSense_SENSOR states as an input only if there is at least * one CSD widget. Similarly, this function accepts the CapSense_TX_PIN * and CapSense_RX_PIN states as an input only if there is at least * one CSX widget in the project. * Calling this function directly from the application layer is not * recommended. This function is used to implement only the custom-specific * use cases. Functions that perform a setup and scan of a sensor/widget * automatically set the required pin states. They ignore changes * in the design made by the CapSense_SetPinState() function. * This function neither check wdgtIndex nor sensorElement for the correctness. * * \param widgetId * Specifies the ID of the widget to change the pin state of the specified * sensor. * A macro for the widget ID can be found in the CapSense Configuration * header file defined as CapSense_<WidgetName>_WDGT_ID. * * \param sensorElement * Specifies the ID of the sensor element within the widget to change * its pin state. * For the CSD widgets, sensorElement is the sensor ID and can be found in the * CapSense Configuration header file defined as * CapSense_<WidgetName>_SNS<SensorNumber>_ID. * For the CSX widgets, sensorElement is defined either as Rx ID or Tx ID. * The first Rx in a widget corresponds to sensorElement = 0, the second * Rx in a widget corresponds to sensorElement = 1, and so on. * The last Tx in a widget corresponds to sensorElement = (RxNum + TxNum). * Macros for Rx and Tx IDs can be found in the * CapSense Configuration header file defined as: * - CapSense_<WidgetName>_RX<RXNumber>_ID * - CapSense_<WidgetName>_TX<TXNumber>_ID. * * \param state * Specifies the state of the sensor to be set: * 1. CapSense_GROUND - The pin is connected to the ground. * 2. CapSense_HIGHZ - The drive mode of the pin is set to High-Z * Analog. * 3. CapSense_SHIELD - The shield signal is routed to the pin * (available only if CSD sensing method with shield electrode is enabled). * 4. CapSense_SENSOR - The pin is connected to the scanning bus * (available only if CSD sensing method is enabled). * 5. CapSense_TX_PIN - The Tx signal is routed to the sensor * (available only if CSX sensing method is enabled). * 6. CapSense_RX_PIN - The pin is connected to the scanning bus * (available only if CSX sensing method is enabled). * *******************************************************************************/ void CapSense_SetPinState(uint32 widgetId, uint32 sensorElement, uint32 state) { uint32 eltdNum; uint32 eltdIndex; uint32 interruptState; CapSense_FLASH_IO_STRUCT const *ioPtr; #if (CapSense_ENABLE == CapSense_GANGED_SNS_EN) CapSense_FLASH_SNS_STRUCT const *curFlashSnsPtr; #endif /* Getting sensor element pointer and number of electrodes */ #if (CapSense_ENABLE == CapSense_GANGED_SNS_EN) /* Check the ganged sns flag */ if (CapSense_GANGED_SNS_MASK == (CapSense_dsFlash.wdgtArray[widgetId].staticConfig & CapSense_GANGED_SNS_MASK)) { curFlashSnsPtr = CapSense_dsFlash.wdgtArray[widgetId].ptr2SnsFlash; curFlashSnsPtr += sensorElement; ioPtr = &CapSense_ioList[curFlashSnsPtr->firstPinId]; eltdNum = curFlashSnsPtr->numPins; } else { ioPtr = (CapSense_FLASH_IO_STRUCT const *)CapSense_dsFlash.wdgtArray[widgetId].ptr2SnsFlash + sensorElement; eltdNum = 1u; } #else ioPtr = (CapSense_FLASH_IO_STRUCT const *)CapSense_dsFlash.wdgtArray[widgetId].ptr2SnsFlash + sensorElement; eltdNum = 1u; #endif /* Loop through all electrodes of the specified sensor element */ for (eltdIndex = 0u; eltdIndex < eltdNum; eltdIndex++) { /* Reset HSIOM and PC registers */ interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, (en_hsiom_sel_t)CapSense_HSIOM_SEL_GPIO); Cy_SysLib_ExitCriticalSection(interruptState); switch (state) { case CapSense_GROUND: interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetDrivemode((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_STRONG_IN_OFF); Cy_GPIO_Clr((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber); Cy_SysLib_ExitCriticalSection(interruptState); break; case CapSense_HIGHZ: interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetDrivemode((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_ANALOG); Cy_GPIO_Clr((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber); Cy_SysLib_ExitCriticalSection(interruptState); break; #if (CapSense_ENABLE == CapSense_CSD_EN) case CapSense_SENSOR: /* Enable sensor */ CapSense_CSDConnectSns(ioPtr); break; #if (CapSense_ENABLE == CapSense_CSD_SHIELD_EN) case CapSense_SHIELD: interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetDrivemode((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_STRONG_IN_OFF); Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, (en_hsiom_sel_t)CapSense_HSIOM_SEL_CSD_SHIELD); Cy_SysLib_ExitCriticalSection(interruptState); break; #endif /* (CapSense_ENABLE == CapSense_CSD_SHIELD_EN) */ #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_ENABLE == CapSense_CSX_EN) case CapSense_TX_PIN: interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, (en_hsiom_sel_t)CapSense_HSIOM_SEL_CSD_SHIELD); Cy_GPIO_SetDrivemode((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_STRONG_IN_OFF); Cy_SysLib_ExitCriticalSection(interruptState); break; case CapSense_RX_PIN: interruptState = Cy_SysLib_EnterCriticalSection(); Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, (en_hsiom_sel_t)CapSense_HSIOM_SEL_AMUXA); Cy_GPIO_SetDrivemode((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_ANALOG); Cy_SysLib_ExitCriticalSection(interruptState); break; #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ default: /* Wrong state */ break; } ioPtr++; } } #if ((CapSense_ENABLE == CapSense_CSD_CSX_EN) || \ (CapSense_ENABLE == CapSense_SELF_TEST_EN) || \ (CapSense_ENABLE == CapSense_ADC_EN)) #if (CapSense_ENABLE == CapSense_CSD_EN) /******************************************************************************* * Function Name: CapSense_SsCSDDisableMode ****************************************************************************//** * * \brief * This function disables CSD mode. * * \details * To disable CSD mode the following tasks are performed: * 1. Disconnect Cmod from AMUXBUS-A. * 2. Disconnect previous CSX electrode if it has been connected. * 3. Disconnect Csh from AMUXBUS-B. * 4. Disable Shield Electrodes. * *******************************************************************************/ static void CapSense_SsCSDDisableMode(void) { uint32 newRegValue = 0uL; /* To remove unreferenced local variable warning */ (void)newRegValue; Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)CapSense_CSD_CMOD_PORT_PTR, CapSense_CSD_CMOD_PIN, (en_hsiom_sel_t)CapSense_HSIOM_SEL_GPIO); #if ((CapSense_ENABLE == CapSense_CSD_IDAC_COMP_EN) && \ (CapSense_ENABLE == CapSense_CSD_DEDICATED_IDAC_COMP_EN)) /* Disconnect IDACA and IDACB */ newRegValue = CY_GET_REG32(CapSense_CSD_SW_REFGEN_SEL_PTR); newRegValue &= (uint32)(~CapSense_CSD_SW_REFGEN_SEL_SW_IAIB_MSK); CY_SET_REG32(CapSense_CSD_SW_REFGEN_SEL_PTR, newRegValue); #endif /* ((CapSense_ENABLE == CapSense_CSD_IDAC_COMP_EN) && \ (CapSense_ENABLE == CapSense_CSD_DEDICATED_IDAC_COMP_EN)) */ /* Disconnect previous CSD electrode if it has been connected */ CapSense_SsCSDElectrodeCheck(); /* Disconnect Csh from AMUXBUS-B */ #if ((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (CapSense_ENABLE == CapSense_CSD_SHIELD_TANK_EN)) Cy_GPIO_SetHSIOM((GPIO_PRT_Type*)CapSense_CSD_CTANK_PORT_PTR, CapSense_CSD_CTANK_PIN, (en_hsiom_sel_t)CapSense_HSIOM_SEL_GPIO); #endif /* ((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (CapSense_ENABLE == CapSense_CSD_SHIELD_TANK_EN)) */ #if ((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (0u != CapSense_CSD_TOTAL_SHIELD_COUNT)) CapSense_SsCSDDisableShieldElectrodes(); #endif /* ((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (0u != CapSense_CSD_TOTAL_SHIELD_COUNT)) */ } #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_ENABLE == CapSense_CSX_EN) /******************************************************************************* * Function Name: CapSense_SsDisableCSXMode ****************************************************************************//** * * \brief * This function disables CSX mode. * * \details * To disable CSX mode the following tasks are performed: * 1. Disconnect CintA and CintB from AMUXBUS-A. * 2. Disconnect previous CSX electrode if it has been connected. * *******************************************************************************/ static void CapSense_SsDisableCSXMode(void) { /* Disconnect previous CSX electrode if it has been connected */ CapSense_CSXElectrodeCheck(); } #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ /******************************************************************************* * Function Name: CapSense_SsSwitchSensingMode ****************************************************************************//** * * \brief * This function changes the mode for case when both CSD and CSX widgets are * scanned. * * \details * To switch to the CSD mode the following tasks are performed: * 1. Disconnect CintA and CintB from AMUXBUS-A. * 2. Disconnect previous CSD electrode if it has been connected. * 3. Initialize CSD mode. * * To switch to the CSX mode the following tasks are performed: * 1. Disconnect Cmod from AMUXBUS-A. * 2. Disconnect previous CSX electrode if it has been connected. * 3. Initialize CSX mode. * * \param mode * Specifies the scan mode: * - CapSense_SENSE_METHOD_CSD_E * - CapSense_SENSE_METHOD_CSX_E * - CapSense_SENSE_METHOD_BIST_E * - CapSense_UNDEFINED_E * *******************************************************************************/ void CapSense_SsSwitchSensingMode(CapSense_SENSE_METHOD_ENUM mode) { if (CapSense_currentSenseMethod != mode) { /* The requested mode differes to the current one. Disable the current mode */ if (CapSense_SENSE_METHOD_CSD_E == CapSense_currentSenseMethod) { #if (CapSense_ENABLE == CapSense_CSD_EN) CapSense_SsCSDDisableMode(); #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ } else if (CapSense_SENSE_METHOD_CSX_E == CapSense_currentSenseMethod) { #if (CapSense_ENABLE == CapSense_CSX_EN) CapSense_SsDisableCSXMode(); #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ } else if (CapSense_SENSE_METHOD_BIST_E == CapSense_currentSenseMethod) { #if (CapSense_ENABLE == CapSense_SELF_TEST_EN) CapSense_BistDisableMode(); #endif /* (CapSense_ENABLE == CapSense_SELF_TEST_EN) */ } else { #if (CapSense_ENABLE == CapSense_ADC_EN) /* Release ADC resources */ (void)CapSense_AdcReleaseResources(); #endif /* (CapSense_ENABLE == CapSense_ADC_EN) */ } /* Enable the specified mode */ if (CapSense_SENSE_METHOD_CSD_E == mode) { #if (CapSense_ENABLE == CapSense_CSD_EN) /* Initialize CSD mode to guarantee configured CSD mode */ CapSense_SsCSDInitialize(); CapSense_currentSenseMethod = CapSense_SENSE_METHOD_CSD_E; #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ } else if (CapSense_SENSE_METHOD_CSX_E == mode) { #if (CapSense_ENABLE == CapSense_CSX_EN) /* Initialize CSX mode to guarantee configured CSX mode */ CapSense_CSXInitialize(); CapSense_currentSenseMethod = CapSense_SENSE_METHOD_CSX_E; #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ } else if (CapSense_SENSE_METHOD_BIST_E == mode) { #if (CapSense_ENABLE == CapSense_SELF_TEST_EN) CapSense_BistInitialize(); CapSense_currentSenseMethod = CapSense_SENSE_METHOD_BIST_E; #endif /* (CapSense_ENABLE == CapSense_SELF_TEST_EN) */ } else { CapSense_currentSenseMethod = CapSense_UNDEFINED_E; } } } #endif /* ((CapSense_ENABLE == CapSense_CSD_CSX_EN) || \ (CapSense_ENABLE == CapSense_ADC_EN)) */ /******************************************************************************* * Function Name: CapSense_SsSetIOsInDefaultState ****************************************************************************//** * * \brief * Sets all electrodes into a default state. * * \details * Sets all the CSD/CSX IOs into a default state: * - HSIOM - Disconnected, the GPIO mode. * - DM - Strong drive. * - State - Zero. * * Sets all the ADC channels into a default state: * - HSIOM - Disconnected, the GPIO mode. * - DM - HiZ-Analog. * - State - Zero. * * It is not recommended to call this function directly from the application * layer. * *******************************************************************************/ void CapSense_SsSetIOsInDefaultState(void) { CapSense_FLASH_IO_STRUCT const *ioPtr = &CapSense_ioList[0u]; uint32 loopIndex; /* Loop through all electrodes */ for (loopIndex = 0u; loopIndex < CapSense_TOTAL_ELECTRODES; loopIndex++) { /* * 1. Disconnect HSIOM * 2. Set strong DM * 3. Set pin state to logic 0 */ Cy_GPIO_Pin_FastInit((GPIO_PRT_Type*)ioPtr->pcPtr, (uint32)ioPtr->pinNumber, CY_GPIO_DM_STRONG, 0u, (en_hsiom_sel_t)CapSense_HSIOM_SEL_GPIO); /* Get next electrode */ ioPtr++; } #if(CapSense_ENABLE == CapSense_ADC_EN) CapSense_ClearAdcChannels(); #endif /* (CapSense_ENABLE == CapSense_ADC_EN) */ } #if (CapSense_ENABLE == CapSense_ADC_EN) /******************************************************************************* * Function Name: CapSense_SsReleaseResources() ****************************************************************************//** * * \brief * This function sets the resources that do not belong to the sensing HW block to * default state. * * \details * The function performs following tasks: * 1. Checks if CSD block busy and returns error if it is busy * 2. Disconnects integration capacitors (CintA, CintB for CSX mode and * Cmod for CSD mode) * 3. Disconnect electroded if they have been connected. * * \return * Returns the status of the operation: * - Zero - Resources released successfully. * - Non-zero - One or more errors occurred in releasing process. * *******************************************************************************/ cy_status CapSense_SsReleaseResources(void) { cy_status busyStatus = CY_RET_SUCCESS; if (CapSense_SW_STS_BUSY == (CapSense_dsRam.status & CapSense_SW_STS_BUSY)) { /* Previous widget is being scanned. Return error. */ busyStatus = CY_RET_INVALID_STATE; } else { #if (CapSense_ENABLE == CapSense_CSX_EN) CapSense_SsDisableCSXMode(); #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ #if (CapSense_ENABLE == CapSense_CSD_EN) CapSense_SsCSDDisableMode(); #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_ENABLE == CapSense_SELF_TEST_EN) CapSense_BistDisableMode(); #endif /* (CapSense_ENABLE == CapSense_SELF_TEST_EN) */ #if ((CapSense_ENABLE == CapSense_CSD_EN) && \ (CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (CapSense_SNS_CONNECTION_SHIELD == CapSense_CSD_INACTIVE_SNS_CONNECTION)) CapSense_SsSetIOsInDefaultState(); #endif /* ((CapSense_ENABLE == CapSense_CSD_EN) && \ (CapSense_DISABLE != CapSense_CSD_SHIELD_EN) && \ (CapSense_SNS_CONNECTION_SHIELD == CapSense_CSD_INACTIVE_SNS_CONNECTION)) */ /* * Reset of the currentSenseMethod variable to make sure that the next * call of SetupWidget() API setups the correct widget mode */ CapSense_currentSenseMethod = CapSense_UNDEFINED_E; } return busyStatus; } #endif /* (CapSense_ENABLE == CapSense_ADC_EN) */ /******************************************************************************* * Function Name: CapSense_SsPostAllWidgetsScan ****************************************************************************//** * * \brief * The ISR function for multiple widget scanning implementation. * * \details * This is the function used by the CapSense ISR to implement multiple widget * scanning. * Should not be used by the application layer. * *******************************************************************************/ void CapSense_SsPostAllWidgetsScan(void) { /* * 1. Increment widget index * 2. Check if all the widgets are scanned * 3. If all the widgets are not scanned, set up and scan next widget */ #if (1u != CapSense_TOTAL_WIDGETS) cy_status postScanStatus; do { CapSense_widgetIndex++; postScanStatus = CapSense_SetupWidget((uint32)CapSense_widgetIndex); if (CY_RET_SUCCESS == postScanStatus) { if((CapSense_TOTAL_WIDGETS - 1u) == CapSense_widgetIndex) { /* The last widget will be scanned. Reset flag to skip configuring the next widget setup in ISR. */ CapSense_requestScanAllWidget = CapSense_DISABLE; } (void)CapSense_Scan(); } else if((CapSense_TOTAL_WIDGETS - 1u) == CapSense_widgetIndex) { #if ((CapSense_ENABLE == CapSense_BLOCK_OFF_AFTER_SCAN_EN) && \ (CapSense_ENABLE == CapSense_CSD_EN)) if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[CapSense_widgetIndex])) { /* Disable the CSD block */ CY_SET_REG32(CapSense_CSD_CONFIG_PTR, CapSense_configCsd); } #endif /* ((CapSense_ENABLE == CapSense_BLOCK_OFF_AFTER_SCAN_EN) && \ (CapSense_ENABLE == CapSense_CSD_EN)) */ /* Update scan Counter */ CapSense_dsRam.scanCounter++; /* all the widgets are totally processed. Reset BUSY flag */ CapSense_dsRam.status &= ~CapSense_SW_STS_BUSY; /* Update status with with the failure */ CapSense_dsRam.status &= ~CapSense_STATUS_ERR_MASK; CapSense_dsRam.status |= ((postScanStatus & CapSense_STATUS_ERR_SIZE) << CapSense_STATUS_ERR_SHIFT); /* Set postScanStatus to exit the while loop */ postScanStatus = CY_RET_SUCCESS; } else { /* Update status with with the failure. Configure the next widget in while() loop */ CapSense_dsRam.status &= ~CapSense_STATUS_ERR_MASK; CapSense_dsRam.status |= ((postScanStatus & CapSense_STATUS_ERR_SIZE) << CapSense_STATUS_ERR_SHIFT); } } while (CY_RET_SUCCESS != postScanStatus); #endif /* (1u != CapSense_TOTAL_WIDGETS) */ } /******************************************************************************* * Function Name: CapSense_SsIsrInitialize ****************************************************************************//** * * \brief * Enables and initializes for the function pointer for a callback for the ISR. * * \details * The "address" is a special type cy_israddress defined by syslib. This function * is used by Component APIs and should not be used by an application program for * proper working of the Component. * * \param address * The address of the function to be called when interrupt is fired. * *******************************************************************************/ void CapSense_SsIsrInitialize(cy_israddress address) { /* Disable interrupt */ #if defined(CapSense_ISR__INTC_ASSIGNED) NVIC_DisableIRQ(CapSense_ISR_cfg.intrSrc); #endif /* Configure interrupt with priority and vector */ #if defined(CapSense_ISR__INTC_ASSIGNED) (void)Cy_SysInt_Init(&CapSense_ISR_cfg, address); #endif /* Enable interrupt */ #if defined(CapSense_ISR__INTC_ASSIGNED) NVIC_EnableIRQ(CapSense_ISR_cfg.intrSrc); #endif } /******************************************************************************* * Function Name: CapSense_SsSetSnsFirstPhaseWidth ****************************************************************************//** * * \brief * Defines the length of the first phase of the sense clock in clk_csd cycles. * * \details * It is not recommended to call this function directly by the application layer. * It is used by initialization, widget APIs or wakeup functions to * enable the clocks. * At all times it must be assured that the phases are at least 2 clk_csd cycles * (1 for non overlap, if used), if this rule is violated the result is undefined. * * \param * snsClk The divider value for the sense clock. * *******************************************************************************/ void CapSense_SsSetSnsFirstPhaseWidth(uint32 phaseWidth) { uint32 newRegValue; newRegValue = CY_GET_REG32(CapSense_CSD_SENSE_DUTY_PTR); newRegValue &= (uint32)(~CapSense_CSD_SENSE_DUTY_SENSE_WIDTH_MSK); newRegValue |= phaseWidth; CY_SET_REG32(CapSense_CSD_SENSE_DUTY_PTR, newRegValue); } /******************************************************************************* * Function Name: CapSense_SsSetSnsClockDivider ****************************************************************************//** * * \brief * Sets the divider values for the sense clock and then starts * the sense clock. * * \details * It is not recommended to call this function directly by the application layer. * It is used by initialization, widget APIs or wakeup functions to * enable the clocks. * * \param * snsClk The divider value for the sense clock. * *******************************************************************************/ void CapSense_SsSetSnsClockDivider(uint32 snsClk) { uint32 newRegValue; /* * Set divider value for sense clock. * 1u is subtracted from snsClk because SENSE_DIV value 0 corresponds * to dividing by 1. */ newRegValue = CY_GET_REG32(CapSense_CSD_SENSE_PERIOD_PTR); newRegValue &= (uint32)(~CapSense_CSD_SENSE_PERIOD_SENSE_DIV_MSK); newRegValue |= snsClk - 1u; CY_SET_REG32(CapSense_CSD_SENSE_PERIOD_PTR, newRegValue); } /******************************************************************************* * Function Name: CapSense_SsSetClockDividers ****************************************************************************//** * * \brief * Sets the divider values for sense and modulator clocks and then starts * a modulator clock-phase aligned to HFCLK and sense clock-phase aligned to * the modulator clock. * * \details * It is not recommended to call this function directly by the application layer. * It is used by initialization, widget APIs or wakeup functions to * enable the clocks. * * \param * snsClk The divider value for the sense clock. * modClk The divider value for the modulator clock. * *******************************************************************************/ void CapSense_SsSetClockDividers(uint32 snsClk, uint32 modClk) { /* Configure Mod clock */ CapSense_ModClk_SetDivider((uint32)modClk - 1uL); /* Configure Sns clock */ CapSense_SsSetSnsClockDivider(snsClk); } #if ((CapSense_ENABLE == CapSense_CSD_IDAC_AUTOCAL_EN) || \ (CapSense_ENABLE == CapSense_CSX_IDAC_AUTOCAL_EN)) /******************************************************************************* * Function Name: CapSense_CalibrateWidget ****************************************************************************//** * * \brief * Calibrates the IDACs for all the sensors in the specified widget to the default * target, this function detects the sensing method used by the * widget prior to calibration. * * \details * This function performs exactly the same tasks as * CapSense_CalibrateAllWidgets, but only for a specified widget. * This function detects the sensing method used by the widgets and uses * the Enable compensation IDAC parameter. * * This function is available when the CSD and/or CSX Enable IDAC * auto-calibration parameter is enabled. * * \param widgetId * Specifies the ID number of the widget to calibrate its raw count. * A macro for the widget ID can be found in the * CapSense Configuration header file defined as * CapSense_<WidgetName>_WDGT_ID. * * \return * Returns the status of the specified widget calibration: * - CY_RET_SUCCESS - The operation is successfully completed. * - CY_RET_BAD_PARAM - The input parameter is invalid. * - CY_RET_BAD_DATA - The calibration failed and the Component may not * operate as expected. * *******************************************************************************/ cy_status CapSense_CalibrateWidget(uint32 widgetId) { cy_status calibrateStatus = CY_RET_SUCCESS; do { if (CapSense_TOTAL_WIDGETS <= widgetId) { calibrateStatus = CY_RET_BAD_PARAM; } /* * Check if widget id is valid, specified widget did not * detect any faults conditions if BIST is enabled. */ #if (CapSense_ENABLE == CapSense_SELF_TEST_EN) if (0u != CapSense_GET_WIDGET_EN_STATUS(widgetId)) { calibrateStatus = CY_RET_SUCCESS; } else { calibrateStatus = CY_RET_INVALID_STATE; } #endif /* (CapSense_ENABLE == CapSense_SELF_TEST_EN) */ if (CY_RET_SUCCESS != calibrateStatus) { /* Exit from the loop because of a fail */ break; } /* If both CSD and CSX are enabled, calibrate widget using sensing method */ #if (CapSense_ENABLE == CapSense_CSD_CSX_EN) /* Check widget sensing method and call appropriate APIs */ #if (CapSense_ENABLE == CapSense_CSX_IDAC_AUTOCAL_EN) if (CapSense_SENSE_METHOD_CSX_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[widgetId])) { /* Calibrate CSX widget */ CapSense_CSXCalibrateWidget(widgetId, CapSense_CSX_RAWCOUNT_CAL_LEVEL); } #endif /* (CapSense_ENABLE == CapSense_CSX_IDAC_AUTOCAL_EN) */ #if (CapSense_ENABLE == CapSense_CSD_IDAC_AUTOCAL_EN) if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[widgetId])) { /* Calibrate CSD widget */ calibrateStatus = CapSense_CSDCalibrateWidget(widgetId, CapSense_CSD_RAWCOUNT_CAL_LEVEL); } #endif /* (CapSense_ENABLE == CapSense_CSD_IDAC_AUTOCAL_EN) */ /* If only CSD is enabled, calibrate CSD sensor */ #elif (CapSense_ENABLE == CapSense_CSD_EN) calibrateStatus = CapSense_CSDCalibrateWidget(widgetId, CapSense_CSD_RAWCOUNT_CAL_LEVEL); /* If only CSX is enabled, call CSX scan */ #elif (CapSense_ENABLE == CapSense_CSX_EN) CapSense_CSXCalibrateWidget(widgetId, CapSense_CSX_RAWCOUNT_CAL_LEVEL); #else calibrateStatus = CY_RET_UNKNOWN; #endif /* (CapSense_ENABLE == CapSense_CSD_CSX_EN) */ /* Update CRC */ #if (CapSense_ENABLE ==CapSense_TST_WDGT_CRC_EN) CapSense_DsUpdateWidgetCrc(widgetId); #endif /* (CapSense_ENABLE ==CapSense_TST_WDGT_CRC_EN) */ } while (0u); return calibrateStatus; } /******************************************************************************* * Function Name: CapSense_CalibrateAllWidgets ****************************************************************************//** * * \brief * Calibrates the IDACs for all the widgets in the Component to the default * target, this function detects the sensing method used by the widgets * prior to calibration. * * \details * Calibrates the IDACs for all the widgets in the Component to the default * target value. This function detects the sensing method used by the widgets * and regards the Enable compensation IDAC parameter. * * This function is available when the CSD and/or CSX Enable IDAC * auto-calibration parameter is enabled. * * \return * Returns the status of the calibration process: * - CY_RET_SUCCESS - The operation is successfully completed. * - CY_RET_BAD_DATA - The calibration failed and the Component may not * operate as expected. * *******************************************************************************/ cy_status CapSense_CalibrateAllWidgets(void) { cy_status calibrateStatus = CY_RET_SUCCESS; uint32 wdgtIndex; for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { calibrateStatus |= CapSense_CalibrateWidget(wdgtIndex); } return calibrateStatus; } #endif /* ((CapSense_ENABLE == CapSense_CSD_IDAC_AUTOCAL_EN) || (CapSense_ENABLE == CapSense_CSX_IDAC_AUTOCAL_EN)) */ #if (CapSense_CSD_SS_DIS != CapSense_CSD_AUTOTUNE) /******************************************************************************* * Function Name: CapSense_SsAutoTune ****************************************************************************//** * * \brief * This API performs the parameters auto-tuning for the optimal CapSense operation. * * \details * This API performs the following: * - Calibrates Modulator and Compensation IDACs. * - Tunes the Sense Clock optimal value to get a Sense Clock period greater than * 2*5*R*Cp. * - Calculates the resolution for the optimal finger capacitance. * * \return * Returns the status of the operation: * - Zero - All the widgets are auto-tuned successfully. * - Non-zero - Auto-tuning failed for any widget. * *******************************************************************************/ cy_status CapSense_SsAutoTune(void) { cy_status autoTuneStatus = CY_RET_SUCCESS; uint32 wdgtIndex; uint32 cp = 0uL; #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) uint32 cpRow = 0uL; #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ uint32 cpWidget[CapSense_TOTAL_WIDGETS]; CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; AUTO_TUNE_CONFIG_TYPE autoTuneConfig; /* Configure common config variables */ autoTuneConfig.snsClkConstantR = CapSense_CSD_SNSCLK_R_CONST; autoTuneConfig.vRef = CapSense_CSD_VREF_MV; autoTuneConfig.iDacGain = CapSense_CSD_IDAC_GAIN_VALUE_NA; /* Calculate snsClk Input Clock in KHz */ /* Dividers are chained */ autoTuneConfig.snsClkInputClock = (CYDEV_CLK_PERICLK__KHZ / CapSense_dsRam.modCsdClk); /* If both CSD and CSX are enabled, calibrate widget using sensing method */ #if (CapSense_ENABLE == CapSense_CSD_CSX_EN) /* Initialize CSD mode */ CapSense_SsCSDInitialize(); #endif /* (CapSense_ENABLE == CapSense_CSD_CSX_EN) */ /* * Autotune phase #1: * - performing the first calibration at fixed settings * - getting sensor Cp * - getting sense clock frequency based on Cp */ /* Tune sense clock for all the widgets */ for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[wdgtIndex])) { ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2WdgtRam; /* Set calibration resolution to 12 bits */ ptrWdgt->resolution = CapSense_CALIBRATION_RESOLUTION; /* Set clock source direct and sense clock frequency to 1.5 MHz */ ptrWdgt->snsClkSource = (uint8)CapSense_CLK_SOURCE_DIRECT; ptrWdgt->snsClk = (uint16)((uint32)autoTuneConfig.snsClkInputClock / CapSense_CALIBRATION_FREQ_KHZ); #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) if ((CapSense_WD_TOUCHPAD_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType) || (CapSense_WD_MATRIX_BUTTON_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType)) { ptrWdgt->rowSnsClkSource = (uint8)CapSense_CLK_SOURCE_DIRECT; ptrWdgt->rowSnsClk = (uint16)((uint32)autoTuneConfig.snsClkInputClock / CapSense_CALIBRATION_FREQ_KHZ); } #endif /* Calibrate CSD widget to the default calibration target */ (void)CapSense_CSDCalibrateWidget(wdgtIndex, CapSense_CSD_AUTOTUNE_CAL_LEVEL); #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) if ((CapSense_WD_TOUCHPAD_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType) || (CapSense_WD_MATRIX_BUTTON_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType)) { /* Get pointer to Sense Clock Divider for columns */ autoTuneConfig.ptrSenseClk = &ptrWdgt->rowSnsClk; /* Get IDAC */ autoTuneConfig.iDac = CapSense_calibratedIdacRow; /* Calculate achived calibration level */ autoTuneConfig.calTarget = (uint16)(((uint32)CapSense_calibratedRawcountRow * CapSense_CSD_AUTOTUNE_CAL_UNITS) / ((uint32)(0x01uL << CapSense_CALIBRATION_RESOLUTION) - 1u)); /* Find correct sense clock value */ cpRow = SmartSense_TunePrescalers(&autoTuneConfig); if ((CapSense_CP_MAX + CapSense_CP_ERROR) <= cpRow) { autoTuneStatus = CY_RET_BAD_DATA; } /* * Multiply the sense Clock Divider by 2 while the desired Sense Clock Frequency is greater * than maximum supported Sense Clock Frequency. */ while((((uint32)autoTuneConfig.snsClkInputClock) > ((uint32)ptrWdgt->snsClk * CapSense_CSD_SNS_FREQ_KHZ_MAX)) || (CapSense_MIN_SNS_CLK_DIVIDER > ptrWdgt->snsClk)) { ptrWdgt->snsClk <<= 1u; } } #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ /* Get pointer to Sense Clock Divider for columns */ autoTuneConfig.ptrSenseClk = &ptrWdgt->snsClk; /* Get IDAC */ autoTuneConfig.iDac = CapSense_calibratedIdac; /* Calculate achived calibration level */ autoTuneConfig.calTarget = (uint16)(((uint32)CapSense_calibratedRawcount * CapSense_CSD_AUTOTUNE_CAL_UNITS) / ((uint32)(0x01uL << CapSense_CALIBRATION_RESOLUTION) - 1u)); /* Find correct sense clock value */ cp = SmartSense_TunePrescalers(&autoTuneConfig); if ((CapSense_CP_MAX + CapSense_CP_ERROR) <= cp) { autoTuneStatus = CY_RET_BAD_DATA; } /* * Multiply the sense Clock Divider by 2 while the desired Sense Clock Frequency is greater * than MAX supported Sense Clock Frequency. */ while((((uint32)autoTuneConfig.snsClkInputClock) > ((uint32)ptrWdgt->snsClk * CapSense_CSD_SNS_FREQ_KHZ_MAX)) || (CapSense_MIN_SNS_CLK_DIVIDER > ptrWdgt->snsClk)) { ptrWdgt->snsClk <<= 1u; } cpWidget[wdgtIndex] = cp; #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) if ((CapSense_WD_TOUCHPAD_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType) || (CapSense_WD_MATRIX_BUTTON_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType)) { if (cpRow > cp) { cpWidget[wdgtIndex] = cpRow; } } #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ } else { #if (CapSense_ENABLE == CapSense_CSX_EN) /* Non-CSD widget */ cpWidget[wdgtIndex] = 1u; #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ } } /* * Autotune phase #2: * - repeating calibration with new sense clock frequency * - getting resolution */ /* Tune resolution for all the widgets */ for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[wdgtIndex])) { ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2WdgtRam; /* Calibrate CSD widget to the default calibration target */ autoTuneStatus |= CapSense_CSDCalibrateWidget(wdgtIndex, CapSense_CSD_AUTOTUNE_CAL_LEVEL); /* Get pointer to Sense Clock Divider (column or row) */ autoTuneConfig.ptrSenseClk = &ptrWdgt->snsClk; /* Set parasitic capacitance for columns */ autoTuneConfig.sensorCap = cpWidget[wdgtIndex]; /* Get IDAC */ autoTuneConfig.iDac = CapSense_calibratedIdac; #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) if ((CapSense_WD_TOUCHPAD_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType) || (CapSense_WD_MATRIX_BUTTON_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType)) { /* Set the minimum sense clock frequency to calculate the resolution */ if (ptrWdgt->snsClk < ptrWdgt->rowSnsClk) { /* Rewrite pointer to Sense Clock Divider for rows */ autoTuneConfig.ptrSenseClk = &ptrWdgt->rowSnsClk; /* Set parasitic capacitance for rows */ autoTuneConfig.sensorCap = cpWidget[wdgtIndex]; /* Get IDAC */ autoTuneConfig.iDac = CapSense_calibratedIdacRow; } } #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ /* Get finger capacitance */ autoTuneConfig.fingerCap = ptrWdgt->fingerCap; /* Init pointer to sigPFC */ autoTuneConfig.sigPFC = &ptrWdgt->sigPFC; /* Find resolution */ ptrWdgt->resolution = SmartSense_TuneSensitivity(&autoTuneConfig); } } /* * Autotune phase #3: * - selecting a widget clock source if AUTO * - repeating calibration with found clock frequency, resolution and clock source * - updating sensitivity */ /* Tune sensitivity for all the widgets */ for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[wdgtIndex])) { ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2WdgtRam; CapSense_SsSetWidgetSenseClkSrc(wdgtIndex, ptrWdgt); /* Calibrate CSD widget to the default calibration target */ autoTuneStatus |= CapSense_CSDCalibrateWidget(wdgtIndex, CapSense_CSD_AUTOTUNE_CAL_LEVEL); #if (CapSense_ENABLE == CapSense_TST_WDGT_CRC_EN) CapSense_DsUpdateWidgetCrc(wdgtIndex); #endif /* (CapSense_ENABLE == CapSense_TST_WDGT_CRC_EN) */ } } return autoTuneStatus; } #endif /* (CapSense_CSD_SS_DIS != CapSense_CSD_AUTOTUNE)) */ #if (CapSense_ENABLE == CapSense_MULTI_FREQ_SCAN_EN) /******************************************************************************* * Function Name: CapSense_SsChangeClkFreq ****************************************************************************//** * * \brief * This function changes the sensor clock frequency by configuring * the corresponding divider. * * \details * This function changes the sensor clock frequency by configuring * the corresponding divider. * * \param chId * The frequency channel ID. * *******************************************************************************/ void CapSense_SsChangeClkFreq(uint32 chId) { uint32 snsClkDivider; uint32 freqOffset1 = 0u; uint32 freqOffset2 = 0u; #if (0u != CapSense_TOTAL_CSD_WIDGETS) uint32 conversionsNum; #if((CapSense_CLK_SOURCE_PRS8 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRS12 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE)) uint32 snsClkSrc; #endif #endif #if ((0u != CapSense_TOTAL_CSD_WIDGETS) || \ ((CapSense_DISABLE == CapSense_CSX_COMMON_TX_CLK_EN) && (0u != CapSense_TOTAL_CSX_WIDGETS))) CapSense_FLASH_WD_STRUCT const *ptrFlashWdgt = &CapSense_dsFlash.wdgtArray[CapSense_widgetIndex]; CapSense_RAM_WD_BASE_STRUCT const *ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *)ptrFlashWdgt->ptr2WdgtRam; #endif switch(CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[CapSense_widgetIndex])) { #if (0u != CapSense_TOTAL_CSD_WIDGETS) case CapSense_SENSE_METHOD_CSD_E: /* Get sensor clock divider value */ #if (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) snsClkDivider = CapSense_dsRam.snsCsdClk; #else /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) /* Get SnsClck divider for rows or columns */ if (CapSense_dsFlash.wdgtArray[CapSense_widgetIndex].numCols <= CapSense_sensorIndex) { snsClkDivider = ptrWdgt->rowSnsClk; } else { snsClkDivider = ptrWdgt->snsClk; } #else snsClkDivider = ptrWdgt->snsClk; #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ #endif /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ freqOffset1 = CapSense_CSD_MFS_DIVIDER_OFFSET_F1; freqOffset2 = CapSense_CSD_MFS_DIVIDER_OFFSET_F2; #if((CapSense_CLK_SOURCE_PRS8 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRS12 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE)) /* Get sense clk source */ #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) /* Get SnsClc Source for rows or columns */ if (CapSense_dsFlash.wdgtArray[CapSense_widgetIndex].numCols <= CapSense_sensorIndex) { snsClkSrc = (uint32)ptrWdgt->rowSnsClkSource; } else { snsClkSrc = (uint32)ptrWdgt->snsClkSource; } #else snsClkSrc = (uint32)ptrWdgt->snsClkSource; #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ switch (snsClkSrc) { case CapSense_CLK_SOURCE_PRS8: case CapSense_CLK_SOURCE_PRS12: /* Multiply by 2 for PRS8/PRS12 mode */ freqOffset1 <<= 1u; freqOffset2 <<= 1u; break; default: break; } #endif /* Change the divider based on the chId */ switch (chId) { case CapSense_FREQ_CHANNEL_1: { snsClkDivider += freqOffset1; break; } case CapSense_FREQ_CHANNEL_2: { snsClkDivider += freqOffset2; break; } default: { break; } } /* Set Number Of Conversions based on scanning resolution */ conversionsNum = CapSense_SsCSDGetNumberOfConversions(snsClkDivider, (uint32)ptrWdgt->resolution, (uint32)ptrWdgt->snsClkSource); CY_SET_REG32(CapSense_CSD_SEQ_NORM_CNT_PTR, (conversionsNum & CapSense_CSD_SEQ_NORM_CNT_CONV_CNT_MSK)); #if((CapSense_CLK_SOURCE_PRS8 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRS12 == CapSense_CSD_SNS_CLK_SOURCE) ||\ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE)) switch (snsClkSrc) { case CapSense_CLK_SOURCE_PRS8: case CapSense_CLK_SOURCE_PRS12: /* Divide by 2 for PRS8/PRS12 mode */ snsClkDivider >>= 1; if (snsClkDivider == 0u) { snsClkDivider = 1u; } break; default: break; } #endif /* Configure the new divider */ CapSense_SsSetSnsClockDivider(snsClkDivider); break; #endif /* #if (0u != CapSense_TOTAL_CSD_WIDGETS) */ #if (0u != CapSense_TOTAL_CSX_WIDGETS) case CapSense_SENSE_METHOD_CSX_E: #if (CapSense_ENABLE == CapSense_CSX_COMMON_TX_CLK_EN) snsClkDivider = CapSense_dsRam.snsCsxClk; #else /* (CapSense_ENABLE == CapSense_CSX_COMMON_TX_CLK_EN) */ snsClkDivider = ptrWdgt->snsClk; #endif /* (CapSense_ENABLE == CapSense_CSX_COMMON_TX_CLK_EN) */ freqOffset1 = CapSense_CSX_MFS_DIVIDER_OFFSET_F1; freqOffset2 = CapSense_CSX_MFS_DIVIDER_OFFSET_F2; /* Change the divider based on the chId */ switch (chId) { case CapSense_FREQ_CHANNEL_1: { snsClkDivider += freqOffset1; break; } case CapSense_FREQ_CHANNEL_2: { snsClkDivider += freqOffset2; break; } default: { break; } } /* Configure the new divider */ CapSense_SsSetSnsClockDivider(snsClkDivider); break; #endif /* #if (0u != CapSense_TOTAL_CSX_WIDGETS) */ default: CY_ASSERT(0 != 0); break; } } #endif /* (CapSense_ENABLE == CapSense_MULTI_FREQ_SCAN_EN) */ #if((CapSense_ENABLE == CapSense_CSD_EN) ||\ (CapSense_ENABLE == CapSense_CSX_EN)) /******************************************************************************* * Function Name: CapSense_SsInitializeSourceSenseClk ****************************************************************************//** * * \brief * Sets a source for Sense Clk for all CSD widgets. * * \details * Updates snsClkSource and rowSnsClkSource with a source for the sense Clk. * for all CSD widgets. * *******************************************************************************/ void CapSense_SsInitializeSourceSenseClk(void) { uint32 wdgtIndex; CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *)CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2WdgtRam; switch(CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[wdgtIndex])) { #if (0u != CapSense_TOTAL_CSD_WIDGETS) case CapSense_SENSE_METHOD_CSD_E: CapSense_SsSetWidgetSenseClkSrc(wdgtIndex, ptrWdgt); break; #endif /* #if (0u != CapSense_TOTAL_CSD_WIDGETS) */ #if (0u != CapSense_TOTAL_CSX_WIDGETS) case CapSense_SENSE_METHOD_CSX_E: CapSense_SsSetWidgetTxClkSrc(wdgtIndex, ptrWdgt); break; #endif /* #if (0u != CapSense_TOTAL_CSX_WIDGETS) */ default: CY_ASSERT(0 != 0); break; } #if (CapSense_ENABLE == CapSense_TST_WDGT_CRC_EN) CapSense_DsUpdateWidgetCrc(wdgtIndex); #endif /* (CapSense_ENABLE == CapSense_TST_WDGT_CRC_EN) */ } } #endif /* ((CapSense_ENABLE == CapSense_CSD_EN) ||\ (CapSense_ENABLE == CapSense_CSX_EN)) */ #if (CapSense_ENABLE == CapSense_CSD_EN) /******************************************************************************* * Function Name: CapSense_SsSetWidgetSenseClkSrc ****************************************************************************//** * * \brief * Sets a source for the sense clock for a widget. * * \param wdgtIndex * Specifies the ID of the widget. * \param ptrWdgt * The pointer to the RAM_WD_BASE_STRUCT structure. * * \details * Updates snsClkSource and rowSnsClkSource with a source for the sense Clk for a * widget. * *******************************************************************************/ static void CapSense_SsSetWidgetSenseClkSrc(uint32 wdgtIndex, CapSense_RAM_WD_BASE_STRUCT * ptrWdgt) { uint8 lfsrSize; uint8 lfsrScale; #if(CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) uint32 conversionsNum; uint32 snsClkDivider; #endif /* (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) */ #if(CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) snsClkDivider = CapSense_SsCSDGetColSnsClkDivider(wdgtIndex); conversionsNum = CapSense_SsCSDGetNumberOfConversions(snsClkDivider, (uint32)ptrWdgt->resolution, CapSense_CLK_SOURCE_DIRECT); lfsrSize = CapSense_SsCalcLfsrSize(snsClkDivider, conversionsNum); if (CapSense_CLK_SOURCE_DIRECT == lfsrSize) { lfsrSize = CapSense_SsCSDCalcPrsSize(snsClkDivider << 1uL, (uint32)ptrWdgt->resolution); } lfsrScale = CapSense_SsCalcLfsrScale(snsClkDivider, lfsrSize); if((lfsrSize == CapSense_CLK_SOURCE_PRS8) || (lfsrSize == CapSense_CLK_SOURCE_PRS12)) { CapSense_SsCSDSetColSnsClkDivider(wdgtIndex, snsClkDivider); } #else lfsrSize = (uint8)CapSense_DEFAULT_MODULATION_MODE; lfsrScale = 0u; (void)wdgtIndex; /* This parameter is unused in such configurations */ #endif /* (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) */ ptrWdgt->snsClkSource = lfsrSize | (uint8)(lfsrScale << CapSense_CLK_SOURCE_LFSR_SCALE_OFFSET); #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) if ((CapSense_WD_TOUCHPAD_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType) || (CapSense_WD_MATRIX_BUTTON_E == (CapSense_WD_TYPE_ENUM)CapSense_dsFlash.wdgtArray[wdgtIndex].wdgtType)) { #if(CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) snsClkDivider = CapSense_SsCSDGetRowSnsClkDivider(wdgtIndex); lfsrSize = CapSense_SsCalcLfsrSize(snsClkDivider, conversionsNum); if (CapSense_CLK_SOURCE_DIRECT == lfsrSize) { lfsrSize = CapSense_SsCSDCalcPrsSize(snsClkDivider << 1uL, (uint32)ptrWdgt->resolution); } lfsrScale = CapSense_SsCalcLfsrScale(snsClkDivider, lfsrSize); if((lfsrSize == CapSense_CLK_SOURCE_PRS8) || (lfsrSize == CapSense_CLK_SOURCE_PRS12)) { CapSense_SsCSDSetRowSnsClkDivider(wdgtIndex, snsClkDivider); } #else lfsrSize = (uint8)CapSense_DEFAULT_MODULATION_MODE; lfsrScale = 0u; #endif /* (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) */ ptrWdgt->rowSnsClkSource = lfsrSize | (uint8)(lfsrScale << CapSense_CLK_SOURCE_LFSR_SCALE_OFFSET); } #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ } #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ #if (CapSense_ENABLE == CapSense_CSX_EN) /******************************************************************************* * Function Name: CapSense_SsSetWidgetTxClkSrc ****************************************************************************//** * * \brief * Sets a source for the Tx clock for a widget. * * \param wdgtIndex * Specifies the ID of the widget. * \param ptrWdgt * The pointer to the RAM_WD_BASE_STRUCT structure. * * \details * Updates snsClkSource with with a source for Tx Clk for a widget. * *******************************************************************************/ __STATIC_INLINE void CapSense_SsSetWidgetTxClkSrc(uint32 wdgtIndex, CapSense_RAM_WD_BASE_STRUCT * ptrWdgt) { uint8 lfsrSize; uint8 lfsrScale; #if ((CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) && \ (CapSense_DISABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES)) uint32 conversionsNum; uint32 snsClkDivider; #endif #if(CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) #if (CapSense_DISABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES) conversionsNum = (uint32)ptrWdgt->resolution; snsClkDivider = CapSense_SsCSXGetTxClkDivider(wdgtIndex); lfsrSize = CapSense_SsCalcLfsrSize(snsClkDivider, conversionsNum); lfsrScale = CapSense_SsCalcLfsrScale(snsClkDivider, lfsrSize); #else lfsrSize = (uint8)CapSense_CLK_SOURCE_DIRECT; lfsrScale = 0u; /* Unused function argument */ (void)wdgtIndex; #endif /* (CapSense_ENABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES) */ #else lfsrSize = (uint8)CapSense_CSX_TX_CLK_SOURCE; lfsrScale = 0u; /* Unused function argument */ (void)wdgtIndex; #endif /* (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) */ ptrWdgt->snsClkSource = lfsrSize | (uint8)(lfsrScale << CapSense_CLK_SOURCE_LFSR_SCALE_OFFSET); } #endif /* (CapSense_ENABLE == CapSense_CSX_EN) */ #if(((CapSense_ENABLE == CapSense_CSX_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) && \ (CapSense_DISABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES)) ||\ ((CapSense_ENABLE == CapSense_CSD_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE))) /******************************************************************************* * Function Name: CapSense_SsCalcLfsrSize ****************************************************************************//** * * \brief * This is an internal function that finds a SSC polynomial size in the Auto mode. * * \details * The SSC polynomial size in the auto mode is found based on the following * requirements: * - an LFSR value should be selected so that the max clock dither is limited with +/-10%. * - at least one full spread spectrum polynomial should pass during the scan time. * - the value of the number of conversions should be an integer multiple of the * repeat period of the programmed LFSR_SIZE. * * \param * snsClkDivider The divider value for the sense clock. * resolution The widget resolution. * * \return lfsrSize The LFSRSIZE value for the SENSE_PERIOD register. * *******************************************************************************/ static uint8 CapSense_SsCalcLfsrSize(uint32 snsClkDivider, uint32 conversionsNum) { uint8 lfsrSize = 0u; /* Find LFSR value */ if((CapSense_SNSCLK_SSC4_THRESHOLD <= snsClkDivider) && (CapSense_SNSCLK_SSC4_PERIOD <= conversionsNum) && (0uL == (conversionsNum % CapSense_SNSCLK_SSC4_PERIOD))) { lfsrSize = CapSense_CLK_SOURCE_SSC4; } else if((CapSense_SNSCLK_SSC3_THRESHOLD <= snsClkDivider) && (CapSense_SNSCLK_SSC3_PERIOD <= conversionsNum) && (0uL == (conversionsNum % CapSense_SNSCLK_SSC3_PERIOD))) { lfsrSize = CapSense_CLK_SOURCE_SSC3; } else if((CapSense_SNSCLK_SSC2_THRESHOLD <= snsClkDivider) && (CapSense_SNSCLK_SSC2_PERIOD <= conversionsNum) && (0uL == (conversionsNum % CapSense_SNSCLK_SSC2_PERIOD))) { lfsrSize = CapSense_CLK_SOURCE_SSC2; } else if((CapSense_SNSCLK_SSC1_THRESHOLD <= snsClkDivider) && (CapSense_SNSCLK_SSC1_PERIOD <= conversionsNum) && (0uL == (conversionsNum % CapSense_SNSCLK_SSC1_PERIOD))) { lfsrSize = CapSense_CLK_SOURCE_SSC1; } else { lfsrSize = (uint8)CapSense_CLK_SOURCE_DIRECT; } return (lfsrSize); } /******************************************************************************* * Function Name: CapSense_SsCalcLfsrScale ****************************************************************************//** * * \brief * This is an internal function that calculates the LFSR scale value. * * \details * The LFSR scale value is used to increase the clock dither if the desired dither * is wider than can be achieved with the current Sense Clock Divider and current LFSR * period. * * This returns the LFSR scale value needed to keep the clock dither in * range +/-10%. * * \param * snsClkDivider The divider value for the sense clock. * lfsrSize The period of the LFSR sequence. * CapSense_CLK_SOURCE_DIRECT The spreadspectrum is not used. * CapSense_CLK_SOURCE_SSC1 The length of LFSR sequence is 63 cycles. * CapSense_CLK_SOURCE_SSC2 The length of LFSR sequence is 127 cycles. * CapSense_CLK_SOURCE_SSC3 The length of LFSR sequence is 255 cycles. * CapSense_CLK_SOURCE_SSC4 The length of LFSR sequence is 511 cycles. * * \return The LFSR scale value needed to keep the clock dither in range +/-10%. * *******************************************************************************/ static uint8 CapSense_SsCalcLfsrScale(uint32 snsClkDivider, uint8 lfsrSize) { uint32 lfsrScale; uint32 lfsrRange; uint32 lfsrDither; /* Initialize the lfsrSize variable with the LFSR Range for given Lfsr Size. */ switch(lfsrSize) { case CapSense_CLK_SOURCE_SSC1: { lfsrRange = CapSense_SNSCLK_SSC1_RANGE; break; } case CapSense_CLK_SOURCE_SSC2: { lfsrRange = CapSense_SNSCLK_SSC2_RANGE; break; } case CapSense_CLK_SOURCE_SSC3: { lfsrRange = CapSense_SNSCLK_SSC3_RANGE; break; } case CapSense_CLK_SOURCE_SSC4: { lfsrRange = CapSense_SNSCLK_SSC4_RANGE; break; } default: { lfsrRange = 0u; break; } } /* Calculate the LFSR Scale value that is required to keep the Clock dither * as close as possible to the +/-10% limit of the used frequency. */ if((lfsrSize != CapSense_CLK_SOURCE_DIRECT) && (0u != lfsrRange)) { /* Calculate the LFSR Dither in percents. */ lfsrDither = ((lfsrRange * 100uL) / snsClkDivider); lfsrScale = 0uL; while(lfsrDither < CapSense_LFSR_DITHER_PERCENTAGE) { lfsrScale++; lfsrDither <<=1uL; } if(lfsrDither > CapSense_LFSR_DITHER_PERCENTAGE) { lfsrScale--; } } else { lfsrScale = 0uL; } return ((uint8)lfsrScale); } #endif /* (((CapSense_ENABLE == CapSense_CSX_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSX_TX_CLK_SOURCE) && \ (CapSense_DISABLE == CapSense_CSX_SKIP_OVSMPL_SPECIFIC_NODES)) ||\ ((CapSense_ENABLE == CapSense_CSD_EN) && \ (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE))) */ #if (CapSense_ENABLE == CapSense_CSD_EN) /******************************************************************************* * Function Name: CapSense_SsClearCSDSensors ****************************************************************************//** * * \brief * Resets all the CSD sensors to the non-sampling state by sequentially * disconnecting all the sensors from the Analog MUX bus and putting them to * an inactive state. * * \details * The function goes through all the widgets and updates appropriate bits in * the IO HSIOM, PC and DR registers depending on the Inactive sensor connection * parameter. DR register bits are set to zero when the Inactive sensor * connection is Ground or Hi-Z. * *******************************************************************************/ void CapSense_SsClearCSDSensors(void) { uint32 wdgtIndex; uint32 snsIndex; #if (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) uint32 pinIndex; #endif /* (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) */ #if (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) /* Declare ptr to sensor IO structure */ CapSense_FLASH_IO_STRUCT const *curDedicatedSnsIOPtr; /* Pointer to Flash structure holding info of sensor to be scanned */ CapSense_FLASH_SNS_STRUCT const *curFlashSnsPtr; #endif /* (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) */ CapSense_FLASH_IO_STRUCT const *curSnsIOPtr; for (wdgtIndex = 0u; wdgtIndex < CapSense_TOTAL_WIDGETS; wdgtIndex++) { if (CapSense_SENSE_METHOD_CSD_E == CapSense_GET_SENSE_METHOD(&CapSense_dsFlash.wdgtArray[wdgtIndex])) { curSnsIOPtr = (CapSense_FLASH_IO_STRUCT const *) CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2SnsFlash; /* Go through all the sensors in widget */ for (snsIndex = 0u; snsIndex < (uint8)CapSense_dsFlash.wdgtArray[wdgtIndex].totalNumSns; snsIndex++) { #if (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) /* Check ganged sns flag */ if (CapSense_GANGED_SNS_MASK == (CapSense_dsFlash.wdgtArray[wdgtIndex].staticConfig & CapSense_GANGED_SNS_MASK)) { /* Get sns pointer */ curFlashSnsPtr = (CapSense_FLASH_SNS_STRUCT const *) CapSense_dsFlash.wdgtArray[wdgtIndex].ptr2SnsFlash + snsIndex; for(pinIndex = 0u; pinIndex < curFlashSnsPtr->numPins; pinIndex++) { /* Get IO pointer for dedicated pin */ curDedicatedSnsIOPtr = &CapSense_ioList[curFlashSnsPtr->firstPinId + pinIndex]; /* Disconnect dedicated pin */ CapSense_CSDDisconnectSns(curDedicatedSnsIOPtr); } } else { /* Disable sensor */ CapSense_CSDDisconnectSns(&curSnsIOPtr[snsIndex]); } #else /* Disable sensor */ CapSense_CSDDisconnectSns(&curSnsIOPtr[snsIndex]); #endif /* (CapSense_ENABLE == CapSense_CSD_GANGED_SNS_EN) */ } } } } /******************************************************************************* * Function Name: CapSense_SsCSDGetColSnsClkDivider ****************************************************************************//** * * \brief * This function gets the Sense Clock Divider value for one-dimension widgets * and Column Sense Clock divider value for two-dimension widgets. * * \details * This function gets the Sense Clock Divider value based on the Component * configuration. The function is applicable for one-dimension widgets and for * two-dimension widgets. * * \param * widgetId Specifies the ID of the widget. * * \return The Sense Clock Divider value for one-dimension widgets * and the Column Sense Clock divider value for two-dimension widgets. * *******************************************************************************/ uint32 CapSense_SsCSDGetColSnsClkDivider(uint32 widgetId) { uint32 retVal; /* Get sense divider based on configuration */ #if (CapSense_ENABLE != CapSense_CSD_COMMON_SNS_CLK_EN) CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[widgetId].ptr2WdgtRam; retVal = (uint32)(ptrWdgt->snsClk); #else retVal = (uint32)CapSense_dsRam.snsCsdClk; (void)widgetId; /* This parameter is unused in such configurations */ #endif /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ return (retVal); } /******************************************************************************* * Function Name: CapSense_SsCSDSetColSnsClkDivider ****************************************************************************//** * * \brief * This function sets the Sense Clock Divider value for one-dimension widgets * and Column Sense Clock divider value for two-dimension widgets. * * \details * This function sets the Sense Clock Divider value based on the Component * configuration. The function is applicable for one-dimension widgets and for * two-dimension widgets. * * \param * widgetId Specifies the ID of the widget. * * \return The Sense Clock Divider value for one-dimension widgets * and the Column Sense Clock divider value for two-dimension widgets. * *******************************************************************************/ void CapSense_SsCSDSetColSnsClkDivider(uint32 widgetId, uint32 dividerVal) { /* Get sense divider based on configuration */ #if (CapSense_ENABLE != CapSense_CSD_COMMON_SNS_CLK_EN) CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[widgetId].ptr2WdgtRam; ptrWdgt->snsClk = (uint16)dividerVal; #else CapSense_dsRam.snsCsdClk = (uint16)dividerVal; (void)widgetId; /* This parameter is unused in such configurations */ #endif /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ } #if (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) /******************************************************************************* * Function Name: CapSense_SsCSDGetRowSnsClkDivider ****************************************************************************//** * * \brief * This function gets the Sense Clock Divider value for one-dimension widgets * and the Column Sense Clock divider value for two-dimension widgets. * * \details * This function gets the Sense Clock Divider value based on the Component * configuration. The function is applicable for one-dimension widgets and for * two-dimension widgets. * * \param * widgetId Specifies the ID of the widget. * * \return * Returns the sense clock divider value for one-dimension widgets * and column sense clock divider value for two-dimension widgets. * *******************************************************************************/ uint32 CapSense_SsCSDGetRowSnsClkDivider(uint32 widgetId) { uint32 retVal; /* Get sense divider based on configuration */ #if (CapSense_ENABLE != CapSense_CSD_COMMON_SNS_CLK_EN) CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[widgetId].ptr2WdgtRam; retVal = ptrWdgt->rowSnsClk; #else retVal = (uint32)CapSense_dsRam.snsCsdClk; (void)widgetId; /* This parameter is unused in such configurations */ #endif /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ return (retVal); } /******************************************************************************* * Function Name: CapSense_SsCSDSetRowSnsClkDivider ****************************************************************************//** * * \brief * This function sets the Sense Clock Divider value for one-dimension widgets * and the Column Sense Clock divider value for two-dimension widgets. * * \details * This function sets the Sense Clock Divider value based on the Component * configuration. The function is applicable for one-dimension widgets and for * two-dimension widgets. * * \param * widgetId Specifies the ID of the widget. * * \param * dividerVal Specifies the Sense Clock Divider value. * *******************************************************************************/ void CapSense_SsCSDSetRowSnsClkDivider(uint32 widgetId, uint32 dividerVal) { /* Get sense divider based on configuration */ #if (CapSense_ENABLE != CapSense_CSD_COMMON_SNS_CLK_EN) CapSense_RAM_WD_BASE_STRUCT *ptrWdgt; ptrWdgt = (CapSense_RAM_WD_BASE_STRUCT *) CapSense_dsFlash.wdgtArray[widgetId].ptr2WdgtRam; ptrWdgt->rowSnsClk = (uint16)dividerVal; #else CapSense_dsRam.snsCsdClk = (uint16)dividerVal; (void)widgetId; /* This parameter is unused in such configurations */ #endif /* (CapSense_ENABLE == CapSense_CSD_COMMON_SNS_CLK_EN) */ } #endif /* (CapSense_CSD_MATRIX_WIDGET_EN || CapSense_CSD_TOUCHPAD_WIDGET_EN) */ #if (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) /******************************************************************************* * Function Name: CapSense_SsCSDCalcPrsSize ****************************************************************************//** * * \brief * The function finds PRS polynomial size in the Auto mode. * * \details * The PRS polynomial size in the Auto mode is found based on the following * requirements: * - at least one full spread spectrum polynomial should pass during scan time. * * \param * snsClkDivider The divider value for the sense clock. * resolution The widget resolution. * * \return prsSize PRS value for SENSE_PERIOD register. * *******************************************************************************/ uint8 CapSense_SsCSDCalcPrsSize(uint32 snsClkDivider, uint32 resolution) { uint32 prsSize; if ((snsClkDivider * CapSense_PRS_LENGTH_12_BITS) <= ((0x00000001Lu << resolution) - 1u)) { /* Set PRS12 mode */ prsSize = CapSense_CLK_SOURCE_PRS12; } else if ((snsClkDivider * CapSense_PRS_LENGTH_8_BITS) <= ((0x00000001Lu << resolution) - 1u)) { /* Set PRS8 mode */ prsSize = CapSense_CLK_SOURCE_PRS8; } else { /* Set Direct clock mode */ prsSize = CapSense_CLK_SOURCE_DIRECT; } return (uint8)prsSize; } #endif /* (CapSense_CLK_SOURCE_PRSAUTO == CapSense_CSD_SNS_CLK_SOURCE) */ #endif /* (CapSense_ENABLE == CapSense_CSD_EN) */ /******************************************************************************* * Function Name: CapSense_BistDischargeExtCapacitors ****************************************************************************//** * * \brief * The function discharge available external capacitors. * * \details * The function discharge available external capacitors by connection them * to GND using STRONG GPIO drive mode. Additionaly, the function disconnects * the capacitors from analog mux buses if connected. * Note: the function does not restore the connection to analog mux busses * and supposes that all the capacitors belong to a single device port. * *******************************************************************************/ void CapSense_BistDischargeExtCapacitors(void) { #if (CapSense_ENABLE == CapSense_CSD_EN) Cy_GPIO_SetHSIOM(CapSense_Cmod_0_PORT, CapSense_Cmod_0_NUM, HSIOM_SEL_GPIO); Cy_GPIO_Clr(CapSense_Cmod_0_PORT, CapSense_Cmod_0_NUM); Cy_GPIO_SetDrivemode(CapSense_Cmod_0_PORT, CapSense_Cmod_0_NUM, CY_GPIO_DM_STRONG_IN_OFF); #if((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (CapSense_ENABLE == CapSense_CSD_SHIELD_TANK_EN)) Cy_GPIO_SetHSIOM(CapSense_Csh_0_PORT, CapSense_Csh_0_NUM, HSIOM_SEL_GPIO); Cy_GPIO_Clr(CapSense_Csh_0_PORT, CapSense_Csh_0_NUM); Cy_GPIO_SetDrivemode(CapSense_Csh_0_PORT, CapSense_Csh_0_NUM, CY_GPIO_DM_STRONG_IN_OFF); #endif #endif #if (CapSense_ENABLE == CapSense_CSX_EN) Cy_GPIO_SetHSIOM(CapSense_CintA_0_PORT, CapSense_CintA_0_NUM, HSIOM_SEL_GPIO); Cy_GPIO_Clr(CapSense_CintA_0_PORT, CapSense_CintA_0_NUM); Cy_GPIO_SetDrivemode(CapSense_CintA_0_PORT, CapSense_CintA_0_NUM, CY_GPIO_DM_STRONG_IN_OFF); Cy_GPIO_SetHSIOM(CapSense_CintB_0_PORT, CapSense_CintB_0_NUM, HSIOM_SEL_GPIO); Cy_GPIO_Clr(CapSense_CintB_0_PORT, CapSense_CintB_0_NUM); Cy_GPIO_SetDrivemode(CapSense_CintB_0_PORT, CapSense_CintB_0_NUM, CY_GPIO_DM_STRONG_IN_OFF); #endif Cy_SysLib_DelayUs(CapSense_EXT_CAP_DISCHARGE_TIME); #if (CapSense_ENABLE == CapSense_CSD_EN) Cy_GPIO_SetDrivemode(CapSense_Cmod_0_PORT, CapSense_Cmod_0_NUM, CY_GPIO_DM_ANALOG); #if((CapSense_ENABLE == CapSense_CSD_SHIELD_EN) && \ (CapSense_ENABLE == CapSense_CSD_SHIELD_TANK_EN)) Cy_GPIO_SetDrivemode(CapSense_Csh_0_PORT, CapSense_Csh_0_NUM, CY_GPIO_DM_ANALOG); #endif #endif #if (CapSense_ENABLE == CapSense_CSX_EN) Cy_GPIO_SetDrivemode(CapSense_CintA_0_PORT, CapSense_CintA_0_NUM, CY_GPIO_DM_ANALOG); Cy_GPIO_SetDrivemode(CapSense_CintB_0_PORT, CapSense_CintB_0_NUM, CY_GPIO_DM_ANALOG); #endif } /* [] END OF FILE */
86002.c
/* crypto/err/err.c */ /* 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.] */ /* ==================================================================== * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ #define OPENSSL_NO_FIPS_ERR #include <stdio.h> #include <stdarg.h> #include <string.h> #include "cryptlib.h" #include <openssl/lhash.h> #include <openssl/crypto.h> #include <openssl/buffer.h> #include <openssl/bio.h> #include <openssl/err.h> DECLARE_LHASH_OF(ERR_STRING_DATA); DECLARE_LHASH_OF(ERR_STATE); static void err_load_strings(int lib, ERR_STRING_DATA *str); static void ERR_STATE_free(ERR_STATE *s); #ifndef OPENSSL_NO_ERR static ERR_STRING_DATA ERR_str_libraries[]= { {ERR_PACK(ERR_LIB_NONE,0,0) ,"unknown library"}, {ERR_PACK(ERR_LIB_SYS,0,0) ,"system library"}, {ERR_PACK(ERR_LIB_BN,0,0) ,"bignum routines"}, {ERR_PACK(ERR_LIB_RSA,0,0) ,"rsa routines"}, {ERR_PACK(ERR_LIB_DH,0,0) ,"Diffie-Hellman routines"}, {ERR_PACK(ERR_LIB_EVP,0,0) ,"digital envelope routines"}, {ERR_PACK(ERR_LIB_BUF,0,0) ,"memory buffer routines"}, {ERR_PACK(ERR_LIB_OBJ,0,0) ,"object identifier routines"}, {ERR_PACK(ERR_LIB_PEM,0,0) ,"PEM routines"}, {ERR_PACK(ERR_LIB_DSA,0,0) ,"dsa routines"}, {ERR_PACK(ERR_LIB_X509,0,0) ,"x509 certificate routines"}, {ERR_PACK(ERR_LIB_ASN1,0,0) ,"asn1 encoding routines"}, {ERR_PACK(ERR_LIB_CONF,0,0) ,"configuration file routines"}, {ERR_PACK(ERR_LIB_CRYPTO,0,0) ,"common libcrypto routines"}, {ERR_PACK(ERR_LIB_EC,0,0) ,"elliptic curve routines"}, {ERR_PACK(ERR_LIB_ECDSA,0,0) ,"ECDSA routines"}, {ERR_PACK(ERR_LIB_ECDH,0,0) ,"ECDH routines"}, {ERR_PACK(ERR_LIB_SSL,0,0) ,"SSL routines"}, {ERR_PACK(ERR_LIB_BIO,0,0) ,"BIO routines"}, {ERR_PACK(ERR_LIB_PKCS7,0,0) ,"PKCS7 routines"}, {ERR_PACK(ERR_LIB_X509V3,0,0) ,"X509 V3 routines"}, {ERR_PACK(ERR_LIB_PKCS12,0,0) ,"PKCS12 routines"}, {ERR_PACK(ERR_LIB_RAND,0,0) ,"random number generator"}, {ERR_PACK(ERR_LIB_DSO,0,0) ,"DSO support routines"}, {ERR_PACK(ERR_LIB_TS,0,0) ,"time stamp routines"}, {ERR_PACK(ERR_LIB_ENGINE,0,0) ,"engine routines"}, {ERR_PACK(ERR_LIB_OCSP,0,0) ,"OCSP routines"}, {ERR_PACK(ERR_LIB_FIPS,0,0) ,"FIPS routines"}, {ERR_PACK(ERR_LIB_CMS,0,0) ,"CMS routines"}, {ERR_PACK(ERR_LIB_HMAC,0,0) ,"HMAC routines"}, {0,NULL}, }; static ERR_STRING_DATA ERR_str_functs[]= { {ERR_PACK(0,SYS_F_FOPEN,0), "fopen"}, {ERR_PACK(0,SYS_F_CONNECT,0), "connect"}, {ERR_PACK(0,SYS_F_GETSERVBYNAME,0), "getservbyname"}, {ERR_PACK(0,SYS_F_SOCKET,0), "socket"}, {ERR_PACK(0,SYS_F_IOCTLSOCKET,0), "ioctlsocket"}, {ERR_PACK(0,SYS_F_BIND,0), "bind"}, {ERR_PACK(0,SYS_F_LISTEN,0), "listen"}, {ERR_PACK(0,SYS_F_ACCEPT,0), "accept"}, #ifdef OPENSSL_SYS_WINDOWS {ERR_PACK(0,SYS_F_WSASTARTUP,0), "WSAstartup"}, #endif {ERR_PACK(0,SYS_F_OPENDIR,0), "opendir"}, {ERR_PACK(0,SYS_F_FREAD,0), "fread"}, {0,NULL}, }; static ERR_STRING_DATA ERR_str_reasons[]= { {ERR_R_SYS_LIB ,"system lib"}, {ERR_R_BN_LIB ,"BN lib"}, {ERR_R_RSA_LIB ,"RSA lib"}, {ERR_R_DH_LIB ,"DH lib"}, {ERR_R_EVP_LIB ,"EVP lib"}, {ERR_R_BUF_LIB ,"BUF lib"}, {ERR_R_OBJ_LIB ,"OBJ lib"}, {ERR_R_PEM_LIB ,"PEM lib"}, {ERR_R_DSA_LIB ,"DSA lib"}, {ERR_R_X509_LIB ,"X509 lib"}, {ERR_R_ASN1_LIB ,"ASN1 lib"}, {ERR_R_CONF_LIB ,"CONF lib"}, {ERR_R_CRYPTO_LIB ,"CRYPTO lib"}, {ERR_R_EC_LIB ,"EC lib"}, {ERR_R_SSL_LIB ,"SSL lib"}, {ERR_R_BIO_LIB ,"BIO lib"}, {ERR_R_PKCS7_LIB ,"PKCS7 lib"}, {ERR_R_X509V3_LIB ,"X509V3 lib"}, {ERR_R_PKCS12_LIB ,"PKCS12 lib"}, {ERR_R_RAND_LIB ,"RAND lib"}, {ERR_R_DSO_LIB ,"DSO lib"}, {ERR_R_ENGINE_LIB ,"ENGINE lib"}, {ERR_R_OCSP_LIB ,"OCSP lib"}, {ERR_R_TS_LIB ,"TS lib"}, {ERR_R_ECDSA_LIB ,"ECDSA lib"}, {ERR_R_NESTED_ASN1_ERROR ,"nested asn1 error"}, {ERR_R_BAD_ASN1_OBJECT_HEADER ,"bad asn1 object header"}, {ERR_R_BAD_GET_ASN1_OBJECT_CALL ,"bad get asn1 object call"}, {ERR_R_EXPECTING_AN_ASN1_SEQUENCE ,"expecting an asn1 sequence"}, {ERR_R_ASN1_LENGTH_MISMATCH ,"asn1 length mismatch"}, {ERR_R_MISSING_ASN1_EOS ,"missing asn1 eos"}, {ERR_R_FATAL ,"fatal"}, {ERR_R_MALLOC_FAILURE ,"malloc failure"}, {ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED ,"called a function you should not call"}, {ERR_R_PASSED_NULL_PARAMETER ,"passed a null parameter"}, {ERR_R_INTERNAL_ERROR ,"internal error"}, {ERR_R_DISABLED ,"called a function that was disabled at compile-time"}, {0,NULL}, }; #endif /* Define the predeclared (but externally opaque) "ERR_FNS" type */ struct st_ERR_FNS { /* Works on the "error_hash" string table */ LHASH_OF(ERR_STRING_DATA) *(*cb_err_get)(int create); void (*cb_err_del)(void); ERR_STRING_DATA *(*cb_err_get_item)(const ERR_STRING_DATA *); ERR_STRING_DATA *(*cb_err_set_item)(ERR_STRING_DATA *); ERR_STRING_DATA *(*cb_err_del_item)(ERR_STRING_DATA *); /* Works on the "thread_hash" error-state table */ LHASH_OF(ERR_STATE) *(*cb_thread_get)(int create); void (*cb_thread_release)(LHASH_OF(ERR_STATE) **hash); ERR_STATE *(*cb_thread_get_item)(const ERR_STATE *); ERR_STATE *(*cb_thread_set_item)(ERR_STATE *); void (*cb_thread_del_item)(const ERR_STATE *); /* Returns the next available error "library" numbers */ int (*cb_get_next_lib)(void); }; /* Predeclarations of the "err_defaults" functions */ static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create); static void int_err_del(void); static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *); static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *); static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *); static LHASH_OF(ERR_STATE) *int_thread_get(int create); static void int_thread_release(LHASH_OF(ERR_STATE) **hash); static ERR_STATE *int_thread_get_item(const ERR_STATE *); static ERR_STATE *int_thread_set_item(ERR_STATE *); static void int_thread_del_item(const ERR_STATE *); static int int_err_get_next_lib(void); /* The static ERR_FNS table using these defaults functions */ static const ERR_FNS err_defaults = { int_err_get, int_err_del, int_err_get_item, int_err_set_item, int_err_del_item, int_thread_get, int_thread_release, int_thread_get_item, int_thread_set_item, int_thread_del_item, int_err_get_next_lib }; /* The replacable table of ERR_FNS functions we use at run-time */ static const ERR_FNS *err_fns = NULL; /* Eg. rather than using "err_get()", use "ERRFN(err_get)()". */ #define ERRFN(a) err_fns->cb_##a /* The internal state used by "err_defaults" - as such, the setting, reading, * creating, and deleting of this data should only be permitted via the * "err_defaults" functions. This way, a linked module can completely defer all * ERR state operation (together with requisite locking) to the implementations * and state in the loading application. */ static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL; static LHASH_OF(ERR_STATE) *int_thread_hash = NULL; static int int_thread_hash_references = 0; static int int_err_library_number= ERR_LIB_USER; /* Internal function that checks whether "err_fns" is set and if not, sets it to * the defaults. */ static void err_fns_check(void) { if (err_fns) return; CRYPTO_w_lock(CRYPTO_LOCK_ERR); if (!err_fns) err_fns = &err_defaults; CRYPTO_w_unlock(CRYPTO_LOCK_ERR); } /* API functions to get or set the underlying ERR functions. */ const ERR_FNS *ERR_get_implementation(void) { err_fns_check(); return err_fns; } int ERR_set_implementation(const ERR_FNS *fns) { int ret = 0; CRYPTO_w_lock(CRYPTO_LOCK_ERR); /* It's too late if 'err_fns' is non-NULL. BTW: not much point setting * an error is there?! */ if (!err_fns) { err_fns = fns; ret = 1; } CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return ret; } /* These are the callbacks provided to "lh_new()" when creating the LHASH tables * internal to the "err_defaults" implementation. */ static unsigned long get_error_values(int inc,int top,const char **file,int *line, const char **data,int *flags); /* The internal functions used in the "err_defaults" implementation */ static unsigned long err_string_data_hash(const ERR_STRING_DATA *a) { unsigned long ret,l; l=a->error; ret=l^ERR_GET_LIB(l)^ERR_GET_FUNC(l); return(ret^ret%19*13); } static IMPLEMENT_LHASH_HASH_FN(err_string_data, ERR_STRING_DATA) static int err_string_data_cmp(const ERR_STRING_DATA *a, const ERR_STRING_DATA *b) { return (int)(a->error - b->error); } static IMPLEMENT_LHASH_COMP_FN(err_string_data, ERR_STRING_DATA) static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create) { LHASH_OF(ERR_STRING_DATA) *ret = NULL; CRYPTO_w_lock(CRYPTO_LOCK_ERR); if (!int_error_hash && create) { CRYPTO_push_info("int_err_get (err.c)"); int_error_hash = lh_ERR_STRING_DATA_new(); CRYPTO_pop_info(); } if (int_error_hash) ret = int_error_hash; CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return ret; } static void int_err_del(void) { CRYPTO_w_lock(CRYPTO_LOCK_ERR); if (int_error_hash) { lh_ERR_STRING_DATA_free(int_error_hash); int_error_hash = NULL; } CRYPTO_w_unlock(CRYPTO_LOCK_ERR); } static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d) { ERR_STRING_DATA *p; LHASH_OF(ERR_STRING_DATA) *hash; err_fns_check(); hash = ERRFN(err_get)(0); if (!hash) return NULL; CRYPTO_r_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STRING_DATA_retrieve(hash, d); CRYPTO_r_unlock(CRYPTO_LOCK_ERR); return p; } static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *d) { ERR_STRING_DATA *p; LHASH_OF(ERR_STRING_DATA) *hash; err_fns_check(); hash = ERRFN(err_get)(1); if (!hash) return NULL; CRYPTO_w_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STRING_DATA_insert(hash, d); CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return p; } static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *d) { ERR_STRING_DATA *p; LHASH_OF(ERR_STRING_DATA) *hash; err_fns_check(); hash = ERRFN(err_get)(0); if (!hash) return NULL; CRYPTO_w_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STRING_DATA_delete(hash, d); CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return p; } static unsigned long err_state_hash(const ERR_STATE *a) { return CRYPTO_THREADID_hash(&a->tid) * 13; } static IMPLEMENT_LHASH_HASH_FN(err_state, ERR_STATE) static int err_state_cmp(const ERR_STATE *a, const ERR_STATE *b) { return CRYPTO_THREADID_cmp(&a->tid, &b->tid); } static IMPLEMENT_LHASH_COMP_FN(err_state, ERR_STATE) static LHASH_OF(ERR_STATE) *int_thread_get(int create) { LHASH_OF(ERR_STATE) *ret = NULL; CRYPTO_w_lock(CRYPTO_LOCK_ERR); if (!int_thread_hash && create) { CRYPTO_push_info("int_thread_get (err.c)"); int_thread_hash = lh_ERR_STATE_new(); CRYPTO_pop_info(); } if (int_thread_hash) { int_thread_hash_references++; ret = int_thread_hash; } CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return ret; } static void int_thread_release(LHASH_OF(ERR_STATE) **hash) { int i; if (hash == NULL || *hash == NULL) return; i = CRYPTO_add(&int_thread_hash_references, -1, CRYPTO_LOCK_ERR); #ifdef REF_PRINT fprintf(stderr,"%4d:%s\n",int_thread_hash_references,"ERR"); #endif if (i > 0) return; #ifdef REF_CHECK if (i < 0) { fprintf(stderr,"int_thread_release, bad reference count\n"); abort(); /* ok */ } #endif *hash = NULL; } static ERR_STATE *int_thread_get_item(const ERR_STATE *d) { ERR_STATE *p; LHASH_OF(ERR_STATE) *hash; err_fns_check(); hash = ERRFN(thread_get)(0); if (!hash) return NULL; CRYPTO_r_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STATE_retrieve(hash, d); CRYPTO_r_unlock(CRYPTO_LOCK_ERR); ERRFN(thread_release)(&hash); return p; } static ERR_STATE *int_thread_set_item(ERR_STATE *d) { ERR_STATE *p; LHASH_OF(ERR_STATE) *hash; err_fns_check(); hash = ERRFN(thread_get)(1); if (!hash) return NULL; CRYPTO_w_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STATE_insert(hash, d); CRYPTO_w_unlock(CRYPTO_LOCK_ERR); ERRFN(thread_release)(&hash); return p; } static void int_thread_del_item(const ERR_STATE *d) { ERR_STATE *p; LHASH_OF(ERR_STATE) *hash; err_fns_check(); hash = ERRFN(thread_get)(0); if (!hash) return; CRYPTO_w_lock(CRYPTO_LOCK_ERR); p = lh_ERR_STATE_delete(hash, d); /* make sure we don't leak memory */ if (int_thread_hash_references == 1 && int_thread_hash && lh_ERR_STATE_num_items(int_thread_hash) == 0) { lh_ERR_STATE_free(int_thread_hash); int_thread_hash = NULL; } CRYPTO_w_unlock(CRYPTO_LOCK_ERR); ERRFN(thread_release)(&hash); if (p) ERR_STATE_free(p); } static int int_err_get_next_lib(void) { int ret; CRYPTO_w_lock(CRYPTO_LOCK_ERR); ret = int_err_library_number++; CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return ret; } #ifndef OPENSSL_NO_ERR #define NUM_SYS_STR_REASONS 127 #define LEN_SYS_STR_REASON 32 static ERR_STRING_DATA SYS_str_reasons[NUM_SYS_STR_REASONS + 1]; /* SYS_str_reasons is filled with copies of strerror() results at * initialization. * 'errno' values up to 127 should cover all usual errors, * others will be displayed numerically by ERR_error_string. * It is crucial that we have something for each reason code * that occurs in ERR_str_reasons, or bogus reason strings * will be returned for SYSerr(), which always gets an errno * value and never one of those 'standard' reason codes. */ static void build_SYS_str_reasons(void) { /* OPENSSL_malloc cannot be used here, use static storage instead */ static char strerror_tab[NUM_SYS_STR_REASONS][LEN_SYS_STR_REASON]; int i; static int init = 1; CRYPTO_r_lock(CRYPTO_LOCK_ERR); if (!init) { CRYPTO_r_unlock(CRYPTO_LOCK_ERR); return; } CRYPTO_r_unlock(CRYPTO_LOCK_ERR); CRYPTO_w_lock(CRYPTO_LOCK_ERR); if (!init) { CRYPTO_w_unlock(CRYPTO_LOCK_ERR); return; } for (i = 1; i <= NUM_SYS_STR_REASONS; i++) { ERR_STRING_DATA *str = &SYS_str_reasons[i - 1]; str->error = (unsigned long)i; if (str->string == NULL) { char (*dest)[LEN_SYS_STR_REASON] = &(strerror_tab[i - 1]); char *src = strerror(i); if (src != NULL) { strncpy(*dest, src, sizeof *dest); (*dest)[sizeof *dest - 1] = '\0'; str->string = *dest; } } if (str->string == NULL) str->string = "unknown"; } /* Now we still have SYS_str_reasons[NUM_SYS_STR_REASONS] = {0, NULL}, * as required by ERR_load_strings. */ init = 0; CRYPTO_w_unlock(CRYPTO_LOCK_ERR); } #endif #define err_clear_data(p,i) \ do { \ if (((p)->err_data[i] != NULL) && \ (p)->err_data_flags[i] & ERR_TXT_MALLOCED) \ { \ OPENSSL_free((p)->err_data[i]); \ (p)->err_data[i]=NULL; \ } \ (p)->err_data_flags[i]=0; \ } while(0) #define err_clear(p,i) \ do { \ (p)->err_flags[i]=0; \ (p)->err_buffer[i]=0; \ err_clear_data(p,i); \ (p)->err_file[i]=NULL; \ (p)->err_line[i]= -1; \ } while(0) static void ERR_STATE_free(ERR_STATE *s) { int i; if (s == NULL) return; for (i=0; i<ERR_NUM_ERRORS; i++) { err_clear_data(s,i); } OPENSSL_free(s); } void ERR_load_ERR_strings(void) { err_fns_check(); #ifndef OPENSSL_NO_ERR err_load_strings(0,ERR_str_libraries); err_load_strings(0,ERR_str_reasons); err_load_strings(ERR_LIB_SYS,ERR_str_functs); build_SYS_str_reasons(); err_load_strings(ERR_LIB_SYS,SYS_str_reasons); #endif } static void err_load_strings(int lib, ERR_STRING_DATA *str) { while (str->error) { if (lib) str->error|=ERR_PACK(lib,0,0); ERRFN(err_set_item)(str); str++; } } void ERR_load_strings(int lib, ERR_STRING_DATA *str) { ERR_load_ERR_strings(); err_load_strings(lib, str); } void ERR_unload_strings(int lib, ERR_STRING_DATA *str) { while (str->error) { if (lib) str->error|=ERR_PACK(lib,0,0); ERRFN(err_del_item)(str); str++; } } void ERR_free_strings(void) { err_fns_check(); ERRFN(err_del)(); } /********************************************************/ void ERR_put_error(int lib, int func, int reason, const char *file, int line) { ERR_STATE *es; #ifdef _OSD_POSIX /* In the BS2000-OSD POSIX subsystem, the compiler generates * path names in the form "*POSIX(/etc/passwd)". * This dirty hack strips them to something sensible. * @@@ We shouldn't modify a const string, though. */ if (strncmp(file,"*POSIX(", sizeof("*POSIX(")-1) == 0) { char *end; /* Skip the "*POSIX(" prefix */ file += sizeof("*POSIX(")-1; end = &file[strlen(file)-1]; if (*end == ')') *end = '\0'; /* Optional: use the basename of the path only. */ if ((end = strrchr(file, '/')) != NULL) file = &end[1]; } #endif es=ERR_get_state(); es->top=(es->top+1)%ERR_NUM_ERRORS; if (es->top == es->bottom) es->bottom=(es->bottom+1)%ERR_NUM_ERRORS; es->err_flags[es->top]=0; es->err_buffer[es->top]=ERR_PACK(lib,func,reason); es->err_file[es->top]=file; es->err_line[es->top]=line; err_clear_data(es,es->top); } void ERR_clear_error(void) { int i; ERR_STATE *es; es=ERR_get_state(); for (i=0; i<ERR_NUM_ERRORS; i++) { err_clear(es,i); } es->top=es->bottom=0; } unsigned long ERR_get_error(void) { return(get_error_values(1,0,NULL,NULL,NULL,NULL)); } unsigned long ERR_get_error_line(const char **file, int *line) { return(get_error_values(1,0,file,line,NULL,NULL)); } unsigned long ERR_get_error_line_data(const char **file, int *line, const char **data, int *flags) { return(get_error_values(1,0,file,line,data,flags)); } unsigned long ERR_peek_error(void) { return(get_error_values(0,0,NULL,NULL,NULL,NULL)); } unsigned long ERR_peek_error_line(const char **file, int *line) { return(get_error_values(0,0,file,line,NULL,NULL)); } unsigned long ERR_peek_error_line_data(const char **file, int *line, const char **data, int *flags) { return(get_error_values(0,0,file,line,data,flags)); } unsigned long ERR_peek_last_error(void) { return(get_error_values(0,1,NULL,NULL,NULL,NULL)); } unsigned long ERR_peek_last_error_line(const char **file, int *line) { return(get_error_values(0,1,file,line,NULL,NULL)); } unsigned long ERR_peek_last_error_line_data(const char **file, int *line, const char **data, int *flags) { return(get_error_values(0,1,file,line,data,flags)); } static unsigned long get_error_values(int inc, int top, const char **file, int *line, const char **data, int *flags) { int i=0; ERR_STATE *es; unsigned long ret; es=ERR_get_state(); if (inc && top) { if (file) *file = ""; if (line) *line = 0; if (data) *data = ""; if (flags) *flags = 0; return ERR_R_INTERNAL_ERROR; } if (es->bottom == es->top) return 0; if (top) i=es->top; /* last error */ else i=(es->bottom+1)%ERR_NUM_ERRORS; /* first error */ ret=es->err_buffer[i]; if (inc) { es->bottom=i; es->err_buffer[i]=0; } if ((file != NULL) && (line != NULL)) { if (es->err_file[i] == NULL) { *file="NA"; if (line != NULL) *line=0; } else { *file=es->err_file[i]; if (line != NULL) *line=es->err_line[i]; } } if (data == NULL) { if (inc) { err_clear_data(es, i); } } else { if (es->err_data[i] == NULL) { *data=""; if (flags != NULL) *flags=0; } else { *data=es->err_data[i]; if (flags != NULL) *flags=es->err_data_flags[i]; } } return ret; } void ERR_error_string_n(unsigned long e, char *buf, size_t len) { char lsbuf[64], fsbuf[64], rsbuf[64]; const char *ls,*fs,*rs; unsigned long l,f,r; l=ERR_GET_LIB(e); f=ERR_GET_FUNC(e); r=ERR_GET_REASON(e); ls=ERR_lib_error_string(e); fs=ERR_func_error_string(e); rs=ERR_reason_error_string(e); if (ls == NULL) BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l); if (fs == NULL) BIO_snprintf(fsbuf, sizeof(fsbuf), "func(%lu)", f); if (rs == NULL) BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r); BIO_snprintf(buf, len,"error:%08lX:%s:%s:%s", e, ls?ls:lsbuf, fs?fs:fsbuf, rs?rs:rsbuf); if (strlen(buf) == len-1) { /* output may be truncated; make sure we always have 5 * colon-separated fields, i.e. 4 colons ... */ #define NUM_COLONS 4 if (len > NUM_COLONS) /* ... if possible */ { int i; char *s = buf; for (i = 0; i < NUM_COLONS; i++) { char *colon = strchr(s, ':'); if (colon == NULL || colon > &buf[len-1] - NUM_COLONS + i) { /* set colon no. i at last possible position * (buf[len-1] is the terminating 0)*/ colon = &buf[len-1] - NUM_COLONS + i; *colon = ':'; } s = colon + 1; } } } } /* BAD for multi-threading: uses a local buffer if ret == NULL */ /* ERR_error_string_n should be used instead for ret != NULL * as ERR_error_string cannot know how large the buffer is */ char *ERR_error_string(unsigned long e, char *ret) { static char buf[256]; if (ret == NULL) ret=buf; ERR_error_string_n(e, ret, 256); return ret; } LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void) { err_fns_check(); return ERRFN(err_get)(0); } LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void) { err_fns_check(); return ERRFN(thread_get)(0); } void ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash) { err_fns_check(); ERRFN(thread_release)(hash); } const char *ERR_lib_error_string(unsigned long e) { ERR_STRING_DATA d,*p; unsigned long l; err_fns_check(); l=ERR_GET_LIB(e); d.error=ERR_PACK(l,0,0); p=ERRFN(err_get_item)(&d); return((p == NULL)?NULL:p->string); } const char *ERR_func_error_string(unsigned long e) { ERR_STRING_DATA d,*p; unsigned long l,f; err_fns_check(); l=ERR_GET_LIB(e); f=ERR_GET_FUNC(e); d.error=ERR_PACK(l,f,0); p=ERRFN(err_get_item)(&d); return((p == NULL)?NULL:p->string); } const char *ERR_reason_error_string(unsigned long e) { ERR_STRING_DATA d,*p=NULL; unsigned long l,r; err_fns_check(); l=ERR_GET_LIB(e); r=ERR_GET_REASON(e); d.error=ERR_PACK(l,0,r); p=ERRFN(err_get_item)(&d); if (!p) { d.error=ERR_PACK(0,0,r); p=ERRFN(err_get_item)(&d); } return((p == NULL)?NULL:p->string); } void ERR_remove_thread_state(const CRYPTO_THREADID *id) { ERR_STATE tmp; if (id) CRYPTO_THREADID_cpy(&tmp.tid, id); else CRYPTO_THREADID_current(&tmp.tid); err_fns_check(); /* thread_del_item automatically destroys the LHASH if the number of * items reaches zero. */ ERRFN(thread_del_item)(&tmp); } #ifndef OPENSSL_NO_DEPRECATED void ERR_remove_state(unsigned long pid) { ERR_remove_thread_state(NULL); } #endif ERR_STATE *ERR_get_state(void) { static ERR_STATE fallback; ERR_STATE *ret,tmp,*tmpp=NULL; int i; CRYPTO_THREADID tid; err_fns_check(); CRYPTO_THREADID_current(&tid); CRYPTO_THREADID_cpy(&tmp.tid, &tid); ret=ERRFN(thread_get_item)(&tmp); /* ret == the error state, if NULL, make a new one */ if (ret == NULL) { ret=(ERR_STATE *)OPENSSL_malloc(sizeof(ERR_STATE)); if (ret == NULL) return(&fallback); CRYPTO_THREADID_cpy(&ret->tid, &tid); ret->top=0; ret->bottom=0; for (i=0; i<ERR_NUM_ERRORS; i++) { ret->err_data[i]=NULL; ret->err_data_flags[i]=0; } tmpp = ERRFN(thread_set_item)(ret); /* To check if insertion failed, do a get. */ if (ERRFN(thread_get_item)(ret) != ret) { ERR_STATE_free(ret); /* could not insert it */ return(&fallback); } /* If a race occurred in this function and we came second, tmpp * is the first one that we just replaced. */ if (tmpp) ERR_STATE_free(tmpp); } return ret; } int ERR_get_next_error_library(void) { err_fns_check(); return ERRFN(get_next_lib)(); } void ERR_set_error_data(char *data, int flags) { ERR_STATE *es; int i; es=ERR_get_state(); i=es->top; if (i == 0) i=ERR_NUM_ERRORS-1; err_clear_data(es,i); es->err_data[i]=data; es->err_data_flags[i]=flags; } void ERR_add_error_data(int num, ...) { va_list args; va_start(args, num); ERR_add_error_vdata(num, args); va_end(args); } void ERR_add_error_vdata(int num, va_list args) { int i,n,s; char *str,*p,*a; s=80; str=OPENSSL_malloc(s+1); if (str == NULL) return; str[0]='\0'; n=0; for (i=0; i<num; i++) { a=va_arg(args, char*); /* ignore NULLs, thanks to Bob Beck <[email protected]> */ if (a != NULL) { n+=strlen(a); if (n > s) { s=n+20; p=OPENSSL_realloc(str,s+1); if (p == NULL) { OPENSSL_free(str); return; } else str=p; } BUF_strlcat(str,a,(size_t)s+1); } } ERR_set_error_data(str,ERR_TXT_MALLOCED|ERR_TXT_STRING); } int ERR_set_mark(void) { ERR_STATE *es; es=ERR_get_state(); if (es->bottom == es->top) return 0; es->err_flags[es->top]|=ERR_FLAG_MARK; return 1; } int ERR_pop_to_mark(void) { ERR_STATE *es; es=ERR_get_state(); while(es->bottom != es->top && (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) { err_clear(es,es->top); es->top-=1; if (es->top == -1) es->top=ERR_NUM_ERRORS-1; } if (es->bottom == es->top) return 0; es->err_flags[es->top]&=~ERR_FLAG_MARK; return 1; }
29840.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "os/os.h" #include <string.h> #include <assert.h> #include <stdbool.h> #define OS_MEM_TRUE_BLOCK_SIZE(bsize) OS_ALIGN(bsize, OS_ALIGNMENT) #define OS_MEMPOOL_TRUE_BLOCK_SIZE(mp) OS_MEM_TRUE_BLOCK_SIZE(mp->mp_block_size) STAILQ_HEAD(, os_mempool) g_os_mempool_list = STAILQ_HEAD_INITIALIZER(g_os_mempool_list); #if MYNEWT_VAL(OS_MEMPOOL_POISON) static uint32_t os_mem_poison = 0xde7ec7ed; static void os_mempool_poison(void *start, int sz) { int i; char *p = start; for (i = sizeof(struct os_memblock); i < sz; i = i + sizeof(os_mem_poison)) { memcpy(p + i, &os_mem_poison, min(sizeof(os_mem_poison), sz - i)); } } static void os_mempool_poison_check(void *start, int sz) { int i; char *p = start; for (i = sizeof(struct os_memblock); i < sz; i = i + sizeof(os_mem_poison)) { assert(!memcmp(p + i, &os_mem_poison, min(sizeof(os_mem_poison), sz - i))); } } #else #define os_mempool_poison(start, sz) #define os_mempool_poison_check(start, sz) #endif os_error_t os_mempool_init(struct os_mempool *mp, uint16_t blocks, uint32_t block_size, void *membuf, char *name) { int true_block_size; uint8_t *block_addr; struct os_memblock *block_ptr; /* Check for valid parameters */ if (!mp || (block_size == 0)) { return OS_INVALID_PARM; } if ((!membuf) && (blocks != 0)) { return OS_INVALID_PARM; } if (membuf != NULL) { /* Blocks need to be sized properly and memory buffer should be * aligned */ if (((uintptr_t)membuf & (OS_ALIGNMENT - 1)) != 0) { return OS_MEM_NOT_ALIGNED; } } true_block_size = OS_MEM_TRUE_BLOCK_SIZE(block_size); /* Initialize the memory pool structure */ mp->mp_block_size = block_size; mp->mp_num_free = blocks; mp->mp_min_free = blocks; mp->mp_flags = 0; mp->mp_num_blocks = blocks; mp->mp_membuf_addr = (uintptr_t)membuf; mp->name = name; os_mempool_poison(membuf, true_block_size); SLIST_FIRST(mp) = membuf; /* Chain the memory blocks to the free list */ block_addr = (uint8_t *)membuf; block_ptr = (struct os_memblock *)block_addr; while (blocks > 1) { block_addr += true_block_size; os_mempool_poison(block_addr, true_block_size); SLIST_NEXT(block_ptr, mb_next) = (struct os_memblock *)block_addr; block_ptr = (struct os_memblock *)block_addr; --blocks; } /* Last one in the list should be NULL */ SLIST_NEXT(block_ptr, mb_next) = NULL; STAILQ_INSERT_TAIL(&g_os_mempool_list, mp, mp_list); return OS_OK; } os_error_t os_mempool_ext_init(struct os_mempool_ext *mpe, uint16_t blocks, uint32_t block_size, void *membuf, char *name) { int rc; rc = os_mempool_init(&mpe->mpe_mp, blocks, block_size, membuf, name); if (rc != 0) { return rc; } mpe->mpe_mp.mp_flags = OS_MEMPOOL_F_EXT; mpe->mpe_put_cb = NULL; mpe->mpe_put_arg = NULL; return 0; } os_error_t os_mempool_clear(struct os_mempool *mp) { struct os_memblock *block_ptr; int true_block_size; uint8_t *block_addr; uint16_t blocks; if (!mp) { return OS_INVALID_PARM; } true_block_size = OS_MEM_TRUE_BLOCK_SIZE(mp->mp_block_size); /* cleanup the memory pool structure */ mp->mp_num_free = mp->mp_num_blocks; mp->mp_min_free = mp->mp_num_blocks; os_mempool_poison((void *)mp->mp_membuf_addr, true_block_size); SLIST_FIRST(mp) = (void *)mp->mp_membuf_addr; /* Chain the memory blocks to the free list */ block_addr = (uint8_t *)mp->mp_membuf_addr; block_ptr = (struct os_memblock *)block_addr; blocks = mp->mp_num_blocks; while (blocks > 1) { block_addr += true_block_size; os_mempool_poison(block_addr, true_block_size); SLIST_NEXT(block_ptr, mb_next) = (struct os_memblock *)block_addr; block_ptr = (struct os_memblock *)block_addr; --blocks; } /* Last one in the list should be NULL */ SLIST_NEXT(block_ptr, mb_next) = NULL; return OS_OK; } os_error_t os_mempool_ext_clear(struct os_mempool_ext *mpe) { mpe->mpe_mp.mp_flags = 0; mpe->mpe_put_cb = NULL; mpe->mpe_put_arg = NULL; return os_mempool_clear(&mpe->mpe_mp); } bool os_mempool_is_sane(const struct os_mempool *mp) { struct os_memblock *block; /* Verify that each block in the free list belongs to the mempool. */ SLIST_FOREACH(block, mp, mb_next) { if (!os_memblock_from(mp, block)) { return false; } os_mempool_poison_check(block, OS_MEMPOOL_TRUE_BLOCK_SIZE(mp)); } return true; } int os_memblock_from(const struct os_mempool *mp, const void *block_addr) { uintptr_t true_block_size; uintptr_t baddr_ptr; uintptr_t end; _Static_assert(sizeof block_addr == sizeof baddr_ptr, "Pointer to void must be native word size."); baddr_ptr = (uintptr_t)block_addr; true_block_size = OS_MEMPOOL_TRUE_BLOCK_SIZE(mp); end = mp->mp_membuf_addr + (mp->mp_num_blocks * true_block_size); /* Check that the block is in the memory buffer range. */ if ((baddr_ptr < mp->mp_membuf_addr) || (baddr_ptr >= end)) { return 0; } /* All freed blocks should be on true block size boundaries! */ if (((baddr_ptr - mp->mp_membuf_addr) % true_block_size) != 0) { return 0; } return 1; } void * os_memblock_get(struct os_mempool *mp) { os_sr_t sr; struct os_memblock *block; /* Check to make sure they passed in a memory pool (or something) */ block = NULL; if (mp) { OS_ENTER_CRITICAL(sr); /* Check for any free */ if (mp->mp_num_free) { /* Get a free block */ block = SLIST_FIRST(mp); /* Set new free list head */ SLIST_FIRST(mp) = SLIST_NEXT(block, mb_next); /* Decrement number free by 1 */ mp->mp_num_free--; if (mp->mp_min_free > mp->mp_num_free) { mp->mp_min_free = mp->mp_num_free; } } OS_EXIT_CRITICAL(sr); if (block) { os_mempool_poison_check(block, OS_MEMPOOL_TRUE_BLOCK_SIZE(mp)); } } return (void *)block; } os_error_t os_memblock_put_from_cb(struct os_mempool *mp, void *block_addr) { os_sr_t sr; struct os_memblock *block; os_mempool_poison(block_addr, OS_MEMPOOL_TRUE_BLOCK_SIZE(mp)); block = (struct os_memblock *)block_addr; OS_ENTER_CRITICAL(sr); /* Chain current free list pointer to this block; make this block head */ SLIST_NEXT(block, mb_next) = SLIST_FIRST(mp); SLIST_FIRST(mp) = block; /* XXX: Should we check that the number free <= number blocks? */ /* Increment number free */ mp->mp_num_free++; OS_EXIT_CRITICAL(sr); return OS_OK; } os_error_t os_memblock_put(struct os_mempool *mp, void *block_addr) { struct os_mempool_ext *mpe; int rc; #if MYNEWT_VAL(OS_MEMPOOL_CHECK) struct os_memblock *block; #endif /* Make sure parameters are valid */ if ((mp == NULL) || (block_addr == NULL)) { return OS_INVALID_PARM; } #if MYNEWT_VAL(OS_MEMPOOL_CHECK) /* Check that the block we are freeing is a valid block! */ assert(os_memblock_from(mp, block_addr)); /* * Check for duplicate free. */ SLIST_FOREACH(block, mp, mb_next) { assert(block != (struct os_memblock *)block_addr); } #endif /* If this is an extended mempool with a put callback, call the callback * instead of freeing the block directly. */ if (mp->mp_flags & OS_MEMPOOL_F_EXT) { mpe = (struct os_mempool_ext *)mp; if (mpe->mpe_put_cb != NULL) { rc = mpe->mpe_put_cb(mpe, block_addr, mpe->mpe_put_arg); return rc; } } /* No callback; free the block. */ return os_memblock_put_from_cb(mp, block_addr); } struct os_mempool * os_mempool_info_get_next(struct os_mempool *mp, struct os_mempool_info *omi) { struct os_mempool *cur; if (mp == NULL) { cur = STAILQ_FIRST(&g_os_mempool_list); } else { cur = STAILQ_NEXT(mp, mp_list); } if (cur == NULL) { return (NULL); } omi->omi_block_size = cur->mp_block_size; omi->omi_num_blocks = cur->mp_num_blocks; omi->omi_num_free = cur->mp_num_free; omi->omi_min_free = cur->mp_min_free; strncpy(omi->omi_name, cur->name, sizeof(omi->omi_name)); return (cur); }
796566.c
/** * @file * @brief * * @date 19.06.2012 * @author Alexander Kalmuk * @author Roman Kurbatov * - clock_source_get_list() function. */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <util/dlist.h> #include <util/math.h> #include <kernel/time/clock_source.h> #include <kernel/time/time.h> static DLIST_DEFINE(clock_source_list); extern int clock_tick_init(void); int clock_source_register(struct clock_source *cs) { if (!cs) { return -EINVAL; } dlist_add_prev(dlist_head_init(&cs->lnk), &clock_source_list); clock_tick_init(); jiffies_init(); return ENOERR; } int clock_source_unregister(struct clock_source *cs) { if (!cs) { return -EINVAL; } dlist_del(&cs->lnk); return ENOERR; } struct timespec clock_source_read(struct clock_source *cs) { struct timespec ts; struct time_event_device *ed; struct time_counter_device *cd; uint64_t ns = 0; ed = cs->event_device; if (ed) { ns += ((uint64_t) cs->jiffies * NSEC_PER_SEC) / ed->event_hz; } cd = cs->counter_device; if (cd) { ns += ((uint64_t) cd->read() * NSEC_PER_SEC) / cd->cycle_hz; } ts = ns_to_timespec(ns); return ts; } struct clock_source *clock_source_get_best(enum clock_source_property pr) { struct clock_source *cs, *best; uint32_t event_hz, cycle_hz, best_hz, hz; best_hz = 0; best = NULL; dlist_foreach_entry(cs, &clock_source_list, lnk) { event_hz = cs->event_device ? cs->event_device->event_hz : 0; cycle_hz = cs->counter_device ? cs->counter_device->cycle_hz : 0; switch (pr) { case CS_ANY: hz = max(event_hz, cycle_hz); break; case CS_WITH_IRQ: hz = event_hz; break; case CS_WITHOUT_IRQ: hz = cycle_hz; break; } if (hz > best_hz) { best_hz = hz; best = cs; } } return best; } struct clock_source *clock_source_get_by_name(const char *name) { struct clock_source *cs; dlist_foreach_entry(cs, &clock_source_list, lnk) { if (!strcmp(cs->name, name)) { return cs; } } return NULL; } time64_t clock_source_get_hwcycles(struct clock_source *cs) { int load; /* TODO: support for counter-less and event-less clock sources */ assert(cs->event_device && cs->counter_device); load = cs->counter_device->cycle_hz / cs->event_device->event_hz; return ((uint64_t) cs->jiffies) * load + cs->counter_device->read(); }
658713.c
/***************************************************************************** * Copyright(C)2009-2019 by VSF Team * * * * 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. * * * ****************************************************************************/ /*============================ INCLUDES ======================================*/ #include "component/usb/vsf_usb_cfg.h" #if VSF_USE_USB_DEVICE == ENABLED #define __VSF_EDA_CLASS_INHERIT__ #if VSF_USBD_CFG_STREAM_EN == ENABLED # if VSF_USE_SIMPLE_STREAM == ENABLED # define __VSF_SIMPLE_STREAM_CLASS_INHERIT__ # elif VSF_USE_STREAM == ENABLED # define __VSF_STREAM_BASE_CLASS_INHERIT__ # endif #endif #define __VSF_USBD_CLASS_IMPLEMENT #include "kernel/vsf_kernel.h" #include "./vsf_usbd.h" #include "./vsf_usbd_drv_ifs.h" /*============================ MACROS ========================================*/ /*============================ MACROFIED FUNCTIONS ===========================*/ /*============================ TYPES =========================================*/ /*============================ GLOBAL VARIABLES ==============================*/ /*============================ LOCAL VARIABLES ===============================*/ /*============================ PROTOTYPES ====================================*/ static void __vk_usbd_hal_evthandler(void *, usb_evt_t, uint_fast8_t); extern vsf_err_t vsf_usbd_vendor_prepare(vk_usbd_dev_t *dev); extern void vsf_usbd_vendor_process(vk_usbd_dev_t *dev); extern vsf_err_t vsf_usbd_notify_user(vk_usbd_dev_t *dev, usb_evt_t evt, void *param); /*============================ IMPLEMENTATION ================================*/ vk_usbd_desc_t * vk_usbd_get_descriptor(vk_usbd_desc_t *desc, uint_fast8_t desc_num, uint_fast8_t type, uint_fast8_t index, uint_fast16_t langid) { VSF_USB_ASSERT(desc != NULL); for (uint_fast8_t i = 0; i < desc_num; i++) { if ( (desc->type == type) && (desc->index == index) && (desc->langid == langid)) { return desc; } desc++; } return NULL; } #if VSF_USBD_CFG_RAW_MODE != ENABLED static vk_usbd_ifs_t * __vk_usbd_get_ifs_byep(vk_usbd_cfg_t *config, uint_fast8_t ep) { int_fast8_t ifs; ep = (ep & 0x0F) | ((ep & 0x80) >> 3); ifs = config->ep_ifs_map[ep]; return ifs >= 0 ? &config->ifs[ifs] : NULL; } static void __vk_usbd_cfg_fini(vk_usbd_dev_t *dev) { vk_usbd_cfg_t *config = vk_usbd_get_cur_cfg(dev); vk_usbd_ifs_t *ifs = config->ifs; for (uint_fast8_t i = 0; i < config->num_of_ifs; i++, ifs++) { if (ifs->is_inited) { ifs->is_inited = false; if (ifs->class_op->fini != NULL) { ifs->class_op->fini(dev, ifs); } } } } #endif static vk_usbd_trans_t * __vk_usbd_get_trans(vk_usbd_dev_t *dev, uint_fast8_t ep) { vk_usbd_trans_t *trans; vsf_slist_peek_next(vk_usbd_trans_t, node, &dev->trans_list, trans); while (trans != NULL) { if (trans->ep == ep) { break; } vsf_slist_peek_next(vk_usbd_trans_t, node, &trans->node, trans); } return trans; } static void __vk_usbd_trans_finish(vk_usbd_dev_t *dev, vk_usbd_trans_t *trans) { vsf_slist_remove(vk_usbd_trans_t, node, &dev->trans_list, trans); #if VSF_USE_KERNEL == ENABLED if (trans->notify_eda) { vsf_eda_post_msg(trans->eda, trans); } else #endif if (trans->on_finish != NULL) { trans->on_finish(trans->param); } } vsf_err_t vk_usbd_ep_stall(vk_usbd_dev_t *dev, uint_fast8_t ep) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); return vk_usbd_drv_ep_set_stall(ep); } vsf_err_t vk_usbd_ep_recv(vk_usbd_dev_t *dev, vk_usbd_trans_t *trans) { VSF_USB_ASSERT((dev != NULL) && (trans != NULL)); VSF_USBD_DRV_PREPARE(dev); vsf_err_t err; trans->ep &= ~USB_DIR_MASK; vsf_slist_init_node(vk_usbd_trans_t, node, trans); vsf_slist_add_to_head(vk_usbd_trans_t, node, &dev->trans_list, trans); if (vk_usbd_drv_ep_get_feature(trans->ep, trans->feature) & USB_DC_FEATURE_TRANSFER) { err = vk_usbd_drv_ep_transfer_recv(trans->ep, trans->use_as__vsf_mem_t.buffer, trans->use_as__vsf_mem_t.size); } else { trans->cur = trans->use_as__vsf_mem_t.buffer; err = vk_usbd_drv_ep_transaction_enable_out(trans->ep); } if (VSF_ERR_NONE != err) { vsf_slist_remove(vk_usbd_trans_t, node, &dev->trans_list, trans); } return err; } static vsf_err_t __vk_usbd_ep_send_imp(vk_usbd_dev_t *dev, vk_usbd_trans_t *trans) { uint_fast8_t ep = trans->ep; VSF_USBD_DRV_PREPARE(dev); uint_fast16_t ep_size = vk_usbd_drv_ep_get_size(ep); uint_fast16_t pkg_size = min(ep_size, trans->use_as__vsf_mem_t.size); vk_usbd_drv_ep_transaction_write_buffer(ep, trans->cur, pkg_size); trans->cur += pkg_size; trans->use_as__vsf_mem_t.size -= pkg_size; if (!trans->use_as__vsf_mem_t.size && (pkg_size < ep_size)) { trans->zlp = false; } return vk_usbd_drv_ep_transaction_set_data_size(ep, pkg_size); } vsf_err_t vk_usbd_ep_send(vk_usbd_dev_t *dev, vk_usbd_trans_t *trans) { VSF_USB_ASSERT((dev != NULL) && (trans != NULL)); VSF_USBD_DRV_PREPARE(dev); vsf_err_t err; trans->ep |= USB_DIR_MASK; vsf_slist_init_node(vk_usbd_trans_t, node, trans); vsf_slist_add_to_head(vk_usbd_trans_t, node, &dev->trans_list, trans); if (vk_usbd_drv_ep_get_feature(trans->ep, trans->feature) & USB_DC_FEATURE_TRANSFER) { uint_fast32_t size = trans->use_as__vsf_mem_t.size; bool zlp = trans->zlp; trans->use_as__vsf_mem_t.size = 0; trans->zlp = false; err = vk_usbd_drv_ep_transfer_send(trans->ep, trans->use_as__vsf_mem_t.buffer, size, zlp); } else { trans->cur = trans->use_as__vsf_mem_t.buffer; err = __vk_usbd_ep_send_imp(dev, trans); } if (VSF_ERR_NONE != err) { vsf_slist_remove(vk_usbd_trans_t, node, &dev->trans_list, trans); } return err; } #if VSF_USBD_CFG_RAW_MODE != ENABLED // standard request handlers static int16_t __vk_usbd_get_config(vk_usbd_dev_t *dev, uint_fast8_t value) { for (uint_fast8_t i = 0; i < dev->num_of_config; i++) { if (value == dev->config[i].configuration_value) { return i; } } return -1; } #if VSF_USBD_CFG_AUTOSETUP == ENABLED static vsf_err_t __vk_usbd_auto_init(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); vk_usbd_cfg_t *config; vk_usbd_desc_t *desc; struct usb_config_desc_t *desc_config; uint_fast16_t pos, cur_ifs; uint_fast8_t attr, feature; config = &dev->config[dev->configuration]; // config other eps according to descriptors desc = vk_usbd_get_descriptor(dev->desc, dev->num_of_desc, USB_DT_CONFIG, dev->configuration, 0); VSF_USB_ASSERT(desc != NULL); desc_config = (struct usb_config_desc_t *)desc->buffer; VSF_USB_ASSERT( (desc->size == desc_config->wTotalLength) && (desc_config->bLength == USB_DT_CONFIG_SIZE) && (desc_config->bDescriptorType == USB_DT_CONFIG) && (desc_config->bNumInterfaces == config->num_of_ifs)); // initialize device feature according to // bmAttributes field in configuration descriptor attr = desc_config->bmAttributes; feature = 0; if (attr & USB_CONFIG_ATT_SELFPOWER) { feature |= 1 << USB_DEVICE_SELF_POWERED; } if (attr & USB_CONFIG_ATT_WAKEUP) { feature |= 1 << USB_DEVICE_REMOTE_WAKEUP; } cur_ifs = -1; pos = USB_DT_CONFIG_SIZE; while (desc->size > pos) { struct usb_endpoint_desc_t *desc_header = (struct usb_endpoint_desc_t *)((uint8_t *)desc_config + pos); VSF_USB_ASSERT((desc_header->bLength > 2) && (desc->size >= (pos + desc_header->bLength))); switch (desc_header->bDescriptorType) { case USB_DT_INTERFACE: { struct usb_interface_desc_t *desc_ifs = (struct usb_interface_desc_t *)desc_header; cur_ifs = desc_ifs->bInterfaceNumber; break; } case USB_DT_ENDPOINT: { struct usb_endpoint_desc_t *desc_ep = (struct usb_endpoint_desc_t *)desc_header; uint_fast8_t ep_addr = desc_ep->bEndpointAddress; uint_fast8_t ep_attr = desc_ep->bmAttributes; uint_fast16_t ep_size = desc_ep->wMaxPacketSize; VSF_USB_ASSERT((ep_attr & 0x03) <= 3); if (VSF_ERR_NONE != vk_usbd_drv_ep_add(ep_addr, ep_attr & 0x03, ep_size)) { return VSF_ERR_FAIL; } ep_addr = (ep_addr & 0x0F) | ((ep_addr & 0x80) >> 3); config->ep_ifs_map[ep_addr] = cur_ifs; break; } } pos += desc_header->bLength; } return VSF_ERR_NONE; } #endif // VSF_USBD_CFG_AUTOSETUP static vsf_err_t __vk_usbd_stdctrl_prepare(vk_usbd_dev_t *dev) { VSF_USBD_DRV_PREPARE(dev); vk_usbd_cfg_t *config = &dev->config[dev->configuration]; vk_usbd_ctrl_handler_t *ctrl_handler = &dev->ctrl_handler; struct usb_ctrlrequest_t *request = &ctrl_handler->request; uint8_t *buffer = ctrl_handler->reply_buffer; uint_fast8_t recip = request->bRequestType & USB_RECIP_MASK; uint_fast16_t size = 0; if (USB_RECIP_DEVICE == recip) { switch (request->bRequest) { case USB_REQ_GET_STATUS: if ((request->wValue != 0) || (request->wIndex != 0)) { return VSF_ERR_FAIL; } buffer[0] = dev->feature; buffer[1] = 0; size = 2; break; case USB_REQ_CLEAR_FEATURE: if ( (request->wIndex != 0) || (request->wValue != USB_DEVICE_REMOTE_WAKEUP)) { return VSF_ERR_FAIL; } dev->feature &= ~USB_CONFIG_ATT_WAKEUP; break; case USB_REQ_SET_FEATURE: if ( (request->wIndex != 0) || (request->wValue != USB_DEVICE_REMOTE_WAKEUP)) { return VSF_ERR_FAIL; } dev->feature |= USB_CONFIG_ATT_WAKEUP; break; case USB_REQ_SET_ADDRESS: if ( (request->wValue > 127) || (request->wIndex != 0) || (dev->configuration != 0)) { return VSF_ERR_FAIL; } break; case USB_REQ_GET_DESCRIPTOR: { uint_fast8_t type = (request->wValue >> 8) & 0xFF; uint_fast8_t index = request->wValue & 0xFF; uint_fast16_t langid = request->wIndex; vk_usbd_desc_t *desc = vk_usbd_get_descriptor(dev->desc, dev->num_of_desc, type, index, langid); if (NULL == desc) { return VSF_ERR_FAIL; } buffer = desc->buffer; size = desc->size; } break; case USB_REQ_GET_CONFIGURATION: if ((request->wValue != 0) || (request->wIndex != 0)) { return VSF_ERR_FAIL; } buffer[0] = config->configuration_value; size = 1; break; case USB_REQ_SET_CONFIGURATION: if ((request->wIndex != 0) || (__vk_usbd_get_config(dev, request->wValue) < 0)) { return VSF_ERR_FAIL; } dev->configured = false; break; default: return VSF_ERR_FAIL; } } else if (USB_RECIP_INTERFACE == recip) { uint_fast8_t ifs_idx = request->wIndex; vk_usbd_ifs_t *ifs = &config->ifs[ifs_idx]; const vk_usbd_class_op_t *class_op = ifs->class_op; if (ifs_idx >= config->num_of_ifs) { return VSF_ERR_FAIL; } switch (request->bRequest) { case USB_REQ_GET_STATUS: if ((request->wValue != 0) || (request->wIndex >= config->num_of_ifs)) { return VSF_ERR_FAIL; } buffer[0] = 0; buffer[1] = 0; size = 2; break; case USB_REQ_CLEAR_FEATURE: break; case USB_REQ_SET_FEATURE: break; case USB_REQ_GET_DESCRIPTOR: { uint_fast8_t type = (request->wValue >> 8) & 0xFF; uint_fast8_t index = request->wValue & 0xFF; vk_usbd_desc_t *desc = NULL; if ((class_op != NULL) && (class_op->get_desc != NULL)) { desc = class_op->get_desc(dev, type, index, 0); } if (NULL == desc) { return VSF_ERR_FAIL; } buffer = desc->buffer; size = desc->size; } break; case USB_REQ_GET_INTERFACE: if (request->wValue != 0) { return VSF_ERR_FAIL; } buffer[0] = ifs->alternate_setting; size = 1; break; case USB_REQ_SET_INTERFACE: ifs->alternate_setting = request->wValue; if (class_op->request_prepare != NULL) { class_op->request_prepare(dev, ifs); } break; default: return VSF_ERR_FAIL; } } else if (USB_RECIP_ENDPOINT == recip) { uint_fast8_t ep = request->wIndex & 0xFF; if ((request->bRequestType & USB_DIR_MASK) == USB_DIR_IN) { return VSF_ERR_FAIL; } switch (request->bRequest) { case USB_REQ_GET_STATUS: if (request->wValue != 0) { return VSF_ERR_FAIL; } if (vk_usbd_drv_ep_is_stalled(ep)) { buffer[0] = 1; } else { buffer[0] = 0; } buffer[1] = 0; size = 2; break; case USB_REQ_CLEAR_FEATURE: { if (request->wValue != USB_ENDPOINT_HALT) { return VSF_ERR_FAIL; } if (0 == ep) { break; } else { vk_usbd_ifs_t *ifs = __vk_usbd_get_ifs_byep(config, ep); VSF_USB_ASSERT(ifs != NULL); const vk_usbd_class_op_t *class_op = ifs->class_op; vk_usbd_drv_ep_clear_stall(ep); if (class_op->request_prepare != NULL) { class_op->request_prepare(dev, ifs); } } } break; case USB_REQ_SET_FEATURE: default: return VSF_ERR_FAIL; } } else { return VSF_ERR_FAIL; } if (!size) { buffer = NULL; } ctrl_handler->trans.use_as__vsf_mem_t.buffer = buffer; ctrl_handler->trans.use_as__vsf_mem_t.size = size; return VSF_ERR_NONE; } static vsf_err_t __vk_usbd_stdctrl_process(vk_usbd_dev_t *dev) { struct usb_ctrlrequest_t *request = &dev->ctrl_handler.request; uint8_t recip = request->bRequestType & USB_RECIP_MASK; vk_usbd_cfg_t *config; vk_usbd_ifs_t *ifs; VSF_USBD_DRV_PREPARE(dev); if (USB_RECIP_DEVICE == recip) { switch (request->bRequest) { case USB_REQ_SET_ADDRESS: dev->address = (uint8_t)request->wValue; vk_usbd_drv_set_address(dev->address); break; case USB_REQ_SET_CONFIGURATION: { int_fast16_t config_idx; config_idx = __vk_usbd_get_config(dev, request->wValue); if (config_idx < 0) { return VSF_ERR_FAIL; } __vk_usbd_cfg_fini(dev); dev->configuration = (uint8_t)config_idx; config = &dev->config[dev->configuration]; #if VSF_USBD_CFG_AUTOSETUP == ENABLED if (VSF_ERR_NONE != __vk_usbd_auto_init(dev)) { return VSF_ERR_FAIL; } #endif // call user initialization if ((config->init != NULL) && (VSF_ERR_NONE != config->init(dev))) { return VSF_ERR_FAIL; } ifs = config->ifs; for (uint_fast8_t i = 0; i < config->num_of_ifs; i++, ifs++) { ifs->alternate_setting = 0; if ( (ifs->class_op != NULL) && (ifs->class_op->init != NULL) && (VSF_ERR_NONE != ifs->class_op->init(dev, ifs))) { return VSF_ERR_FAIL; } ifs->is_inited = true; } dev->configured = true; } break; } } else if (USB_RECIP_INTERFACE == recip) { uint_fast8_t ifs_idx = request->wIndex; config = &dev->config[dev->configuration]; ifs = &config->ifs[ifs_idx]; const vk_usbd_class_op_t *class_op = ifs->class_op; if (ifs_idx >= config->num_of_ifs) { return VSF_ERR_FAIL; } switch (request->bRequest) { case USB_REQ_SET_INTERFACE: if (class_op->request_process != NULL) { class_op->request_process(dev, ifs); } break; } } return VSF_ERR_NONE; } #ifndef WEAK_VSF_USBD_VENDOR_PREPARE WEAK(vsf_usbd_vendor_prepare) vsf_err_t vsf_usbd_vendor_prepare(vk_usbd_dev_t *dev) { return VSF_ERR_FAIL; } #endif #ifndef WEAK_VSF_USBD_VENDOR_PROCESS WEAK(vsf_usbd_vendor_process) void vsf_usbd_vendor_process(vk_usbd_dev_t *dev) { } #endif #if __IS_COMPILER_IAR__ //! statement is unreachable # pragma diag_suppress=pe111 #endif static vsf_err_t __vk_usbd_ctrl_prepare(vk_usbd_dev_t *dev) { vk_usbd_cfg_t *config = &dev->config[dev->configuration]; vk_usbd_ctrl_handler_t *ctrl_handler = &dev->ctrl_handler; struct usb_ctrlrequest_t *request = &ctrl_handler->request; uint_fast8_t type = request->bRequestType & USB_TYPE_MASK; vsf_err_t err = VSF_ERR_FAIL; if (USB_TYPE_STANDARD == type) { err = __vk_usbd_stdctrl_prepare(dev); } else if (USB_TYPE_CLASS == type) { uint_fast8_t tmp = request->wIndex & 0xFF; vk_usbd_ifs_t *ifs = NULL; switch (request->bRequestType & USB_RECIP_MASK) { case USB_RECIP_INTERFACE: if (tmp < config->num_of_ifs) { ifs = &config->ifs[tmp]; } break; case USB_RECIP_ENDPOINT: ifs = __vk_usbd_get_ifs_byep(config, tmp); break; default: VSF_USB_ASSERT(false); return VSF_ERR_FAIL; } if (ifs && ifs->class_op->request_prepare != NULL) { err = ifs->class_op->request_prepare(dev, ifs); } } else if (USB_TYPE_VENDOR == type) { err = vsf_usbd_vendor_prepare(dev); } return err; } static void __vk_usbd_ctrl_process(vk_usbd_dev_t *dev) { vk_usbd_cfg_t *config = &dev->config[dev->configuration]; vk_usbd_ctrl_handler_t *ctrl_handler = &dev->ctrl_handler; struct usb_ctrlrequest_t *request = &ctrl_handler->request; uint_fast8_t type = request->bRequestType & USB_TYPE_MASK; if (USB_TYPE_STANDARD == type) { __vk_usbd_stdctrl_process(dev); } else if (USB_TYPE_CLASS == type) { uint_fast8_t tmp = request->wIndex & 0xFF; vk_usbd_ifs_t *ifs = NULL; switch (request->bRequestType & USB_RECIP_MASK) { case USB_RECIP_INTERFACE: if (tmp < config->num_of_ifs) { ifs = &config->ifs[tmp]; } break; case USB_RECIP_ENDPOINT: ifs = __vk_usbd_get_ifs_byep(config, tmp); break; default: VSF_USB_ASSERT(false); return; } if (ifs && ifs->class_op->request_process != NULL) { ifs->class_op->request_process(dev, ifs); } } else if (USB_TYPE_VENDOR == type) { vsf_usbd_vendor_process(dev); } } #if __IS_COMPILER_IAR__ //! statement is unreachable # pragma diag_warning=pe111 #endif #endif // !VSF_USBD_CFG_RAW_MODE static void __vk_usbd_setup_status_callback(void *param) { vk_usbd_dev_t *dev = (vk_usbd_dev_t *)param; VSF_USBD_DRV_PREPARE(dev); vk_usbd_ctrl_handler_t *ctrl_handler = &dev->ctrl_handler; struct usb_ctrlrequest_t *request = &ctrl_handler->request; bool out = (request->bRequestType & USB_DIR_MASK) == USB_DIR_OUT; vk_usbd_drv_status_stage(out); } #ifndef WEAK_VSF_USBD_NOTIFY_USER WEAK(vsf_usbd_notify_user) vsf_err_t vsf_usbd_notify_user(vk_usbd_dev_t *dev, usb_evt_t evt, void *param) { return VSF_ERR_NONE; } #endif static void __vk_usbd_hw_init_reset(vk_usbd_dev_t *dev, bool reset) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); usb_dc_cfg_t cfg = { .speed = dev->speed, .priority = VSF_USBD_CFG_HW_PRIORITY, .evt_handler = __vk_usbd_hal_evthandler, .param = dev, }; if (reset) { vk_usbd_drv_reset(&cfg); } else { vk_usbd_drv_init(&cfg); } } // state machines static void __vk_usbd_hal_evthandler(void *p, usb_evt_t evt, uint_fast8_t value) #if VSF_USBD_CFG_USE_EDA == ENABLED { vk_usbd_dev_t *dev = p; vsf_eda_post_evt(&dev->eda, (vsf_evt_t)(VSF_EVT_USER + (evt | (value << 8)))); } static void __vk_usbd_evthandler(vsf_eda_t *eda, vsf_evt_t evt_eda) { vk_usbd_dev_t *dev; uint_fast8_t value; usb_evt_t evt; if (evt_eda < VSF_EVT_USER) { return; } evt_eda -= VSF_EVT_USER; dev = container_of(eda, vk_usbd_dev_t, eda); value = evt_eda >> 8; evt = (usb_evt_t)(evt_eda & 0xFF); #else { vk_usbd_dev_t *dev = p; #endif VSF_USBD_DRV_PREPARE(dev); switch (evt) { case USB_ON_ATTACH: case USB_ON_DETACH: case USB_ON_SUSPEND: case USB_ON_RESUME: case USB_ON_UNDERFLOW: case USB_ON_OVERFLOW: case USB_ON_ERROR: case USB_ON_SOF: case USB_ON_NAK: vsf_usbd_notify_user(dev, evt, (void *)(uintptr_t)value); break; case USB_ON_RESET: { #if VSF_USBD_CFG_RAW_MODE != ENABLED vk_usbd_cfg_t *config; __vk_usbd_cfg_fini(dev); config = dev->config; for (uint_fast8_t i = 0; i < dev->num_of_config; i++, config++) { memset(config->ep_ifs_map, -1, sizeof(config->ep_ifs_map)); } dev->configured = false; dev->configuration = 0; dev->feature = 0; #endif // reset usb hw __vk_usbd_hw_init_reset(dev, true); #if VSF_USBD_CFG_AUTOSETUP == ENABLED uint_fast16_t ep_size; struct usb_device_desc_t *desc_dev; vk_usbd_desc_t *desc = vk_usbd_get_descriptor(dev->desc, dev->num_of_desc, USB_DT_DEVICE, 0, 0); VSF_USB_ASSERT(desc != NULL); desc_dev = (struct usb_device_desc_t *)desc->buffer; VSF_USB_ASSERT( (desc->size == USB_DT_DEVICE_SIZE) && (desc_dev->bLength == USB_DT_DEVICE_SIZE) && (desc_dev->bDescriptorType == USB_DT_DEVICE) && (desc_dev->bNumConfigurations == dev->num_of_config)); // config ep0 ep_size = desc_dev->bMaxPacketSize0; if ( vk_usbd_drv_ep_add(0 | USB_DIR_OUT, USB_EP_TYPE_CONTROL, ep_size) || vk_usbd_drv_ep_add(0 | USB_DIR_IN, USB_EP_TYPE_CONTROL, ep_size)) { // TODO: return; } #endif vsf_usbd_notify_user(dev, evt, NULL); vk_usbd_drv_set_address(0); break; } case USB_ON_SETUP: { vk_usbd_ctrl_handler_t *ctrl_handler = &dev->ctrl_handler; struct usb_ctrlrequest_t *request = &ctrl_handler->request; vk_usbd_trans_t *trans = &ctrl_handler->trans; vk_usbd_drv_get_setup(request); if ( VSF_ERR_NONE != vsf_usbd_notify_user(dev, evt, request) #if VSF_USBD_CFG_RAW_MODE != ENABLED || (VSF_ERR_NONE != __vk_usbd_ctrl_prepare(dev)) #endif ) { vk_usbd_drv_ep_set_stall(0 | USB_DIR_OUT); vk_usbd_drv_ep_set_stall(0 | USB_DIR_IN); break; } if (ctrl_handler->trans.use_as__vsf_mem_t.size > request->wLength) { ctrl_handler->trans.use_as__vsf_mem_t.size = request->wLength; } if ((request->bRequestType & USB_DIR_MASK) == USB_DIR_OUT) { if (0 == request->wLength) { __vk_usbd_setup_status_callback((void *)dev); } else { trans->on_finish = __vk_usbd_setup_status_callback; vk_usbd_ep_recv(dev, trans); } } else { trans->on_finish = __vk_usbd_setup_status_callback; trans->zlp = ctrl_handler->trans.use_as__vsf_mem_t.size < request->wLength; vk_usbd_ep_send(dev, trans); } break; } case USB_ON_STATUS: vsf_usbd_notify_user(dev, evt, &dev->ctrl_handler.request); #if VSF_USBD_CFG_RAW_MODE != ENABLED __vk_usbd_ctrl_process(dev); #endif break; case USB_ON_IN: { uint_fast8_t ep = value | USB_DIR_IN; vk_usbd_trans_t *trans = __vk_usbd_get_trans(dev, ep); VSF_USB_ASSERT(trans != NULL); if (trans->use_as__vsf_mem_t.size) { __vk_usbd_ep_send_imp(dev, trans); } else if (trans->zlp) { trans->zlp = false; vk_usbd_drv_ep_transaction_set_data_size(ep, 0); } else { __vk_usbd_trans_finish(dev, trans); } break; } case USB_ON_OUT: { uint_fast8_t ep = value | USB_DIR_OUT; vk_usbd_trans_t *trans = __vk_usbd_get_trans(dev, ep); VSF_USB_ASSERT(trans != NULL); if (!trans->use_as__vsf_mem_t.buffer) { __vk_usbd_trans_finish(dev, trans); } else { uint_fast32_t pkg_size = vk_usbd_drv_ep_get_data_size(ep); if (vk_usbd_drv_ep_get_feature(trans->ep, trans->feature) & USB_DC_FEATURE_TRANSFER) { VSF_USB_ASSERT(trans->use_as__vsf_mem_t.size >= pkg_size); trans->use_as__vsf_mem_t.size -= pkg_size; __vk_usbd_trans_finish(dev, trans); } else { uint_fast16_t ep_size = vk_usbd_drv_ep_get_size(ep); // ignore the over-run data pkg_size = min(pkg_size, trans->use_as__vsf_mem_t.size); vk_usbd_drv_ep_transaction_read_buffer(ep, trans->cur, pkg_size); trans->cur += pkg_size; trans->use_as__vsf_mem_t.size -= pkg_size; // TODO: check trans->zlp if ((trans->use_as__vsf_mem_t.size > 0) && (pkg_size == ep_size)) { vk_usbd_drv_ep_transaction_enable_out(ep); } else { __vk_usbd_trans_finish(dev, trans); } } } break; } default: break; } } void vk_usbd_connect(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); vk_usbd_drv_connect(); } void vk_usbd_disconnect(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); vk_usbd_drv_disconnect(); } void vk_usbd_wakeup(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); vk_usbd_drv_wakeup(); } #if VSF_USBD_CFG_RAW_MODE != ENABLED vk_usbd_cfg_t * vk_usbd_get_cur_cfg(vk_usbd_dev_t *dev) { return &dev->config[dev->configuration]; } vk_usbd_ifs_t * vk_usbd_get_ifs(vk_usbd_dev_t *dev, uint_fast8_t ifs_no) { vk_usbd_cfg_t *config = vk_usbd_get_cur_cfg(dev); if (ifs_no < config->num_of_ifs) { return &config->ifs[ifs_no]; } return NULL; } #endif void vk_usbd_init(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); #if VSF_USBD_CFG_RAW_MODE != ENABLED VSF_USB_ASSERT(dev->config != NULL); dev->configured = false; dev->configuration = 0; dev->feature = 0; #endif dev->ctrl_handler.trans.ep = 0; dev->ctrl_handler.trans.param = dev; #if VSF_USBD_CFG_RAW_MODE != ENABLED vk_usbd_desc_t *desc; vk_usbd_cfg_t *config = dev->config; vk_usbd_ifs_t *ifs; struct usb_config_desc_t *desc_config; for (uint_fast8_t i = 0; i < dev->num_of_config; i++, config++) { # if VSF_USBD_CFG_AUTOSETUP == ENABLED desc = vk_usbd_get_descriptor(dev->desc, dev->num_of_desc, USB_DT_CONFIG, i, 0); VSF_USB_ASSERT(desc != NULL); desc_config = (struct usb_config_desc_t *)desc->buffer; VSF_USB_ASSERT( (desc->size == le16_to_cpu(desc_config->wTotalLength)) && (desc_config->bLength == USB_DT_CONFIG_SIZE) && (desc_config->bDescriptorType == USB_DT_CONFIG) && (desc_config->bNumInterfaces == config->num_of_ifs)); config->configuration_value = desc_config->bConfigurationValue; # endif ifs = config->ifs; for (uint_fast8_t i = 0; i < config->num_of_ifs; i++, ifs++) { ifs->is_inited = false; } } #endif #if VSF_USBD_CFG_USE_EDA == ENABLED dev->eda.fn.evthandler = __vk_usbd_evthandler; # if VSF_KERNEL_CFG_EDA_SUPPORT_ON_TERMINATE == ENABLED dev->eda.on_terminate = NULL; # endif vsf_eda_init(&dev->eda, VSF_USBD_CFG_EDA_PRIORITY, false); #endif __vk_usbd_hw_init_reset(dev, false); vsf_usbd_notify_user(dev, (usb_evt_t)USB_ON_INIT, NULL); } // TODO: check fini and re-init void vk_usbd_fini(vk_usbd_dev_t *dev) { VSF_USB_ASSERT(dev != NULL); VSF_USBD_DRV_PREPARE(dev); vk_usbd_drv_disconnect(); vk_usbd_drv_fini(); vsf_usbd_notify_user(dev, (usb_evt_t)USB_ON_FINI, NULL); } // TODO: move stream related code into vk_usbd_stream.c #if VSF_USBD_CFG_STREAM_EN == ENABLED #if VSF_USE_SIMPLE_STREAM == ENABLED static void __vk_usbd_stream_tx_recv(vk_usbd_ep_stream_t *stream_ep, uint_fast16_t ep_size) { uint8_t *buffer; uint_fast32_t size, wbuf_size = vsf_stream_get_wbuf(stream_ep->stream, &buffer); if (stream_ep->total_size > 0) { uint_fast32_t remain_size = stream_ep->total_size - stream_ep->transfered_size; size = min(wbuf_size, remain_size); } else { size = wbuf_size; } if (size >= ep_size) { stream_ep->use_as__vk_usbd_trans_t.use_as__vsf_mem_t.size = size; stream_ep->use_as__vk_usbd_trans_t.use_as__vsf_mem_t.buffer = buffer; } else { stream_ep->use_as__vk_usbd_trans_t.use_as__vsf_mem_t.size = 0; stream_ep->use_as__vk_usbd_trans_t.use_as__vsf_mem_t.buffer = NULL; } stream_ep->cur_size = stream_ep->size; vk_usbd_ep_recv(stream_ep->dev, &stream_ep->use_as__vk_usbd_trans_t); } static void __vk_usbd_stream_tx_on_trans_finish(void *param) { vk_usbd_ep_stream_t *stream_ep = (vk_usbd_ep_stream_t *)param; VSF_USBD_DRV_PREPARE(stream_ep->dev); uint_fast16_t ep_size = vk_usbd_drv_ep_get_size(stream_ep->ep); vsf_stream_t *stream = stream_ep->stream; uint_fast8_t ep = stream_ep->use_as__vk_usbd_trans_t.ep; uint_fast32_t pkg_size; if (0 == stream_ep->cur_size) { uint8_t *buffer; uint_fast32_t size; pkg_size = vk_usbd_drv_ep_get_data_size(ep); for (uint_fast16_t size_read = pkg_size; size_read > 0;) { size = vsf_stream_get_wbuf(stream, &buffer); size = min(size, size_read); vk_usbd_drv_ep_transaction_read_buffer(ep, buffer, size); size_read -= size; } } else { pkg_size = stream_ep->cur_size - stream_ep->size; stream_ep->cur_size = 0; } vsf_stream_write(stream, NULL, pkg_size); stream_ep->transfered_size += pkg_size; if (!stream_ep->total_size || (stream_ep->transfered_size < stream_ep->total_size)) { if (vsf_stream_get_free_size(stream) >= ep_size) { __vk_usbd_stream_tx_recv(stream_ep, ep_size); } else { stream_ep->use_as__vk_usbd_trans_t.on_finish = NULL; } } else if (stream_ep->callback.on_finish != NULL) { vsf_stream_disconnect_tx(stream); stream_ep->callback.on_finish(stream_ep->callback.param); } } static void __vk_usbd_stream_tx_evthandler(void *param, vsf_stream_evt_t evt) { vk_usbd_ep_stream_t *stream_ep = (vk_usbd_ep_stream_t *)param; VSF_USBD_DRV_PREPARE(stream_ep->dev); uint_fast16_t ep_size = vk_usbd_drv_ep_get_size(stream_ep->use_as__vk_usbd_trans_t.ep); vsf_stream_t *stream = stream_ep->stream; switch (evt) { case VSF_STREAM_ON_CONNECT: case VSF_STREAM_ON_OUT: if ( (NULL == stream_ep->on_finish) && ( !stream_ep->total_size || (stream_ep->transfered_size < stream_ep->total_size))) { if (vsf_stream_get_free_size(stream) >= ep_size) { stream_ep->use_as__vk_usbd_trans_t.on_finish = __vk_usbd_stream_tx_on_trans_finish; __vk_usbd_stream_tx_recv(stream_ep, ep_size); } } break; } } vsf_err_t vk_usbd_ep_recv_stream(vk_usbd_ep_stream_t *stream_ep, uint_fast32_t size) { vk_usbd_trans_t *trans = &stream_ep->use_as__vk_usbd_trans_t; vsf_stream_t *stream = stream_ep->stream; stream_ep->total_size = size; stream_ep->transfered_size = 0; stream->tx.param = stream_ep; stream->tx.evthandler = __vk_usbd_stream_tx_evthandler; trans->param = stream_ep; trans->on_finish = NULL; trans->buffer = NULL; vsf_stream_connect_tx(stream); __vk_usbd_stream_tx_evthandler(stream_ep, VSF_STREAM_ON_OUT); return VSF_ERR_NONE; } static void __vk_usbd_stream_rx_on_trans_finish(void *param) { vk_usbd_ep_stream_t *stream_ep = (vk_usbd_ep_stream_t *)param; vsf_stream_t *stream = stream_ep->stream; if (stream_ep->cur_size > 0) { stream_ep->transfered_size += stream_ep->cur_size; vsf_stream_read(stream_ep->stream, NULL, stream_ep->cur_size); stream_ep->cur_size = 0; } if (!stream_ep->total_size || (stream_ep->transfered_size < stream_ep->total_size)) { stream_ep->size = vsf_stream_get_rbuf(stream, &stream_ep->buffer); if (stream_ep->size > 0) { stream_ep->cur_size = stream_ep->size; vk_usbd_ep_send(stream_ep->dev, &stream_ep->use_as__vk_usbd_trans_t); } else { stream_ep->on_finish = NULL; } } else if (stream_ep->callback.on_finish != NULL) { vsf_stream_disconnect_rx(stream); stream_ep->callback.on_finish(stream_ep->callback.param); } } static void __vk_usbd_stream_rx_evthandler(void *param, vsf_stream_evt_t evt) { vk_usbd_ep_stream_t *stream_ep = (vk_usbd_ep_stream_t *)param; vk_usbd_dev_t *dev = stream_ep->dev; vsf_stream_t *stream = stream_ep->stream; switch (evt) { case VSF_STREAM_ON_RX: if ( (NULL == stream_ep->on_finish) && ( !stream_ep->total_size || (stream_ep->transfered_size < stream_ep->total_size))) { stream_ep->size = vsf_stream_get_rbuf(stream, &stream_ep->buffer); if (stream_ep->size > 0) { stream_ep->cur_size = stream_ep->size; stream_ep->on_finish = __vk_usbd_stream_rx_on_trans_finish; stream_ep->use_as__vk_usbd_trans_t.zlp = stream_ep->zlp_save; vk_usbd_ep_send(dev, &stream_ep->use_as__vk_usbd_trans_t); } } break; } } vsf_err_t vk_usbd_ep_send_stream(vk_usbd_ep_stream_t *stream_ep, uint_fast32_t size) { vk_usbd_trans_t *trans = &stream_ep->use_as__vk_usbd_trans_t; vsf_stream_t *stream = stream_ep->stream; stream_ep->zlp_save = trans->zlp; stream_ep->total_size = size; stream_ep->transfered_size = 0; stream->rx.param = stream_ep; stream->rx.evthandler = __vk_usbd_stream_rx_evthandler; trans->param = stream_ep; trans->on_finish = NULL; vsf_stream_connect_rx(stream); __vk_usbd_stream_rx_evthandler(stream_ep, VSF_STREAM_ON_IN); return VSF_ERR_NONE; } #elif VSF_USE_STREAM == ENABLED static vsf_err_t __vk_usbd_ep_rcv_pbuf(vk_usbd_ep_stream_t *this_ptr) { vsf_err_t result = VSF_ERR_NOT_READY; VSF_USBD_DRV_PREPARE(this_ptr->dev); do { if (NULL == this_ptr->dev) { break ; } this_ptr->rx_current = vsf_stream_src_new_pbuf( &this_ptr->use_as__vsf_stream_src_t, //!//! require a big enough pbuf vk_usbd_drv_ep_get_size(this_ptr->rx_trans.ep), -1); if (NULL == this_ptr->rx_current) { VSF_USB_ASSERT(false); result = VSF_ERR_NOT_ENOUGH_RESOURCES; break; } vk_usbd_trans_t *trans = &this_ptr->rx_trans; trans->param = this_ptr; trans->use_as__vsf_mem_t.src_ptr = vsf_pbuf_buffer_get(this_ptr->rx_current); trans->use_as__vsf_mem_t.size = vsf_pbuf_size_get(this_ptr->rx_current); vk_usbd_ep_recv(this_ptr->dev, trans); result = VSF_ERR_NONE; } while(0); return result; } static vsf_err_t __vk_usbd_on_ep_rcv(vk_usbd_ep_stream_t *this_ptr) { vsf_err_t result;// = VSF_ERR_NOT_READY; vsf_pbuf_t *pbuf; uint_fast16_t ep_left_size; VSF_USBD_DRV_PREPARE(this_ptr->dev); __vsf_interrupt_safe( //! this protection might not be necessary pbuf = this_ptr->rx_current; this_ptr->rx_current = NULL; if (pbuf != NULL) { ep_left_size = this_ptr->rx_trans.use_as__vsf_mem_t.size; } result = __vk_usbd_ep_rcv_pbuf(this_ptr); //! start next rcv ) if (NULL != pbuf) { vsf_pbuf_size_set( pbuf, vk_usbd_drv_ep_get_size(this_ptr->rx_trans.ep) - ep_left_size); vsf_stream_src_send_pbuf(&this_ptr->use_as__vsf_stream_src_t, pbuf); } return result; } vsf_err_t vk_usbd_ep_recv_stream(vk_usbd_ep_stream_t *this_ptr) { vsf_err_t result = VSF_ERR_NOT_READY; __vsf_interrupt_safe( if (NULL == this_ptr->rx_current) { result = __vk_usbd_on_ep_rcv(this_ptr); } ) return result; } static void __vk_usbd_ep_on_stream_rx_finish(void *param) { vk_usbd_ep_stream_t *this_ptr = (vk_usbd_ep_stream_t *)param; __vk_usbd_on_ep_rcv(this_ptr); } static vsf_err_t __vk_usbd_ep_send_pbuf(vk_usbd_ep_stream_t *this_ptr) { vsf_err_t result = VSF_ERR_NOT_READY; do { if (NULL == this_ptr->dev) { break ; } this_ptr->tx_current = vsf_stream_usr_fetch_pbuf(&this_ptr->use_as__vsf_stream_usr_t); if (NULL == this_ptr->tx_current) { result = VSF_ERR_NONE; break; } vk_usbd_trans_t *trans = &this_ptr->tx_trans; trans->param = this_ptr; trans->use_as__vsf_mem_t.src_ptr = vsf_pbuf_buffer_get(this_ptr->tx_current); trans->use_as__vsf_mem_t.size = vsf_pbuf_size_get(this_ptr->tx_current); vk_usbd_ep_send(this_ptr->dev, trans); result = VSF_ERR_NONE; } while(0); return result; } static void __vk_usbd_ep_on_stream_tx_finish(void *param) { vk_usbd_ep_stream_t *this_ptr = (vk_usbd_ep_stream_t *)param; vsf_pbuf_t *ptBuff; __vsf_interrupt_safe( ptBuff = this_ptr->tx_current; this_ptr->tx_current = NULL; __vk_usbd_ep_send_pbuf(this_ptr); ) vsf_pbuf_free(ptBuff); //! free old pbuf } vsf_err_t vk_usbd_ep_send_stream(vk_usbd_ep_stream_t *this_ptr) { vsf_err_t result = VSF_ERR_NOT_READY; VSF_USB_ASSERT(NULL != this_ptr); __vsf_interrupt_safe( if (NULL == this_ptr->tx_current) { result = __vk_usbd_ep_send_pbuf(this_ptr); } ) return result; } static void __vk_usbd_on_data_ready_event( void *target_ptr, vsf_stream_rx_t *ptRX, vsf_stream_status_t Status) { vk_usbd_ep_stream_t *this_ptr = (vk_usbd_ep_stream_t *)target_ptr; vk_usbd_ep_send_stream(this_ptr); } void vk_usbd_ep_stream_init( vk_usbd_ep_stream_t *this_ptr, vk_usbd_ep_stream_cfg_t *cfg) { VSF_USB_ASSERT(NULL != this_ptr); this_ptr->tx_trans.on_finish = __vk_usbd_ep_on_stream_tx_finish; this_ptr->rx_trans.on_finish = __vk_usbd_ep_on_stream_rx_finish; this_ptr->tx_current = NULL; this_ptr->rx_current = NULL; this_ptr->rx_trans.ep = cfg->rx_ep; this_ptr->rx_trans.zlp = false; this_ptr->tx_trans.ep = cfg->tx_ep; this_ptr->tx_trans.zlp = true; this_ptr->dev = NULL; //! access protected member of vsf_stream_usr_t with_protected(vsf_stream_usr_t, &this_ptr->use_as__vsf_stream_usr_t, { if (NULL != _->ptRX) { //! register data rdy event handler _->ptRX->piMethod->DataReadyEvent.Register( _->ptRX, (vsf_stream_dat_rdy_evt_t){__vk_usbd_on_data_ready_event, this_ptr}); } }); #if VSF_STREAM_CFG_SUPPORT_OPEN_CLOSE == ENABLED vsf_stream_usr_open(&(this_ptr->use_as__vsf_stream_usr_t)); #endif } void vk_usbd_ep_stream_connect_dev(vk_usbd_ep_stream_t *this_ptr, vk_usbd_dev_t *dev) { VSF_USB_ASSERT(NULL != this_ptr); this_ptr->dev = dev; vk_usbd_ep_send_stream(this_ptr); } #endif // VSF_USE_STREAM || VSF_USE_SIMPLE_STREAM #endif // VSF_USBD_CFG_STREAM_EN #endif // VSF_USE_USB_DEVICE
157018.c
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Functions for dealing with method prototypes */ #include "DexProto.h" #include <stdlib.h> #include <string.h> /* * =========================================================================== * String Cache * =========================================================================== */ /* * Make sure that the given cache can hold a string of the given length, * including the final '\0' byte. */ static void dexStringCacheAlloc(DexStringCache* pCache, size_t length) { if (pCache->allocatedSize != 0) { if (pCache->allocatedSize >= length) { return; } free((void*) pCache->value); } if (length <= sizeof(pCache->buffer)) { pCache->value = pCache->buffer; pCache->allocatedSize = 0; } else { pCache->value = malloc(length); pCache->allocatedSize = length; } } /* * Initialize the given DexStringCache. Use this function before passing * one into any other function. */ void dexStringCacheInit(DexStringCache* pCache) { pCache->value = pCache->buffer; pCache->allocatedSize = 0; pCache->buffer[0] = '\0'; } /* * Release the allocated contents of the given DexStringCache, if any. * Use this function after your last use of a DexStringCache. */ void dexStringCacheRelease(DexStringCache* pCache) { if (pCache->allocatedSize != 0) { free((void*) pCache->value); pCache->value = pCache->buffer; pCache->allocatedSize = 0; } } /* * If the given DexStringCache doesn't already point at the given value, * make a copy of it into the cache. This always returns a writable * pointer to the contents (whether or not a copy had to be made). This * function is intended to be used after making a call that at least * sometimes doesn't populate a DexStringCache. */ char* dexStringCacheEnsureCopy(DexStringCache* pCache, const char* value) { if (value != pCache->value) { size_t length = strlen(value) + 1; dexStringCacheAlloc(pCache, length); memcpy(pCache->value, value, length); } return pCache->value; } /* * Abandon the given DexStringCache, and return a writable copy of the * given value (reusing the string cache's allocation if possible). * The return value must be free()d by the caller. Use this instead of * dexStringCacheRelease() if you want the buffer to survive past the * scope of the DexStringCache. */ char* dexStringCacheAbandon(DexStringCache* pCache, const char* value) { if ((value == pCache->value) && (pCache->allocatedSize != 0)) { char* result = pCache->value; pCache->allocatedSize = 0; pCache->value = pCache->buffer; return result; } else { return strdup(value); } } /* * =========================================================================== * Method Prototypes * =========================================================================== */ /* * Return the DexProtoId from the given DexProto. The DexProto must * actually refer to a DexProtoId. */ static inline const DexProtoId* getProtoId(const DexProto* pProto) { return dexGetProtoId(pProto->dexFile, pProto->protoIdx); } /* * Get the short-form method descriptor for the given prototype. The * prototype must be protoIdx-based. */ const char* dexProtoGetShorty(const DexProto* pProto) { const DexProtoId* protoId = getProtoId(pProto); return dexStringById(pProto->dexFile, protoId->shortyIdx); } /* * Get the full method descriptor for the given prototype. */ const char* dexProtoGetMethodDescriptor(const DexProto* pProto, DexStringCache* pCache) { const DexFile* dexFile = pProto->dexFile; const DexProtoId* protoId = getProtoId(pProto); const DexTypeList* typeList = dexGetProtoParameters(dexFile, protoId); size_t length = 3; // parens and terminating '\0' u4 paramCount = (typeList == NULL) ? 0 : typeList->size; u4 i; for (i = 0; i < paramCount; i++) { u4 idx = dexTypeListGetIdx(typeList, i); length += strlen(dexStringByTypeIdx(dexFile, idx)); } length += strlen(dexStringByTypeIdx(dexFile, protoId->returnTypeIdx)); dexStringCacheAlloc(pCache, length); char *at = (char*) pCache->value; *(at++) = '('; for (i = 0; i < paramCount; i++) { u4 idx = dexTypeListGetIdx(typeList, i); const char* desc = dexStringByTypeIdx(dexFile, idx); strcpy(at, desc); at += strlen(desc); } *(at++) = ')'; strcpy(at, dexStringByTypeIdx(dexFile, protoId->returnTypeIdx)); return pCache->value; } /* * Get a copy of the descriptor string associated with the given prototype. * The returned pointer must be free()ed by the caller. */ char* dexProtoCopyMethodDescriptor(const DexProto* pProto) { DexStringCache cache; dexStringCacheInit(&cache); return dexStringCacheAbandon(&cache, dexProtoGetMethodDescriptor(pProto, &cache)); } /* * Get the parameter descriptors for the given prototype. This is the * concatenation of all the descriptors for all the parameters, in * order, with no other adornment. */ const char* dexProtoGetParameterDescriptors(const DexProto* pProto, DexStringCache* pCache) { DexParameterIterator iterator; size_t length = 1; /* +1 for the terminating '\0' */ dexParameterIteratorInit(&iterator, pProto); for (;;) { const char* descriptor = dexParameterIteratorNextDescriptor(&iterator); if (descriptor == NULL) { break; } length += strlen(descriptor); } dexParameterIteratorInit(&iterator, pProto); dexStringCacheAlloc(pCache, length); char *at = (char*) pCache->value; for (;;) { const char* descriptor = dexParameterIteratorNextDescriptor(&iterator); if (descriptor == NULL) { break; } strcpy(at, descriptor); at += strlen(descriptor); } return pCache->value; } /* * Get the type descriptor for the return type of the given prototype. */ const char* dexProtoGetReturnType(const DexProto* pProto) { const DexProtoId* protoId = getProtoId(pProto); return dexStringByTypeIdx(pProto->dexFile, protoId->returnTypeIdx); } /* * Get the parameter count of the given prototype. */ size_t dexProtoGetParameterCount(const DexProto* pProto) { const DexProtoId* protoId = getProtoId(pProto); const DexTypeList* typeList = dexGetProtoParameters(pProto->dexFile, protoId); return (typeList == NULL) ? 0 : typeList->size; } /* * Compute the number of parameter words (u4 units) required by the * given prototype. For example, if the method takes (int, long) and * returns double, this would return 3 (one for the int, two for the * long, and the return type isn't relevant). */ int dexProtoComputeArgsSize(const DexProto* pProto) { const char* shorty = dexProtoGetShorty(pProto); int count = 0; /* Skip the return type. */ shorty++; for (;;) { switch (*(shorty++)) { case '\0': { return count; } case 'D': case 'J': { count += 2; break; } default: { count++; break; } } } } /* * Common implementation for dexProtoCompare() and dexProtoCompareParameters(). */ static int protoCompare(const DexProto* pProto1, const DexProto* pProto2, bool compareReturnType) { if (pProto1 == pProto2) { // Easy out. return 0; } else { const DexFile* dexFile1 = pProto1->dexFile; const DexProtoId* protoId1 = getProtoId(pProto1); const DexTypeList* typeList1 = dexGetProtoParameters(dexFile1, protoId1); int paramCount1 = (typeList1 == NULL) ? 0 : typeList1->size; const DexFile* dexFile2 = pProto2->dexFile; const DexProtoId* protoId2 = getProtoId(pProto2); const DexTypeList* typeList2 = dexGetProtoParameters(dexFile2, protoId2); int paramCount2 = (typeList2 == NULL) ? 0 : typeList2->size; if (protoId1 == protoId2) { // Another easy out. return 0; } // Compare return types. if (compareReturnType) { int result = strcmp(dexStringByTypeIdx(dexFile1, protoId1->returnTypeIdx), dexStringByTypeIdx(dexFile2, protoId2->returnTypeIdx)); if (result != 0) { return result; } } // Compare parameters. int minParam = (paramCount1 > paramCount2) ? paramCount2 : paramCount1; int i; for (i = 0; i < minParam; i++) { u4 idx1 = dexTypeListGetIdx(typeList1, i); u4 idx2 = dexTypeListGetIdx(typeList2, i); int result = strcmp(dexStringByTypeIdx(dexFile1, idx1), dexStringByTypeIdx(dexFile2, idx2)); if (result != 0) { return result; } } if (paramCount1 < paramCount2) { return -1; } else if (paramCount1 > paramCount2) { return 1; } else { return 0; } } } /* * Compare the two prototypes. The two prototypes are compared * with the return type as the major order, then the first arguments, * then second, etc. If two prototypes are identical except that one * has extra arguments, then the shorter argument is considered the * earlier one in sort order (similar to strcmp()). */ int dexProtoCompare(const DexProto* pProto1, const DexProto* pProto2) { return protoCompare(pProto1, pProto2, true); } /* * Compare the two prototypes. The two prototypes are compared * with the first argument as the major order, then second, etc. If two * prototypes are identical except that one has extra arguments, then the * shorter argument is considered the earlier one in sort order (similar * to strcmp()). */ int dexProtoCompareParameters(const DexProto* pProto1, const DexProto* pProto2){ return protoCompare(pProto1, pProto2, false); } /* * Helper for dexProtoCompareToDescriptor(), which gets the return type * descriptor from a method descriptor string. */ static const char* methodDescriptorReturnType(const char* descriptor) { const char* result = strchr(descriptor, ')'); if (result == NULL) { return NULL; } // The return type is the character just past the ')'. return result + 1; } /* * Helper for dexProtoCompareToDescriptor(), which indicates the end * of an embedded argument type descriptor, which is also the * beginning of the next argument type descriptor. Since this is for * argument types, it doesn't accept 'V' as a valid type descriptor. */ static const char* methodDescriptorNextType(const char* descriptor) { // Skip any array references. while (*descriptor == '[') { descriptor++; } switch (*descriptor) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': { return descriptor + 1; } case 'L': { const char* result = strchr(descriptor + 1, ';'); if (result != NULL) { // The type ends just past the ';'. return result + 1; } } } return NULL; } /* * Compare a prototype and a string method descriptor. The comparison * is done as if the descriptor were converted to a prototype and compared * with dexProtoCompare(). */ int dexProtoCompareToDescriptor(const DexProto* proto, const char* descriptor) { // First compare the return types. int result = strcmp(dexProtoGetReturnType(proto), methodDescriptorReturnType(descriptor)); if (result != 0) { return result; } // The return types match, so we have to check arguments. DexParameterIterator iterator; dexParameterIteratorInit(&iterator, proto); // Skip the '('. assert (*descriptor == '('); descriptor++; for (;;) { const char* protoDesc = dexParameterIteratorNextDescriptor(&iterator); if (*descriptor == ')') { // It's the end of the descriptor string. if (protoDesc == NULL) { // It's also the end of the prototype's arguments. return 0; } else { // The prototype still has more arguments. return 1; } } if (protoDesc == NULL) { /* * The prototype doesn't have arguments left, but the * descriptor string does. */ return -1; } // Both prototype and descriptor have arguments. Compare them. const char* nextDesc = methodDescriptorNextType(descriptor); for (;;) { char c1 = *(protoDesc++); char c2 = (descriptor < nextDesc) ? *(descriptor++) : '\0'; if (c1 < c2) { // This includes the case where the proto is shorter. return -1; } else if (c1 > c2) { // This includes the case where the desc is shorter. return 1; } else if (c1 == '\0') { // The two types are equal in length. (c2 necessarily == '\0'.) break; } } /* * If we made it here, the two arguments matched, and * descriptor == nextDesc. */ } } /* * =========================================================================== * Parameter Iterators * =========================================================================== */ /* * Initialize the given DexParameterIterator to be at the start of the * parameters of the given prototype. */ void dexParameterIteratorInit(DexParameterIterator* pIterator, const DexProto* pProto) { pIterator->proto = pProto; pIterator->cursor = 0; pIterator->parameters = dexGetProtoParameters(pProto->dexFile, getProtoId(pProto)); pIterator->parameterCount = (pIterator->parameters == NULL) ? 0 : pIterator->parameters->size; } /* * Get the type_id index for the next parameter, if any. This returns * kDexNoIndex if the last parameter has already been consumed. */ u4 dexParameterIteratorNextIndex(DexParameterIterator* pIterator) { int cursor = pIterator->cursor; int parameterCount = pIterator->parameterCount; if (cursor >= parameterCount) { // The iteration is complete. return kDexNoIndex; } else { u4 idx = dexTypeListGetIdx(pIterator->parameters, cursor); pIterator->cursor++; return idx; } } /* * Get the type descriptor for the next parameter, if any. This returns * NULL if the last parameter has already been consumed. */ const char* dexParameterIteratorNextDescriptor( DexParameterIterator* pIterator) { u4 idx = dexParameterIteratorNextIndex(pIterator); if (idx == kDexNoIndex) { return NULL; } return dexStringByTypeIdx(pIterator->proto->dexFile, idx); }
191190.c
#include "mykernel.h" MyKernel myKernelNew(void) { MyKernel myKernel; myKernel.console = myKernelConsoleNew(COM1); return myKernel; }
418541.c
/* * Copyright 2020 Intel Corporation * SPDX-License-Identifier: Apache 2.0 */ /*! * \file * \brief Main application. This file has implementation for entry point into * the platform and necessary things to initialize fdo, run it and exit * gracefully. */ #include "fdo.h" #include "fdomodules.h" #include "util.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "blob.h" #include "safe_lib.h" #ifdef SECURE_ELEMENT #include "se_provisioning.h" #endif #define STORAGE_NAMESPACE "storage" #define OWNERSHIP_TRANSFER_FILE "data/owner_transfer" #define ERROR_RETRY_COUNT 5 static bool is_ownership_transfer(bool do_resale) { FILE *fp = NULL; char state = 0; fdo_sdk_status ret; if (do_resale) { state = '1'; } else { return false; } #ifdef RASALE_BASED_ON_FILE fp = fopen(OWNERSHIP_TRANSFER_FILE, "r"); if (!fp) return false; if (fread(&state, 1, 1, fp) != 1) { if (fclose(fp) == EOF) LOG(LOG_INFO, "Fclose Failed"); return false; } if (fclose(fp) == EOF) LOG(LOG_INFO, "Fclose Failed"); #endif if (state == '1') { ret = fdo_sdk_resale(); if (ret == FDO_ERROR) { LOG(LOG_INFO, "Failed to set Ownership transfer app exits\n"); exit(-1); } if (ret == FDO_SUCCESS) { fp = fopen(OWNERSHIP_TRANSFER_FILE, "w"); if (!fp) return false; state = '0'; if (fwrite(&state, 1, 1, fp) != 1) { LOG(LOG_INFO, "Fwrite Failed"); if (fclose(fp) == EOF) LOG(LOG_INFO, "Fclose Failed"); return false; } ret = 0; if (fclose(fp) == EOF) LOG(LOG_INFO, "Fclose Failed"); return true; } else if (ret == FDO_RESALE_NOT_READY) { /*Device is not yet ready for ownership transfer * First do the initial configuration */ return false; } else if (ret == FDO_RESALE_NOT_SUPPORTED) { LOG(LOG_INFO, "Device doesn't support Resale\n"); return false; } } return false; } /** * API to initialize service-info modules with their correspoding data. This * in-turn calls another API, which finally register them to FDO. * * @return * pointer to array of Sv_info modules. */ static fdo_sdk_service_info_module *fdo_sv_info_modules_init(void) { fdo_sdk_service_info_module *module_info = NULL; #ifdef MODULES_ENABLED module_info = malloc(FDO_MAX_MODULES * (sizeof(*module_info))); if (!module_info) { LOG(LOG_ERROR, "Malloc failed!\n"); return NULL; } /* module#1: fdo_sys */ if (strncpy_s(module_info[0].module_name, FDO_MODULE_NAME_LEN, "fdo_sys", FDO_MODULE_NAME_LEN) != 0) { LOG(LOG_ERROR, "Strcpy failed"); free(module_info); return NULL; } module_info[0].service_info_callback = fdo_sys; #if defined(EXTRA_MODULES) /* module#2: devconfig */ if (strncpy_s(module_info[1].module_name, FDO_MODULE_NAME_LEN, "devconfig", FDO_MODULE_NAME_LEN) != 0) { LOG(LOG_ERROR, "Strcpy failed"); free(module_info); return NULL; } module_info[1].service_info_callback = devconfig; /* module#3: keypair */ if (strncpy_s(module_info[2].module_name, FDO_MODULE_NAME_LEN, "keypair", FDO_MODULE_NAME_LEN) != 0) { LOG(LOG_ERROR, "Strcpy failed"); free(module_info); return NULL; } module_info[2].service_info_callback = keypair; #ifdef TARGET_OS_LINUX /* module#4: pelionconfig (only supported on linux as of now) */ if (strncpy_s(module_info[3].module_name, FDO_MODULE_NAME_LEN, "pelionconfig", FDO_MODULE_NAME_LEN) != 0) { LOG(LOG_ERROR, "Strcpy failed"); free(module_info); return NULL; } module_info[3].service_info_callback = pelionconfig; #endif // #ifdef TARGET_OS_LINUX #endif #endif return module_info; } static int error_cb(fdo_sdk_status type, fdo_sdk_error errorcode) { static unsigned int rv_timeout; static unsigned int conn_timeout; static unsigned int di_err; static unsigned int to1_err; static unsigned int to2_err; (void)type; switch (errorcode) { case FDO_RV_TIMEOUT: rv_timeout++; if (rv_timeout > ERROR_RETRY_COUNT) { LOG(LOG_INFO, "Sending ABORT RV connection from app\n"); return FDO_ABORT; } break; case FDO_CONN_TIMEOUT: conn_timeout++; if (conn_timeout > ERROR_RETRY_COUNT) { LOG(LOG_INFO, "Sending ABORT connection from app\n"); return FDO_ABORT; } break; case FDO_DI_ERROR: di_err++; if (di_err > ERROR_RETRY_COUNT) { LOG(LOG_INFO, "Sending ABORT DI from app\n"); return FDO_ABORT; } break; case FDO_TO1_ERROR: to1_err++; if (to1_err > ERROR_RETRY_COUNT) { LOG(LOG_INFO, "Sending ABORT T01 from app\n"); return FDO_ABORT; } break; case FDO_TO2_ERROR: to2_err++; if (to2_err > ERROR_RETRY_COUNT) { LOG(LOG_INFO, "Sending ABORT T02 from app\n"); return FDO_ABORT; } break; default: break; } LOG(LOG_INFO, "rv_timeout: %u, conn_timeout: %u, di_err: %u, to1_err: " "%u, to2_err: %u\n", rv_timeout, conn_timeout, di_err, to1_err, to2_err); return FDO_SUCCESS; } static void print_device_status(void) { fdo_sdk_device_state status = FDO_STATE_ERROR; status = fdo_sdk_get_status(); if (status == FDO_STATE_PRE_DI) LOG(LOG_DEBUG, "Device is ready for DI\n"); if (status == FDO_STATE_PRE_TO1) LOG(LOG_DEBUG, "Device is ready for Ownership transfer\n"); if (status == FDO_STATE_IDLE) LOG(LOG_DEBUG, "Device Ownership transfer Done\n"); if (status == FDO_STATE_RESALE) LOG(LOG_DEBUG, "Device is ready for Ownership transfer\n"); if (status == FDO_STATE_ERROR) LOG(LOG_DEBUG, "Error in getting device status\n"); } /** * This is the main entry point of the Platform. * @return * 0 if success, -ve if error. */ #ifdef TARGET_OS_LINUX int main(int argc, char **argv) #else int app_main(bool is_resale) #endif { fdo_sdk_service_info_module *module_info; bool do_resale = false; LOG(LOG_DEBUG, "Starting Secure Device Onboard\n"); #ifdef SECURE_ELEMENT if (-1 == se_provisioning()) { LOG(LOG_ERROR, "Provisioning Secure element failed!\n"); return -1; } #endif /* SECURE_ELEMENT */ if (-1 == configure_normal_blob()) { LOG(LOG_ERROR, "Provisioning Normal blob for the 1st time failed!\n"); return -1; } /* List and Init all Sv_info modules */ module_info = fdo_sv_info_modules_init(); if (!module_info) { LOG(LOG_DEBUG, "Sv_info Modules not loaded!\n"); } /* Init fdo sdk */ if (FDO_SUCCESS != fdo_sdk_init(error_cb, FDO_MAX_MODULES, module_info)) { LOG(LOG_ERROR, "fdo_sdk_init failed!!\n"); free(module_info); return -1; } /* free the module related info * FDO has created the required DB */ free(module_info); #ifdef TARGET_OS_LINUX /* Change stdout to unbuffered mode, without this we don't get logs * if app crashes */ setbuf(stdout, NULL); #endif #if defined TARGET_OS_MBEDOS /* TODO: ad nvs and network */ #endif #if defined TARGET_OS_LINUX if (argc > 1 && *argv[1] == '1') { do_resale = true; } #else if (is_resale == true) { do_resale = true; } #endif if (is_ownership_transfer(do_resale)) { return 0; } print_device_status(); if (FDO_SUCCESS != fdo_sdk_run()) { LOG(LOG_ERROR, "Secure device onboarding failed\n"); return -1; } // Return 0 on success return 0; }
536272.c
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1996-2003 * Sleepycat Software. All rights reserved. */ #include "db_config.h" #ifndef lint static const char revid[] = "$Id: db_iface.c,v 11.106 2003/10/02 02:57:46 margo Exp $"; #endif /* not lint */ #ifndef NO_SYSTEM_INCLUDES #include <sys/types.h> #include <string.h> #endif #include "db_int.h" #include "dbinc/db_page.h" #include "dbinc/db_shash.h" #include "dbinc/btree.h" #include "dbinc/hash.h" #include "dbinc/qam.h" #include "dbinc/lock.h" #include "dbinc/log.h" #include "dbinc/mp.h" #include <stdlib.h> #include <pthread.h> #include <walkback.h> #include <debug_switches.h> #ifndef TESTSUITE extern pthread_key_t comdb2_open_key; #endif static int __db_associate_arg __P((DB *, DB *, int (*)(DB *, const DBT *, const DBT *, DBT *), u_int32_t)); static int __db_c_get_arg __P((DBC *, DBT *, DBT *, u_int32_t)); static int __db_c_pget_arg __P((DBC *, DBT *, u_int32_t)); static int __db_c_put_arg __P((DBC *, DBT *, DBT *, u_int32_t)); static int __db_curinval __P((const DB_ENV *)); static int __db_cursor_arg __P((DB *, u_int32_t)); static int __db_del_arg __P((DB *, u_int32_t)); static int __db_get_arg __P((const DB *, const DBT *, DBT *, u_int32_t)); static int __db_join_arg __P((DB *, DBC **, u_int32_t)); static int __db_open_arg __P((DB *, DB_TXN *, const char *, const char *, DBTYPE, u_int32_t)); static int __db_pget_arg __P((DB *, DBT *, u_int32_t)); static int __db_put_arg __P((DB *, DBT *, DBT *, u_int32_t)); static int __db_rdonly __P((const DB_ENV *, const char *)); static int __db_invwrite __P((const DB_ENV *, const char *)); static int __db_stat_arg __P((DB *, u_int32_t)); static int __dbt_ferr __P((const DB *, const char *, const DBT *, int)); /* * A database should be required to be readonly if it's been explicitly * specified as such or if we're a client in a replicated environment and * we don't have the special "client-writer" designation. */ #define IS_READONLY(dbp) \ (F_ISSET(dbp, DB_AM_RDONLY) || \ (IS_REP_CLIENT((dbp)->dbenv) && \ !IS_REP_LOGSONLY((dbp)->dbenv) && \ !F_ISSET((dbp), DB_AM_CL_WRITER))) /* * These functions implement the Berkeley DB API. They are organized in a * layered fashion. The interface functions (XXX_pp) perform all generic * error checks (for example, PANIC'd region, replication state change * in progress, inconsistent transaction usage), call function-specific * check routines (_arg) to check for proper flag usage, etc., do pre-amble * processing (incrementing handle counts, handling auto-commit), call the * function and then do post-amble processing (DB_AUTO_COMMIT, dec handle * counts). * * So, the basic structure is: * Check for generic errors * Call function-specific check routine * Increment handle count * Create internal transaction if necessary * Call underlying worker function * Commit/abort internal transaction if necessary * Decrement handle count */ /* * __db_associate_pp -- * DB->associate pre/post processing. * * PUBLIC: int __db_associate_pp __P((DB *, DB_TXN *, DB *, * PUBLIC: int (*)(DB *, const DBT *, const DBT *, DBT *), u_int32_t)); */ int __db_associate_pp(dbp, txn, sdbp, callback, flags) DB *dbp, *sdbp; DB_TXN *txn; int (*callback) __P((DB *, const DBT *, const DBT *, DBT *)); u_int32_t flags; { DBC *sdbc; DB_ENV *dbenv; int handle_check, ret, txn_local; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_associate_arg(dbp, sdbp, callback, flags)) != 0) return (ret); /* * Secondary cursors may have the primary's lock file ID, so we need * to make sure that no older cursors are lying around when we make * the transition. */ if (TAILQ_FIRST(&sdbp->active_queue) != NULL || TAILQ_FIRST(&sdbp->join_queue) != NULL) { __db_err(dbenv, "Databases may not become secondary indices while cursors are open"); return (EINVAL); } /* * Create a local transaction as necessary, check for consistent * transaction usage, and, if we have no transaction but do have * locking on, acquire a locker id for the handle lock acquisition. */ txn_local = 0; if (IS_AUTO_COMMIT(dbenv, txn, flags)) { if ((ret = __db_txn_auto_init(dbenv, &txn)) != 0) return (ret); txn_local = 1; LF_CLR(DB_AUTO_COMMIT); } else if (txn != NULL && !TXN_ON(dbenv)) return (__db_not_txn_env(dbenv)); /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, 0)) != 0) goto err; /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) goto err; while ((sdbc = TAILQ_FIRST(&sdbp->free_queue)) != NULL) if ((ret = __db_c_destroy(sdbc)) != 0) break; if (ret == 0) ret = __db_associate(dbp, txn, sdbp, callback, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); err: return (txn_local ? __db_txn_auto_resolve(dbenv, txn, 0, ret) : ret); } /* * __db_associate_arg -- * Check DB->associate arguments. */ static int __db_associate_arg(dbp, sdbp, callback, flags) DB *dbp, *sdbp; int (*callback) __P((DB *, const DBT *, const DBT *, DBT *)); u_int32_t flags; { DB_ENV *dbenv; int ret; dbenv = dbp->dbenv; if (F_ISSET(sdbp, DB_AM_SECONDARY)) { __db_err(dbenv, "Secondary index handles may not be re-associated"); return (EINVAL); } if (F_ISSET(dbp, DB_AM_SECONDARY)) { __db_err(dbenv, "Secondary indices may not be used as primary databases"); return (EINVAL); } if (F_ISSET(dbp, DB_AM_DUP)) { __db_err(dbenv, "Primary databases may not be configured with duplicates"); return (EINVAL); } if (F_ISSET(dbp, DB_AM_RENUMBER)) { __db_err(dbenv, "Renumbering recno databases may not be used as primary databases"); return (EINVAL); } if (dbp->dbenv != sdbp->dbenv && (!F_ISSET(dbp->dbenv, DB_ENV_DBLOCAL) || !F_ISSET(sdbp->dbenv, DB_ENV_DBLOCAL))) { __db_err(dbenv, "The primary and secondary must be opened in the same environment"); return (EINVAL); } if (DB_IS_THREADED(dbp) != DB_IS_THREADED(sdbp)) { __db_err(dbenv, "The DB_THREAD setting must be the same for primary and secondary"); return (EINVAL); } if (callback == NULL && (!F_ISSET(dbp, DB_AM_RDONLY) || !F_ISSET(sdbp, DB_AM_RDONLY))) { __db_err(dbenv, "Callback function may be NULL only when database handles are read-only"); return (EINVAL); } if ((ret = __db_fchk(dbenv, "DB->associate", flags, DB_CREATE | DB_AUTO_COMMIT)) != 0) return (ret); return (0); } /* * __db_close_pp -- * DB->close pre/post processing. * * PUBLIC: int __db_close_pp __P((DB *, u_int32_t)); */ int __db_close_pp(dbp, flags) DB *dbp; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret, t_ret; dbenv = dbp->dbenv; ret = 0; PANIC_CHECK(dbenv); /* * !!! * The actual argument checking is simple, do it inline. * * Validate arguments and complain if they're wrong, but as a DB * handle destructor, we can't fail. */ if (flags != 0 && flags != DB_NOSYNC && (t_ret = __db_ferr(dbenv, "DB->close", 0)) != 0 && ret == 0) ret = t_ret; /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (t_ret = __db_rep_enter(dbp, 0, 0)) != 0 && ret == 0) ret = t_ret; if ((t_ret = __db_close(dbp, NULL, flags)) != 0 && ret == 0) ret = t_ret; /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * PUBLIC: int __db_cursor_pp_paired_from_lid __P((DB *, u_int32_t, DBC **, u_int32_t)); */ int __db_cursor_pp_paired_from_lid(dbp, clone_lid, dbcp, flags) DB *dbp; u_int32_t clone_lid; DBC **dbcp; u_int32_t flags; { int rc = 0; rc = __db_cursor_pp_real(dbp, /* db */ NULL, /* txn */ NULL, /* txn_clone */ NULL, /* dbcp_old */ clone_lid, /* lid_clone */ NULL, /* dbcs */ dbcp, /* dbcp_out */ flags, /* flags */ 1); /* count this cursor */ #if 0 ctrace("LL lid %d open %d (%d)\n", pthread_self(), (!rc) ? (*dbcp)->locker : -1, rc); #endif return rc; } /* * PUBLIC: int __db_cursor_pp_paired_from_txn __P((DB *, DB_TXN *, DBC **, u_int32_t)); */ int __db_cursor_pp_paired_from_txn(dbp, clone_txn, dbcp, flags) DB *dbp; DB_TXN *clone_txn; DBC **dbcp; u_int32_t flags; { int rc = 0; rc = __db_cursor_pp_real(dbp, /* db */ NULL, /* txn */ clone_txn, /* txn_clone */ NULL, /* dbcp_old */ 0, /* lid_clone */ NULL, /* dbcs */ dbcp, /* dbcp_out */ flags, /* flags */ 1); /* count this cursor */ #if 0 ctrace("LL txn %d open %d (%d)\n", pthread_self(), (!rc) ? (*dbcp)->locker : -1, rc); #endif return rc; } /* * PUBLIC: int __db_cursor_pp_paired __P((DB *, DBC *, DBC **, u_int32_t)); */ int __db_cursor_pp_paired(dbp, dbc_old, dbcp, flags) DB *dbp; DBC *dbc_old; DBC **dbcp; u_int32_t flags; { int rc = 0; #ifdef LULU fprintf(stdout, "[%d] __db_cursor_pp_paired: creating cursor, old lockerid " "= %u\n", pthread_self(), (dbc_old) ? dbc_old->locker : 0); #endif rc = __db_cursor_pp_real(dbp, NULL, NULL, dbc_old, 0, NULL, /* dbcs */ dbcp, flags, /* flags */ 1); /* count this cursor */ #ifdef LULU fprintf(stdout, "[%d] __db_cursor_pp_paired: created cursor lockerid = " "%u\n", pthread_self(), (*dbcp) ? (*dbcp)->locker : 0); #endif #if 0 ctrace("LL cur %d open %d (%d)\n", pthread_self(), (!rc) ? (*dbcp)->locker : -1, rc); #endif return rc; } pthread_key_t DBG_FREE_CURSOR; int transfer_cursor_ownership(DBC *cold, DBC *cnew) { if (cold->pp_allocated) { #ifdef LULU2 fprintf(stdout, "TT: tid %d locker %lu lid %lu addr %lx [pp_allocated " "%u] ->tid %d locker %lu lid %lu addr %lx [pp_allocated %u] \n", cold->tid, cold->locker, cold->lid, cold, cold->pp_allocated, cnew->tid, cnew->locker, cnew->lid, cnew, cnew->pp_allocated); #endif /* change ownership of thread tracking struct */ cnew->pp_allocated = cold->pp_allocated; cold->pp_allocated = 0; return 1; } return 0; } /* * __db_cursor_ser_pp -- * DB->cursor_ser pre/post processing. * * PUBLIC: int __db_cursor_ser_pp * PUBLIC: __P((DB *, DB_TXN *, DBCS *, DBC **, u_int32_t)); */ int __db_cursor_ser_pp(dbp, txn, dbcs, dbcp, flags) DB *dbp; DB_TXN *txn; DBCS *dbcs; DBC **dbcp; u_int32_t flags; { int rc; DBC *d; struct cursor_track *vptr; int nframes; int i; rc = __db_cursor_pp_real(dbp, txn, NULL, NULL, 0, dbcs, dbcp, flags, 1); #if 0 ctrace("LL none %d open %d (%d)\n", pthread_self(), (!rc) ? (*dbcp)->locker : -1, rc); #endif if (rc == 0) { d = *dbcp; d->pp_allocated = 1; #ifndef TESTSUITE vptr = pthread_getspecific(comdb2_open_key); if (vptr) { u_int32_t l; l = (u_int32_t)vptr->lockerid; if ((l != 0) && (d->locker != 0)) { if (l != d->locker && debug_switch_check_multiple_lockers()) { unsigned int nframes; void *stack[MAXSTACKDEPTH]; fprintf(stderr, "ERROR thread %d opened 2 cursors w/ 2 lockerids %d %d\n", pthread_self(), l, d->locker); fprintf(stderr, "First stack:\n"); for (i = SKIPFRAMES; i < vptr->nframes; i++) fprintf(stderr, " [%2d] %p\n", i - SKIPFRAMES, vptr->stack[i]); #ifndef __linux rc = stack_pc_getlist(NULL, stack, MAXSTACKDEPTH, &nframes); if (!rc) { fprintf(stderr, "Second stack:\n"); for (i = SKIPFRAMES; i < nframes; i++) fprintf(stderr, " [%2d] %p\n", i - SKIPFRAMES, stack[i]); } #endif } } } else { vptr = malloc(sizeof(struct cursor_track)); vptr->lockerid = d->locker; vptr->nframes = 0; /* save the first stack */ #ifndef __linux stack_pc_getlist(NULL, vptr->stack, MAXSTACKDEPTH, &vptr->nframes); #endif pthread_setspecific(comdb2_open_key, vptr); } #endif } /*fprintf(stderr, "thread %d opened cursor %x !\n", pthread_self(), d); */ return rc; } /* * __db_cursor_pp -- * DB->cursor pre/post processing. * * PUBLIC: int __db_cursor_pp __P((DB *, DB_TXN *, DBC **, u_int32_t)); */ int gbl_berk_track_cursors = 0; int __db_cursor_pp(dbp, txn, dbcp, flags) DB *dbp; DB_TXN *txn; DBC **dbcp; u_int32_t flags; { return __db_cursor_ser_pp(dbp, txn, NULL /*dbcs */ , dbcp, flags); } /* * __db_cursor_pp_real -- * DB->cursor pre/post processing. * * PUBLIC: int __db_cursor_pp_real * PUBLIC: __P((DB *, DB_TXN *, DB_TXN *, DBC *, u_int32_t, DBCS *, DBC **, * PUBLIC: u_int32_t, u_int32_t)); */ int __db_cursor_pp_real(dbp, txn, txn_clone, dbcp_old, lid_clone, dbcs, dbcp, flags, countmein) DB *dbp; DB_TXN *txn; DB_TXN *txn_clone; DBC *dbcp_old; u_int32_t lid_clone; DBCS *dbcs; DBC **dbcp; u_int32_t flags; u_int32_t countmein; { DB_ENV *dbenv; int handle_check, ret; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->cursor"); if ((ret = __db_cursor_arg(dbp, flags)) != 0) return (ret); /* * Check for consistent transaction usage. For now, assume that * this cursor might be used for read operations only (in which * case it may not require a txn). We'll check more stringently * in c_del and c_put. (Note that this all means that the * read-op txn tests have to be a subset of the write-op ones.) */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, 1)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) return (ret); ret = __db_cursor_real(dbp, txn, txn_clone, dbcp_old, lid_clone, dbcs, dbcp, flags, countmein); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_cursor -- * DB->cursor. * * PUBLIC: int __db_cursor * PUBLIC: __P((DB *, DB_TXN *, DBC **, u_int32_t)); */ int __db_cursor(dbp, txn, dbcp, flags) DB *dbp; DB_TXN *txn; DBC **dbcp; u_int32_t flags; { return __db_cursor_real(dbp, /* db */ txn, /* txn */ NULL, /* txn_clone */ NULL, /* dbcp_old */ 0, /* lid_clone */ NULL, /* dbcs */ dbcp, /* dbcp_out */ flags, /* flags */ 1); } /* * __db_cursor_pp_nocount -- * DB->cursor_nocount. * * PUBLIC: int __db_cursor_pp_nocount * PUBLIC: __P((DB *, DB_TXN *, DBC **, u_int32_t)); */ int __db_cursor_pp_nocount(dbp, txn, dbcp, flags) DB *dbp; DB_TXN *txn; DBC **dbcp; u_int32_t flags; { return __db_cursor_pp_real(dbp, /* db */ txn, /* txn */ NULL, /* txn_clone */ NULL, /* dbcp_old */ 0, /* lid_clone */ NULL, /* dbcs */ dbcp, /* dbcp_out */ flags, /* flags */ 0); /* do not count me, used to get a dummy cursor */ } /* * __db_cursor_real -- * DB->cursor. * * PUBLIC: int __db_cursor_real * PUBLIC: __P((DB *, DB_TXN *, DB_TXN *, DBC *, u_int32_t, DBCS *, DBC **, * PUBLIC: u_int32_t, int)); */ int __db_cursor_real(dbp, txn, txn_clone, dbcp_old, lid_clone, dbcs, dbcp, flags, countmein) DB *dbp; DB_TXN *txn; DB_TXN *txn_clone; DBC *dbcp_old; u_int32_t lid_clone; DBCS *dbcs; DBC **dbcp; u_int32_t flags; int countmein; { DB_ENV *dbenv; DBC *dbc; db_lockmode_t mode; u_int32_t op; int ret; dbenv = dbp->dbenv; if (dbcs) { if ((ret = __db_cursor_ser_int(dbp, NULL, dbcs, &dbc, flags)) != 0) return (ret); } else if (txn_clone) { if ((ret = __db_cursor_int(dbp, NULL, dbp->type, PGNO_INVALID, 0, txn_clone->txnid, &dbc, flags)) != 0) return (ret); } else if (dbcp_old) { if ((ret = __db_cursor_int(dbp, NULL, dbp->type, PGNO_INVALID, 0, dbcp_old->locker, &dbc, flags)) != 0) return (ret); } else if (lid_clone) { if ((ret = __db_cursor_int(dbp, NULL, dbp->type, PGNO_INVALID, 0, lid_clone, &dbc, flags)) != 0) return (ret); } else { if ((ret = __db_cursor_int(dbp, txn, dbp->type, PGNO_INVALID, 0, DB_LOCK_INVALIDID, &dbc, flags)) != 0) return (ret); } /* * If this is CDB, do all the locking in the interface, which is * right here. */ if (CDB_LOCKING(dbenv)) { op = LF_ISSET(DB_OPFLAGS_MASK); mode = (op == DB_WRITELOCK) ? DB_LOCK_WRITE : ((op == DB_WRITECURSOR) ? DB_LOCK_IWRITE : DB_LOCK_READ); if ((ret = __lock_get(dbenv, dbc->locker, 0, &dbc->lock_dbt, mode, &dbc->mylock)) != 0) goto err; if (op == DB_WRITECURSOR) F_SET(dbc, DBC_WRITECURSOR); if (op == DB_WRITELOCK) F_SET(dbc, DBC_WRITER); } if (LF_ISSET(DB_DIRTY_READ) || (txn != NULL &&F_ISSET(txn, TXN_DIRTY_READ))) F_SET(dbc, DBC_DIRTY_READ); { dbc->tid = pthread_self(); /* register the creator tid */ #ifdef LULU2 fprintf(stdout, "NC: tid %d locker %lu lid %lu addr %lx [pp_allocated " "%u]\n", dbc->tid, dbc->locker, dbc->lid, dbc, dbc->pp_allocated); #endif if (countmein) { #ifndef TESTSUITE struct __dbg_free_cursor *p = pthread_getspecific(DBG_FREE_CURSOR); if (p) { p->counter++; } else { struct __dbg_free_cursor *p = malloc(sizeof(struct __dbg_free_cursor)); if (!p) { fprintf(stderr, "error allocating __dbg_free_cursor\n"); } else { p->counter = 1; pthread_setspecific(DBG_FREE_CURSOR, p); } } #endif } } *dbcp = dbc; return (0); err: (void)__db_c_close(dbc); return (ret); } /* * __db_cursor_arg -- * Check DB->cursor arguments. */ static int __db_cursor_arg(dbp, flags) DB *dbp; u_int32_t flags; { DB_ENV *dbenv; int pgorder = 0; int discardp = 0; int pausible = 0; dbenv = dbp->dbenv; /* DB_DIRTY_READ is the only valid bit-flag and requires locking. */ if (LF_ISSET(DB_DIRTY_READ)) { if (!LOCKING_ON(dbenv)) return (__db_fnl(dbenv, "DB->cursor")); LF_CLR(DB_DIRTY_READ); } if (LF_ISSET(DB_PAUSIBLE)) { pausible = 1; LF_CLR(DB_PAUSIBLE); } /* Mask out page-order flag. */ if (LF_ISSET(DB_PAGE_ORDER)) { pgorder = 1; LF_CLR(DB_PAGE_ORDER | DB_DISCARD_PAGES); } /* Check for invalid function flags. */ switch (flags) { case 0: break; case DB_WRITECURSOR: if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "DB->cursor")); if (!CDB_LOCKING(dbenv)) return (__db_ferr(dbenv, "DB->cursor", 0)); break; case DB_WRITELOCK: if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "DB->cursor")); if (pgorder || discardp || pausible) return (__db_invwrite(dbenv, "DB->cursor")); break; default: return (__db_ferr(dbenv, "DB->cursor", 0)); } return (0); } /* * __db_del_pp -- * DB->del pre/post processing. * * PUBLIC: int __db_del_pp __P((DB *, DB_TXN *, DBT *, u_int32_t)); */ int __db_del_pp(dbp, txn, key, flags) DB *dbp; DB_TXN *txn; DBT *key; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret, txn_local; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->del"); if ((ret = __db_del_arg(dbp, flags)) != 0) return (ret); /* Create local transaction as necessary. */ if (IS_AUTO_COMMIT(dbenv, txn, flags)) { if ((ret = __db_txn_auto_init(dbenv, &txn)) != 0) return (ret); txn_local = 1; LF_CLR(DB_AUTO_COMMIT); } else txn_local = 0; /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, 0)) != 0) goto err; /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) goto err; ret = __db_del(dbp, txn, key, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); err: return (txn_local ? __db_txn_auto_resolve(dbenv, txn, 0, ret) : ret); } /* * __db_del_arg -- * Check DB->delete arguments. */ static int __db_del_arg(dbp, flags) DB *dbp; u_int32_t flags; { DB_ENV *dbenv; dbenv = dbp->dbenv; /* Check for changes to a read-only tree. */ if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "DB->del")); /* Check for invalid function flags. */ LF_CLR(DB_AUTO_COMMIT); switch (flags) { case 0: break; default: return (__db_ferr(dbenv, "DB->del", 0)); } return (0); } /* * db_fd_pp -- * DB->fd pre/post processing. * * PUBLIC: int __db_fd_pp __P((DB *, int *)); */ int __db_fd_pp(dbp, fdp) DB *dbp; int *fdp; { DB_ENV *dbenv; DB_FH *fhp; int handle_check, ret; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->fd"); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, 0)) != 0) return (ret); /* * !!! * There's no argument checking to be done. * * !!! * The actual method call is simple, do it inline. * * XXX * Truly spectacular layering violation. */ if ((ret = __mp_xxx_fh(dbp->mpf, &fhp)) != 0) goto err; if (fhp == NULL) { *fdp = -1; __db_err(dbenv, "Database does not have a valid file handle"); ret = ENOENT; } else *fdp = fhp->fd; err: /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_get_pp -- * DB->get pre/post processing. * * PUBLIC: int __db_get_pp __P((DB *, DB_TXN *, DBT *, DBT *, u_int32_t)); */ int __db_get_pp(dbp, txn, key, data, flags) DB *dbp; DB_TXN *txn; DBT *key, *data; u_int32_t flags; { DB_ENV *dbenv; u_int32_t mode; int handle_check, ret, txn_local; struct cursor_track *vptr; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->get"); #ifndef TESTSUITE vptr = pthread_getspecific(comdb2_open_key); if (vptr) { u_int32_t lid; unsigned int nframes; void *stack[MAXSTACKDEPTH]; int i; int rc; lid = vptr->lockerid; if (lid && debug_switch_check_multiple_lockers()) { fprintf(stderr, "ERROR thread %d called __db_get_pp with an open " "cursor (lockerid %d)\n", pthread_self(), lid); fprintf(stderr, "First stack:\n"); for (i = SKIPFRAMES; i < vptr->nframes; i++) fprintf(stderr, " %d %p", i - SKIPFRAMES, vptr->stack[i]); printf("\n"); #ifndef __linux rc = stack_pc_getlist(NULL, stack, MAXSTACKDEPTH, &nframes); if (!rc) { fprintf(stderr, "Second stack:\n"); for (i = SKIPFRAMES; i < nframes; i++) fprintf(stderr, "%d %p", i - SKIPFRAMES, stack[i]); printf("\n"); } #endif } } #endif if ((ret = __db_get_arg(dbp, key, data, flags)) != 0) return (ret); mode = 0; txn_local = 0; if (LF_ISSET(DB_DIRTY_READ)) mode = DB_DIRTY_READ; else if ((flags & DB_OPFLAGS_MASK) == DB_CONSUME || (flags & DB_OPFLAGS_MASK) == DB_CONSUME_WAIT) { mode = DB_WRITELOCK; if (IS_AUTO_COMMIT(dbenv, txn, flags)) { if ((ret = __db_txn_auto_init(dbenv, &txn)) != 0) return (ret); txn_local = 1; LF_CLR(DB_AUTO_COMMIT); } } /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, mode == DB_WRITELOCK || LF_ISSET(DB_RMW) ? 0 : 1)) != 0) goto err; /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) goto err; ret = __db_get(dbp, txn, key, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); err: return (txn_local ? __db_txn_auto_resolve(dbenv, txn, 0, ret) : ret); } // PUBLIC: int __db_get_numpages __P((DB *, db_pgno_t *)); int __db_get_numpages(dbp, numpages) DB *dbp; db_pgno_t *numpages; { int ret; switch (dbp->type) { case DB_BTREE: case DB_RECNO: if ((ret = __bam_numpages(dbp, numpages)) != 0) goto err; break; case DB_HASH: case DB_QUEUE: case DB_UNKNOWN: default: ret = __db_unknown_type(dbp->dbenv, "__db_numpages", dbp->type); goto err; } return 0; err: return (ret); } // PUBLIC: void __db_set_compression_flags __P((DB *, uint8_t)); void __db_set_compression_flags(DB *db, uint8_t flags) { db->compression_flags = flags; } // PUBLIC: uint8_t __db_get_compression_flags __P((DB *)); uint8_t __db_get_compression_flags(DB *db) { return db->compression_flags; } /* * __db_get -- * DB->get. * * PUBLIC: int __db_get __P((DB *, DB_TXN *, DBT *, DBT *, u_int32_t)); */ int __db_get(dbp, txn, key, data, flags) DB *dbp; DB_TXN *txn; DBT *key, *data; u_int32_t flags; { DBC *dbc; u_int32_t mode; int ret, t_ret; mode = 0; if (LF_ISSET(DB_DIRTY_READ)) { mode = DB_DIRTY_READ; LF_CLR(DB_DIRTY_READ); } else if ((flags & DB_OPFLAGS_MASK) == DB_CONSUME || (flags & DB_OPFLAGS_MASK) == DB_CONSUME_WAIT) mode = DB_WRITELOCK; if ((ret = __db_cursor(dbp, txn, &dbc, mode)) != 0) return (ret); DEBUG_LREAD(dbc, txn, "DB->get", key, NULL, flags); /* * The DBC_TRANSIENT flag indicates that we're just doing a * single operation with this cursor, and that in case of * error we don't need to restore it to its old position--we're * going to close it right away. Thus, we can perform the get * without duplicating the cursor, saving some cycles in this * common case. */ F_SET(dbc, DBC_TRANSIENT); /* * SET_RET_MEM indicates that if key and/or data have no DBT * flags set and DB manages the returned-data memory, that memory * will belong to this handle, not to the underlying cursor. */ SET_RET_MEM(dbc, dbp); if (LF_ISSET(~(DB_RMW | DB_MULTIPLE)) == 0) LF_SET(DB_SET); ret = __db_c_get(dbc, key, data, flags); if (dbc != NULL && (t_ret = __db_c_close(dbc)) != 0 && ret == 0) ret = t_ret; return (ret); } /* * __db_get_arg -- * DB->get argument checking, used by both DB->get and DB->pget. */ static int __db_get_arg(dbp, key, data, flags) const DB *dbp; const DBT *key; DBT *data; u_int32_t flags; { DB_ENV *dbenv; int check_thread, dirty, multi, ret; dbenv = dbp->dbenv; /* * Check for read-modify-write validity. DB_RMW doesn't make sense * with CDB cursors since if you're going to write the cursor, you * had to create it with DB_WRITECURSOR. Regardless, we check for * LOCKING_ON and not STD_LOCKING, as we don't want to disallow it. * If this changes, confirm that DB does not itself set the DB_RMW * flag in a path where CDB may have been configured. */ check_thread = dirty = 0; if (LF_ISSET(DB_DIRTY_READ | DB_RMW)) { if (!LOCKING_ON(dbenv)) return (__db_fnl(dbenv, "DB->get")); if (LF_ISSET(DB_DIRTY_READ)) dirty = 1; LF_CLR(DB_DIRTY_READ | DB_RMW); } multi = 0; if (LF_ISSET(DB_MULTIPLE | DB_MULTIPLE_KEY)) { if (LF_ISSET(DB_MULTIPLE_KEY)) goto multi_err; multi = LF_ISSET(DB_MULTIPLE) ? 1 : 0; LF_CLR(DB_MULTIPLE); } if (LF_ISSET(DB_AUTO_COMMIT)) { LF_CLR(DB_AUTO_COMMIT); if (flags != DB_CONSUME && flags != DB_CONSUME_WAIT) goto err; } /* Check for invalid function flags. */ switch (flags) { case 0: case DB_GET_BOTH: break; case DB_SET_RECNO: check_thread = 1; if (!F_ISSET(dbp, DB_AM_RECNUM)) goto err; break; case DB_CONSUME: case DB_CONSUME_WAIT: check_thread = 1; if (dirty) { __db_err(dbenv, "DB_DIRTY_READ is not supported with DB_CONSUME or DB_CONSUME_WAIT"); return (EINVAL); } if (multi) multi_err: return (__db_ferr(dbenv, "DB->get", 1)); if (dbp->type == DB_QUEUE) break; /* FALLTHROUGH */ default: err: return (__db_ferr(dbenv, "DB->get", 0)); } /* * Check for invalid key/data flags. * * XXX: Dave Krinsky * Remember to modify this when we fix the flag-returning problem. */ if ((ret = __dbt_ferr(dbp, "key", key, check_thread)) != 0) return (ret); if ((ret = __dbt_ferr(dbp, "data", data, 1)) != 0) return (ret); if (multi) { if (!F_ISSET(data, DB_DBT_USERMEM)) { __db_err(dbenv, "DB_MULTIPLE requires DB_DBT_USERMEM be set"); return (EINVAL); } if (F_ISSET(key, DB_DBT_PARTIAL) || F_ISSET(data, DB_DBT_PARTIAL)) { __db_err(dbenv, "DB_MULTIPLE does not support DB_DBT_PARTIAL"); return (EINVAL); } if (data->ulen < 1024 || data->ulen < dbp->pgsize || data->ulen % 1024 != 0) { __db_err(dbenv, "%s%s", "DB_MULTIPLE buffers must be ", "aligned, at least page size and multiples of 1KB"); return (EINVAL); } } return (0); } /* * __db_join_pp -- * DB->join pre/post processing. * * PUBLIC: int __db_join_pp __P((DB *, DBC **, DBC **, u_int32_t)); */ int __db_join_pp(primary, curslist, dbcp, flags) DB *primary; DBC **curslist, **dbcp; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret; dbenv = primary->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_join_arg(primary, curslist, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, primary); if (handle_check && (ret = __db_rep_enter(primary, 1, curslist[0]->txn != NULL)) != 0) return (ret); ret = __db_join(primary, curslist, dbcp, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_join_arg -- * Check DB->join arguments. */ int __db_join_arg(primary, curslist, flags) DB *primary; DBC **curslist; u_int32_t flags; { DB_ENV *dbenv; DB_TXN *txn; int i; dbenv = primary->dbenv; switch (flags) { case 0: case DB_JOIN_NOSORT: break; default: return (__db_ferr(dbenv, "DB->join", 0)); } if (curslist == NULL || curslist[0] == NULL) { __db_err(dbenv, "At least one secondary cursor must be specified to DB->join"); return (EINVAL); } txn = curslist[0]->txn; for (i = 1; curslist[i] != NULL; i++) if (curslist[i]->txn != txn) { __db_err(dbenv, "All secondary cursors must share the same transaction"); return (EINVAL); } return (0); } /* * __db_key_range_pp -- * DB->key_range pre/post processing. * * PUBLIC: int __db_key_range_pp * PUBLIC: __P((DB *, DB_TXN *, DBT *, DB_KEY_RANGE *, u_int32_t)); */ int __db_key_range_pp(dbp, txn, key, kr, flags) DB *dbp; DB_TXN *txn; DBT *key; DB_KEY_RANGE *kr; u_int32_t flags; { DBC *dbc; DB_ENV *dbenv; int handle_check, ret, t_ret; dbenv = dbp->dbenv; PANIC_CHECK(dbp->dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->key_range"); /* * !!! * The actual argument checking is simple, do it inline. */ if (flags != 0) return (__db_ferr(dbenv, "DB->key_range", 0)); /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, 1)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) return (ret); /* * !!! * The actual method call is simple, do it inline. */ switch (dbp->type) { case DB_BTREE: /* Acquire a cursor. */ if ((ret = __db_cursor(dbp, txn, &dbc, 0)) != 0) break; DEBUG_LWRITE(dbc, NULL, "bam_key_range", NULL, NULL, 0); ret = __bam_key_range(dbc, key, kr, flags); if ((t_ret = __db_c_close(dbc)) != 0 && ret == 0) ret = t_ret; break; case DB_HASH: case DB_QUEUE: case DB_RECNO: ret = __dbh_am_chk(dbp, DB_OK_BTREE); break; case DB_UNKNOWN: default: ret = __db_unknown_type(dbenv, "DB->key_range", dbp->type); break; } /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_open_pp -- * DB->open pre/post processing. * * PUBLIC: int __db_open_pp __P((DB *, DB_TXN *, * PUBLIC: const char *, const char *, DBTYPE, u_int32_t, int)); */ int __db_open_pp(dbp, txn, fname, dname, type, flags, mode) DB *dbp; DB_TXN *txn; const char *fname, *dname; DBTYPE type; u_int32_t flags; int mode; { DB_ENV *dbenv; int handle_check, nosync, remove_me, ret, txn_local; dbenv = dbp->dbenv; nosync = 1; remove_me = 0; PANIC_CHECK(dbenv); if ((ret = __db_open_arg(dbp, txn, fname, dname, type, flags)) != 0) return (ret); /* * Save the file and database names and flags. We do this here * because we don't pass all of the flags down into the actual * DB->open method call, we strip DB_AUTO_COMMIT at this layer. */ if ((fname != NULL && (ret = __os_strdup(dbenv, fname, &dbp->fname)) != 0) || (dname != NULL && (ret = __os_strdup(dbenv, dname, &dbp->dname)) != 0)) return (ret); dbp->open_flags = flags; /* Save the current DB handle flags for refresh. */ dbp->orig_flags = dbp->flags; /* * Create local transaction as necessary, check for consistent * transaction usage. */ txn_local = 0; if (IS_AUTO_COMMIT(dbenv, txn, flags)) { if ((ret = __db_txn_auto_init(dbenv, &txn)) != 0) return (ret); txn_local = 1; LF_CLR(DB_AUTO_COMMIT); } else if (txn != NULL &&!TXN_ON(dbenv)) return (__db_not_txn_env(dbenv)); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) goto err; if ((ret = __db_open(dbp, txn, fname, dname, type, flags, mode, PGNO_BASE_MD)) != 0) goto err; /* * You can open the database that describes the subdatabases in the * rest of the file read-only. The content of each key's data is * unspecified and applications should never be adding new records * or updating existing records. However, during recovery, we need * to open these databases R/W so we can redo/undo changes in them. * Likewise, we need to open master databases read/write during * rename and remove so we can be sure they're fully sync'ed, so * we provide an override flag for the purpose. */ if (dname == NULL && !IS_RECOVERING(dbenv) && !LF_ISSET(DB_RDONLY) && !LF_ISSET(DB_RDWRMASTER) && F_ISSET(dbp, DB_AM_SUBDB)) { __db_err(dbenv, "files containing multiple databases may only be opened read-only"); ret = EINVAL; goto err; } /* * Success: file creations have to be synchronous, otherwise we don't * care. */ if (F_ISSET(dbp, DB_AM_CREATED | DB_AM_CREATED_MSTR)) nosync = 0; /* Success: don't discard the file on close. */ F_CLR(dbp, DB_AM_DISCARD | DB_AM_CREATED | DB_AM_CREATED_MSTR); /* * If not transactional, remove the databases/subdatabases. If we're * transactional, the child transaction abort cleans up. */ err: if (ret != 0 && txn == NULL) { remove_me = F_ISSET(dbp, DB_AM_CREATED); if (F_ISSET(dbp, DB_AM_CREATED_MSTR) || (dname == NULL && remove_me)) /* Remove file. */ (void)__db_remove_int(dbp, txn, fname, NULL, DB_FORCE); else if (remove_me) /* Remove subdatabase. */ (void)__db_remove_int(dbp, txn, fname, dname, DB_FORCE); } /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (txn_local ? __db_txn_auto_resolve(dbenv, txn, nosync, ret) : ret); } /* * __db_open_arg -- * Check DB->open arguments. */ static int __db_open_arg(dbp, txn, fname, dname, type, flags) DB *dbp; DB_TXN *txn; const char *fname, *dname; DBTYPE type; u_int32_t flags; { DB_ENV *dbenv; u_int32_t ok_flags; int ret; dbenv = dbp->dbenv; /* Validate arguments. */ #undef OKFLAGS #define OKFLAGS \ (DB_AUTO_COMMIT | DB_CREATE | DB_DIRTY_READ | DB_EXCL | \ DB_FCNTL_LOCKING | DB_NO_AUTO_COMMIT | DB_NOMMAP | DB_RDONLY | \ DB_RDWRMASTER | DB_THREAD | DB_TRUNCATE | DB_WRITEOPEN | \ DB_TEMPTABLE | DB_DATAFILE | DB_OLCOMPACT) if ((ret = __db_fchk(dbenv, "DB->open", flags, OKFLAGS)) != 0) return (ret); if (LF_ISSET(DB_EXCL) && !LF_ISSET(DB_CREATE)) return (__db_ferr(dbenv, "DB->open", 1)); if (LF_ISSET(DB_RDONLY) && LF_ISSET(DB_CREATE)) return (__db_ferr(dbenv, "DB->open", 1)); #ifdef HAVE_VXWORKS if (LF_ISSET(DB_TRUNCATE)) { __db_err(dbenv, "DB_TRUNCATE not supported on VxWorks"); return (DB_OPNOTSUP); } #endif switch (type) { case DB_UNKNOWN: if (LF_ISSET(DB_CREATE|DB_TRUNCATE)) { __db_err(dbenv, "%s: DB_UNKNOWN type specified with DB_CREATE or DB_TRUNCATE", fname); return (EINVAL); } ok_flags = 0; break; case DB_BTREE: ok_flags = DB_OK_BTREE; break; case DB_HASH: #ifndef HAVE_HASH return (__db_no_hash_am(dbenv)); #endif ok_flags = DB_OK_HASH; break; case DB_QUEUE: #ifndef HAVE_QUEUE return (__db_no_queue_am(dbenv)); #endif ok_flags = DB_OK_QUEUE; break; case DB_RECNO: ok_flags = DB_OK_RECNO; break; default: __db_err(dbenv, "unknown type: %lu", (u_long)type); return (EINVAL); } if (ok_flags) DB_ILLEGAL_METHOD(dbp, ok_flags); /* The environment may have been created, but never opened. */ if (!F_ISSET(dbenv, DB_ENV_DBLOCAL | DB_ENV_OPEN_CALLED)) { __db_err(dbenv, "environment not yet opened"); return (EINVAL); } /* * Historically, you could pass in an environment that didn't have a * mpool, and DB would create a private one behind the scenes. This * no longer works. */ if (!F_ISSET(dbenv, DB_ENV_DBLOCAL) && !MPOOL_ON(dbenv)) { __db_err(dbenv, "environment did not include a memory pool"); return (EINVAL); } /* * You can't specify threads during DB->open if subsystems in the * environment weren't configured with them. */ if (LF_ISSET(DB_THREAD) && !F_ISSET(dbenv, DB_ENV_DBLOCAL | DB_ENV_THREAD)) { __db_err(dbenv, "environment not created using DB_THREAD"); return (EINVAL); } /* DB_TRUNCATE is neither transaction recoverable nor lockable. */ if (LF_ISSET(DB_TRUNCATE) && (LOCKING_ON(dbenv) || txn != NULL)) { __db_err(dbenv, "DB_TRUNCATE illegal with %s specified", LOCKING_ON(dbenv) ? "locking" : "transactions"); return (EINVAL); } /* Subdatabase checks. */ if (dname != NULL) { /* Subdatabases must be created in named files. */ if (fname == NULL) { __db_err(dbenv, "multiple databases cannot be created in temporary files"); return (EINVAL); } /* QAM can't be done as a subdatabase. */ if (type == DB_QUEUE) { __db_err(dbenv, "Queue databases must be one-per-file"); return (EINVAL); } } return (0); } /* * __db_pget_pp -- * DB->pget pre/post processing. * * PUBLIC: int __db_pget_pp * PUBLIC: __P((DB *, DB_TXN *, DBT *, DBT *, DBT *, u_int32_t)); */ int __db_pget_pp(dbp, txn, skey, pkey, data, flags) DB *dbp; DB_TXN *txn; DBT *skey, *pkey, *data; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->pget"); if ((ret = __db_pget_arg(dbp, pkey, flags)) != 0) return (ret); if ((ret = __db_get_arg(dbp, skey, data, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) return (ret); ret = __db_pget(dbp, txn, skey, pkey, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_pget -- * DB->pget. * * PUBLIC: int __db_pget * PUBLIC: __P((DB *, DB_TXN *, DBT *, DBT *, DBT *, u_int32_t)); */ int __db_pget(dbp, txn, skey, pkey, data, flags) DB *dbp; DB_TXN *txn; DBT *skey, *pkey, *data; u_int32_t flags; { DBC *dbc; int ret, t_ret; if ((ret = __db_cursor(dbp, txn, &dbc, 0)) != 0) return (ret); SET_RET_MEM(dbc, dbp); DEBUG_LREAD(dbc, txn, "__db_pget", skey, NULL, flags); /* * !!! * The actual method call is simple, do it inline. * * The underlying cursor pget will fill in a default DBT for null * pkeys, and use the cursor's returned-key memory internally to * store any intermediate primary keys. However, we've just set * the returned-key memory to the DB handle's key memory, which * is unsafe to use if the DB handle is threaded. If the pkey * argument is NULL, use the DBC-owned returned-key memory * instead; it'll go away when we close the cursor before we * return, but in this case that's just fine, as we're not * returning the primary key. */ if (pkey == NULL) dbc->rkey = &dbc->my_rkey; /* * The cursor is just a perfectly ordinary secondary database cursor. * Call its c_pget() method to do the dirty work. */ if (flags == 0 || flags == DB_RMW) flags |= DB_SET; ret = __db_c_pget(dbc, skey, pkey, data, flags); if ((t_ret = __db_c_close(dbc)) != 0 && ret == 0) ret = t_ret; return (ret); } /* * __db_pget_arg -- * Check DB->pget arguments. */ static int __db_pget_arg(dbp, pkey, flags) DB *dbp; DBT *pkey; u_int32_t flags; { DB_ENV *dbenv; int ret; dbenv = dbp->dbenv; if (!F_ISSET(dbp, DB_AM_SECONDARY)) { __db_err(dbenv, "DB->pget may only be used on secondary indices"); return (EINVAL); } if (LF_ISSET(DB_MULTIPLE | DB_MULTIPLE_KEY)) { __db_err(dbenv, "DB_MULTIPLE and DB_MULTIPLE_KEY may not be used on secondary indices"); return (EINVAL); } /* DB_CONSUME makes no sense on a secondary index. */ LF_CLR(DB_RMW); switch (flags) { case DB_CONSUME: case DB_CONSUME_WAIT: return (__db_ferr(dbenv, "DB->pget", 0)); default: /* __db_get_arg will catch the rest. */ break; } /* * We allow the pkey field to be NULL, so that we can make the * two-DBT get calls into wrappers for the three-DBT ones. */ if (pkey != NULL && (ret = __dbt_ferr(dbp, "primary key", pkey, 1)) != 0) return (ret); /* But the pkey field can't be NULL if we're doing a DB_GET_BOTH. */ if (pkey == NULL && flags == DB_GET_BOTH) { __db_err(dbenv, "DB_GET_BOTH on a secondary index requires a primary key"); return (EINVAL); } return (0); } /* * __db_put_pp -- * DB->put pre/post processing. * * PUBLIC: int __db_put_pp __P((DB *, DB_TXN *, DBT *, DBT *, u_int32_t)); */ int __db_put_pp(dbp, txn, key, data, flags) DB *dbp; DB_TXN *txn; DBT *key, *data; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret, txn_local; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->put"); if ((ret = __db_put_arg(dbp, key, data, flags)) != 0) return (ret); /* Create local transaction as necessary. */ if (IS_AUTO_COMMIT(dbenv, txn, flags)) { if ((ret = __db_txn_auto_init(dbenv, &txn)) != 0) return (ret); txn_local = 1; LF_CLR(DB_AUTO_COMMIT); } else txn_local = 0; /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, txn, DB_LOCK_INVALIDID, 0)) != 0) goto err; /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, txn != NULL)) != 0) goto err; ret = __db_put(dbp, txn, key, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); err: return (txn_local ? __db_txn_auto_resolve(dbenv, txn, 0, ret) : ret); } /* * __db_put_arg -- * Check DB->put arguments. */ static int __db_put_arg(dbp, key, data, flags) DB *dbp; DBT *key, *data; u_int32_t flags; { DB_ENV *dbenv; int ret, returnkey; dbenv = dbp->dbenv; returnkey = 0; /* Check for changes to a read-only tree. */ if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "put")); /* Check for puts on a secondary. */ if (F_ISSET(dbp, DB_AM_SECONDARY)) { __db_err(dbenv, "DB->put forbidden on secondary indices"); return (EINVAL); } /* Check for invalid function flags. */ LF_CLR(DB_AUTO_COMMIT); switch (flags) { case 0: case DB_NOOVERWRITE: break; case DB_APPEND: if (dbp->type != DB_RECNO && dbp->type != DB_QUEUE) goto err; returnkey = 1; break; case DB_NODUPDATA: if (F_ISSET(dbp, DB_AM_DUPSORT)) break; /* FALLTHROUGH */ default: err: return (__db_ferr(dbenv, "DB->put", 0)); } /* Check for invalid key/data flags. */ if ((ret = __dbt_ferr(dbp, "key", key, returnkey)) != 0) return (ret); if ((ret = __dbt_ferr(dbp, "data", data, 0)) != 0) return (ret); /* Check for partial puts in the presence of duplicates. */ if (F_ISSET(data, DB_DBT_PARTIAL) && (F_ISSET(dbp, DB_AM_DUP) || F_ISSET(key, DB_DBT_DUPOK))) { __db_err(dbenv, "a partial put in the presence of duplicates requires a cursor operation"); return (EINVAL); } return (0); } /* * __db_stat_pp -- * DB->stat pre/post processing. * * PUBLIC: int __db_stat_pp __P((DB *, void *, u_int32_t)); */ int __db_stat_pp(dbp, spp, flags) DB *dbp; void *spp; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret; dbenv = dbp->dbenv; PANIC_CHECK(dbp->dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->stat"); if ((ret = __db_stat_arg(dbp, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, 0)) != 0) return (ret); ret = __db_stat(dbp, spp, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_stat -- * DB->stat. * * PUBLIC: int __db_stat __P((DB *, void *, u_int32_t)); */ int __db_stat(dbp, spp, flags) DB *dbp; void *spp; u_int32_t flags; { DB_ENV *dbenv; DBC *dbc; int ret, t_ret; dbenv = dbp->dbenv; /* Acquire a cursor. */ if ((ret = __db_cursor(dbp, NULL, &dbc, 0)) != 0) return (ret); DEBUG_LWRITE(dbc, NULL, "DB->stat", NULL, NULL, flags); switch (dbp->type) { case DB_BTREE: case DB_RECNO: ret = __bam_stat(dbc, spp, flags); break; case DB_HASH: ret = __ham_stat(dbc, spp, flags); break; case DB_QUEUE: ret = __qam_stat(dbc, spp, flags); break; case DB_UNKNOWN: default: ret = (__db_unknown_type(dbenv, "DB->stat", dbp->type)); break; } if ((t_ret = __db_c_close(dbc)) != 0 && ret == 0) ret = t_ret; return (ret); } /* * __db_stat_arg -- * Check DB->stat arguments. */ static int __db_stat_arg(dbp, flags) DB *dbp; u_int32_t flags; { DB_ENV *dbenv; dbenv = dbp->dbenv; /* Check for invalid function flags. */ switch (flags) { case 0: case DB_FAST_STAT: case DB_CACHED_COUNTS: /* Deprecated and undocumented. */ break; case DB_RECORDCOUNT: /* Deprecated and undocumented. */ if (dbp->type == DB_RECNO) break; if (dbp->type == DB_BTREE && F_ISSET(dbp, DB_AM_RECNUM)) break; goto err; default: err: return (__db_ferr(dbenv, "DB->stat", 0)); } return (0); } /* * __db_sync_pp -- * DB->sync pre/post processing. * * PUBLIC: int __db_sync_pp __P((DB *, u_int32_t)); */ int __db_sync_pp(dbp, flags) DB *dbp; u_int32_t flags; { DB_ENV *dbenv; int handle_check, ret; dbenv = dbp->dbenv; PANIC_CHECK(dbp->dbenv); DB_ILLEGAL_BEFORE_OPEN(dbp, "DB->sync"); /* * !!! * The actual argument checking is simple, do it inline. */ if (flags != 0) return (__db_ferr(dbenv, "DB->sync", 0)); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, 0)) != 0) return (ret); ret = __db_sync(dbp); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_close_pp -- * DBC->c_close pre/post processing. * * PUBLIC: int __db_c_close_pp __P((DBC *)); */ int __db_c_close_pp(dbc) DBC *dbc; { DB_ENV *dbenv; DB *dbp; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); /* * If the cursor is already closed we have a serious problem, and we * assume that the cursor isn't on the active queue. Don't do any of * the remaining cursor close processing. */ if (!F_ISSET(dbc, DBC_ACTIVE)) { if (dbp != NULL) __db_err(dbenv, "Closing already-closed cursor"); DB_ASSERT(0); return (EINVAL); } /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 0, dbc->txn != NULL)) != 0) return (ret); ret = __db_c_close(dbc); /* Release replication block. */ if (handle_check) __env_rep_exit(dbenv); return (ret); } /* * __db_c_count_pp -- * DBC->c_count pre/post processing. * * PUBLIC: int __db_c_count_pp __P((DBC *, db_recno_t *, u_int32_t)); */ int __db_c_count_pp(dbc, recnop, flags) DBC *dbc; db_recno_t *recnop; u_int32_t flags; { DB_ENV *dbenv; DB *dbp; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); /* * !!! * The actual argument checking is simple, do it inline. */ if (flags != 0) return (__db_ferr(dbenv, "DBcursor->count", 0)); /* * The cursor must be initialized, return EINVAL for an invalid cursor, * otherwise 0. */ if (!IS_INITIALIZED(dbc)) return (__db_curinval(dbenv)); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); ret = __db_c_count(dbc, recnop); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_del_pp -- * DBC->c_del pre/post processing. * * PUBLIC: int __db_c_del_pp __P((DBC *, u_int32_t)); */ int __db_c_del_pp(dbc, flags) DBC *dbc; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_c_del_arg(dbc, flags)) != 0) return (ret); /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, dbc->txn, dbc->locker, 0)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); DEBUG_LWRITE(dbc, dbc->txn, "DBcursor->del", NULL, NULL, flags); ret = __db_c_del(dbc, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_del_arg -- * Check DBC->c_del arguments. * * PUBLIC: int __db_c_del_arg __P((DBC *, u_int32_t)); */ int __db_c_del_arg(dbc, flags) DBC *dbc; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; dbp = dbc->dbp; dbenv = dbp->dbenv; /* Check for changes to a read-only tree. */ if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "DBcursor->del")); /* Check for invalid function flags. */ switch (flags) { case 0: break; case DB_UPDATE_SECONDARY: DB_ASSERT(F_ISSET(dbp, DB_AM_SECONDARY)); break; default: return (__db_ferr(dbenv, "DBcursor->del", 0)); } /* * The cursor must be initialized, return EINVAL for an invalid cursor, * otherwise 0. */ if (!IS_INITIALIZED(dbc)) return (__db_curinval(dbenv)); return (0); } /* * __db_c_dup_pp -- * DBC->c_dup pre/post processing. * * PUBLIC: int __db_c_dup_pp __P((DBC *, DBC **, u_int32_t)); */ int __db_c_dup_pp(dbc, dbcp, flags) DBC *dbc, **dbcp; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); /* * !!! * The actual argument checking is simple, do it inline. */ if (flags != 0 && flags != DB_POSITION) return (__db_ferr(dbenv, "DBcursor->dup", 0)); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); ret = __db_c_dup(dbc, dbcp, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_get_dup_pp -- * * DBC->c_get_dup pre/post processing. * * PUBLIC: int __db_c_get_dup_pp __P((DBC *, DBC **, DBT *, DBT *, u_int32_t)); */ int __db_c_get_dup_pp(dbc, dbcp, key, data, flags) DBC *dbc, **dbcp; DBT *key, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_c_get_arg(dbc, key, data, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); DEBUG_LREAD(dbc, dbc->txn, "DBcursor->get", flags == DB_SET ||flags == DB_SET_RANGE ? key : NULL, NULL, flags); ret = __db_c_get_dup(dbc, dbcp, key, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_get_pp -- * DBC->c_get pre/post processing. * * PUBLIC: int __db_c_get_pp __P((DBC *, DBT *, DBT *, u_int32_t)); */ int __db_c_get_pp(dbc, key, data, flags) DBC *dbc; DBT *key, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_c_get_arg(dbc, key, data, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); DEBUG_LREAD(dbc, dbc->txn, "DBcursor->get", flags == DB_SET || flags == DB_SET_RANGE ? key : NULL, NULL, flags); ret = __db_c_get(dbc, key, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_get_arg -- * Common DBC->get argument checking, used by both DBC->get and DBC->pget. */ static int __db_c_get_arg(dbc, key, data, flags) DBC *dbc; DBT *key, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int dirty, multi, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; /* * Typically in checking routines that modify the flags, we have * to save them and restore them, because the checking routine * calls the work routine. However, this is a pure-checking * routine which returns to a function that calls the work routine, * so it's OK that we do not save and restore the flags, even though * we modify them. * * Check for read-modify-write validity. DB_RMW doesn't make sense * with CDB cursors since if you're going to write the cursor, you * had to create it with DB_WRITECURSOR. Regardless, we check for * LOCKING_ON and not STD_LOCKING, as we don't want to disallow it. * If this changes, confirm that DB does not itself set the DB_RMW * flag in a path where CDB may have been configured. */ dirty = 0; if (LF_ISSET(DB_DIRTY_READ | DB_RMW)) { if (!LOCKING_ON(dbenv)) return (__db_fnl(dbenv, "DBcursor->get")); if (LF_ISSET(DB_DIRTY_READ)) dirty = 1; LF_CLR(DB_DIRTY_READ | DB_RMW); } multi = 0; if (LF_ISSET(DB_MULTIPLE | DB_MULTIPLE_KEY)) { multi = 1; if (LF_ISSET(DB_MULTIPLE) && LF_ISSET(DB_MULTIPLE_KEY)) goto multi_err; LF_CLR(DB_MULTIPLE | DB_MULTIPLE_KEY); } /* Check for invalid function flags. */ switch (flags) { case DB_CONSUME: case DB_CONSUME_WAIT: if (dirty) { __db_err(dbenv, "DB_DIRTY_READ is not supported with DB_CONSUME or DB_CONSUME_WAIT"); return (EINVAL); } if (dbp->type != DB_QUEUE) goto err; break; case DB_CURRENT: case DB_FIRST: case DB_GET_BOTH: case DB_GET_BOTH_RANGE: case DB_NEXT: case DB_NEXT_DUP: case DB_NEXT_VALUE: case DB_NEXT_NODUP: case DB_SET: case DB_SET_RANGE: break; case DB_LAST: case DB_PREV: case DB_PREV_VALUE: case DB_PREV_NODUP: if (multi) multi_err: return (__db_ferr(dbenv, "DBcursor->get", 1)); break; case DB_GET_BOTHC: if (dbp->type == DB_QUEUE) goto err; break; case DB_GET_RECNO: /* * The one situation in which this might be legal with a * non-RECNUM dbp is if dbp is a secondary and its primary is * DB_AM_RECNUM. */ if (!F_ISSET(dbp, DB_AM_RECNUM) && (!F_ISSET(dbp, DB_AM_SECONDARY) || !F_ISSET(dbp->s_primary, DB_AM_RECNUM))) goto err; break; case DB_SET_RECNO: if (!F_ISSET(dbp, DB_AM_RECNUM)) goto err; break; default: err: return (__db_ferr(dbenv, "DBcursor->get", 0)); } /* Check for invalid key/data flags. */ if ((ret = __dbt_ferr(dbp, "key", key, 0)) != 0) return (ret); if ((ret = __dbt_ferr(dbp, "data", data, 0)) != 0) return (ret); if (multi) { if (!F_ISSET(data, DB_DBT_USERMEM)) { __db_err(dbenv, "DB_MULTIPLE/DB_MULTIPLE_KEY require DB_DBT_USERMEM be set"); return (EINVAL); } if (F_ISSET(key, DB_DBT_PARTIAL) || F_ISSET(data, DB_DBT_PARTIAL)) { __db_err(dbenv, "DB_MULTIPLE/DB_MULTIPLE_KEY do not support DB_DBT_PARTIAL"); return (EINVAL); } if (data->ulen < 1024 || data->ulen < dbp->pgsize || data->ulen % 1024 != 0) { __db_err(dbenv, "%s%s", "DB_MULTIPLE/DB_MULTIPLE_KEY buffers must be ", "aligned, at least page size and multiples of 1KB"); return (EINVAL); } } /* * The cursor must be initialized for DB_CURRENT, DB_GET_RECNO and * DB_NEXT_DUP. Return EINVAL for an invalid cursor, otherwise 0. */ if (!IS_INITIALIZED(dbc) && (flags == DB_CURRENT || flags == DB_GET_RECNO || flags == DB_NEXT_DUP)) return (__db_curinval(dbenv)); /* Check for consistent transaction usage. */ if (LF_ISSET(DB_RMW) && (ret = __db_check_txn(dbp, dbc->txn, dbc->locker, 0)) != 0) return (ret); return (0); } /* * __db_c_pget_pp -- * DBC->c_pget pre/post processing. * * PUBLIC: int __db_c_pget_pp __P((DBC *, DBT *, DBT *, DBT *, u_int32_t)); */ int __db_c_pget_pp(dbc, skey, pkey, data, flags) DBC *dbc; DBT *skey, *pkey, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_c_pget_arg(dbc, pkey, flags)) != 0) return (ret); if ((ret = __db_c_get_arg(dbc, skey, data, flags)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); ret = __db_c_pget(dbc, skey, pkey, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_pget_arg -- * Check DBC->pget arguments. */ static int __db_c_pget_arg(dbc, pkey, flags) DBC *dbc; DBT *pkey; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int ret; dbp = dbc->dbp; dbenv = dbp->dbenv; if (!F_ISSET(dbp, DB_AM_SECONDARY)) { __db_err(dbenv, "DBcursor->pget may only be used on secondary indices"); return (EINVAL); } if (LF_ISSET(DB_MULTIPLE | DB_MULTIPLE_KEY)) { __db_err(dbenv, "DB_MULTIPLE and DB_MULTIPLE_KEY may not be used on secondary indices"); return (EINVAL); } switch (LF_ISSET(~DB_RMW)) { case DB_CONSUME: case DB_CONSUME_WAIT: /* These flags make no sense on a secondary index. */ return (__db_ferr(dbenv, "DBcursor->pget", 0)); case DB_GET_BOTH: /* DB_GET_BOTH is "get both the primary and the secondary". */ if (pkey == NULL) { __db_err(dbenv, "DB_GET_BOTH requires both a secondary and a primary key"); return (EINVAL); } break; default: /* __db_c_get_arg will catch the rest. */ break; } /* * We allow the pkey field to be NULL, so that we can make the * two-DBT get calls into wrappers for the three-DBT ones. */ if (pkey != NULL && (ret = __dbt_ferr(dbp, "primary key", pkey, 0)) != 0) return (ret); /* But the pkey field can't be NULL if we're doing a DB_GET_BOTH. */ if (pkey == NULL && (flags & DB_OPFLAGS_MASK) == DB_GET_BOTH) { __db_err(dbenv, "DB_GET_BOTH on a secondary index requires a primary key"); return (EINVAL); } return (0); } /* * __db_c_put_pp -- * DBC->put pre/post processing. * * PUBLIC: int __db_c_put_pp __P((DBC *, DBT *, DBT *, u_int32_t)); */ int __db_c_put_pp(dbc, key, data, flags) DBC *dbc; DBT *key, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int handle_check, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; PANIC_CHECK(dbenv); if ((ret = __db_c_put_arg(dbc, key, data, flags)) != 0) return (ret); /* Check for consistent transaction usage. */ if ((ret = __db_check_txn(dbp, dbc->txn, dbc->locker, 0)) != 0) return (ret); /* Check for replication block. */ handle_check = IS_REPLICATED(dbenv, dbp); if (handle_check && (ret = __db_rep_enter(dbp, 1, dbc->txn != NULL)) != 0) return (ret); DEBUG_LWRITE(dbc, dbc->txn, "DBcursor->put", flags == DB_KEYFIRST || flags == DB_KEYLAST || flags == DB_NODUPDATA || flags == DB_UPDATE_SECONDARY ? key : NULL, data, flags); ret =__db_c_put(dbc, key, data, flags); /* Release replication block. */ if (handle_check) __db_rep_exit(dbenv); return (ret); } /* * __db_c_put_arg -- * Check DBC->put arguments. */ static int __db_c_put_arg(dbc, key, data, flags) DBC *dbc; DBT *key, *data; u_int32_t flags; { DB *dbp; DB_ENV *dbenv; int key_flags, ret; dbp = dbc->dbp; dbenv = dbp->dbenv; key_flags = 0; /* Check for changes to a read-only tree. */ if (IS_READONLY(dbp)) return (__db_rdonly(dbenv, "c_put")); /* Check for puts on a secondary. */ if (F_ISSET(dbp, DB_AM_SECONDARY)) { if (flags == DB_UPDATE_SECONDARY) flags = DB_KEYLAST; else { __db_err(dbenv, "DBcursor->put forbidden on secondary indices"); return (EINVAL); } } /* Check for invalid function flags. */ switch (flags) { case DB_AFTER: case DB_BEFORE: switch (dbp->type) { case DB_BTREE: case DB_HASH: /* Only with unsorted duplicates. */ if (!F_ISSET(dbp, DB_AM_DUP)) goto err; if (dbp->dup_compare != NULL) goto err; break; case DB_QUEUE: /* Not permitted. */ goto err; case DB_RECNO: /* Only with mutable record numbers. */ if (!F_ISSET(dbp, DB_AM_RENUMBER)) goto err; key_flags = 1; break; case DB_UNKNOWN: default: goto err; } break; case DB_CURRENT: /* * If there is a comparison function, doing a DB_CURRENT * must not change the part of the data item that is used * for the comparison. */ break; case DB_NODUPDATA: if (!F_ISSET(dbp, DB_AM_DUPSORT)) goto err; /* FALLTHROUGH */ case DB_KEYFIRST: case DB_KEYLAST: key_flags = 1; break; default: err: return (__db_ferr(dbenv, "DBcursor->put", 0)); } /* Check for invalid key/data flags. */ if (key_flags && (ret = __dbt_ferr(dbp, "key", key, 0)) != 0) return (ret); if ((ret = __dbt_ferr(dbp, "data", data, 0)) != 0) return (ret); /* * The cursor must be initialized for anything other than DB_KEYFIRST * and DB_KEYLAST, return EINVAL for an invalid cursor, otherwise 0. */ if (!IS_INITIALIZED(dbc) && flags != DB_KEYFIRST && flags != DB_KEYLAST && flags != DB_NODUPDATA) return (__db_curinval(dbenv)); return (0); } /* * __dbt_ferr -- * Check a DBT for flag errors. */ static int __dbt_ferr(dbp, name, dbt, check_thread) const DB *dbp; const char *name; const DBT *dbt; int check_thread; { DB_ENV *dbenv; int ret; dbenv = dbp->dbenv; /* * Check for invalid DBT flags. We allow any of the flags to be * specified to any DB or DBcursor call so that applications can * set DB_DBT_MALLOC when retrieving a data item from a secondary * database and then specify that same DBT as a key to a primary * database, without having to clear flags. */ if ((ret = __db_fchk(dbenv, name, dbt->flags, DB_DBT_APPMALLOC | DB_DBT_MALLOC | DB_DBT_DUPOK | DB_DBT_REALLOC | DB_DBT_USERMEM | DB_DBT_PARTIAL)) != 0) return (ret); switch (F_ISSET(dbt, DB_DBT_MALLOC | DB_DBT_REALLOC | DB_DBT_USERMEM)) { case 0: case DB_DBT_MALLOC: case DB_DBT_REALLOC: case DB_DBT_USERMEM: break; default: return (__db_ferr(dbenv, name, 1)); } if (check_thread && DB_IS_THREADED(dbp) && !F_ISSET(dbt, DB_DBT_MALLOC | DB_DBT_REALLOC | DB_DBT_USERMEM)) { __db_err(dbenv, "DB_THREAD mandates memory allocation flag on DBT %s", name); return (EINVAL); } return (0); } /* * __db_rdonly -- * Common readonly message. */ static int __db_rdonly(dbenv, name) const DB_ENV *dbenv; const char *name; { __db_err(dbenv, "%s: attempt to modify a read-only tree", name); return (EACCES); } /* * __db_invwrite -- * Invalid write options */ static int __db_invwrite(dbenv, name) const DB_ENV *dbenv; const char *name; { __db_err(dbenv, "%s: cannot write using a page-order cursor", name); return (EINVAL); } /* * __db_curinval * Report that a cursor is in an invalid state. */ static int __db_curinval(dbenv) const DB_ENV *dbenv; { __db_err(dbenv, "Cursor position must be set before performing this operation"); return (EINVAL); } /* * __db_txn_auto_init -- * Handle DB_AUTO_COMMIT initialization. * * PUBLIC: int __db_txn_auto_init __P((DB_ENV *, DB_TXN **)); */ int __db_txn_auto_init(dbenv, txnidp) DB_ENV *dbenv; DB_TXN **txnidp; { if (*txnidp != NULL) { __db_err(dbenv, "DB_AUTO_COMMIT may not be specified along with a transaction handle"); return (EINVAL); } if (!TXN_ON(dbenv)) { __db_err(dbenv, "DB_AUTO_COMMIT may not be specified in non-transactional environment"); return (EINVAL); } /* * We're creating a transaction for the user, and we want it to block * if replication recovery is running. Call the user-level API. */ return (dbenv->txn_begin(dbenv, NULL, txnidp, 0)); } /* * __db_txn_auto_resolve -- * Handle DB_AUTO_COMMIT resolution. * * PUBLIC: int __db_txn_auto_resolve __P((DB_ENV *, DB_TXN *, int, int)); */ int __db_txn_auto_resolve(dbenv, txn, nosync, ret) DB_ENV *dbenv; DB_TXN *txn; int nosync, ret; { int t_ret; /* * We're resolving a transaction for the user, and must decrement the * replication handle count. Call the user-level API. */ if (ret == 0) return (txn->commit(txn, nosync ? DB_TXN_NOSYNC : 0)); if ((t_ret = txn->abort(txn)) != 0) return (__db_panic(dbenv, t_ret)); return (ret); }
239579.c
#include "tai.h" void tai_add(struct tai *t,const struct tai *u,const struct tai *v) { t->x = u->x + v->x; }
41202.c
/******************************************************************************* XX Mission (c) 1986 UPL Video hardware driver by Uki 31/Mar/2001 - *******************************************************************************/ #include "driver.h" UINT8 *xxmissio_bgram; UINT8 *xxmissio_fgram; UINT8 *xxmissio_spriteram; static tilemap *bg_tilemap; static tilemap *fg_tilemap; static UINT8 xscroll; static UINT8 yscroll; static UINT8 flipscreen; WRITE8_DEVICE_HANDLER( xxmissio_scroll_x_w ) { xscroll = data; } WRITE8_DEVICE_HANDLER( xxmissio_scroll_y_w ) { yscroll = data; } WRITE8_HANDLER( xxmissio_flipscreen_w ) { flipscreen = data & 0x01; } WRITE8_HANDLER( xxmissio_bgram_w ) { int x = (offset + (xscroll >> 3)) & 0x1f; offset = (offset & 0x7e0) | x; xxmissio_bgram[offset] = data; } READ8_HANDLER( xxmissio_bgram_r ) { int x = (offset + (xscroll >> 3)) & 0x1f; offset = (offset & 0x7e0) | x; return xxmissio_bgram[offset]; } WRITE8_HANDLER( xxmissio_paletteram_w ) { paletteram_BBGGRRII_w(space,offset,data); } /****************************************************************************/ static TILE_GET_INFO( get_bg_tile_info ) { int code = ((xxmissio_bgram[0x400 | tile_index] & 0xc0) << 2) | xxmissio_bgram[0x000 | tile_index]; int color = xxmissio_bgram[0x400 | tile_index] & 0x0f; SET_TILE_INFO(2, code, color, 0); } static TILE_GET_INFO( get_fg_tile_info ) { int code = xxmissio_fgram[0x000 | tile_index]; int color = xxmissio_fgram[0x400 | tile_index] & 0x07; SET_TILE_INFO(0, code, color, 0); } VIDEO_START( xxmissio ) { bg_tilemap = tilemap_create(machine, get_bg_tile_info, tilemap_scan_rows, 16, 8, 32, 32); fg_tilemap = tilemap_create(machine, get_fg_tile_info, tilemap_scan_rows, 16, 8, 32, 32); tilemap_set_scroll_cols(bg_tilemap, 1); tilemap_set_scroll_rows(bg_tilemap, 1); tilemap_set_scrolldx(bg_tilemap, 2, 12); tilemap_set_transparent_pen(fg_tilemap, 0); } static void draw_sprites(bitmap_t *bitmap, const rectangle *cliprect, const gfx_element *gfx) { int offs; int chr,col; int x,y,px,py,fx,fy; for (offs=0; offs<0x800; offs +=0x20) { chr = xxmissio_spriteram[offs]; col = xxmissio_spriteram[offs+3]; fx = ((col & 0x10) >> 4) ^ flipscreen; fy = ((col & 0x20) >> 5) ^ flipscreen; x = xxmissio_spriteram[offs+1]*2; y = xxmissio_spriteram[offs+2]; chr = chr + ((col & 0x40) << 2); col = col & 0x07; if (flipscreen==0) { px = x-8; py = y; } else { px = 480-x-6; py = 240-y; } px &= 0x1ff; drawgfx_transpen(bitmap,cliprect,gfx, chr, col, fx,fy, px,py,0); if (px>0x1e0) drawgfx_transpen(bitmap,cliprect,gfx, chr, col, fx,fy, px-0x200,py,0); } } VIDEO_UPDATE( xxmissio ) { tilemap_mark_all_tiles_dirty_all(screen->machine); tilemap_set_flip_all(screen->machine, flipscreen ? TILEMAP_FLIPX | TILEMAP_FLIPY : 0); tilemap_set_scrollx(bg_tilemap, 0, xscroll * 2); tilemap_set_scrolly(bg_tilemap, 0, yscroll); tilemap_draw(bitmap, cliprect, bg_tilemap, 0, 0); draw_sprites(bitmap, cliprect, screen->machine->gfx[1]); tilemap_draw(bitmap, cliprect, fg_tilemap, 0, 0); return 0; }
66544.c
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) /* Copyright Authors of Cilium */ #include <bpf/ctx/skb.h> #include <bpf/api.h> /* most values taken from node_config.h */ #define ENDPOINTS_MAP test_cilium_lxc #define POLICY_PROG_MAP_SIZE ENDPOINTS_MAP_SIZE #define METRICS_MAP test_cilium_metrics #define ENDPOINTS_MAP_SIZE 65536 #define IPCACHE_MAP_SIZE 512000 #define METRICS_MAP_SIZE 65536 #define EVENTS_MAP test_events_map #define CT_MAP_TCP6 test_cilium_ct_tcp6_65535 #define CT_MAP_ANY6 test_cilium_ct_any6_65535 #define CT_MAP_TCP4 test_cilium_ct_tcp4_65535 #define CT_MAP_ANY4 test_cilium_ct_any4_65535 #define CT_MAP_SIZE_TCP 4096 #define CT_MAP_SIZE_ANY 4096 #define CT_CONNECTION_LIFETIME_TCP 21600 #define CT_CONNECTION_LIFETIME_NONTCP 60 #define CT_SERVICE_LIFETIME_TCP 21600 #define CT_SERVICE_LIFETIME_NONTCP 60 #define CT_SERVICE_CLOSE_REBALANCE 30 #define CT_SYN_TIMEOUT 60 #define CT_CLOSE_TIMEOUT 10 #define CT_REPORT_INTERVAL 5 #define CT_REPORT_FLAGS 0xff #define MTU 1500 #define DEBUG #include <lib/dbg.h> #include <lib/conntrack.h> #include <lib/conntrack_map.h> __section("action/test-nop") int test_nop(struct __ctx_buff __maybe_unused *ctx) { return CTX_ACT_OK; } __section("action/test-map") int test_map(struct __ctx_buff __maybe_unused *ctx) { /* * Declare static, otherwise this ends up in .rodata. * On new clang + pre-5.12 kernel, this causes BTF to be rejected, * since the Datasec is patched up to the real size of .rodata, * but vlen remains 0, since this is a var with local scope. * See https://lore.kernel.org/bpf/[email protected]. */ static struct ipv4_ct_tuple ct_key = (struct ipv4_ct_tuple){ .saddr = bpf_htonl(16843009), /* 1.1.1.1 */ .daddr = bpf_htonl(16843010), /* 1.1.1.2 */ .sport = bpf_htons(1001), .dport = bpf_htons(1002), .nexthdr = 0, .flags = 0, }; struct ct_entry ct_val = (struct ct_entry){ .rx_packets = 1000, .tx_packets = 1000, }; map_update_elem(&CT_MAP_TCP4, &ct_key, &ct_val, 0); return CTX_ACT_OK; } __section("action/test-ct4-rst1") int test_ct4_rst1(struct __ctx_buff *ctx) { struct ipv4_ct_tuple tuple = {}; void *data, *data_end; struct iphdr *ip4; int l3_off = ETH_HLEN, l4_off; struct ct_state ct_state = {}, ct_state_new = {}; __u16 proto; __u32 monitor = 0; int ret; bpf_clear_meta(ctx); if (!validate_ethertype(ctx, &proto)) { ret = DROP_UNSUPPORTED_L2; goto out; } if (!revalidate_data(ctx, &data, &data_end, &ip4)) { ret = DROP_INVALID; goto out; } tuple.nexthdr = ip4->protocol; tuple.daddr = ip4->daddr; tuple.saddr = ip4->saddr; l4_off = l3_off + ipv4_hdrlen(ip4); ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, CT_EGRESS, &ct_state, &monitor); switch (ret) { case CT_NEW: ct_state_new.node_port = ct_state.node_port; ct_state_new.ifindex = ct_state.ifindex; ret = ct_create4(get_ct_map4(&tuple), &CT_MAP_ANY4, &tuple, ctx, CT_EGRESS, &ct_state_new, false, false); break; default: ret = -1; break; } out: /* mark the termination of our program so that the go program stops * blocking on the ring buffer */ cilium_dbg(ctx, DBG_UNSPEC, 0xe3d, 0xe3d); return ret; } __section("action/test-ct4-rst2") int test_ct4_rst2(struct __ctx_buff *ctx) { struct ipv4_ct_tuple tuple = {}; void *data, *data_end; struct iphdr *ip4; int l3_off = ETH_HLEN, l4_off; struct ct_state ct_state = {}; __u16 proto; __u32 monitor = 0; int ret; bpf_clear_meta(ctx); if (!validate_ethertype(ctx, &proto)) { ret = DROP_UNSUPPORTED_L2; goto out; } if (!revalidate_data(ctx, &data, &data_end, &ip4)) { ret = DROP_INVALID; goto out; } tuple.nexthdr = ip4->protocol; tuple.daddr = ip4->daddr; tuple.saddr = ip4->saddr; l4_off = l3_off + ipv4_hdrlen(ip4); ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, CT_INGRESS, &ct_state, &monitor); cilium_dbg(ctx, DBG_UNSPEC, 1000, ret); out: /* mark the termination of our program so that the go program stops * blocking on the ring buffer */ cilium_dbg(ctx, DBG_UNSPEC, 0xe3d, 0xe3d); return CTX_ACT_OK; } BPF_LICENSE("Dual BSD/GPL");
511534.c
/* * Copyright (c) 2010-2016 SURFnet bv * Copyright (c) 2016 Roland van Rijswijk-Deij * 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 SURFnet bv 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * The Extensible IP Monitor (EEMO) * IP reassembly */ #include "config.h" #include "ip_reassemble.h" #include "eemo.h" #include "eemo_packet.h" #include "eemo_log.h" #include "eemo_config.h" #include <pcap.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> /* Set this define to provide extra debug logging about reassembly */ /*#define FRAG_DBG*/ #undef FRAG_DBG #ifdef FRAG_DBG #define FRAG_MSG(...) DEBUG_MSG(__VA_ARGS__) #else #define FRAG_MSG(...) #endif /* Reassembly identification of an IPv4 packet */ typedef struct { int af; struct in_addr src; struct in_addr dst; u_char proto; u_short id; } ip4_reasm_id; /* Reassembly identification of an IPv6 packet */ typedef struct { int af; struct in6_addr src; struct in6_addr dst; u_int id; } ip6_reasm_id; /* Generic reassembly identification structure */ typedef struct { int af; } generic_reasm_id; /* Abstract reassembly identification type */ typedef union { ip4_reasm_id ip4_id; ip6_reasm_id ip6_id; generic_reasm_id gen_id; } ip_reasm_id; /* Reassembly buffer type */ typedef struct { ip_reasm_id id; time_t first_frag_arr; /* arrival time of first fragment, needed to time reassembly */ int in_use; /* is the buffer in use? */ int reassembled; /* set to true if reassembly is complete */ u_char buffer[65536]; u_short first_hole; /* pointer to the first hole descriptor */ u_short frag_count; /* total number of fragments that make up the packet */ int pkt_len; /* the expected reassembled length; set to -1 if unknown */ } ip_reasm_buf; /* Hole descriptor */ #define HD_NULL 0xffff #pragma pack(push,1) typedef struct { u_short hd_first; /* Offset of first octet */ u_short hd_last; /* Offset of last octet */ u_short hd_next; /* Offset of next hole descriptor */ } hole_desc; #pragma pack(pop) /* Module variables */ static ip_reasm_buf* ra_buffers = NULL; static int ra_buf_count = -1; static int ra_timeout = -1; static int ra_enabled = 1; static int ra_log = 1; /* Initialise reassembly module */ eemo_rv eemo_reasm_init(void) { int i = 0; if (eemo_conf_get_bool("ip", "reassemble", &ra_enabled, 1) != ERV_OK) { ERROR_MSG("Failed to retrieve configuration setting for IP reassembly"); return ERV_CONFIG_ERROR; } if (!ra_enabled) { INFO_MSG("IP reassembly is disabled"); return ERV_OK; } if ((eemo_conf_get_int("ip", "reassembly_timeout", &ra_timeout, 30) != ERV_OK) || (ra_timeout <= 0)) { ERROR_MSG("Failed to retrieve configuration setting for IP reassembly timeout"); return ERV_CONFIG_ERROR; } if (ra_timeout < 30) { WARNING_MSG("IP reassembly timeout is set to a value below that of most operating systems (%ds < 30s)", ra_timeout); } if ((eemo_conf_get_int("ip", "reassembly_buffers", &ra_buf_count, 1000) != ERV_OK) || (ra_buf_count <= 0)) { ERROR_MSG("Failed to retrieve number of IP reassembly buffers from the configuration"); return ERV_CONFIG_ERROR; } if (eemo_conf_get_bool("ip", "reassemble_log", &ra_log, 1) != ERV_OK) { ERROR_MSG("Failed to retrieve reassembly log setting from the configuration"); return ERV_CONFIG_ERROR; } /* Allocate and clear reassembly buffers */ ra_buffers = (ip_reasm_buf*) malloc(ra_buf_count * sizeof(ip_reasm_buf)); for (i = 0; i < ra_buf_count; i++) { memset(&ra_buffers[i], 0, sizeof(ip_reasm_buf)); ra_buffers[i].pkt_len = -1; } INFO_MSG("Initialised %d IP reassembly buffers", ra_buf_count); return ERV_OK; } /* Uninitialise reassembly module */ eemo_rv eemo_reasm_finalize(void) { if (ra_enabled) { int i = 0; int in_use_ct = 0; int reass_ct = 0; for (i = 0; i < ra_buf_count; i++) { if (ra_buffers[i].in_use) { if (!ra_buffers[i].reassembled) { in_use_ct++; } else { reass_ct++; } } } if (in_use_ct > 0) { WARNING_MSG("%d reassembly buffers with partially reassembled packets still in use on exit", in_use_ct); } if (reass_ct > 0) { WARNING_MSG("%d reassembly buffers with fully reassembled packets still in use on exit", reass_ct); } /* Clean up */ free(ra_buffers); } INFO_MSG("Finalised IP reassembly module"); return ERV_OK; } /* Get a string representation of the source IP address in a reassembly ID */ static const char* eemo_reasm_int_get_src_str(const ip_reasm_id* id) { assert(id != NULL); /* WARNING! It is not safe to call this function from multiple threads concurrently */ static char ip_str[INET6_ADDRSTRLEN] = { 0 }; const generic_reasm_id* gen_id = &id->gen_id; const ip4_reasm_id* ip4_id = &id->ip4_id; const ip6_reasm_id* ip6_id = &id->ip6_id; if (gen_id->af == AF_INET) { if (inet_ntop(AF_INET, &ip4_id->src, ip_str, INET6_ADDRSTRLEN) == NULL) { WARNING_MSG("Failed to convert IPv4 source address from reassembly ID to string"); return NULL; } } else if (gen_id->af == AF_INET6) { if (inet_ntop(AF_INET6, &ip6_id->src, ip_str, INET6_ADDRSTRLEN) == NULL) { WARNING_MSG("Failed to convert IPv6 source address from reassembly ID to string"); return NULL; } } else { ERROR_MSG("Reassembly ID with unknown address family %d", gen_id->af); return NULL; } return &ip_str[0]; } /* Get a string representation of the destination IP address in a reassembly ID */ static const char* eemo_reasm_int_get_dst_str(const ip_reasm_id* id) { assert(id != NULL); /* WARNING! It is not safe to call this function from multiple threads concurrently */ static char ip_str[INET6_ADDRSTRLEN] = { 0 }; const generic_reasm_id* gen_id = &id->gen_id; const ip4_reasm_id* ip4_id = &id->ip4_id; const ip6_reasm_id* ip6_id = &id->ip6_id; if (gen_id->af == AF_INET) { if (inet_ntop(AF_INET, &ip4_id->dst, ip_str, INET6_ADDRSTRLEN) == NULL) { WARNING_MSG("Failed to convert IPv4 destination address from reassembly ID to string"); return NULL; } } else if (gen_id->af == AF_INET6) { if (inet_ntop(AF_INET6, &ip6_id->dst, ip_str, INET6_ADDRSTRLEN) == NULL) { WARNING_MSG("Failed to convert IPv6 destination address from reassembly ID to string"); return NULL; } } else { ERROR_MSG("Reassembly ID with unknown address family %d", gen_id->af); return NULL; } return &ip_str[0]; } /* Find a reassembly buffer for the packet with the specified ID or allocate an empty one */ static ip_reasm_buf* eemo_reasm_int_find_buf(const ip_reasm_id* id) { assert(id != NULL); int i = 0; ip_reasm_buf* rv = NULL; time_t now = time(NULL); ip_reasm_buf* empty = NULL; ip_reasm_buf* prunable = NULL; ip_reasm_buf* oldest = NULL; generic_reasm_id* gen_id = (generic_reasm_id*) id; /* Try to find the reassembly buffer first */ for (i = 0; i < ra_buf_count; i++) { if (ra_buffers[i].in_use && (memcmp(&ra_buffers[i].id, id, (gen_id->af == AF_INET) ? sizeof(ip4_reasm_id) : sizeof(ip6_reasm_id)) == 0)) { rv = &ra_buffers[i]; /* Found it, check for reassembly timeout */ if (((now - rv->first_frag_arr) > ra_timeout) && !rv->reassembled) { if (ra_log) WARNING_MSG("Fragment reassembly timeout occurred, assuming new packet (src %s, dst %s)", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); rv->first_frag_arr = now; rv->in_use = 1; rv->reassembled = 0; rv->first_hole = HD_NULL; rv->frag_count = 0; memset(rv->buffer, 0, 65536 * sizeof(u_char)); } FRAG_MSG("Found matching fragment reassembly buffer for packet with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); return rv; } /* * Record the first empty, first prunable and oldest buffer, in case we * cannot find a buffer for this packet ID */ if ((empty == NULL) && !ra_buffers[i].in_use) { empty = &ra_buffers[i]; } if ((prunable == NULL) && ((now - ra_buffers[i].first_frag_arr) > ra_timeout)) { prunable = &ra_buffers[i]; } if ((oldest == NULL) || (ra_buffers[i].first_frag_arr < oldest->first_frag_arr)) { oldest = &ra_buffers[i]; } } /* No reassembly buffer found, this is the first fragment to arrive */ if (empty != NULL) { rv = empty; } else if (prunable != NULL) { rv = prunable; } else { /* * This is problematic, we ran out of buffers and are sacrificing the * oldest packet being reassembled under the assumption that that one * will time out first. */ rv = oldest; if (ra_log) WARNING_MSG("Ran out of reassembly buffers, discarding partially reassembled packet of age %ds with src %s and dst %s", (int) (now - oldest->first_frag_arr), eemo_reasm_int_get_src_str(&oldest->id), eemo_reasm_int_get_dst_str(&oldest->id)); } /* Clean up the new buffer */ memcpy(&rv->id, id, sizeof(ip_reasm_id)); rv->first_frag_arr = now; rv->in_use = 1; rv->reassembled = 0; rv->first_hole = HD_NULL; rv->frag_count = 0; rv->pkt_len = -1; /* This may not be efficient but it is more secure */ memset(rv->buffer, 0, 65536 * sizeof(u_char)); FRAG_MSG("Returning blank reassembly buffer for packet with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); return rv; } /* Process a single fragment */ static eemo_rv eemo_reasm_int_process_fragment(const ip_reasm_id* id, const eemo_packet_buf* fragment, u_short ofs, const int is_last, eemo_packet_buf* pkt) { assert(id != NULL); assert(fragment != NULL); assert(pkt != NULL); ip_reasm_buf* buf = NULL; hole_desc* hd = NULL; hole_desc hd_found = { 0, 0, 0 }; FRAG_MSG("Processing fragment with src %s, dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); /* Find a buffer for the fragment */ if ((buf = eemo_reasm_int_find_buf(id)) == NULL) { if (ra_log) ERROR_MSG("Could not find a reassembly buffer for fragment with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); return ERV_REASM_FAILED; } /* Check the sanity of the fragment */ if ((fragment->len + ofs) > 65536) { if (ra_log) ERROR_MSG("Fragment with src %s and dst %s has offset %u and length %u, which would exceed the maximum allowed packet length!", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ofs, fragment->len); buf->in_use = 0; return ERV_REASM_FAILED; } /* Check if we already know the length of the whole reassembled packet and if this fragment is within that size */ if ((buf->pkt_len > 0) && ((fragment->len + ofs) > buf->pkt_len)) { if (ra_log) ERROR_MSG("Fragment with src %s and dst %s has offset %u and length %u, which exceeds the expected length %d", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ofs, fragment->len, buf->pkt_len); /* Return the buffer */ buf->in_use = 0; return ERV_REASM_FAILED; } /* Is this the first fragment to arrive? */ if (buf->first_hole == HD_NULL) { FRAG_MSG("First fragment with offset %u and length %u", ofs, fragment->len); if (ofs == 0) { FRAG_MSG("First fragment is start of packet"); if (is_last) { if (ra_log) ERROR_MSG("First fragment is also the last fragment; packet should not be reassembled"); buf->in_use = 0; return ERV_REASM_FAILED; } /* Copy the data in */ memcpy(&buf->buffer[0], fragment->data, fragment->len); /* Create first hole descriptor after the fragment */ hd = (hole_desc*) &buf->buffer[fragment->len]; hd->hd_first = fragment->len; hd->hd_last = HD_NULL; hd->hd_next = HD_NULL; FRAG_MSG("Added hole f=%u l=%u n=%u", hd->hd_first, hd->hd_last, hd->hd_next); buf->first_hole = fragment->len; } else { FRAG_MSG("First fragment is somewhere in the packet, creating new holes"); hd = (hole_desc*) &buf->buffer[0]; hd->hd_first = 0; hd->hd_last = (ofs - 1); hd->hd_next = is_last ? HD_NULL : (ofs + fragment->len); /* Check if the hole is 8 octets or more */ if (hd->hd_last + 1 - hd->hd_first < 8) { ERROR_MSG("Fragment reassembly starting with hole of less than 8 octets; packet should not be reassembled"); buf->in_use = 0; return ERV_REASM_FAILED; } FRAG_MSG("Added hole f=%u l=%u n=%u", hd->hd_first, hd->hd_last, hd->hd_next); /* Copy the fragment data in */ memcpy(&buf->buffer[ofs], fragment->data, fragment->len); if (!is_last) { hd = (hole_desc*) &buf->buffer[ofs + fragment->len]; hd->hd_first = ofs + fragment->len; hd->hd_last = HD_NULL; hd->hd_next = HD_NULL; FRAG_MSG("Added hole f=%u l=%u n=%u", hd->hd_first, hd->hd_last, hd->hd_next); } buf->first_hole = 0; } } else { hole_desc* hd_prev = NULL; /* Iterate over the holes that we have to see where the packet fits */ hd = (hole_desc*) &buf->buffer[buf->first_hole]; while (hd != NULL) { if (ofs > hd->hd_last) { if (hd->hd_next != HD_NULL) { hd_prev = hd; hd = (hole_desc*) &buf->buffer[hd->hd_next]; continue; } hd = NULL; } else if (((ofs + fragment->len - 1) > hd->hd_last) || (ofs < hd->hd_first)) { /* Overlapping fragment! */ if (ra_log) ERROR_MSG("Overlapping fragment in packet with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); buf->in_use = 0; return ERV_REASM_FAILED; } break; } if (hd == NULL) { if (ra_log) ERROR_MSG("Found a fragment with src %s and dst %s but no hole to put it in", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); buf->in_use = 0; return ERV_REASM_FAILED; } FRAG_MSG("Found matching hole f=%u l=%u n=%u for fragment at ofs=%u with len=%u", hd->hd_first, hd->hd_last, hd->hd_next, ofs, fragment->len); memcpy(&hd_found, hd, sizeof(hole_desc)); if (ofs > hd_found.hd_first) { /* Create a new hole */ hole_desc* new_hd = (hole_desc*) &buf->buffer[hd_found.hd_first]; new_hd->hd_first = hd_found.hd_first; new_hd->hd_last = ofs - 1; new_hd->hd_next = hd_found.hd_next; /* Check if the hole is more than 8 octets */ if (new_hd->hd_last + 1 - new_hd->hd_first < 8) { ERROR_MSG("Fragment would create a new hole of less than 8 octets; stopping reassembly"); buf->in_use = 0; return ERV_REASM_FAILED; } FRAG_MSG("Added hole f=%u l=%u n=%u", new_hd->hd_first, new_hd->hd_last, new_hd->hd_next); hd_prev = new_hd; } else { /* Remove the hole */ if (hd_prev != NULL) { hd_prev->hd_next = hd_found.hd_next; } else { buf->first_hole = hd_found.hd_next; } } if (((ofs + fragment->len - 1) < hd_found.hd_last) && !is_last) { /* Create a new hole */ hole_desc* new_hd = (hole_desc*) &buf->buffer[ofs + fragment->len]; new_hd->hd_first = ofs + fragment->len; new_hd->hd_last = hd_found.hd_last; new_hd->hd_next = hd_found.hd_next; /* Check if the hole is more than 8 octets */ if (new_hd->hd_last + 1 - new_hd->hd_first < 8) { ERROR_MSG("Fragment would resize existing hole to less than 8 octets; stopping reassembly"); buf->in_use = 0; return ERV_REASM_FAILED; } FRAG_MSG("Added hole f=%u l=%u n=%u", new_hd->hd_first, new_hd->hd_last, new_hd->hd_next); if (hd_prev != NULL) { hd_prev->hd_next = new_hd->hd_first; FRAG_MSG("Chained new hole to previous hole at %u", hd_prev->hd_first); } else { buf->first_hole = new_hd->hd_first; FRAG_MSG("New hole is first hole"); } } /* Copy data in last (overwrites old hole descriptors!) */ memcpy(&buf->buffer[ofs], fragment->data, fragment->len); /* Check if the hole descriptor list is now empty */ buf->reassembled = (buf->first_hole == HD_NULL); } /* Is this the last fragment of the packet? Then we can calculate the total reassembled length */ if (is_last) { buf->pkt_len = ofs + fragment->len; FRAG_MSG("Total packet length for packet with src %s and dst %s is %u octets", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), buf->pkt_len); } /* Did reassembly complete? */ if (buf->reassembled) { FRAG_MSG("Reassembly of packet with src %s and dst %s of %u octets completed", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), buf->pkt_len); /* Make the reassembled packet available */ pkt->data = &buf->buffer[0]; pkt->len = buf->pkt_len; return ERV_OK; } return ERV_NEED_MORE_FRAGS; } /* * Process an IPv4 fragment; will return ERV_NEED_MORE_FRAGS if more * fragments are needed to reasmemble the packet, and ERV_OK if a full * packet was reassembled (in which case <pkt> contains the packet * data. Caller must release reasmembled packets with the appropriate * call below! */ eemo_rv eemo_reasm_v4_fragment(const struct in_addr* src, const struct in_addr* dst, const u_char ip_proto, const u_short ip_id, const u_short ip_ofs, const eemo_packet_buf* fragment, const int is_last, eemo_packet_buf* pkt) { assert(src != NULL); assert(dst != NULL); assert(fragment != NULL); assert(pkt != NULL); ip4_reasm_id id4; ip_reasm_id* id = (ip_reasm_id*) &id4; if (!ra_enabled) return ERV_REASM_DISABLED; /* Exit early */ /* Assemble fragment identifier */ memset(&id4, 0, sizeof(ip4_reasm_id)); memcpy(&id4.src, src, sizeof(struct in_addr)); memcpy(&id4.dst, dst, sizeof(struct in_addr)); id4.proto = ip_proto; id4.id = ip_id; id4.af = AF_INET; FRAG_MSG("Processing IPv4 fragment with src %s, dst %s, proto=%u and ID=%u", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ip_proto, ip_id); return eemo_reasm_int_process_fragment(id, fragment, ip_ofs, is_last, pkt); } /* Process an IPv6 fragment; semantics of parameters same as for IPv4 */ eemo_rv eemo_reasm_v6_fragment(const struct in6_addr* src, const struct in6_addr* dst, const u_int ip_id, const u_short ip_ofs, const eemo_packet_buf* fragment, const int is_last, eemo_packet_buf* pkt) { assert(src != NULL); assert(dst != NULL); assert(fragment != NULL); assert(pkt != NULL); ip6_reasm_id id6; ip_reasm_id* id = (ip_reasm_id*) &id6; if (!ra_enabled) return ERV_REASM_DISABLED; /* Exit early */ /* Assemble fragment identifier */ memset(&id6, 0, sizeof(ip6_reasm_id)); memcpy(&id6.src, src, sizeof(struct in6_addr)); memcpy(&id6.dst, dst, sizeof(struct in6_addr)); id6.id = ip_id; id6.af = AF_INET6; FRAG_MSG("Processing IPv6 fragment with src %s, dst %s and ID=%u", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ip_id); return eemo_reasm_int_process_fragment(id, fragment, ip_ofs, is_last, pkt); } /* Discard a reassembled IPv4 packet */ void eemo_reasm_v4_free(const struct in_addr* src, const struct in_addr* dst, const u_char ip_proto, const u_short ip_id) { assert(src != NULL); assert(dst != NULL); ip4_reasm_id id4; ip_reasm_id* id = (ip_reasm_id*) &id4; ip_reasm_buf* buf = NULL; if (!ra_enabled) return; /* Exit early */ /* Assemble fragment identifier */ memset(&id4, 0, sizeof(ip4_reasm_id)); memcpy(&id4.src, src, sizeof(struct in_addr)); memcpy(&id4.dst, dst, sizeof(struct in_addr)); id4.proto = ip_proto; id4.id = ip_id; id4.af = AF_INET; FRAG_MSG("Releasing IPv4 fragment with src %s, dst %s, proto=%u and ID=%u", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ip_proto, ip_id); if ((buf = eemo_reasm_int_find_buf(id)) == NULL) { if (ra_log) ERROR_MSG("Could not find a reassembly buffer for fragment with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); return; } if (!buf->reassembled) { if (ra_log) WARNING_MSG("Releasing packet that was not fully reassembled"); } buf->in_use = 0; } /* Discard a reassembled IPv6 packet */ void eemo_reasm_v6_free(const struct in6_addr* src, const struct in6_addr* dst, const u_int ip_id) { assert(src != NULL); assert(dst != NULL); ip6_reasm_id id6; ip_reasm_id* id = (ip_reasm_id*) &id6; ip_reasm_buf* buf = NULL; if (!ra_enabled) return; /* Exit early */ FRAG_MSG("Releasing reassembled IPv6 fragment"); /* Assemble fragment identifier */ memset(&id6, 0, sizeof(ip6_reasm_id)); memcpy(&id6.src, src, sizeof(struct in6_addr)); memcpy(&id6.dst, dst, sizeof(struct in6_addr)); id6.id = ip_id; id6.af = AF_INET6; FRAG_MSG("Releasing IPv6 fragment with src %s, dst %s and ID=%u", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id), ip_id); if ((buf = eemo_reasm_int_find_buf(id)) == NULL) { if (ra_log) ERROR_MSG("Could not find a reassembly buffer for fragment with src %s and dst %s", eemo_reasm_int_get_src_str(id), eemo_reasm_int_get_dst_str(id)); return; } if (!buf->reassembled) { if (ra_log) WARNING_MSG("Releasing packet that was not fully reassembled"); } buf->in_use = 0; }
751766.c
/***************************************************************************//** * \file cyhal_utils_psoc.c * * \brief * Provides internal utility functions for working with interrupts on CAT1/CAT2. * ******************************************************************************** * \copyright * Copyright 2018-2021 Cypress Semiconductor Corporation (an Infineon company) or * an affiliate of Cypress Semiconductor Corporation * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "cyhal_irq_psoc.h" /** * \addtogroup group_hal_impl_irq IRQ Muxing (Interrupt muxing) * \ingroup group_hal_impl * \{ * There are two situations where system interrupts do not correlate 1:1 to CPU interrupts. * ("System interrupt" refers to a signal on a peripheral that can request an interrupt. * "CPU interrupt" refers to an IRQ input line on the cpu). Each has a different potential * impact on application behavior. * - When running on the CM0+ on PSoC 6 S1 devices, there are 32 CPU interrupts available. * Each CPU interrupt can be associatedd with exactly one system interrupt. This means that * if the application attempts to initialize more than 32 HAL driver instances which require * unique interrupt handlers, the initialization will fail because there are no CPU interrupt * slots remaining. * - When running on the CM0+ on all other CAT1 devices, or when running on the CM7 on CAT3 devices, * there are 8 CPU interrupts. Any system interrupt can be assigned to any CPU interrupt. In the event * that more than one system interrupt fires at the same time for a given CPU interrupt, the interrupts * are serviced in ascending numerical order (see the device datasheet for numeric IRQ values). This * means that the above error case where all CPU interrupts have been consumed does not apply. The HAL * automatically divides the system interrupts across the CPU interrupts. * However, it is only possible to assign one priority per CPU interrupt, even though the HAL APIs expose * the interrupt priority per system interrupt. The CAT1 HAL handles this situation by tracking the requested * priority for each system interrupt, then setting the priority for each CPU interrupt as the lowest * (i.e. most important) value requested across all of its associated system interrupts. * \} */ #if _CYHAL_IRQ_LEGACY_M0 #include "cyhal_hwmgr.h" static const uint8_t _CYHAL_IRQ_COUNT_M0 = 32; /* Fixed in the IP definition */ #elif _CYHAL_IRQ_MUXING static uint8_t _cyhal_system_irq_priority[((_CYHAL_IRQ_PRIO_BITS * _CYHAL_IRQ_COUNT) + 7) / 8]; /* Round up to nearest byte */ uint8_t _cyhal_system_irq_lookup_priority(cy_en_intr_t system_irq) { uint16_t start_bit = ((uint16_t)system_irq) * _CYHAL_IRQ_PRIO_BITS; uint8_t result = 0u; for(uint16_t bit = start_bit; bit < start_bit + _CYHAL_IRQ_PRIO_BITS; ++bit) { uint16_t byte = bit / 8u; uint8_t bit_in_byte = bit % 8u; uint8_t offset = bit - start_bit; uint8_t bit_value = ((_cyhal_system_irq_priority[byte] >> bit_in_byte) & 1u); result |= (bit_value << offset); } return result; } void _cyhal_system_irq_store_priority(cy_en_intr_t system_irq, uint8_t priority) { uint16_t start_bit = ((uint16_t)system_irq) * _CYHAL_IRQ_PRIO_BITS; for(uint16_t bit = start_bit; bit < start_bit + _CYHAL_IRQ_PRIO_BITS; ++bit) { uint16_t byte = bit / 8u; uint8_t bit_in_byte = bit % 8u; uint8_t offset = bit - start_bit; uint8_t bit_value = priority & (1u << offset); if(0u != bit_value) { _cyhal_system_irq_priority[byte] |= (1u << bit_in_byte); } else { _cyhal_system_irq_priority[byte] &= ~(1u << bit_in_byte); } } } uint8_t _cyhal_system_irq_lowest_priority(IRQn_Type cpu_irq) { uint8_t lowest_priority = 0xFF; for(uint32_t i = 0; i < _CYHAL_IRQ_COUNT; ++i) { /* No reverse mapping from CPU interrupt to system interrupt, we have to look * through all of the system interrupts to see which ones correspond to this one */ if(cpu_irq == Cy_SysInt_GetNvicConnection((cy_en_intr_t)i)) { uint8_t priority = _cyhal_system_irq_lookup_priority((cy_en_intr_t)i); if(priority < lowest_priority) { lowest_priority = priority; } } } return lowest_priority; } #endif cy_rslt_t _cyhal_irq_register(_cyhal_system_irq_t system_intr, uint8_t intr_priority, cy_israddress irq_handler) { #if _CYHAL_IRQ_MUXING #if _CYHAL_IRQ_LEGACY_M0 /* Find a free CM0 slot */ IRQn_Type chosen_irq = unconnected_IRQn; bool deepsleep_irq = (uint16_t)system_intr < CPUSS_DPSLP_IRQ_NR; uint8_t max_cm0_irq = deepsleep_irq ? CPUSS_CM0_DPSLP_IRQ_NR : _CYHAL_IRQ_COUNT_M0; for(int i = 0; i < max_cm0_irq; ++i) { IRQn_Type irqn = (IRQn_Type)i; if(disconnected_IRQn == Cy_SysInt_GetInterruptSource(irqn)) { chosen_irq = irqn; break; } } if(unconnected_IRQn == chosen_irq) { /* This is a highly device specific situation. "None free" is the closest matching generic error */ return CYHAL_HWMGR_RSLT_ERR_NONE_FREE; } cy_stc_sysint_t intr_cfg = { chosen_irq, system_intr, intr_priority }; #else /* CM0+ on CPUSSv2, or CM4/CM7 on CPUSSv2 with SYSTEM_IRQ_PRESENT */ /* Any system interrupt can go to any CPU interrupt. Map the system interrupts evenly across the CPU interrupts. Cluster * adjacent system interrupts together to make it more likely that interrupts from the same FFB type, which are reasonably * likely to want similar priorities. */ #if defined(CY_IP_M4CPUSS) const uint8_t NUM_CPU_INTERRUPTS = 8u; /* Value fixed in the IP */ #else /* M7CPUSS */ #if defined(CY_CPU_CORTEX_M0P) /* There are 8 general purpose interrupts on the CM0+, but per comments in Cy_SysInt_Init, the first two * CPU interrupts are reserved for ROM */ const uint8_t NUM_CPU_INTERRUPTS = 6u; #else const uint8_t NUM_CPU_INTERRUPTS = CPUSS_CM7_INT_NR; #endif #endif const uint8_t SYSTEM_IRQ_PER_CPU_IRQ = (_CYHAL_IRQ_COUNT + (NUM_CPU_INTERRUPTS / 2)) / NUM_CPU_INTERRUPTS; uint8_t cpu_irq = ((uint32_t)system_intr) / SYSTEM_IRQ_PER_CPU_IRQ; #if defined (CY_IP_M7CPUSS) #if defined(CY_CPU_CORTEX_M0P) cpu_irq += 2u; /* Handle offset from interrupts reserved for ROM */ #endif /* For CM7, the upper 16 bits of the intrSrc field are the CPU interrupt number */ uint32_t intr_src = (uint32_t)system_intr; intr_src |= cpu_irq << 16; _cyhal_system_irq_store_priority(system_intr, intr_priority); /* We can avoid a "lowest priority" search here, because the currently set value is the lowest except * possibly for the one we're just now registering */ uint8_t existing_priority = NVIC_GetPriority((IRQn_Type)cpu_irq); uint8_t lowest_priority = (existing_priority < intr_priority) ? existing_priority : intr_priority; cy_stc_sysint_t intr_cfg = { intr_src, lowest_priority }; #else /* M4CPUSS */ cy_stc_sysint_t intr_cfg = { (IRQn_Type)cpu_irq, system_intr, intr_priority }; #endif #endif #else cy_stc_sysint_t intr_cfg = { system_intr, intr_priority }; #endif return Cy_SysInt_Init(&intr_cfg, irq_handler); } #if _CYHAL_IRQ_LEGACY_M0 IRQn_Type _cyhal_irq_find_cm0(cy_en_intr_t system_irq) { /* Need to look through all of the enabled CPU interrupts and see if any of them * is connected to this IRQn */ for(int i = 0; i < _CYHAL_IRQ_COUNT_M0; ++i) { IRQn_Type irqn = (IRQn_Type)i; if(system_irq == Cy_SysInt_GetInterruptSource(irqn)) { return irqn; } } return unconnected_IRQn; } #endif
865782.c
/* * Copyright (c) 2000-2003,2005 Silicon Graphics, Inc. * All Rights Reserved. * * 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. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include <linux/proc_fs.h> struct xstats xfsstats; static int counter_val(struct xfsstats __percpu *stats, int idx) { int val = 0, cpu; for_each_possible_cpu(cpu) val += *(((__u32 *)per_cpu_ptr(stats, cpu) + idx)); return val; } int xfs_stats_format(struct xfsstats __percpu *stats, char *buf) { int i, j; int len = 0; __uint64_t xs_xstrat_bytes = 0; __uint64_t xs_write_bytes = 0; __uint64_t xs_read_bytes = 0; static const struct xstats_entry { char *desc; int endpoint; } xstats[] = { { "extent_alloc", XFSSTAT_END_EXTENT_ALLOC }, { "abt", XFSSTAT_END_ALLOC_BTREE }, { "blk_map", XFSSTAT_END_BLOCK_MAPPING }, { "bmbt", XFSSTAT_END_BLOCK_MAP_BTREE }, { "dir", XFSSTAT_END_DIRECTORY_OPS }, { "trans", XFSSTAT_END_TRANSACTIONS }, { "ig", XFSSTAT_END_INODE_OPS }, { "log", XFSSTAT_END_LOG_OPS }, { "push_ail", XFSSTAT_END_TAIL_PUSHING }, { "xstrat", XFSSTAT_END_WRITE_CONVERT }, { "rw", XFSSTAT_END_READ_WRITE_OPS }, { "attr", XFSSTAT_END_ATTRIBUTE_OPS }, { "icluster", XFSSTAT_END_INODE_CLUSTER }, { "vnodes", XFSSTAT_END_VNODE_OPS }, { "buf", XFSSTAT_END_BUF }, { "abtb2", XFSSTAT_END_ABTB_V2 }, { "abtc2", XFSSTAT_END_ABTC_V2 }, { "bmbt2", XFSSTAT_END_BMBT_V2 }, { "ibt2", XFSSTAT_END_IBT_V2 }, { "fibt2", XFSSTAT_END_FIBT_V2 }, { "rmapbt", XFSSTAT_END_RMAP_V2 }, { "refcntbt", XFSSTAT_END_REFCOUNT }, /* we print both series of quota information together */ { "qm", XFSSTAT_END_QM }, }; /* Loop over all stats groups */ for (i = j = 0; i < ARRAY_SIZE(xstats); i++) { len += snprintf(buf + len, PATH_MAX - len, "%s", xstats[i].desc); /* inner loop does each group */ for (; j < xstats[i].endpoint; j++) len += snprintf(buf + len, PATH_MAX - len, " %u", counter_val(stats, j)); len += snprintf(buf + len, PATH_MAX - len, "\n"); } /* extra precision counters */ for_each_possible_cpu(i) { xs_xstrat_bytes += per_cpu_ptr(stats, i)->xs_xstrat_bytes; xs_write_bytes += per_cpu_ptr(stats, i)->xs_write_bytes; xs_read_bytes += per_cpu_ptr(stats, i)->xs_read_bytes; } len += snprintf(buf + len, PATH_MAX-len, "xpc %Lu %Lu %Lu\n", xs_xstrat_bytes, xs_write_bytes, xs_read_bytes); len += snprintf(buf + len, PATH_MAX-len, "debug %u\n", #if defined(DEBUG) 1); #else 0); #endif return len; } void xfs_stats_clearall(struct xfsstats __percpu *stats) { int c; __uint32_t vn_active; xfs_notice(NULL, "Clearing xfsstats"); for_each_possible_cpu(c) { preempt_disable(); /* save vn_active, it's a universal truth! */ vn_active = per_cpu_ptr(stats, c)->vn_active; memset(per_cpu_ptr(stats, c), 0, sizeof(*stats)); per_cpu_ptr(stats, c)->vn_active = vn_active; preempt_enable(); } } /* legacy quota interfaces */ #ifdef CONFIG_XFS_QUOTA static int xqm_proc_show(struct seq_file *m, void *v) { /* maximum; incore; ratio free to inuse; freelist */ seq_printf(m, "%d\t%d\t%d\t%u\n", 0, counter_val(xfsstats.xs_stats, XFSSTAT_END_XQMSTAT), 0, counter_val(xfsstats.xs_stats, XFSSTAT_END_XQMSTAT + 1)); return 0; } static int xqm_proc_open(struct inode *inode, struct file *file) { return single_open(file, xqm_proc_show, NULL); } static const struct file_operations xqm_proc_fops = { .open = xqm_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /* legacy quota stats interface no 2 */ static int xqmstat_proc_show(struct seq_file *m, void *v) { int j; seq_printf(m, "qm"); for (j = XFSSTAT_END_IBT_V2; j < XFSSTAT_END_XQMSTAT; j++) seq_printf(m, " %u", counter_val(xfsstats.xs_stats, j)); seq_putc(m, '\n'); return 0; } static int xqmstat_proc_open(struct inode *inode, struct file *file) { return single_open(file, xqmstat_proc_show, NULL); } static const struct file_operations xqmstat_proc_fops = { .owner = THIS_MODULE, .open = xqmstat_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif /* CONFIG_XFS_QUOTA */ #ifdef CONFIG_PROC_FS int xfs_init_procfs(void) { if (!proc_mkdir("fs/xfs", NULL)) return -ENOMEM; if (!proc_symlink("fs/xfs/stat", NULL, "/sys/fs/xfs/stats/stats")) goto out; #ifdef CONFIG_XFS_QUOTA if (!proc_create("fs/xfs/xqmstat", 0, NULL, &xqmstat_proc_fops)) goto out; if (!proc_create("fs/xfs/xqm", 0, NULL, &xqm_proc_fops)) goto out; #endif return 0; out: remove_proc_subtree("fs/xfs", NULL); return -ENOMEM; } void xfs_cleanup_procfs(void) { remove_proc_subtree("fs/xfs", NULL); } #endif /* CONFIG_PROC_FS */