file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/86075605.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* > \brief \b CLADIV performs complex division in real arithmetic, avoiding unnecessary overflow. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CLADIV + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cladiv.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cladiv.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cladiv.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* COMPLEX FUNCTION CLADIV( X, Y ) */
/* COMPLEX X, Y */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CLADIV := X / Y, where X and Y are complex. The computation of X / Y */
/* > will not overflow on an intermediary step unless the results */
/* > overflows. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] X */
/* > \verbatim */
/* > X is COMPLEX */
/* > \endverbatim */
/* > */
/* > \param[in] Y */
/* > \verbatim */
/* > Y is COMPLEX */
/* > The complex scalars X and Y. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexOTHERauxiliary */
/* ===================================================================== */
/* Complex */ VOID cladiv_(complex * ret_val, complex *x, complex *y)
{
/* System generated locals */
real r__1, r__2, r__3, r__4;
complex q__1;
/* Local variables */
real zi, zr;
extern /* Subroutine */ int sladiv_(real *, real *, real *, real *, real *
, real *);
/* -- LAPACK auxiliary routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
r__1 = x->r;
r__2 = r_imag(x);
r__3 = y->r;
r__4 = r_imag(y);
sladiv_(&r__1, &r__2, &r__3, &r__4, &zr, &zi);
q__1.r = zr, q__1.i = zi;
ret_val->r = q__1.r, ret_val->i = q__1.i;
return ;
/* End of CLADIV */
} /* cladiv_ */
|
the_stack_data/108672.c | /*
Description: A strncpy generates a string that may be missing a NUL termination. When it is copied with strcpy a stack buffer can be overrun.
Keywords: Port C Size0 Complex1 BufferOverflow Stack Strcpy NoNul
ValidArg: "a"*30
InvalidArg: "a"*100
Copyright 2005 Fortify Software.
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL FORTIFY SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF FORTIFY SOFTWARE HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
FORTIFY SOFTWARE SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND FORTIFY SOFTWARE HAS NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
*/
#include <stdio.h>
#include <string.h>
/*
* we pick a round buffer size in hopes that the compiler lays these
* out next to each other without padding. Other layouts may
* inadvertantly NUL terminate the buffer with stack garbage.
*/
#define MAXSIZE 32
void
test(char *str)
{
char buf3[MAXSIZE];
char buf2[MAXSIZE];
char buf1[MAXSIZE];
/* strncpy does not NUL terminate if buffer isnt large enough */
strncpy(buf1, str, sizeof buf1); /* BAD */
strncpy(buf2, "This is a Test string", sizeof buf2);
strcpy(buf3, buf1); /* BAD */
printf("result: %s\n", buf3);
}
int
main(int argc, char **argv)
{
char *userstr;
if(argc > 1) {
userstr = argv[1];
test(userstr);
}
return 0;
}
|
the_stack_data/27485.c | /*
* Copyright (c) 1987 Regents of the University of California.
* 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 acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
/*static char *sccsid = "from: @(#)bzero.c 5.7 (Berkeley) 2/24/91";*/
static char *rcsid = "$NetBSD: bzero.c,v 1.7 1997/10/13 11:55:23 lukem Exp $";
#endif /* LIBC_SCCS and not lint */
#ifndef _KERNEL
#include <string.h>
#else
#include <lib/libkern/libkern.h>
#endif
/*
* bzero -- vax movc5 instruction
*/
void
bzero(b, length)
void *b;
register size_t length;
{
register char *p;
for (p = b; length--;)
*p++ = '\0';
}
|
the_stack_data/153268505.c | // Copyright (c) 2013, Sergey Lyubka
// Copyright (c) 2017-2019, BITRUBCOIN, The Monero Project
// All rights reserved.
// Released under the MIT license.
// This program takes a list of files as an input, and produces C++ code that
// contains the contents of all these files as a collection of strings.
//
// Usage:
// 1. Compile this file:
// cc -o generate-translations-header generate-translations-header.c
//
// 2. Convert list of files into single header:
// ./generate-translations-header monero_fr.qm monero_it.qm > translations_files.h
//
// 3. In your application code, include translations_files.h, then you can
// access the files using this function:
// static bool find_embedded_file(const std::string &file_name, std::string &data);
// std::string data;
// find_embedded_file("monero_fr.qm", data);
#include <stdio.h>
#include <stdlib.h>
static const char *code =
"static bool find_embedded_file(const std::string &name, std::string &data) {\n"
" const struct embedded_file *p;\n"
" for (p = embedded_files; p->name != NULL; p++) {\n"
" if (*p->name == name) {\n"
" data = *p->data;\n"
" return true;\n"
" }\n"
" }\n"
" return false;\n"
"}\n";
int main(int argc, char *argv[]) {
FILE *fp, *foutput;
int i, j, ch;
if((foutput = fopen("translation_files.h", "w")) == NULL) {
exit(EXIT_FAILURE);
}
fprintf(foutput, "#ifndef TRANSLATION_FILES_H\n");
fprintf(foutput, "#define TRANSLATION_FILES_H\n\n");
fprintf(foutput, "#include <string>\n\n");
for (i = 1; i < argc; i++) {
if ((fp = fopen(argv[i], "rb")) == NULL) {
exit(EXIT_FAILURE);
} else {
fprintf(foutput, "static const std::string translation_file_name_%d = \"%s\";\n", i, argv[i]);
fprintf(foutput, "static const std::string translation_file_data_%d = std::string(", i);
for (j = 0; (ch = fgetc(fp)) != EOF; j++) {
if ((j % 16) == 0) {
if (j > 0) {
fprintf(foutput, "%s", "\"");
}
fprintf(foutput, "%s", "\n \"");
}
fprintf(foutput, "\\x%02x", ch);
}
fprintf(foutput, "\",\n %d);\n\n", j);
fclose(fp);
}
}
fprintf(foutput, "%s", "static const struct embedded_file {\n");
fprintf(foutput, "%s", " const std::string *name;\n");
fprintf(foutput, "%s", " const std::string *data;\n");
fprintf(foutput, "%s", "} embedded_files[] = {\n");
for (i = 1; i < argc; i++) {
fprintf(foutput, " {&translation_file_name_%d, &translation_file_data_%d},\n", i, i);
}
fprintf(foutput, "%s", " {NULL, NULL}\n");
fprintf(foutput, "%s", "};\n\n");
fprintf(foutput, "%s\n", code);
fprintf(foutput, "#endif /* TRANSLATION_FILES_H */\n");
fclose(foutput);
return EXIT_SUCCESS;
}
|
the_stack_data/248581072.c | #include<stdio.h>
#include<malloc.h>
int main()
{
void *p1,*p2,*p3,*p4;
// tcache & small size
p1 = malloc(10);
// tcache & large size
p2 = malloc(20000);
// not tcache & large size
p3 = malloc(1000000);
// not tcache & huge size
p4 = malloc(6000000);
free(p1);
free(p2);
free(p3);
free(p4);
return 0;
}
|
the_stack_data/932215.c | #define VLEN 256
#if defined(USE_COMBINED_GEMM_12) || defined(USE_COMBINED_GEMM_EACH)
void w2v_gemm0( unsigned long n, unsigned long h, unsigned long w, int *Aoffsets, int *Boffsets, float *A, float *B, float *Ad, float *C )
{
float abuf[VLEN] ;
#pragma _NEC vreg(abuf)
if( h <= VLEN ) {
for( int i=0; i<n; i++ ) {
int baseA = h * Aoffsets[i] ;
#pragma _NEC shortloop
for( int k=0; k<h ; k++ ) {
abuf[k] = A[baseA+k] ;
#ifdef USE_COMBINED_GEMM_EACH
Ad[h*i+k] = abuf[k];
#endif
}
#pragma _NEC novector
for( int j=0; j<w; j++) {
float sum = 0 ;
int baseB = h * Boffsets[j] ;
#pragma _NEC shortloop
for( int k=0; k<h ; k++ ) {
sum += abuf[k] * B[baseB+k] ;
}
C[w*i+j] = sum ;
}
}
}
else {
for( int i=0; i<n; i++ ) {
for( int k=0; k<h ; k++ ) {
Ad[h*i+k] = A[h*Aoffsets[i]+k] ;
}
#pragma _NEC novector
for( int j=0; j<w; j++) {
float sum = 0 ;
for( int k=0; k<h ; k++ ) {
sum += A[h*Aoffsets[i]+k] * B[h*Boffsets[j]+k] ;
}
C[w*i+j] = sum ;
}
}
}
}
#else
void w2v_gemm0( unsigned long n, unsigned long h, unsigned long w, float *A, float *B, float *C )
{
float abuf[VLEN] ;
#pragma _NEC vreg(abuf)
if( h <= VLEN ) {
for( int i=0; i<n; i++ ) {
#pragma _NEC shortloop
for( int k=0; k<h ; k++ ) {
abuf[k] = A[h*i+k] ;
}
#pragma _NEC novector
for( int j=0; j<w; j++) {
float sum = 0 ;
#pragma _NEC shortloop
for( int k=0; k<h ; k++ ) {
sum += abuf[k] * B[h*j+k] ;
}
C[w*i+j] = sum ;
}
}
}
else {
for( int i=0; i<n; i++ ) {
#pragma _NEC novector
for( int j=0; j<w; j++) {
float sum = 0 ;
for( int k=0; k<h ; k++ ) {
sum += A[h*i+k] * B[h*j+k] ;
}
C[w*i+j] = sum ;
}
}
}
}
#endif
|
the_stack_data/184517680.c | #define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
//#include <math.h>
#define xstr(s) str(s)
#define str(s) #s
// Algebraic functions
static double (*real_sqrt)(double dbl);
static float (*real_sqrtf)(float dbl);
static double (*real_cbrt)(double dbl);
static float (*real_cbrtf)(float dbl);
static double (*real_hypot)(double dbl1, double dbl2);
static float (*real_hypotf)(float dbl1, float dbl2);
// Elementary transcendental functions
static double (*real_log)(double dbl);
static float (*real_logf)(float dbl);
static double (*real_log10)(double dbl);
static float (*real_log10f)(float dbl);
static double (*real_log1p)(double dbl);
static float (*real_log1pf)(float dbl);
static double (*real_log2)(double dbl);
static float (*real_log2f)(float dbl);
static double (*real_sin)(double dbl);
static float (*real_sinf)(float dbl);
static double (*real_asin)(double dbl);
static float (*real_asinf)(float dbl);
static double (*real_asinh)(double dbl);
static float (*real_asinhf)(float dbl);
// Higher transcendental functions
static double (*real_cos)(double dbl);
static float (*real_cosf)(float dbl);
static double (*real_acos)(double dbl);
static float (*real_acosf)(float dbl);
static double (*real_acosh)(double dbl);
static float (*real_acoshf)(float dbl);
static double (*real_atan)(double dbl);
static float (*real_atanf)(float dbl);
static double (*real_atan2)(double dbl1, double dbl2);
static float (*real_atan2f)(float dbl1, float dbl2);
static double (*real_atanh)(double dbl);
static float (*real_atanhf)(float dbl);
static double (*real_exp)(double dbl);
static float (*real_expf)(float dbl);
static double (*real_exp10)(double dbl);
static float (*real_exp10f)(float dbl);
static double (*real_exp2)(double dbl);
static float (*real_exp2f)(float dbl);
static double (*real_expm1)(double dbl);
static float (*real_expm1f)(float dbl);
static double (*real_pow)(double dbl1, double dbl2);
static float (*real_powf)(float dbl1, float dbl2);
// Higher transcendental functions
static double (*real_j0)(double dbl);
static float (*real_j0f)(float dbl);
static double (*real_j1)(double dbl);
static float (*real_j1f)(float dbl);
static double (*real_jn)(int n, double dbl);
static float (*real_jnf)(int n, float dbl);
static double (*real_y0)(double dbl);
static float (*real_y0f)(float dbl);
static double (*real_y1)(double dbl);
static float (*real_y1f)(float dbl);
static double (*real_yn)(int n, double dbl);
static float (*real_ynf)(int n, float dbl);
static double (*real_erf)(double dbl);
static float (*real_erff)(float dbl);
static double (*real_erfc)(double dbl);
static float (*real_erfcf)(float dbl);
static double (*real_lgamma)(double dbl);
static float (*real_lgammaf)(float dbl);
static double (*real_tgamma)(double dbl);
static float (*real_tgammaf)(float dbl);
static double (*real_lgamma_r)(double dbl, int *signgamp);
static float (*real_lgammaf_r)(float dbl, int *signgamp);
static void (*real_sincos)(double dbl, double *sin, double *cos);
static void (*real_sincosf)(float dbl, float *sin, float *cos);
// Override
#define ZERO(TYPE) _Generic(TYPE, float : 0.0f, double : 0.0)
#define DEFINE_1_WRAPPER(NAME, TYPE) \
TYPE NAME(TYPE x) { \
real_##NAME = dlsym(RTLD_NEXT, #NAME); \
return real_##NAME(x) + ZERO(x); \
}
#define DEFINE_1i_1_WRAPPER(NAME, TYPE) \
TYPE NAME(int n, TYPE x) { \
real_##NAME = dlsym(RTLD_NEXT, #NAME); \
return real_##NAME(n, x) + ZERO(x); \
}
#define DEFINE_1_1p_WRAPPER(NAME, TYPE) \
TYPE NAME(TYPE x, int *s) { \
real_##NAME = dlsym(RTLD_NEXT, #NAME); \
return real_##NAME(x, s) + ZERO(x); \
}
#define DEFINE_1_2p_WRAPPER(NAME, TYPE) \
void NAME(TYPE x, TYPE *o1, TYPE *o2) { \
real_##NAME = dlsym(RTLD_NEXT, #NAME); \
real_##NAME(x, o1, o2); \
*o1 += ZERO(x); \
*o2 += ZERO(x); \
}
#define DEFINE_2_WRAPPER(NAME, TYPE) \
TYPE NAME(TYPE x, TYPE y) { \
real_##NAME = dlsym(RTLD_NEXT, #NAME); \
return real_##NAME(x, y) + ZERO(x); \
}
DEFINE_1_WRAPPER(sqrt, double);
DEFINE_1_WRAPPER(sqrtf, float);
DEFINE_1_WRAPPER(cbrt, double);
DEFINE_1_WRAPPER(cbrtf, float);
DEFINE_2_WRAPPER(hypot, double);
DEFINE_2_WRAPPER(hypotf, float);
DEFINE_1_WRAPPER(log, double);
DEFINE_1_WRAPPER(logf, float);
DEFINE_1_WRAPPER(log10, double);
DEFINE_1_WRAPPER(log10f, float);
DEFINE_1_WRAPPER(log1p, double);
DEFINE_1_WRAPPER(log1pf, float);
DEFINE_1_WRAPPER(log2, double);
DEFINE_1_WRAPPER(log2f, float);
DEFINE_1_WRAPPER(sin, double);
DEFINE_1_WRAPPER(sinf, float);
DEFINE_1_WRAPPER(asin, double);
DEFINE_1_WRAPPER(asinf, float);
DEFINE_1_WRAPPER(asinh, double);
DEFINE_1_WRAPPER(asinhf, float);
DEFINE_1_WRAPPER(cos, double);
DEFINE_1_WRAPPER(cosf, float);
DEFINE_1_WRAPPER(acos, double);
DEFINE_1_WRAPPER(acosf, float);
DEFINE_1_WRAPPER(acosh, double);
DEFINE_1_WRAPPER(acoshf, float);
DEFINE_1_WRAPPER(atan, double);
DEFINE_1_WRAPPER(atanf, float);
DEFINE_1_WRAPPER(atanh, double);
DEFINE_1_WRAPPER(atanhf, float);
DEFINE_2_WRAPPER(atan2, double);
DEFINE_2_WRAPPER(atan2f, float);
DEFINE_1_WRAPPER(exp, double);
DEFINE_1_WRAPPER(expf, float);
DEFINE_2_WRAPPER(pow, double);
DEFINE_2_WRAPPER(powf, float);
DEFINE_1_WRAPPER(exp10, double);
DEFINE_1_WRAPPER(exp10f, float);
DEFINE_1_WRAPPER(exp2, double);
DEFINE_1_WRAPPER(exp2f, float);
DEFINE_1_WRAPPER(expm1, double);
DEFINE_1_WRAPPER(expm1f, float);
DEFINE_1_WRAPPER(j0, double);
DEFINE_1_WRAPPER(j0f, float);
DEFINE_1_WRAPPER(j1, double);
DEFINE_1_WRAPPER(j1f, float);
DEFINE_1i_1_WRAPPER(jn, double);
DEFINE_1i_1_WRAPPER(jnf, float);
DEFINE_1_WRAPPER(y0, double);
DEFINE_1_WRAPPER(y0f, float);
DEFINE_1_WRAPPER(y1, double);
DEFINE_1_WRAPPER(y1f, float);
DEFINE_1i_1_WRAPPER(yn, double);
DEFINE_1i_1_WRAPPER(ynf, float);
DEFINE_1_WRAPPER(erf, double);
DEFINE_1_WRAPPER(erff, float);
DEFINE_1_WRAPPER(erfc, double);
DEFINE_1_WRAPPER(erfcf, float);
DEFINE_1_WRAPPER(lgamma, double);
DEFINE_1_WRAPPER(lgammaf, float);
DEFINE_1_WRAPPER(tgamma, double);
DEFINE_1_WRAPPER(tgammaf, float);
DEFINE_1_1p_WRAPPER(lgamma_r, double);
DEFINE_1_1p_WRAPPER(lgammaf_r, float);
DEFINE_1_2p_WRAPPER(sincos, double);
DEFINE_1_2p_WRAPPER(sincosf, float); |
the_stack_data/25136797.c | #include <stdio.h>
int main()
{
// test the return value for printf function
// int i = 43;
// printf("%d\n", printf("%d", printf("%d", i)));
// Print the diamond
int n = 10; // the size of the diamond
// print the up part
for(int i = 0; i <= n; i++)
{
for(int j = 0; j <= n-i; j++)
printf(" ");
for(int k = 0; k <= i ; k++)
printf("* ");
// printf("\n");
putchar(10);
}
// print the down part
for (int i = 0; i <= n-1; i++)
{
for(int j = 0; j <= i+1; j++)
printf(" ");
for(int k = 0; k <= n-1-i; k++)
printf("* ");
// printf("\n");
putchar(10);
}
return 0;
}
|
the_stack_data/68981.c | #include <stdio.h>
int number_of_spaces(char *s, int index)
{
int n = 0;
int i = index;
while(s[i] != '\0') {
if(s[i] == ' ') {
n++;
}
i++;
}
return n;
}
int main()
{
int n, index;
scanf("%d\n", &index);
char s[10];
fgets(s, 10, stdin);
/* puts(s); */
n = number_of_spaces(s, index);
printf("%d", n);
return 0;
}
|
the_stack_data/154826819.c | /*
Copyright (c) 2009 Sascha Steinbiss <[email protected]>
Copyright (c) 2009 Center for Bioinformatics, University of Hamburg
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef HAVE_MYSQL
#include <string.h>
#include <mysql/mysql.h>
#include "core/class_alloc_lock.h"
#include "core/log.h"
#include "core/ma_api.h"
#include "core/minmax_api.h"
#include "core/hashtable.h"
#include "core/str_api.h"
#include "core/undef_api.h"
#include "core/unused_api.h"
#include "extended/rdb_mysql_api.h"
#include "extended/rdb_rep.h"
struct GtRDBMySQL {
const GtRDB parent_instance;
MYSQL conn;
GtStr *database;
};
struct GtRDBStmtMySQL {
const GtRDBStmt parent_instance;
GtUword num_params;
GtHashtable *buffers, *returned_strings;
bool executed;
my_bool update_maxlengths;
GtStr *query;
MYSQL_BIND *params, *results;
MYSQL_STMT *stmt;
MYSQL *conn;
};
const GtRDBClass* gt_rdb_mysql_class(void);
const GtRDBStmtClass* gt_rdb_stmt_mysql_class(void);
#define GT_MYSQL_ERRMSG "MySQL error code %d: %s"
#define gt_rdb_mysql_cast(RDB)\
gt_rdb_cast(gt_rdb_mysql_class(), RDB)
#define gt_rdb_stmt_mysql_cast(RDB)\
gt_rdb_stmt_cast(gt_rdb_stmt_mysql_class(), RDB)
GtRDB* gt_rdb_mysql_new(const char *server,
unsigned int port,
const char *database,
const char *username,
const char *password,
GtError *err)
{
GtRDBMySQL *rdbm;
GtRDB *rdb = gt_rdb_create(gt_rdb_mysql_class());
rdbm = gt_rdb_mysql_cast(rdb);
mysql_init(&rdbm->conn);
mysql_options(&rdbm->conn, MYSQL_READ_DEFAULT_GROUP, "genometools");
if (!mysql_real_connect(&rdbm->conn, server, username, password, database,
port, NULL,
CLIENT_COMPRESS | CLIENT_MULTI_STATEMENTS))
{
gt_error_set(err, "cannot connect to database: %s",
mysql_error(&rdbm->conn));
mysql_close(&rdbm->conn);
gt_rdb_delete(rdb);
return NULL;
}
rdbm->database = gt_str_new_cstr(database);
return rdb;
}
static void free_buf(void *elem)
{
gt_free(*(void**) elem);
}
static void free_str(void *elem)
{
gt_str_delete(*(GtStr**) elem);
}
static GtRDBStmt* gt_rdb_mysql_prepare(GtRDB *rdb, const char *query,
GtUword num_params, GtError *err)
{
GtRDBStmt *st = NULL;
GtRDBStmtMySQL *stm = NULL;
GtRDBMySQL *rdbm;
int had_err = 0, retval = 0;
/* we need these to keep track of result/parameter and string buffers */
HashElemInfo str_buffer_hash = {
gt_ht_ptr_elem_hash,
{ free_str },
sizeof (GtStr*),
gt_ht_ptr_elem_cmp,
NULL,
NULL
},
buffer_hash = {
gt_ht_ptr_elem_hash,
{ free_buf },
sizeof (void*),
gt_ht_ptr_elem_cmp,
NULL,
NULL
};
MYSQL_STMT *tmp = NULL;
gt_assert(rdb && query);
gt_error_check(err);
rdbm = gt_rdb_mysql_cast(rdb);
tmp = mysql_stmt_init(&rdbm->conn);
if ((retval = mysql_stmt_prepare(tmp, query, strlen(query)))) {
gt_error_set(err, GT_MYSQL_ERRMSG, retval, mysql_stmt_error(tmp));
had_err = -1;
}
if (!had_err) {
int param_count;
param_count = mysql_stmt_param_count(tmp);
if (param_count != num_params) {
gt_error_set(err, "invalid parameter count: "GT_WU" expected, %d given",
num_params, param_count);
mysql_stmt_close(tmp);
had_err = -1;
}
}
if (!had_err) {
st = gt_rdb_stmt_create(gt_rdb_stmt_mysql_class());
stm = gt_rdb_stmt_mysql_cast(st);
stm->num_params = num_params;
stm->query = gt_str_new_cstr(query);
stm->buffers = gt_hashtable_new(buffer_hash);
stm->returned_strings = gt_hashtable_new(str_buffer_hash);
stm->stmt = tmp;
stm->update_maxlengths = true;
stm->params = gt_calloc(num_params, sizeof (MYSQL_BIND));
mysql_stmt_attr_set(tmp, STMT_ATTR_UPDATE_MAX_LENGTH,
&stm->update_maxlengths);
memset(stm->params, 0, num_params*sizeof (MYSQL_BIND));
stm->conn = &rdbm->conn;
}
return st;
}
static GtUword gt_rdb_mysql_last_inserted_id(GtRDB *rdb,
GT_UNUSED const char *table,
GT_UNUSED GtError *err)
{
GtRDBMySQL *rdbm;
gt_assert(rdb);
gt_error_check(err);
rdbm = gt_rdb_mysql_cast(rdb);
return mysql_insert_id(&rdbm->conn); /* TODO: find out whether this is better
replaced by INFORMATION_SCHEMA
query */
}
static GtCstrTable* gt_rdb_mysql_get_tables(GtRDB *rdb, GtError *err)
{
GtRDBMySQL *rdbm;
MYSQL_RES *res;
MYSQL_ROW row;
GtCstrTable *tab;
gt_assert(rdb);
gt_error_check(err);
rdbm = gt_rdb_mysql_cast(rdb);
gt_assert(&rdbm->conn);
res = mysql_list_tables(&rdbm->conn, NULL); /* NULL means 'all tables' */
if (!res) {
gt_error_set(err, "error trying to list tables: %s",
mysql_error(&rdbm->conn));
return NULL;
}
tab = gt_cstr_table_new();
while ((row = mysql_fetch_row(res))) {
char buf[BUFSIZ];
GtUword *lengths;
memset(buf, 0, BUFSIZ);
lengths = mysql_fetch_lengths(res);
(void) snprintf(buf, GT_MIN(BUFSIZ, lengths[0])*sizeof (char), "%s",
(char*) row[0] ? (char*) row[0] : "NULL");
gt_cstr_table_add(tab, buf);
}
mysql_free_result(res);
return tab;
}
static GtCstrTable* gt_rdb_mysql_get_indexes(GtRDB *rdb, GtError *err)
{
GT_UNUSED GtRDBMySQL *rdbm;
GtRDBStmt *stmt;
GtCstrTable *tab;
int rval = 0;
gt_assert(rdb);
gt_error_check(err);
rdbm = gt_rdb_mysql_cast(rdb);
/* TODO: implement a way to do this in MySQL 4 */
if ((stmt = gt_rdb_prepare(rdb, "SELECT DISTINCT INDEX_NAME "
"FROM INFORMATION_SCHEMA.STATISTICS ",
0,
err)) == NULL)
return NULL;
tab = gt_cstr_table_new();
while (!rval) {
GtStr *key;
rval = gt_rdb_stmt_exec(stmt, err);
if (rval) break;
key = gt_str_new();
gt_rdb_stmt_get_string(stmt, 0, key, err);
gt_cstr_table_add(tab, gt_str_get(key));
gt_str_delete(key);
}
if (rval < 0) {
gt_cstr_table_delete(tab);
gt_rdb_stmt_delete(stmt);
return NULL;
}
gt_rdb_stmt_delete(stmt);
return tab;
}
static int gt_rdb_mysql_accept(GtRDB *rdb, GtRDBVisitor *v, GtError *err)
{
GtRDBMySQL *rdbm;
gt_assert(rdb && v);
gt_error_check(err);
rdbm = gt_rdb_mysql_cast(rdb);
return gt_rdb_visitor_visit_mysql(v, rdbm, err);
}
static void gt_rdb_mysql_delete(GtRDB *rdb)
{
GtRDBMySQL *rdbm;
if (!rdb) return;
rdbm = gt_rdb_mysql_cast(rdb);
mysql_close(&rdbm->conn);
gt_str_delete(rdbm->database);
}
static void gt_rdb_stmt_mysql_delete(GtRDBStmt *st)
{
GtRDBStmtMySQL *stm;
if (!st) return;
stm = gt_rdb_stmt_mysql_cast(st);
if (stm->stmt) {
mysql_stmt_free_result(stm->stmt);
mysql_stmt_close(stm->stmt);
}
gt_free(stm->params);
gt_free(stm->results);
gt_hashtable_delete(stm->buffers);
gt_hashtable_delete(stm->returned_strings);
gt_str_delete(stm->query);
}
static int gt_rdb_stmt_mysql_reset(GtRDBStmt *st, GtError *err)
{
GtRDBStmtMySQL *stm;
int rval, had_err = 0;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
gt_hashtable_reset(stm->buffers);
gt_hashtable_reset(stm->returned_strings);
mysql_stmt_free_result(stm->stmt);
if ((rval = mysql_stmt_reset(stm->stmt))) {
gt_error_set(err, GT_MYSQL_ERRMSG, rval, mysql_stmt_error(stm->stmt));
had_err = -1;
}
memset(stm->params, 0, stm->num_params*sizeof (MYSQL_BIND));
gt_free(stm->results);
stm->results = NULL;
if (!had_err)
stm->executed = false;
return had_err;
}
static int gt_rdb_stmt_mysql_bind_int(GtRDBStmt *st, GtUword param_no,
int val, GT_UNUSED GtError *err)
{
GtRDBStmtMySQL *stm;
int *lval, had_err = 0;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
gt_assert(param_no < stm->num_params);
lval = gt_malloc(sizeof (int));
*lval = val;
gt_hashtable_add(stm->buffers, &lval);
stm->params[param_no].buffer_type = MYSQL_TYPE_LONG;
stm->params[param_no].buffer = (char*) lval;
stm->params[param_no].is_null = 0;
stm->params[param_no].length = 0;
return had_err;
}
static int gt_rdb_stmt_mysql_bind_ulong(GtRDBStmt *st, GtUword param_no,
GtUword val,
GT_UNUSED GtError *err)
{
GtRDBStmtMySQL *stm;
GtUword *lval;
int had_err = 0;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
gt_assert(param_no < stm->num_params);
lval = gt_malloc(sizeof (GtUword));
*lval = val;
gt_hashtable_add(stm->buffers, &lval);
stm->params[param_no].buffer_type = MYSQL_TYPE_LONG;
stm->params[param_no].is_unsigned = true;
stm->params[param_no].buffer = (char*) lval;
stm->params[param_no].is_null = 0;
stm->params[param_no].length = 0;
return had_err;
}
static int gt_rdb_stmt_mysql_bind_string(GtRDBStmt *st, GtUword param_no,
const char *val,
GT_UNUSED GtError *err)
{
GtRDBStmtMySQL *stm;
int had_err = 0;
char *str;
GtUword *length;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
gt_assert(param_no < stm->num_params);
/* allocate buffer for string until execution */
str = gt_calloc(strlen(val)+1, sizeof (char));
strncpy(str, val, strlen(val));
gt_hashtable_add(stm->buffers, &str);
/* allocate space for length */
length = gt_malloc(sizeof (GtUword));
*length = strlen(str);
gt_hashtable_add(stm->buffers, &length);
/* fill param structure */
stm->params[param_no].buffer_type = MYSQL_TYPE_STRING;
stm->params[param_no].buffer = str;
stm->params[param_no].is_null = 0;
stm->params[param_no].buffer_length = strlen(str);
stm->params[param_no].length = length;
return had_err;
}
static int gt_rdb_stmt_mysql_bind_double(GtRDBStmt *st, GtUword param_no,
double val, GT_UNUSED GtError *err)
{
GtRDBStmtMySQL *stm;
int had_err = 0;
double *lval;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
gt_assert(param_no < stm->num_params);
lval = gt_malloc(sizeof (double));
*lval = val;
gt_hashtable_add(stm->buffers, &lval);
stm->params[param_no].buffer_type = MYSQL_TYPE_DOUBLE;
stm->params[param_no].is_unsigned = false;
stm->params[param_no].buffer = (char*) lval;
stm->params[param_no].is_null = 0;
stm->params[param_no].length = 0;
return had_err;
}
#define CHECK_INIT_STATEMENT \
if (!stm->stmt || !stm->executed) { \
gt_error_set(err, "uninitialized statement"); \
had_err = -1; \
} \
if (!had_err && !stm->results) { \
gt_error_set(err, "results not fetched!"); \
had_err = -1; \
}
static int gt_rdb_stmt_mysql_get_int(GtRDBStmt *st, GtUword field_no,
int *result, GtError *err)
{
GtRDBStmtMySQL *stm;
int had_err = 0;
gt_assert(st && result);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
CHECK_INIT_STATEMENT
if (!had_err /* TODO: check these VVV */
&& stm->results[field_no].buffer_type != MYSQL_TYPE_LONG
&& stm->results[field_no].buffer_type != MYSQL_TYPE_TINY
&& stm->results[field_no].buffer_type != MYSQL_TYPE_INT24
&& stm->results[field_no].buffer_type != MYSQL_TYPE_SHORT) {
gt_error_set(err, "incompatible type: %d!",
stm->results[field_no].buffer_type);
had_err = -1;
}
if (!had_err) {
switch (stm->results[field_no].buffer_type) {
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_INT24:
{int val = *(int*) stm->results[field_no].buffer;
*result = val;}
break;
case MYSQL_TYPE_SHORT:
{short int val = *(short int*) stm->results[field_no].buffer;
*result = (int) val;}
break;
case MYSQL_TYPE_TINY:
{signed char val = *(signed char*) stm->results[field_no].buffer;
*result = (int) val;}
break;
default:
gt_assert(false); /* should not happen */
}
}
return had_err;
}
static int gt_rdb_stmt_mysql_get_ulong(GtRDBStmt *st, GtUword field_no,
GtUword *result, GtError *err)
{
GtRDBStmtMySQL *stm;
int had_err = 0;
gt_assert(st && result);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
CHECK_INIT_STATEMENT
if (!had_err && stm->results[field_no].buffer_type != MYSQL_TYPE_LONG) {
gt_error_set(err, "incompatible type!");
had_err = -1;
}
if (!had_err)
*result = *(GtUword*) stm->results[field_no].buffer;
return had_err;
}
static int gt_rdb_stmt_mysql_get_string(GtRDBStmt *st, GtUword field_no,
GtStr *result, GtError *err)
{
GtRDBStmtMySQL *stm;
int had_err = 0;
gt_assert(st && result);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
CHECK_INIT_STATEMENT
if (!had_err
&& stm->results[field_no].buffer_type != MYSQL_TYPE_STRING
&& stm->results[field_no].buffer_type != MYSQL_TYPE_VAR_STRING
&& stm->results[field_no].buffer_type != MYSQL_TYPE_BLOB
&& stm->results[field_no].buffer_type != MYSQL_TYPE_TINY_BLOB
&& stm->results[field_no].buffer_type != MYSQL_TYPE_MEDIUM_BLOB
&& stm->results[field_no].buffer_type != MYSQL_TYPE_LONG_BLOB
&& stm->results[field_no].buffer_type != MYSQL_TYPE_BIT)
{
gt_error_set(err, "incompatible type!");
had_err = -1;
}
if (!had_err) {
gt_str_reset(result);
gt_str_append_cstr_nt(result,
(char*)stm->results[field_no].buffer,
*stm->results[field_no].length);
}
return had_err;
}
static int gt_rdb_stmt_mysql_get_double(GtRDBStmt *st, GtUword field_no,
double *result, GtError *err)
{
GtRDBStmtMySQL *stm;
MYSQL_BIND res_bind;
int had_err = 0;
double res_double = GT_UNDEF_DOUBLE;
my_bool error, is_null;
gt_assert(st && result);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
CHECK_INIT_STATEMENT
if (!had_err) {
memset(&res_bind, 0, sizeof (res_bind));
res_bind.buffer_type = MYSQL_TYPE_DOUBLE;
res_bind.buffer = &res_double;
res_bind.error = &error;
res_bind.is_null = &is_null;
if ((had_err = mysql_stmt_fetch_column(stm->stmt, &res_bind, field_no, 0)))
gt_error_set(err, GT_MYSQL_ERRMSG, had_err, mysql_stmt_error(stm->stmt));
}
if (!had_err)
*result = res_double;
return had_err;
}
static int gt_rdb_stmt_mysql_exec(GtRDBStmt *st, GtError *err)
{
GtRDBStmtMySQL *stm;
int rval, had_err = 0, num_fields;
MYSQL_RES *meta_res = NULL;
gt_assert(st);
gt_error_check(err);
stm = gt_rdb_stmt_mysql_cast(st);
if (!stm->executed) {
if (stm->num_params > 0) {
gt_assert(stm->stmt && stm->params);
if ((rval = mysql_stmt_bind_param(stm->stmt, stm->params))) {
gt_error_set(err, GT_MYSQL_ERRMSG, rval, mysql_stmt_error(stm->stmt));
had_err = -1;
}
}
if (!had_err && (rval = mysql_stmt_execute(stm->stmt))) {
gt_error_set(err, GT_MYSQL_ERRMSG, rval, mysql_stmt_error(stm->stmt));
had_err = -1;
}
if (!had_err) {
stm->executed = true;
if (mysql_stmt_store_result(stm->stmt)) {
gt_error_set(err, GT_MYSQL_ERRMSG,
had_err, mysql_stmt_error(stm->stmt));
had_err = -1;
}
meta_res = mysql_stmt_result_metadata(stm->stmt);
if (!had_err && meta_res) {
int i = 0;
/* statement returned a result */
num_fields = mysql_num_fields(meta_res);
stm->results = gt_calloc(num_fields, sizeof (MYSQL_BIND));
/* prepare result buffers for each field */
for (i=0;i<num_fields;i++) {
MYSQL_FIELD *field;
field = mysql_fetch_field(meta_res);
stm->results[i].buffer_type = field->type;
switch (field->type) {
case MYSQL_TYPE_DOUBLE:
{double *dbl = gt_calloc(1, sizeof (double));
gt_hashtable_add(stm->buffers, &dbl);
stm->results[i].buffer_length = sizeof (double);
stm->results[i].buffer = dbl;}
break;
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_INT24:
{int *l = gt_calloc(1, sizeof (int));
gt_hashtable_add(stm->buffers, &l);
stm->results[i].is_unsigned = false;
stm->results[i].buffer_length = sizeof (int);
stm->results[i].buffer = l;}
case MYSQL_TYPE_SHORT:
{short int *l = gt_calloc(1, sizeof (short int));
gt_hashtable_add(stm->buffers, &l);
stm->results[i].is_unsigned = false;
stm->results[i].buffer_length = sizeof (short int);
stm->results[i].buffer = l;}
case MYSQL_TYPE_TINY:
{signed char *l = gt_calloc(1, sizeof (signed char));
gt_hashtable_add(stm->buffers, &l);
stm->results[i].is_unsigned = false;
stm->results[i].buffer_length = sizeof (signed char);
stm->results[i].buffer = l;}
break;
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BIT:
{char *str = gt_calloc(field->max_length+1, sizeof (char));
gt_hashtable_add(stm->buffers, &str);
GtUword *length = gt_calloc(1, sizeof (GtUword));
gt_hashtable_add(stm->buffers, &length);
stm->results[i].buffer = str;
stm->results[i].buffer_length = field->max_length;
stm->results[i].length = length;}
break;
default:
/* unsupported data type */
break;
}
}
if (!had_err)
mysql_stmt_bind_result(stm->stmt, stm->results);
mysql_free_result(meta_res);
} else {
return 1;
}
}
}
if (!had_err) {
switch ((rval = mysql_stmt_fetch(stm->stmt))) {
case 0:
default:
break;
case MYSQL_NO_DATA:
had_err = 1; /* last row read */
break;
case 1:
gt_error_set(err, GT_MYSQL_ERRMSG, mysql_stmt_errno(stm->stmt),
mysql_stmt_error(stm->stmt));
had_err = -1;
break;
}
}
return had_err;
}
const GtRDBClass* gt_rdb_mysql_class(void)
{
static const GtRDBClass *rdbm = NULL;
gt_class_alloc_lock_enter();
if (!rdbm) {
rdbm = gt_rdb_class_new(sizeof (GtRDBMySQL),
gt_rdb_mysql_delete,
gt_rdb_mysql_prepare,
gt_rdb_mysql_last_inserted_id,
gt_rdb_mysql_accept,
gt_rdb_mysql_get_indexes,
gt_rdb_mysql_get_tables);
}
gt_class_alloc_lock_leave();
return rdbm;
}
const GtRDBStmtClass* gt_rdb_stmt_mysql_class(void)
{
static const GtRDBStmtClass *rdbms = NULL;
gt_class_alloc_lock_enter();
if (!rdbms) {
rdbms = gt_rdb_stmt_class_new(sizeof (GtRDBStmtMySQL),
gt_rdb_stmt_mysql_reset,
gt_rdb_stmt_mysql_bind_int,
gt_rdb_stmt_mysql_bind_ulong,
gt_rdb_stmt_mysql_bind_string,
gt_rdb_stmt_mysql_bind_double,
gt_rdb_stmt_mysql_exec,
gt_rdb_stmt_mysql_get_int,
gt_rdb_stmt_mysql_get_ulong,
gt_rdb_stmt_mysql_get_string,
gt_rdb_stmt_mysql_get_double,
gt_rdb_stmt_mysql_delete);
}
gt_class_alloc_lock_leave();
return rdbms;
}
#endif
|
the_stack_data/40762501.c | // A mutex
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define check_status(expr, msg) do { \
if (!(expr)) { \
fprintf(stderr, "%s\n", msg); \
fprintf(stderr, " - errno # %d (%s)\n", errno, strerror(errno)); \
fprintf(stderr, " - line # %d (file # %s)\n", __LINE__, __FUNCTION__); \
exit(1); \
} \
} while (0)
static const uint64_t microseconds = 1000000 * 2;
static const uint64_t limit = 10;
static pthread_mutex_t mutex;
static uint64_t resource = 0;
// Function to be called for pthread
static void* thread_func(void *arg)
{
uint64_t count = 0;
int ret;
printf("ID of thread is %ld\n", pthread_self());
while (count++ < limit)
{
ret = pthread_mutex_lock(&mutex);
check_status(ret == 0, "Failed to lock mutex");
{
++resource;
}
ret = pthread_mutex_unlock(&mutex);
check_status(ret == 0, "Failed to unlock mutex");
usleep(microseconds);
}
printf("ID of thread is %ld -- finished\n", pthread_self());
(void)arg;
return NULL;
}
//
// App entry point
//
int main() {
uint64_t count = 0;
int ret;
pthread_t thread;
printf("--- main - start\n");
// Create a mutex
ret = pthread_mutex_init(&mutex, NULL);
check_status(ret == 0, "Failed to init mutex");
// Create a simple pthread with default settings
ret = pthread_create(&thread, NULL, thread_func, NULL);
check_status(ret == 0, "Failed to create pthread");
while (count++ < (limit + 5))
{
ret = pthread_mutex_trylock(&mutex);
if (ret == EBUSY)
{
printf("Resource is busy\n");
}
else if (ret == 0)
{
printf("Resource = %ld\n", resource);
ret = pthread_mutex_unlock(&mutex);
check_status(ret == 0, "Failed to unlock mutex");
}
usleep(microseconds);
}
// Wait for pthread to finish its execution
ret = pthread_join(thread, NULL);
check_status(ret == 0, "Failed to join pthread");
// Destroy mutex
ret = pthread_mutex_destroy(&mutex);
check_status(ret == 0, "Failed to destroy mutex");
printf("--- main - end\n");
return 0;
}
|
the_stack_data/1206206.c | // https://issues.dlang.org/show_bug.cgi?id=22757
typedef struct S S;
struct T {
int x;
};
struct S {
struct T *pChunk;
};
void foo(struct S pS){
void *p = &pS.pChunk;
}
|
the_stack_data/7949134.c | // 下面的表格给出了一个城市到另一个城市的每日航班信息。
// 编写一个程序,要求用户输入一个时间(用24小时制的时分表示)。
// 程序选择起飞时间与用户输入最接近的航班,显示出相应的起飞时间和抵达时间。
// 提示:把输入用从午夜开始的分钟数表示。
// 将这个时间与表格里也用从午夜开始的分钟数表示的起飞时间相比。
// 例如,13:15从午夜开始是13×60+15 =
// 795分钟,与下午12:47(从午夜开始是767分钟)最接近。
#include <stdio.h>
#define DEPARTURE_TIME_0 480 // 8:00 AM
#define DEPARTURE_TIME_1 583 // 9:43 AM
#define DEPARTURE_TIME_2 679 // 11:19 AM
#define DEPARTURE_TIME_3 767 // 12:47 AM
#define DEPARTURE_TIME_4 840 // 2:00 PM
#define DEPARTURE_TIME_5 945 // 3:45 PM
#define DEPARTURE_TIME_6 1140 // 7:00 PM
#define DEPARTURE_TIME_7 1305 // 9:45 PM
#define ARRIVE_TIME_0 616 // 10:16 AM
#define ARRIVE_TIME_1 712 // 11:52 AM
#define ARRIVE_TIME_2 811 // 1:31 PM
#define ARRIVE_TIME_3 900 // 3:00 PM
#define ARRIVE_TIME_4 968 // 4:08 PM
#define ARRIVE_TIME_5 1075 // 5:55 PM
#define ARRIVE_TIME_6 1280 // 9:20 PM
#define ARRIVE_TIME_7 1438 // 11:58 PM
int main() {
int hour, min;
printf("Enter a 24-hour time: ");
scanf("%d:%d", &hour, &min);
int input_time = hour * 60 + min;
int min_minus = 1440;
int arrive_hour, arrive_min;
if (DEPARTURE_TIME_0 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_0 - input_time)
min_minus = DEPARTURE_TIME_0 - input_time;
if (DEPARTURE_TIME_1 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_1 - input_time)
min_minus = DEPARTURE_TIME_1 - input_time;
if (DEPARTURE_TIME_2 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_2 - input_time)
min_minus = DEPARTURE_TIME_2 - input_time;
if (DEPARTURE_TIME_3 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_3 - input_time)
min_minus = DEPARTURE_TIME_3 - input_time;
if (DEPARTURE_TIME_4 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_4 - input_time)
min_minus = DEPARTURE_TIME_4 - input_time;
if (DEPARTURE_TIME_5 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_5 - input_time)
min_minus = DEPARTURE_TIME_5 - input_time;
if (DEPARTURE_TIME_6 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_6 - input_time)
min_minus = DEPARTURE_TIME_6 - input_time;
if (DEPARTURE_TIME_7 - input_time >= 0 &&
min_minus > DEPARTURE_TIME_7 - input_time)
min_minus = DEPARTURE_TIME_7 - input_time;
if (min_minus + input_time == DEPARTURE_TIME_0) {
arrive_hour = ARRIVE_TIME_0 / 60;
arrive_min = ARRIVE_TIME_0 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_1) {
arrive_hour = ARRIVE_TIME_1 / 60;
arrive_min = ARRIVE_TIME_1 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_2) {
arrive_hour = ARRIVE_TIME_2 / 60;
arrive_min = ARRIVE_TIME_2 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_3) {
arrive_hour = ARRIVE_TIME_3 / 60;
arrive_min = ARRIVE_TIME_3 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_4) {
arrive_hour = ARRIVE_TIME_4 / 60;
arrive_min = ARRIVE_TIME_4 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_5) {
arrive_hour = ARRIVE_TIME_5 / 60;
arrive_min = ARRIVE_TIME_5 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_6) {
arrive_hour = ARRIVE_TIME_6 / 60;
arrive_min = ARRIVE_TIME_6 - arrive_hour * 60;
}
if (min_minus + input_time == DEPARTURE_TIME_7) {
arrive_hour = ARRIVE_TIME_7 / 60;
arrive_min = ARRIVE_TIME_7 - arrive_hour * 60;
}
int depature_hour = (input_time + min_minus) / 60;
int depature_min = (input_time + min_minus) % 60;
if (depature_hour > 12 && arrive_hour > 12)
printf(
"Close departure time is %1d%1d:%1d%1d p.m., arriving at "
"%1d%1d:%1d%1d "
"p.m.\n",
(depature_hour - 12) / 10, (depature_hour - 12) % 10,
depature_min / 10, depature_min % 10, (arrive_hour - 12) / 10,
(arrive_hour - 12) % 10, arrive_min / 10, arrive_min % 10);
if (depature_hour <= 12 && arrive_hour > 12)
printf(
"Close departure time is %1d%1d:%1d%1d a.m., arriving at "
"%1d%1d:%1d%1d p.m.\n",
depature_hour / 10, depature_hour % 10, depature_min / 10,
depature_min % 10, (arrive_hour - 12) / 10, (arrive_hour - 12) % 10,
arrive_min / 10, arrive_min % 10);
if (depature_hour <= 12 && arrive_hour <= 12)
printf(
"Close departure time is %1d%1d:%1d%1d a.m., arriving at "
"%1d%1d:%1d%1d a.m.\n",
depature_hour / 10, depature_hour % 10, depature_min / 10,
depature_min % 10, arrive_hour / 10, arrive_hour % 10,
arrive_min / 10, arrive_min % 10);
return 0;
}
|
the_stack_data/130078.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern int __VERIFIER_nondet_int(void);
extern int printf (__const char *__restrict __format, ...);
/* Generated by CIL v. 1.3.7 */
/* print_CIL_Input is true */
struct JoinPoint {
void **(*fp)(struct JoinPoint * ) ;
void **args ;
int argsCount ;
char const **argsType ;
void *(*arg)(int , struct JoinPoint * ) ;
char const *(*argType)(int , struct JoinPoint * ) ;
void **retValue ;
char const *retType ;
char const *funcName ;
char const *targetName ;
char const *fileName ;
char const *kind ;
void *excep_return ;
};
struct __UTAC__CFLOW_FUNC {
int (*func)(int , int ) ;
int val ;
struct __UTAC__CFLOW_FUNC *next ;
};
struct __UTAC__EXCEPTION {
void *jumpbuf ;
unsigned long long prtValue ;
int pops ;
struct __UTAC__CFLOW_FUNC *cflowfuncs ;
};
typedef unsigned int size_t;
struct __ACC__ERR {
void *v ;
struct __ACC__ERR *next ;
};
#pragma merger(0,"Environment.i","")
void lowerWaterLevel(void) ;
void waterRise(void) ;
void changeMethaneLevel(void) ;
int isMethaneLevelCritical(void) ;
int getWaterLevel(void) ;
void printEnvironment(void) ;
int isHighWaterSensorDry(void) ;
int waterLevel = 1;
int methaneLevelCritical = 0;
void lowerWaterLevel(void)
{
{
if (waterLevel > 0) {
waterLevel = waterLevel - 1;
} else {
}
return;
}
}
void waterRise(void)
{
{
if (waterLevel < 2) {
waterLevel = waterLevel + 1;
} else {
}
return;
}
}
void changeMethaneLevel(void)
{
{
if (methaneLevelCritical) {
methaneLevelCritical = 0;
} else {
methaneLevelCritical = 1;
}
return;
}
}
int isMethaneLevelCritical(void)
{ int retValue_acc ;
{
retValue_acc = methaneLevelCritical;
return (retValue_acc);
return (retValue_acc);
}
}
void printEnvironment(void)
{
{
{
printf("Env(Water:%i", waterLevel);
printf(",Meth:");
}
if (methaneLevelCritical) {
{
printf("CRIT");
}
} else {
{
printf("OK");
}
}
{
printf(")");
}
return;
}
}
int getWaterLevel(void)
{ int retValue_acc ;
{
retValue_acc = waterLevel;
return (retValue_acc);
return (retValue_acc);
}
}
int isHighWaterSensorDry(void)
{ int retValue_acc ;
{
if (waterLevel < 2) {
retValue_acc = 1;
return (retValue_acc);
} else {
retValue_acc = 0;
return (retValue_acc);
}
return (retValue_acc);
}
}
#pragma merger(0,"libacc.i","")
extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion ,
char const *__file ,
unsigned int __line ,
char const *__function ) ;
extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ;
extern __attribute__((__nothrow__)) void free(void *__ptr ) ;
void __utac__exception__cf_handler_set(void *exception , int (*cflow_func)(int ,
int ) ,
int val )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
void *tmp ;
unsigned long __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
int (**mem_15)(int , int ) ;
int *mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
struct __UTAC__CFLOW_FUNC **mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
{
excep = (struct __UTAC__EXCEPTION *)exception;
tmp = malloc(24UL);
cf = (struct __UTAC__CFLOW_FUNC *)tmp;
mem_15 = (int (**)(int , int ))cf;
*mem_15 = cflow_func;
__cil_tmp7 = (unsigned long )cf;
__cil_tmp8 = __cil_tmp7 + 8;
mem_16 = (int *)__cil_tmp8;
*mem_16 = val;
__cil_tmp9 = (unsigned long )cf;
__cil_tmp10 = __cil_tmp9 + 16;
__cil_tmp11 = (unsigned long )excep;
__cil_tmp12 = __cil_tmp11 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp10;
mem_18 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp12;
*mem_17 = *mem_18;
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_19 = cf;
}
return;
}
}
void __utac__exception__cf_handler_free(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
struct __UTAC__CFLOW_FUNC *tmp ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
void *__cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
struct __UTAC__CFLOW_FUNC **mem_15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_15 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_15;
{
while (1) {
while_0_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_0_break;
}
}
{
tmp = cf;
__cil_tmp10 = (unsigned long )cf;
__cil_tmp11 = __cil_tmp10 + 16;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp11;
cf = *mem_16;
__cil_tmp12 = (void *)tmp;
free(__cil_tmp12);
}
}
while_0_break: /* CIL Label */ ;
}
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_17 = (struct __UTAC__CFLOW_FUNC *)0;
return;
}
}
void __utac__exception__cf_handler_reset(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
int (*__cil_tmp10)(int , int ) ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
int __cil_tmp13 ;
unsigned long __cil_tmp14 ;
unsigned long __cil_tmp15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
int (**mem_17)(int , int ) ;
int *mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_16;
{
while (1) {
while_1_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_1_break;
}
}
{
mem_17 = (int (**)(int , int ))cf;
__cil_tmp10 = *mem_17;
__cil_tmp11 = (unsigned long )cf;
__cil_tmp12 = __cil_tmp11 + 8;
mem_18 = (int *)__cil_tmp12;
__cil_tmp13 = *mem_18;
(*__cil_tmp10)(4, __cil_tmp13);
__cil_tmp14 = (unsigned long )cf;
__cil_tmp15 = __cil_tmp14 + 16;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp15;
cf = *mem_19;
}
}
while_1_break: /* CIL Label */ ;
}
{
__utac__exception__cf_handler_free(exception);
}
return;
}
}
void *__utac__error_stack_mgt(void *env , int mode , int count ) ;
static struct __ACC__ERR *head = (struct __ACC__ERR *)0;
void *__utac__error_stack_mgt(void *env , int mode , int count )
{ void *retValue_acc ;
struct __ACC__ERR *new ;
void *tmp ;
struct __ACC__ERR *temp ;
struct __ACC__ERR *next ;
void *excep ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
void *__cil_tmp14 ;
unsigned long __cil_tmp15 ;
unsigned long __cil_tmp16 ;
void *__cil_tmp17 ;
void **mem_18 ;
struct __ACC__ERR **mem_19 ;
struct __ACC__ERR **mem_20 ;
void **mem_21 ;
struct __ACC__ERR **mem_22 ;
void **mem_23 ;
void **mem_24 ;
{
if (count == 0) {
return (retValue_acc);
} else {
}
if (mode == 0) {
{
tmp = malloc(16UL);
new = (struct __ACC__ERR *)tmp;
mem_18 = (void **)new;
*mem_18 = env;
__cil_tmp10 = (unsigned long )new;
__cil_tmp11 = __cil_tmp10 + 8;
mem_19 = (struct __ACC__ERR **)__cil_tmp11;
*mem_19 = head;
head = new;
retValue_acc = (void *)new;
}
return (retValue_acc);
} else {
}
if (mode == 1) {
temp = head;
{
while (1) {
while_2_continue: /* CIL Label */ ;
if (count > 1) {
} else {
goto while_2_break;
}
{
__cil_tmp12 = (unsigned long )temp;
__cil_tmp13 = __cil_tmp12 + 8;
mem_20 = (struct __ACC__ERR **)__cil_tmp13;
next = *mem_20;
mem_21 = (void **)temp;
excep = *mem_21;
__cil_tmp14 = (void *)temp;
free(__cil_tmp14);
__utac__exception__cf_handler_reset(excep);
temp = next;
count = count - 1;
}
}
while_2_break: /* CIL Label */ ;
}
{
__cil_tmp15 = (unsigned long )temp;
__cil_tmp16 = __cil_tmp15 + 8;
mem_22 = (struct __ACC__ERR **)__cil_tmp16;
head = *mem_22;
mem_23 = (void **)temp;
excep = *mem_23;
__cil_tmp17 = (void *)temp;
free(__cil_tmp17);
__utac__exception__cf_handler_reset(excep);
retValue_acc = excep;
}
return (retValue_acc);
} else {
}
if (mode == 2) {
if (head) {
mem_24 = (void **)head;
retValue_acc = *mem_24;
return (retValue_acc);
} else {
retValue_acc = (void *)0;
return (retValue_acc);
}
} else {
}
return (retValue_acc);
}
}
void *__utac__get_this_arg(int i , struct JoinPoint *this )
{ void *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
void **__cil_tmp10 ;
void **__cil_tmp11 ;
int *mem_12 ;
void ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 8;
mem_13 = (void ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
char const *__utac__get_this_argtype(int i , struct JoinPoint *this )
{ char const *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
char const **__cil_tmp10 ;
char const **__cil_tmp11 ;
int *mem_12 ;
char const ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 24;
mem_13 = (char const ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"MinePump.i","")
void timeShift(void) ;
void activatePump(void) ;
void deactivatePump(void) ;
int isPumpRunning(void) ;
void printPump(void) ;
void stopSystem(void) ;
void startSystem(void) ;
int pumpRunning = 0;
int systemActive = 1;
void __utac_acc__Specification5_spec__2(void) ;
void __utac_acc__Specification5_spec__3(void) ;
void processEnvironment(void) ;
void timeShift(void)
{
{
{
__utac_acc__Specification5_spec__2();
}
if (pumpRunning) {
{
lowerWaterLevel();
}
} else {
}
if (systemActive) {
{
processEnvironment();
}
} else {
}
{
__utac_acc__Specification5_spec__3();
}
return;
}
}
void processEnvironment__wrappee__base(void)
{
{
return;
}
}
int isHighWaterLevel(void) ;
void processEnvironment(void)
{ int tmp ;
{
if (! pumpRunning) {
{
tmp = isHighWaterLevel();
}
if (tmp) {
{
activatePump();
}
} else {
{
processEnvironment__wrappee__base();
}
}
} else {
{
processEnvironment__wrappee__base();
}
}
return;
}
}
void activatePump__wrappee__highWaterSensor(void)
{
{
pumpRunning = 1;
return;
}
}
int isMethaneAlarm(void) ;
void activatePump(void)
{ int tmp ;
{
{
tmp = isMethaneAlarm();
}
if (tmp) {
} else {
{
activatePump__wrappee__highWaterSensor();
}
}
return;
}
}
void deactivatePump(void)
{
{
pumpRunning = 0;
return;
}
}
int isMethaneAlarm(void)
{ int retValue_acc ;
{
{
retValue_acc = isMethaneLevelCritical();
}
return (retValue_acc);
return (retValue_acc);
}
}
int isPumpRunning(void)
{ int retValue_acc ;
{
retValue_acc = pumpRunning;
return (retValue_acc);
return (retValue_acc);
}
}
void printPump(void)
{
{
{
printf("Pump(System:");
}
if (systemActive) {
{
printf("On");
}
} else {
{
printf("Off");
}
}
{
printf(",Pump:");
}
if (pumpRunning) {
{
printf("On");
}
} else {
{
printf("Off");
}
}
{
printf(") ");
printEnvironment();
printf("\n");
}
return;
}
}
int isHighWaterLevel(void)
{ int retValue_acc ;
int tmp ;
int tmp___0 ;
{
{
tmp = isHighWaterSensorDry();
}
if (tmp) {
tmp___0 = 0;
} else {
tmp___0 = 1;
}
retValue_acc = tmp___0;
return (retValue_acc);
return (retValue_acc);
}
}
void stopSystem(void)
{
{
if (pumpRunning) {
{
deactivatePump();
}
} else {
}
systemActive = 0;
return;
}
}
void startSystem(void)
{
{
systemActive = 1;
return;
}
}
#pragma merger(0,"scenario.i","")
void cleanup(void) ;
void test(void)
{ int splverifierCounter ;
int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
{
splverifierCounter = 0;
{
while (1) {
while_3_continue: /* CIL Label */ ;
if (splverifierCounter < 4) {
} else {
goto while_3_break;
}
{
tmp = __VERIFIER_nondet_int();
}
if (tmp) {
{
waterRise();
}
} else {
}
{
tmp___0 = __VERIFIER_nondet_int();
}
if (tmp___0) {
{
changeMethaneLevel();
}
} else {
}
{
tmp___2 = __VERIFIER_nondet_int();
}
if (tmp___2) {
{
startSystem();
}
} else {
{
tmp___1 = __VERIFIER_nondet_int();
}
if (tmp___1) {
{
stopSystem();
}
} else {
}
}
{
timeShift();
}
}
while_3_break: /* CIL Label */ ;
}
{
cleanup();
}
return;
}
}
#pragma merger(0,"featureselect.i","")
int select_one(void) ;
void select_features(void) ;
void select_helpers(void) ;
int valid_product(void) ;
int select_one(void)
{ int retValue_acc ;
int choice = __VERIFIER_nondet_int();
{
retValue_acc = choice;
return (retValue_acc);
return (retValue_acc);
}
}
void select_features(void)
{
{
return;
}
}
void select_helpers(void)
{
{
return;
}
}
int valid_product(void)
{ int retValue_acc ;
{
retValue_acc = 1;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"Test.i","")
int cleanupTimeShifts = 4;
void cleanup(void)
{ int i ;
int __cil_tmp2 ;
{
{
timeShift();
i = 0;
}
{
while (1) {
while_4_continue: /* CIL Label */ ;
{
__cil_tmp2 = cleanupTimeShifts - 1;
if (i < __cil_tmp2) {
} else {
goto while_4_break;
}
}
{
timeShift();
i = i + 1;
}
}
while_4_break: /* CIL Label */ ;
}
return;
}
}
void Specification2(void)
{
{
{
timeShift();
printPump();
timeShift();
printPump();
timeShift();
printPump();
waterRise();
printPump();
timeShift();
printPump();
changeMethaneLevel();
printPump();
timeShift();
printPump();
cleanup();
}
return;
}
}
void setup(void)
{
{
return;
}
}
void __utac_acc__Specification5_spec__1(void) ;
void runTest(void)
{
{
{
__utac_acc__Specification5_spec__1();
test();
}
return;
}
}
int main(void)
{ int retValue_acc ;
int tmp ;
{
{
select_helpers();
select_features();
tmp = valid_product();
}
if (tmp) {
{
setup();
runTest();
}
} else {
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"wsllib_check.i","")
void __automaton_fail(void)
{
{
ERROR: __VERIFIER_error();
return;
}
}
#pragma merger(0,"Specification5_spec.i","")
int switchedOnBeforeTS ;
void __utac_acc__Specification5_spec__1(void)
{
{
switchedOnBeforeTS = 0;
return;
}
}
void __utac_acc__Specification5_spec__2(void)
{
{
{
switchedOnBeforeTS = isPumpRunning();
}
return;
}
}
void __utac_acc__Specification5_spec__3(void)
{ int tmp ;
int tmp___0 ;
{
{
tmp = getWaterLevel();
}
if (tmp != 2) {
{
tmp___0 = isPumpRunning();
}
if (tmp___0) {
if (! switchedOnBeforeTS) {
{
__automaton_fail();
}
} else {
}
} else {
}
} else {
}
return;
}
}
|
the_stack_data/618035.c | /*
* Copyright 2016 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char** argv) {
int retval = open("NonExistingFile", O_RDONLY);
if (retval == -1) perror("Cannot open NonExistingFile");
return 0;
}
|
the_stack_data/40763689.c | #include <stdio.h>
#include <stdlib.h>
//Insertion and deletion in Binary Search Tree
struct Node
{
struct Node* left;
int data;
struct Node* right;
};
struct Queue
{
struct Node* data;
struct Queue* next;
};
struct Queue* front = NULL;
struct Queue* rear = NULL;
int isEmpty()
{
if(front==NULL)
return 1;
else
return 0;
}
void Pop()
{
if(isEmpty())
return;
struct Queue* temp = front;
front = front->next;
free(temp);
}
struct Node* Pfront()
{
struct Node* temp ;
temp = front->data;
return temp;
}
void Enqeue(struct Node* data)
{
struct Queue* temp;
temp = (struct Queue*)malloc(sizeof(struct Queue));
temp->data = data;
temp->next=NULL;
if(front==NULL && rear==NULL)
{
front = rear = temp;
return;
}
rear->next = temp;
rear =temp;
}
struct Node* NewNode(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->left = NULL;
temp->data = data;
temp->right = NULL;
return temp;
}
void PostOrder(struct Node* root)
{
if(root==NULL)
return;
PostOrder(root->left);
PostOrder(root->right);
printf("%d ",root->data);
}
struct Node* FindMin(struct Node* root)
{
while(root->left!=NULL)
root = root->left;
return root;
}
void LevelOrder(struct Node* root)
{
if(root==NULL)
return;
Enqeue(root);
while(!isEmpty())
{
struct Node* current = Pfront();
printf("%d ",current->data);
if(current->left!=NULL)
Enqeue(current->left);
if(current->right!=NULL)
Enqeue(current->right);
Pop();
}
}
struct Node* Delete(struct Node* root,int data)
{
if(root==NULL)
return root;
else if(data < root->data)
root->left = Delete(root->left,data);
else if(data > root->data)
root->right = Delete(root->right,data);
else
{
if(root->left==NULL && root->right==NULL)
{
free(root);
root = NULL;
}
else if(root->left!=NULL && root->right==NULL)
{
struct Node* temp = root->left;
free(temp);
root = root->left;
}
else if(root->right!=NULL&& root->left==NULL)
{
struct Node* temp = root->right;
free(temp);
root = root->right;
}
else
{
struct Node* temp = FindMin(root->right);
root->data = temp->data;
root->right = Delete(root->right,temp->data);
}
}
return root;
}
void InOrder(struct Node* root)
{
if(root==NULL)
return;
InOrder(root->left);
printf("%d ",root->data);
InOrder(root->right);
}
void PreOrder(struct Node* root)
{
if(root==NULL)
return;
printf("%d ",root->data);
PreOrder(root->left);
PreOrder(root->right);
}
struct Node* insert(struct Node* root,int data)
{
if(root==NULL)
root = NewNode(data);
else if(data <= root->data)
root->left = insert(root->left,data);
else root->right = insert(root->right,data);
return root;
}
void traverse(struct Node* root)
{
printf("\n\nPreOrder traversal : "); PreOrder(root);
printf("\nInorder traversal : "); InOrder(root);
printf("\nPostOrder traversal: "); PostOrder(root);
printf("\n Level Order Traversal: ");LevelOrder(root);
}
int main()
{
struct Node* root = NULL;
root = insert(root,12);
root = insert(root,5);
root = insert(root,8);
root = insert(root,1);
root = insert(root,9);
root = insert(root,7);
traverse(root);
Delete(root,8);
traverse(root);
return 0;
}
|
the_stack_data/299719.c | #include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"unistd.h"
#include"sys/wait.h"
#include"errno.h"
pid_t waitForAllChld(int *loc);
int main (int argc, char *argv[])
{
pid_t childpid = 0;
int i, n;
int status;
if (argc != 2)
{
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
{
childpid=fork();
if (childpid <=0)
break;
}
while(waitForAllChld(NULL)>0);
fprintf(stderr, "i:%d process ID:%ld parent ID:%ldchild ID:%ld\n",i, (long)getpid(), (long)getppid(),
(long)childpid);
sleep(120);
return 0;
}
pid_t waitForAllChld(int *loc)
{
int retval;
while(((retval=wait(loc))==-1) && (errno==EINTR));
return retval;
}
|
the_stack_data/39641.c | #include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
double atof(const char *s)
{
double val, power;
size_t i = 0;
int sign = 0;
while (isspace(*s)) {
++i;
}
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-') {
i++;
}
for (val = 0.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
}
if (s[i] == '.') {
i++;
}
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
|
the_stack_data/220456822.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* A FAIRE : complétez le début de ce programme. */
#define N(x) (sizeof(x)/sizeof(*x))
#define CHAR_LENGTH_MAX 1024
typedef char* (*Fonction)(const char*);
char* copy(const char* s);
char* to_upper_case_all_a(const char* s);
char* split_at_third_space(const char* s);
char* append_hello(const char* s);
void iterate_over_functions(const char* inputs[], size_t nb_inputs,
Fonction my_functions[], size_t nb_functions);
int main() {
const char* inputs[] = {
"Hallo Anno! Cammant ca va ? Ahlala...",
"aaaaa",
" a a a a a ",
"Une phrose sons oucun o"
};
/* A FAIRE : définissez ici my_functions. */
Fonction my_functions[4] = {
copy,
to_upper_case_all_a,
split_at_third_space,
append_hello
};
iterate_over_functions(inputs, N(inputs),
my_functions, N(my_functions));
return 0;
}
void iterate_over_functions(const char* inputs[], size_t nb_inputs,
Fonction my_functions[], size_t nb_functions)
{
for(int j=0; j<nb_functions; ++j){
Fonction f = my_functions[j];
printf("applying transformation #%d:\n", j);
for(int i=0; i<nb_inputs; ++i){
const char* s = inputs[i];
char* applied = f(s);
printf("\t-> \"%s\"\n", applied);
free(applied);
}
}
}
char* copy(const char* s)
{
size_t len = strlen(s);
char* cpy = calloc(strlen(s)+1, sizeof(char));
if(cpy == NULL){
return NULL;
}
cpy[len] = '\0';
strncpy(cpy, s, len);
return cpy;
}
char* to_upper_case_all_a(const char* s)
{
char* cpy = copy(s);
for(int i=0; i<strlen(cpy); ++i){
char c = cpy[i];
if(c == 'a'){
cpy[i] = 'A';
}
}
return cpy;
}
char* split_at_third_space(const char* s)
{
char* cpy = copy(s);
size_t space = 0;
for(int i=0; i<strlen(cpy); ++i){
char c = cpy[i];
if(c == ' '){
space += 1;
}
if(space >= 3){
cpy[i] = '\0';
return cpy;
}
}
return cpy;
}
char* append_hello(const char* s)
{
size_t len = strlen(s);
char* cpy = copy(s);
cpy = realloc(cpy, len+5+1);
strncpy(cpy+len, "hello", 5);
cpy[len+5] = '\0';
return cpy;
}
|
the_stack_data/179830753.c | /*
** 2006 June 14
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Test extension for testing the sqlite3_load_extension() function.
*/
#include <string.h>
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
/*
** The half() SQL function returns half of its input value.
*/
void halfFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
sqlite3_result_double(context, 0.5*sqlite3_value_double(argv[0]));
}
/*
** SQL functions to call the sqlite3_status function and return results.
*/
void statusFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
int op = 0, mx, cur, resetFlag, rc;
if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
op = sqlite3_value_int(argv[0]);
}else if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
int i;
const char *zName;
static const struct {
const char *zName;
int op;
} aOp[] = {
{ "MEMORY_USED", SQLITE_STATUS_MEMORY_USED },
{ "PAGECACHE_USED", SQLITE_STATUS_PAGECACHE_USED },
{ "PAGECACHE_OVERFLOW", SQLITE_STATUS_PAGECACHE_OVERFLOW },
{ "SCRATCH_USED", SQLITE_STATUS_SCRATCH_USED },
{ "SCRATCH_OVERFLOW", SQLITE_STATUS_SCRATCH_OVERFLOW },
{ "MALLOC_SIZE", SQLITE_STATUS_MALLOC_SIZE },
};
int nOp = sizeof(aOp)/sizeof(aOp[0]);
zName = (const char*)sqlite3_value_text(argv[0]);
for(i=0; i<nOp; i++){
if( strcmp(aOp[i].zName, zName)==0 ){
op = aOp[i].op;
break;
}
}
if( i>=nOp ){
char *zMsg = sqlite3_mprintf("unknown status property: %s", zName);
sqlite3_result_error(context, zMsg, -1);
sqlite3_free(zMsg);
return;
}
}else{
sqlite3_result_error(context, "unknown status type", -1);
return;
}
if( argc==2 ){
resetFlag = sqlite3_value_int(argv[1]);
}else{
resetFlag = 0;
}
rc = sqlite3_status(op, &cur, &mx, resetFlag);
if( rc!=SQLITE_OK ){
char *zMsg = sqlite3_mprintf("sqlite3_status(%d,...) returns %d", op, rc);
sqlite3_result_error(context, zMsg, -1);
sqlite3_free(zMsg);
return;
}
if( argc==2 ){
sqlite3_result_int(context, mx);
}else{
sqlite3_result_int(context, cur);
}
}
/*
** Extension load function.
*/
#ifdef _WIN32
__declspec(dllexport)
#endif
int testloadext_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
int nErr = 0;
SQLITE_EXTENSION_INIT2(pApi);
nErr |= sqlite3_create_function(db, "half", 1, SQLITE_ANY, 0, halfFunc, 0, 0);
nErr |= sqlite3_create_function(db, "sqlite3_status", 1, SQLITE_ANY, 0,
statusFunc, 0, 0);
nErr |= sqlite3_create_function(db, "sqlite3_status", 2, SQLITE_ANY, 0,
statusFunc, 0, 0);
return nErr ? SQLITE_ERROR : SQLITE_OK;
}
/*
** Another extension entry point. This one always fails.
*/
#ifdef _WIN32
__declspec(dllexport)
#endif
int testbrokenext_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
char *zErr;
SQLITE_EXTENSION_INIT2(pApi);
zErr = sqlite3_mprintf("broken!");
*pzErrMsg = zErr;
return 1;
}
|
the_stack_data/74616.c | #include<stdio.h>
int main()
{
int i,j,n,s;
int arr[11]={2,5,7,8,14,16,22,25,30,45};
printf("The sorted array is:-\n");
for(i=0;i<10;i++)
printf("%d, ",arr[i]);
//New element to insert
printf("\nEnter the new element to be inserted:-");
scanf("%d",&n);
//Put element in array using shift
for(i=0;i<10;i++)
{
if(arr[i]<n)
continue;
else
{
s=i;
break;
}
}
s=i;
for(i=9;i>=s;i--)
arr[i+1]=arr[i]; //Shifting
arr[s]=n;
printf("The new sorted array after insertion is:-\n");
for(i=0;i<11;i++)
printf("%d, ",arr[i]);
return 0;
}
|
the_stack_data/53150.c | /*
* mma8451.c
*
* Created on: 19/08/2019
* Author: Evandro Teixeira
*/
|
the_stack_data/43886679.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main(){
setlocale(LC_ALL, "");
printf("\n\n");
system("pause");
return 0;
}
|
the_stack_data/672724.c | const unsigned char dot_frag_spv[] = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x08, 0x00, 0x13, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x06, 0x00,
0x01, 0x00, 0x00, 0x00, 0x47, 0x4C, 0x53, 0x4C, 0x2E, 0x73, 0x74, 0x64, 0x2E, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x0F, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x69, 0x6E,
0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xC2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x69, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0x53, 0x53, 0x42, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x05, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x64, 0x00,
0x05, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
0x12, 0x00, 0x00, 0x00, 0x6F, 0x75, 0x74, 0x5F, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x03, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3B, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x2B, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2B, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x16, 0x00, 0x03, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00,
0x10, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x11, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3B, 0x00, 0x04, 0x00,
0x11, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00,
0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0xF8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x0C, 0x00, 0x00, 0x00,
0x0D, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x03, 0x00,
0x0D, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00
};
const int dot_frag_spv_size = 544;
|
the_stack_data/220454571.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
/*
stringizing operator #
- converts macro parameters to string literals
*/
/*
## operator combines two tokens into a single token
*/
int main()
{
return 0;
}
/*
Macro or Function ?
- no space in the macro name
- Use parentheses
- Use capital letters for macro function names
- Speed up?
*/
|
the_stack_data/161081712.c | #include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int main() {
char string[SIZE] = "Test";
printf("%s\n", string);
return 0;
}
|
the_stack_data/94350.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_numbers.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kchenna <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/19 16:06:09 by kchenna #+# #+# */
/* Updated: 2018/09/19 16:45:15 by kchenna ### ########.fr */
/* */
/* ************************************************************************** */
void ft_print_numbers(void)
{
char number;
number = '0';
while (number < ('9' + 1))
{
ft_putchar(number);
number += 1;
}
}
|
the_stack_data/59513973.c | #include <stdint.h>
#include <stdbool.h>
static inline uint32_t rotr32(uint32_t n, uint32_t e) {
return (n << e) | ( n >> ( (-e)&31) );
}
// does d divide n?
// d = 2**e * d_odd; dbar = multiplicative_inverse(d_odd)
// thresh = 0xffffffff / d
bool gm_divisible(uint32_t n,
uint32_t e, uint32_t dbar,
uint32_t thresh) {
return rotr32(n * dbar, e) <= thresh;
}
|
the_stack_data/26700633.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
char **get_input(char *);
int cd(char *);
int main() {
char **command;
char *input;
pid_t child_pid;
int stat_loc;
signal(SIGINT, SIG_IGN);
while (1) {
input = readline("unixsh> ");
command = get_input(input);
if (!command[0]) { /* Handle empty commands */
free(input);
free(command);
continue;
}
if (strcmp(command[0], "cd") == 0) {
if (cd(command[1]) < 0) {
perror(command[1]);
}
/* Skip the fork */
continue;
}
child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
}
if (child_pid == 0) {
signal(SIGINT, SIG_DFL);
/* Never returns if the call is successful */
if (execvp(command[0], command) < 0) {
perror(command[0]);
exit(1);
}
} else {
waitpid(child_pid, &stat_loc, WUNTRACED);
}
if (!input)
free(input);
if (!command)
free(command);
}
return 0;
}
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
if (command == NULL) {
perror("malloc failed");
exit(1);
}
char *separator = " ";
char *parsed;
int index = 0;
parsed = strtok(input, separator);
while (parsed != NULL) {
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
int cd(char *path) {
return chdir(path);
}
|
the_stack_data/851571.c | /* { dg-do compile } */
/* { dg-options "-O -fdump-tree-cddce1" } */
__SIZE_TYPE__
fx (char *a, __SIZE_TYPE__ sz)
{
char *b = a + sz;
/* The first forwprop pass should optimize this to return sz; */
return b - a;
}
/* { dg-final { scan-tree-dump "return sz" "cddce1" } } */
|
the_stack_data/117329340.c |
#line 3 "lex.yy.c"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
extern int yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 3
#define YY_END_OF_BUFFER 4
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[10] =
{ 0,
0, 0, 4, 3, 3, 1, 2, 1, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 1, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[5] =
{ 0,
1, 2, 1, 3
} ;
static yyconst flex_int16_t yy_base[12] =
{ 0,
0, 0, 7, 8, 0, 0, 8, 0, 8, 4,
2
} ;
static yyconst flex_int16_t yy_def[12] =
{ 0,
9, 1, 9, 9, 10, 11, 9, 11, 0, 9,
9
} ;
static yyconst flex_int16_t yy_nxt[13] =
{ 0,
4, 4, 5, 6, 8, 7, 9, 3, 9, 9,
9, 9
} ;
static yyconst flex_int16_t yy_chk[13] =
{ 0,
1, 1, 1, 1, 11, 10, 3, 9, 9, 9,
9, 9
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "inden.l"
#line 2 "inden.l"
#include<stdio.h>
#line 455 "lex.yy.c"
#define INITIAL 0
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
int yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
static void yyunput (int c,char *buf_ptr );
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
unsigned n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 5 "inden.l"
#line 639 "lex.yy.c"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 10 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 8 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 6 "inden.l"
{ printf("\nIs valid: %s",yytext);}
YY_BREAK
case 2:
/* rule 2 can match eol */
YY_RULE_SETUP
#line 7 "inden.l"
{ printf("\ninvalid");}
YY_BREAK
case 3:
YY_RULE_SETUP
#line 8 "inden.l"
ECHO;
YY_BREAK
#line 738 "lex.yy.c"
case YY_STATE_EOF(INITIAL):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 10 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 10 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 9);
return yy_is_jam ? 0 : yy_current_state;
}
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up yytext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register int number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
int num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
int yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 8 "inden.l"
main()
{
yylex();
}
|
the_stack_data/67324249.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[]) {
if (argc < 2) {
printf("Sintassi: %s <media>\n", argv[0]);
return 1;
}
double x = atof(argv[1]);
double p = (1+x+x*x/2+x*x*x/6+x*x*x*x/24)/pow(M_E, x);
printf("Probabilità promozione: %.2f%\n", p*100);
return 0;
}
|
the_stack_data/1032581.c | /* ASN.1 data display code, copyright Peter Gutmann
<[email protected]>, based on ASN.1 dump program by David Kemp,
with contributions from various people including Matthew Hamrick, Bruno
Couillard, Hallvard Furuseth, Geoff Thorpe, David Boyce, John Hughes,
'Life is hard, and then you die', Hans-Olof Hermansson, Tor Rustad,
Kjetil Barvik, James Sweeny, Chris Ridd, David Lemley, John Tobey, James
Manger and several other people whose names I've misplaced.
Available from http://www.cs.auckland.ac.nz/~pgut001/dumpasn1.c. Last
updated 19 December 2014 (version 20141219, if you prefer it that way).
To build under Windows, use 'cl /MD dumpasn1.c'. To build on OS390 or
z/OS, use '/bin/c89 -D OS390 -o dumpasn1 dumpasn1.c'.
This code grew slowly over time without much design or planning, and with
extra features being tacked on as required. It's not representative of my
normal coding style. cryptlib,
http://www.cs.auckland.ac.nz/~pgut001/cryptlib/, does a much better job of
checking ASN.1 than this does, since dumpasn1 is a display program written
to accept the widest possible range of input and not a compliance checker.
In other words it will bend over backwards to accept even invalid data,
since a common use for it is to try and locate encoding problems that lead
to invalid encoded data. While it will warn about some types of common
errors, the fact that dumpasn1 will display an ASN.1 data item doesn't mean
that the item is valid.
dumpasn1 requires a config file dumpasn1.cfg to be present in the same
location as the program itself or in a standard directory where binaries
live (it will run without it but will display a warning message, you can
configure the path either by hardcoding it in or using an environment
variable as explained further down). The config file is available from
http://www.cs.auckland.ac.nz/~pgut001/dumpasn1.cfg.
This code assumes that the input data is binary, having come from a MIME-
aware mailer or been piped through a decoding utility if the original
format used base64 encoding. If you need to decode it, it's recommended
that you use a utility like uudeview, which will strip virtually any kind
of encoding (MIME, PEM, PGP, whatever) to recover the binary original.
You can use this code in whatever way you want, as long as you don't try
to claim you wrote it.
(Someone asked for clarification on what this means, treat it as a very
mild form of the BSD license in which you're not required to include LONG
LEGAL DISCLAIMERS IN ALL CAPS but just a small note in a corner somewhere
(e.g. the back of a manual) that you're using the dumpasn1 code. And if
you do use it, please make sure you're using a recent version, I
occasionally see screen shots from incredibly ancient versions that are
nowhere near as good as what current versions produce).
Editing notes: Tabs to 4, phasers to malky (and in case anyone wants to
complain about that, see "Program Indentation and Comprehensiblity",
Richard Miara, Joyce Musselman, Juan Navarro, and Ben Shneiderman,
Communications of the ACM, Vol.26, No.11 (November 1983), p.861) */
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef OS390
#include <unistd.h>
#endif /* OS390 */
/* The update string, printed as part of the help screen */
#define UPDATE_STRING "8 June 2013"
/* Useful defines */
#ifndef TRUE
#define FALSE 0
#define TRUE ( !FALSE )
#endif /* TRUE */
#ifndef BYTE
typedef unsigned char BYTE;
#endif /* BYTE */
/* Tandem Guardian NonStop Kernel options */
#ifdef __TANDEM
#pragma nolist /* Spare us the source listing, no GUI... */
#pragma nowarn (1506) /* Implicit type conversion: int to char etc */
#endif /* __TANDEM */
/* SunOS 4.x doesn't define seek codes or exit codes or FILENAME_MAX (it does
define _POSIX_MAX_PATH, but in funny locations and to different values
depending on which include file you use). Strictly speaking this code
isn't right since we need to use PATH_MAX, however not all systems define
this, some use _POSIX_PATH_MAX, and then there are all sorts of variations
and other defines that you have to check, which require about a page of
code to cover each OS, so we just use max( FILENAME_MAX, 512 ) which
should work for everything */
#ifndef SEEK_SET
#define SEEK_SET 0
#define SEEK_CUR 2
#endif /* No fseek() codes defined */
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#define EXIT_SUCCESS ( !EXIT_FAILURE )
#endif /* No exit() codes defined */
#ifndef FILENAME_MAX
#define FILENAME_MAX 512
#else
#if FILENAME_MAX < 128
#undef FILENAME_MAX
#define FILENAME_MAX 512
#endif /* FILENAME_MAX < 128 */
#endif /* FILENAME_MAX */
/* Under Windows we can do special-case handling for paths and Unicode
strings (although in practice it can't really handle much except
latin-1) */
#if ( defined( _WINDOWS ) || defined( WIN32 ) || defined( _WIN32 ) || \
defined( __WIN32__ ) )
#include <windows.h>
#include <io.h> /* For _setmode() */
#include <fcntl.h> /* For _setmode() codes */
#ifndef _O_U16TEXT
#define _O_U16TEXT 0x20000 /* _setmode() code */
#endif /* !_O_U16TEXT */
#define __WIN32__
#endif /* Win32 */
/* Under Unix we can do special-case handling for paths and Unicode strings.
Detecting Unix systems is a bit tricky but the following should find most
versions. This define implicitly assumes that the system has wchar_t
support, but this is almost always the case except for very old systems,
so it's best to default to allow-all rather than deny-all */
#if defined( linux ) || defined( __linux__ ) || defined( sun ) || \
defined( __bsdi__ ) || defined( __FreeBSD__ ) || defined( __NetBSD__ ) || \
defined( __OpenBSD__ ) || defined( __hpux ) || defined( _M_XENIX ) || \
defined( __osf__ ) || defined( _AIX ) || defined( __MACH__ )
#define __UNIX__
#endif /* Every commonly-used Unix */
#if defined( linux ) || defined( __linux__ )
#ifndef __USE_ISOC99
#define __USE_ISOC99
#endif /* __USE_ISOC99 */
#include <wchar.h>
#endif /* Linux */
/* For IBM mainframe OSes we use the Posix environment, so it looks like
Unix */
#ifdef OS390
#define __OS390__
#define __UNIX__
#endif /* OS390 / z/OS */
/* Tandem NSK: Don't tangle with Tandem OSS, which is almost UNIX */
#ifdef __TANDEM
#ifdef _GUARDIAN_TARGET
#define __TANDEM_NSK__
#else
#define __UNIX__
#endif /* _GUARDIAN_TARGET */
#endif /* __TANDEM */
/* Some OS's don't define the min() macro */
#ifndef min
#define min(a,b) ( ( a ) < ( b ) ? ( a ) : ( b ) )
#endif /* !min */
/* Macros to avoid problems with sign extension */
#define byteToInt( x ) ( ( BYTE ) ( x ) )
/* The level of recursion can get scary for deeply-nested structures so we
use a larger-than-normal stack under DOS */
#ifdef __TURBOC__
extern unsigned _stklen = 16384;
#endif /* __TURBOC__ */
/* Turn off pointless VC++ warnings */
#ifdef _MSC_VER
#pragma warning( disable: 4018 )
#endif /* VC++ */
/* When we dump a nested data object encapsulated within a larger object, the
length is initially set to a magic value which is adjusted to the actual
length once we start parsing the object */
#define LENGTH_MAGIC 177545L
/* Tag classes */
#define CLASS_MASK 0xC0 /* Bits 8 and 7 */
#define UNIVERSAL 0x00 /* 0 = Universal (defined by ITU X.680) */
#define APPLICATION 0x40 /* 1 = Application */
#define CONTEXT 0x80 /* 2 = Context-specific */
#define PRIVATE 0xC0 /* 3 = Private */
/* Encoding type */
#define FORM_MASK 0x20 /* Bit 6 */
#define PRIMITIVE 0x00 /* 0 = primitive */
#define CONSTRUCTED 0x20 /* 1 = constructed */
/* Universal tags */
#define TAG_MASK 0x1F /* Bits 5 - 1 */
#define EOC 0x00 /* 0: End-of-contents octets */
#define BOOLEAN 0x01 /* 1: Boolean */
#define INTEGER 0x02 /* 2: Integer */
#define BITSTRING 0x03 /* 2: Bit string */
#define OCTETSTRING 0x04 /* 4: Byte string */
#define NULLTAG 0x05 /* 5: NULL */
#define OID 0x06 /* 6: Object Identifier */
#define OBJDESCRIPTOR 0x07 /* 7: Object Descriptor */
#define EXTERNAL 0x08 /* 8: External */
#define REAL 0x09 /* 9: Real */
#define ENUMERATED 0x0A /* 10: Enumerated */
#define EMBEDDED_PDV 0x0B /* 11: Embedded Presentation Data Value */
#define UTF8STRING 0x0C /* 12: UTF8 string */
#define SEQUENCE 0x10 /* 16: Sequence/sequence of */
#define SET 0x11 /* 17: Set/set of */
#define NUMERICSTRING 0x12 /* 18: Numeric string */
#define PRINTABLESTRING 0x13 /* 19: Printable string (ASCII subset) */
#define T61STRING 0x14 /* 20: T61/Teletex string */
#define VIDEOTEXSTRING 0x15 /* 21: Videotex string */
#define IA5STRING 0x16 /* 22: IA5/ASCII string */
#define UTCTIME 0x17 /* 23: UTC time */
#define GENERALIZEDTIME 0x18 /* 24: Generalized time */
#define GRAPHICSTRING 0x19 /* 25: Graphic string */
#define VISIBLESTRING 0x1A /* 26: Visible string (ASCII subset) */
#define GENERALSTRING 0x1B /* 27: General string */
#define UNIVERSALSTRING 0x1C /* 28: Universal string */
#define BMPSTRING 0x1E /* 30: Basic Multilingual Plane/Unicode string */
/* Length encoding */
#define LEN_XTND 0x80 /* Indefinite or long form */
#define LEN_MASK 0x7F /* Bits 7 - 1 */
/* Various special-case operations to perform on strings */
typedef enum {
STR_NONE, /* No special handling */
STR_UTCTIME, /* Check it's UTCTime */
STR_GENERALIZED, /* Check it's GeneralizedTime */
STR_PRINTABLE, /* Check it's a PrintableString */
STR_IA5, /* Check it's an IA5String */
STR_LATIN1, /* Read and display string as latin-1 */
STR_UTF8, /* Read and display string as UTF8 */
STR_BMP, /* Read and display string as Unicode */
STR_BMP_REVERSED /* STR_BMP with incorrect endianness */
} STR_OPTION;
/* Structure to hold info on an ASN.1 item */
typedef struct {
int id; /* Tag class + primitive/constructed */
int tag; /* Tag */
long length; /* Data length */
int indefinite; /* Item has indefinite length */
int nonCanonical; /* Non-canonical length encoding used */
BYTE header[ 16 ]; /* Tag+length data */
int headerSize; /* Size of tag+length */
} ASN1_ITEM;
/* Configuration options */
static int printDots = FALSE; /* Whether to print dots to align columns */
static int doPure = FALSE; /* Print data without LHS info column */
static int doDumpHeader = FALSE; /* Dump tag+len in hex (level = 0, 1, 2) */
static int extraOIDinfo = FALSE; /* Print extra information about OIDs */
static int doHexValues = FALSE; /* Display size, offset in hex not dec.*/
static int useStdin = FALSE; /* Take input from stdin */
static int zeroLengthAllowed = FALSE;/* Zero-length items allowed */
static int dumpText = FALSE; /* Dump text alongside hex data */
static int printAllData = FALSE; /* Whether to print all data in long blocks */
static int checkEncaps = TRUE; /* Print encaps.data in BIT/OCTET STRINGs */
static int checkCharset = TRUE; /* Check val.of char strs.hidden in OCTET STRs */
#ifndef __OS390__
static int reverseBitString = TRUE; /* Print BIT STRINGs in natural order */
#else
static int reverseBitString = FALSE;/* Natural order on OS390 is the same as ASN.1 */
#endif /* __OS390__ */
static int rawTimeString = FALSE; /* Print raw time strings */
static int shallowIndent = FALSE; /* Perform shallow indenting */
static int outputWidth = 80; /* 80-column display */
static int maxNestLevel = 100; /* Maximum nesting level for which to display output */
static int doOutlineOnly = FALSE; /* Only display constructed-object outline */
/* Formatting information used for the fixed informational column to the
left of the displayed data */
static int infoWidth = 4;
static const char *indentStringTbl[] = {
NULL, NULL, NULL,
" : ", /* "xxx xxx: " (3) */
" : ", /* "xxxx xxxx: " (4) */
" : ", /* "xxxxx xxxxx: " (5) */
" : ", /* "xxxxxx xxxxxx: " (6) */
" : ", /* "xxxxxxx xxxxxxx: " (7) */
" : ", /* "xxxxxxxx xxxxxxxx: " (8) */
"", "", "", ""
};
static const char *lenTbl[] = {
NULL, NULL, NULL,
"%3ld %3ld: ", "%4ld %4ld: ", "%5ld %5ld: ",
"%6ld %6ld: ", "%7ld %7ld: ", "%8ld %8ld: ",
"", "", "", ""
};
static const char *lenIndefTbl[] = {
NULL, NULL, NULL,
"%3ld NDF: ", "%4ld NDEF: ", "%5ld INDEF: ",
"%6ld INDEF : ", "%7ld INDEF : ", "%8ld INDEF : ",
"", "", "", ""
};
static const char *lenHexTbl[] = {
NULL, NULL, NULL,
"%03lX %3lX: ", "%04lX %4lX: ", "%05lX %5lX: ",
"%06lX %6lX: ", "%07lX %7lX: ", "%08lX %8lX: ",
"", "", "", ""
};
static const char *lenHexIndefTbl[] = {
NULL, NULL, NULL,
"%03lX NDF: ", "%04lX NDEF: ", "%05lX INDEF: ",
"%06lX INDEF : ", "%07lX INDEF : ", "%08lX INDEF : ",
"", "", "", ""
};
#define INDENT_SIZE ( infoWidth + 1 + infoWidth + 1 + 1 )
#define INDENT_STRING indentStringTbl[ infoWidth ]
#define LEN lenTbl[ infoWidth ]
#define LEN_INDEF lenIndefTbl[ infoWidth ]
#define LEN_HEX lenHexTbl[ infoWidth ]
#define LEN_HEX_INDEF lenHexIndefTbl[ infoWidth ]
/* Error and warning information */
static int noErrors = 0; /* Number of errors found */
static int noWarnings = 0; /* Number of warnings */
/* Position in the input stream */
static int fPos = 0; /* Absolute position in data */
/* The output stream */
static FILE *output; /* Output stream */
/* Information on an ASN.1 Object Identifier */
#define MAX_OID_SIZE 32
typedef struct tagOIDINFO {
struct tagOIDINFO *next; /* Next item in list */
BYTE oid[ MAX_OID_SIZE ];
int oidLength;
char *comment, *description; /* Name, rank, serial number */
int warn; /* Whether to warn if OID encountered */
} OIDINFO;
static OIDINFO *oidList = NULL;
/* If the config file isn't present in the current directory, we search the
following paths (this is needed for Unix with dumpasn1 somewhere in the
path, since this doesn't set up argv[0] to the full path). Anything
beginning with a '$' uses the appropriate environment variable. In
addition under Unix we also walk down $PATH looking for it */
#ifdef __TANDEM_NSK__
#define CONFIG_NAME "asn1cfg"
#else
#define CONFIG_NAME "dumpasn1.cfg"
#endif /* __TANDEM_NSK__ */
#if defined( __TANDEM_NSK__ )
static const char *configPaths[] = {
"$system.security", "$system.system",
NULL
};
#elif defined( __WIN32__ )
static const char *configPaths[] = {
/* Windoze absolute paths (yeah, this code has been around for awhile,
why do you ask?) */
"c:\\windows\\", "c:\\winnt\\",
/* It's my program, I'm allowed to hardcode in strange paths that no-one
else uses */
"c:\\program files\\bin\\",
"c:\\program files (x86)\\bin\\",
/* This one seems to be popular as well */
"c:\\program files\\utilities\\",
"c:\\program files (x86)\\utilities\\",
/* General environment-based paths */
"$DUMPASN1_PATH/",
NULL
};
#elif defined( __OS390__ )
static const char *configPaths[] = {
/* General environment-based paths */
"$DUMPASN1_PATH/",
NULL
};
#else
static const char *configPaths[] = {
#ifndef DEBIAN
/* Unix absolute paths */
"/usr/bin/", "/usr/local/bin/", "/etc/dumpasn1/",
/* Unix environment-based paths */
"$HOME/", "$HOME/bin/",
/* It's my program, I'm allowed to hardcode in strange paths that no-one
else uses */
"$HOME/BIN/",
#else
/* Debian has specific places where you're supposed to dump things. Note
the dot after $HOME, since config files are supposed to start with a
dot for Debian */
"$HOME/.", "/etc/dumpasn1/",
#endif /* DEBIAN-specific paths */
/* General environment-based paths */
"$DUMPASN1_PATH/",
NULL
};
#endif /* OS-specific search paths */
#define isEnvTerminator( c ) \
( ( ( c ) == '/' ) || ( ( c ) == '.' ) || ( ( c ) == '$' ) || \
( ( c ) == '\0' ) || ( ( c ) == '~' ) )
/****************************************************************************
* *
* Object Identification/Description Routines *
* *
****************************************************************************/
/* Return descriptive strings for universal tags */
static char *idstr( const int tagID )
{
switch( tagID )
{
case EOC:
return( "End-of-contents octets" );
case BOOLEAN:
return( "BOOLEAN" );
case INTEGER:
return( "INTEGER" );
case BITSTRING:
return( "BIT STRING" );
case OCTETSTRING:
return( "OCTET STRING" );
case NULLTAG:
return( "NULL" );
case OID:
return( "OBJECT IDENTIFIER" );
case OBJDESCRIPTOR:
return( "ObjectDescriptor" );
case EXTERNAL:
return( "EXTERNAL" );
case REAL:
return( "REAL" );
case ENUMERATED:
return( "ENUMERATED" );
case EMBEDDED_PDV:
return( "EMBEDDED PDV" );
case UTF8STRING:
return( "UTF8String" );
case SEQUENCE:
return( "SEQUENCE" );
case SET:
return( "SET" );
case NUMERICSTRING:
return( "NumericString" );
case PRINTABLESTRING:
return( "PrintableString" );
case T61STRING:
return( "TeletexString" );
case VIDEOTEXSTRING:
return( "VideotexString" );
case IA5STRING:
return( "IA5String" );
case UTCTIME:
return( "UTCTime" );
case GENERALIZEDTIME:
return( "GeneralizedTime" );
case GRAPHICSTRING:
return( "GraphicString" );
case VISIBLESTRING:
return( "VisibleString" );
case GENERALSTRING:
return( "GeneralString" );
case UNIVERSALSTRING:
return( "UniversalString" );
case BMPSTRING:
return( "BMPString" );
default:
return( "Unknown (Reserved)" );
}
}
/* Return information on an object identifier */
static OIDINFO *getOIDinfo( const BYTE *oid, const int oidLength )
{
const BYTE oidByte = oid[ 1 ];
OIDINFO *oidPtr;
for( oidPtr = oidList; oidPtr != NULL; oidPtr = oidPtr->next )
{
if( oidLength != oidPtr->oidLength - 2 )
continue; /* Quick-reject check */
if( oidByte != oidPtr->oid[ 2 + 1 ] )
continue; /* Quick-reject check */
if( !memcmp( oidPtr->oid + 2, oid, oidLength ) )
return( oidPtr );
}
return( NULL );
}
/* Add an OID attribute */
static int addAttribute( char **buffer, char *attribute )
{
if( ( *buffer = ( char * ) malloc( strlen( attribute ) + 1 ) ) == NULL )
{
puts( "Out of memory." );
return( FALSE );
}
strcpy( *buffer, attribute );
return( TRUE );
}
/* Table to identify valid string chars (taken from cryptlib). Note that
IA5String also allows control chars, but we warn about these since
finding them in a certificate is a sign that there's something
seriously wrong */
#define P 1 /* PrintableString */
#define I 2 /* IA5String */
#define PI 3 /* IA5String and PrintableString */
static int charFlags[] = {
/* 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* ! " # $ % & ' ( ) * + , - . / */
PI, I, I, I, I, I, I, PI, PI, PI, I, PI, PI, PI, PI, PI,
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, I, I, PI, I, PI,
/* @ A B C D E F G H I J K L M N O */
I, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI,
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, I, I, I, I, I,
/* ` a b c d e f g h i j k l m n o */
I, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI,
/* p q r s t u v w x y z { | } ~ DL */
PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, PI, I, I, I, I, 0
};
static int isPrintable( int ch )
{
if( ch >= 128 || !( charFlags[ ch ] & P ) )
return( FALSE );
return( TRUE );
}
static int isIA5( int ch )
{
if( ch >= 128 || !( charFlags[ ch ] & I ) )
return( FALSE );
return( TRUE );
}
/****************************************************************************
* *
* Config File Read Routines *
* *
****************************************************************************/
/* Files coming from DOS/Windows systems may have a ^Z (the CP/M EOF char)
at the end, so we need to filter this out */
#define CPM_EOF 0x1A /* ^Z = CPM EOF char */
/* The maximum input line length */
#define MAX_LINESIZE 512
/* Read a line of text from the config file */
static int lineNo;
static int readLine( FILE *file, char *buffer )
{
int bufCount = 0, ch;
/* Skip whitespace */
while( ( ( ch = getc( file ) ) == ' ' || ch == '\t' ) && !feof( file ) );
/* Get a line into the buffer */
while( ch != '\r' && ch != '\n' && ch != CPM_EOF && !feof( file ) )
{
/* Check for an illegal char in the data. Note that we don't just
check for chars with high bits set because these are legal in
non-ASCII strings */
if( !isprint( ch ) )
{
printf( "Bad character '%c' in config file line %d.\n",
ch, lineNo );
return( FALSE );
}
/* Check to see if it's a comment line */
if( ch == '#' && !bufCount )
{
/* Skip comment section and trailing whitespace */
while( ch != '\r' && ch != '\n' && ch != CPM_EOF && !feof( file ) )
ch = getc( file );
break;
}
/* Make sure that the line is of the correct length */
if( bufCount > MAX_LINESIZE )
{
printf( "Config file line %d too long.\n", lineNo );
return( FALSE );
}
else
if( ch ) /* Can happen if we read a binary file */
buffer[ bufCount++ ] = ch;
/* Get next character */
ch = getc( file );
}
/* If we've just passed a CR, check for a following LF */
if( ch == '\r' )
{
if( ( ch = getc( file ) ) != '\n' )
ungetc( ch, file );
}
/* Skip trailing whitespace and add der terminador */
while( bufCount > 0 &&
( ( ch = buffer[ bufCount - 1 ] ) == ' ' || ch == '\t' ) )
bufCount--;
buffer[ bufCount ] = '\0';
/* Handle special-case of ^Z if file came off an MSDOS system */
if( ch == CPM_EOF )
{
while( !feof( file ) )
{
/* Keep going until we hit the true EOF (or some sort of error) */
( void ) getc( file );
}
}
return( ferror( file ) ? FALSE : TRUE );
}
/* Process an OID specified as space-separated decimal or hex digits */
static int processOID( OIDINFO *oidInfo, char *string )
{
BYTE binaryOID[ MAX_OID_SIZE ];
long value;
int firstValue, valueIndex = 0, oidIndex = 3;
memset( binaryOID, 0, MAX_OID_SIZE );
binaryOID[ 0 ] = OID;
while( *string && oidIndex < MAX_OID_SIZE )
{
if( oidIndex >= MAX_OID_SIZE - 4 )
{
printf( "Excessively long OID in config file line %d.\n",
lineNo );
return( FALSE );
}
if( sscanf( string, "%8ld", &value ) != 1 || value < 0 )
{
printf( "Invalid value in config file line %d.\n", lineNo );
return( FALSE );
}
if( valueIndex == 0 )
{
firstValue = value;
valueIndex++;
}
else
{
if( valueIndex == 1 )
{
if( firstValue < 0 || firstValue > 2 || value < 0 || \
( ( firstValue < 2 && value > 39 ) || \
( firstValue == 2 && value > 175 ) ) )
{
printf( "Invalid value in config file line %d.\n",
lineNo );
return( FALSE );
}
binaryOID[ 2 ] = ( firstValue * 40 ) + ( int ) value;
valueIndex++;
}
else
{
int hasHighBits = FALSE;
if( value >= 0x200000L ) /* 2^21 */
{
binaryOID[ oidIndex++ ] = 0x80 | ( int ) ( value >> 21 );
value %= 0x200000L;
hasHighBits = TRUE;
}
if( ( value >= 0x4000 ) || hasHighBits ) /* 2^14 */
{
binaryOID[ oidIndex++ ] = 0x80 | ( int ) ( value >> 14 );
value %= 0x4000;
hasHighBits = TRUE;
}
if( ( value >= 0x80 ) || hasHighBits ) /* 2^7 */
{
binaryOID[ oidIndex++ ] = 0x80 | ( int ) ( value >> 7 );
value %= 128;
}
binaryOID[ oidIndex++ ] = ( int ) value;
}
}
while( *string && isdigit( byteToInt( *string ) ) )
string++;
if( *string && *string++ != ' ' )
{
printf( "Invalid OID string in config file line %d.\n", lineNo );
return( FALSE );
}
}
binaryOID[ 1 ] = oidIndex - 2;
memcpy( oidInfo->oid, binaryOID, oidIndex );
oidInfo->oidLength = oidIndex;
return( TRUE );
}
static int processHexOID( OIDINFO *oidInfo, char *string )
{
int value, index = 0;
while( *string && index < MAX_OID_SIZE - 1 )
{
if( sscanf( string, "%4x", &value ) != 1 || value > 255 )
{
printf( "Invalid hex value in config file line %d.\n", lineNo );
return( FALSE );
}
oidInfo->oid[ index++ ] = value;
string += 2;
if( *string && *string++ != ' ' )
{
printf( "Invalid hex string in config file line %d.\n", lineNo );
return( FALSE );
}
}
oidInfo->oid[ index ] = 0;
oidInfo->oidLength = index;
if( index >= MAX_OID_SIZE - 1 )
{
printf( "OID value in config file line %d too long.\n", lineNo );
return( FALSE );
}
return( TRUE );
}
/* Read a config file */
static int readConfig( const char *path, const int isDefaultConfig )
{
OIDINFO dummyOID = { NULL, "Dummy", 0, "Dummy", "Dummy", 1 }, *oidPtr;
FILE *file;
int seenHexOID = FALSE;
char buffer[ MAX_LINESIZE ];
int status;
/* Try and open the config file */
if( ( file = fopen( path, "rb" ) ) == NULL )
{
/* If we can't open the default config file, issue a warning but
continue anyway */
if( isDefaultConfig )
{
puts( "Cannot open config file 'dumpasn1.cfg', which should be in the same" );
puts( "directory as the dumpasn1 program, a standard system directory, or" );
puts( "in a location pointed to by the DUMPASN1_PATH environment variable." );
puts( "Operation will continue without the ability to display Object " );
puts( "Identifier information." );
puts( "" );
puts( "If the config file is located elsewhere, you can set the environment" );
puts( "variable DUMPASN1_PATH to the path to the file." );
return( TRUE );
}
printf( "Cannot open config file '%s'.\n", path );
return( FALSE );
}
/* Add the new config entries at the appropriate point in the OID list */
if( oidList == NULL )
oidPtr = &dummyOID;
else
for( oidPtr = oidList; oidPtr->next != NULL; oidPtr = oidPtr->next );
/* Read each line in the config file */
lineNo = 1;
while( ( status = readLine( file, buffer ) ) == TRUE && !feof( file ) )
{
/* If it's a comment line, skip it */
if( !*buffer )
{
lineNo++;
continue;
}
/* Check for an attribute tag */
if( !strncmp( buffer, "OID = ", 6 ) )
{
/* Make sure that all of the required attributes for the current
OID are present */
if( oidPtr->description == NULL )
{
printf( "OID ending on config file line %d has no "
"description attribute.\n", lineNo - 1 );
return( FALSE );
}
/* Allocate storage for the new OID */
if( ( oidPtr->next = ( OIDINFO * ) malloc( sizeof( OIDINFO ) ) ) == NULL )
{
puts( "Out of memory." );
return( FALSE );
}
oidPtr = oidPtr->next;
if( oidList == NULL )
oidList = oidPtr;
memset( oidPtr, 0, sizeof( OIDINFO ) );
/* Add the new OID */
if( !strncmp( buffer + 6, "06", 2 ) )
{
seenHexOID = TRUE;
if( !processHexOID( oidPtr, buffer + 6 ) )
return( FALSE );
}
else
{
if( !processOID( oidPtr, buffer + 6 ) )
return( FALSE );
}
/* Check that this OID isn't already present in the OID list.
This is a quick-and-dirty n^2 algorithm so it's not enabled
by default */
#if 0
{
OIDINFO *oidCursor;
for( oidCursor = oidList; oidCursor->next != NULL; oidCursor = oidCursor->next )
{
if( oidCursor->oidLength == oidPtr->oidLength && \
!memcmp( oidCursor->oid, oidPtr->oid, oidCursor->oidLength ) )
{
printf( "Duplicate OID '%s' at line %d.\n",
buffer, lineNo );
}
}
}
#endif /* 0 */
}
else if( !strncmp( buffer, "Description = ", 14 ) )
{
if( oidPtr->description != NULL )
{
printf( "Duplicate OID description in config file line %d.\n",
lineNo );
return( FALSE );
}
if( !addAttribute( &oidPtr->description, buffer + 14 ) )
return( FALSE );
}
else if( !strncmp( buffer, "Comment = ", 10 ) )
{
if( oidPtr->comment != NULL )
{
printf( "Duplicate OID comment in config file line %d.\n",
lineNo );
return( FALSE );
}
if( !addAttribute( &oidPtr->comment, buffer + 10 ) )
return( FALSE );
}
else if( !strncmp( buffer, "Warning", 7 ) )
{
if( oidPtr->warn )
{
printf( "Duplicate OID warning in config file line %d.\n",
lineNo );
return( FALSE );
}
oidPtr->warn = TRUE;
}
else
{
printf( "Unrecognised attribute '%s', line %d.\n", buffer,
lineNo );
return( FALSE );
}
lineNo++;
}
fclose( file );
/* If we're processing an old-style config file, tell the user to
upgrade */
if( seenHexOID )
{
puts( "\nWarning: Use of old-style hex OIDs detected in "
"configuration file, please\n update your dumpasn1 "
"configuration file.\n" );
}
return( status );
}
/* Check for the existence of a config file path (access() isn't available
on all systems) */
static int testConfigPath( const char *path )
{
FILE *file;
/* Try and open the config file */
if( ( file = fopen( path, "rb" ) ) == NULL )
return( FALSE );
fclose( file );
return( TRUE );
}
/* Build a config path by substituting environment strings for $NAMEs */
static void buildConfigPath( char *path, const char *pathTemplate )
{
char pathBuffer[ FILENAME_MAX ], newPath[ FILENAME_MAX ];
int pathLen, pathPos = 0, newPathPos = 0;
/* Add the config file name at the end */
strcpy( pathBuffer, pathTemplate );
strcat( pathBuffer, CONFIG_NAME );
pathLen = strlen( pathBuffer );
while( pathPos < pathLen )
{
char *strPtr;
int substringSize;
/* Find the next $ and copy the data before it to the new path */
if( ( strPtr = strstr( pathBuffer + pathPos, "$" ) ) != NULL )
substringSize = ( int ) ( ( strPtr - pathBuffer ) - pathPos );
else
substringSize = pathLen - pathPos;
if( substringSize > 0 )
{
memcpy( newPath + newPathPos, pathBuffer + pathPos,
substringSize );
}
newPathPos += substringSize;
pathPos += substringSize;
/* Get the environment string for the $NAME */
if( strPtr != NULL )
{
char envName[ MAX_LINESIZE ], *envString;
int i;
/* Skip the '$', find the end of the $NAME, and copy the name
into an internal buffer */
pathPos++; /* Skip the $ */
for( i = 0; !isEnvTerminator( pathBuffer[ pathPos + i ] ); i++ );
memcpy( envName, pathBuffer + pathPos, i );
envName[ i ] = '\0';
/* Get the env.string and copy it over */
if( ( envString = getenv( envName ) ) != NULL )
{
const int envStrLen = strlen( envString );
if( newPathPos + envStrLen < FILENAME_MAX - 2 )
{
memcpy( newPath + newPathPos, envString, envStrLen );
newPathPos += envStrLen;
}
}
pathPos += i;
}
}
newPath[ newPathPos ] = '\0'; /* Add der terminador */
/* Copy the new path to the output */
strcpy( path, newPath );
}
/* Read the global config file */
static int readGlobalConfig( const char *path )
{
char buffer[ FILENAME_MAX ];
char *searchPos = ( char * ) path, *namePos, *lastPos = NULL;
#ifdef __UNIX__
char *envPath;
#endif /* __UNIX__ */
#ifdef __WIN32__
char filePath[ _MAX_PATH ];
DWORD count;
#endif /* __WIN32__ */
int i;
/* First, try and find the config file in the same directory as the
executable by walking down the path until we find the last occurrence
of the program name. This requires that argv[0] be set up properly,
which isn't the case if Unix search paths are being used and is a
bit hit-and-miss under Windows where the contents of argv[0] depend
on how the program is being executed. To avoid this we perform some
Windows-specific processing to try and find the path to the
executable if we can't otherwise find it */
do
{
namePos = lastPos;
lastPos = strstr( searchPos, "dumpasn1" );
if( lastPos == NULL )
lastPos = strstr( searchPos, "DUMPASN1" );
searchPos = lastPos + 1;
}
while( lastPos != NULL );
#ifdef __UNIX__
if( namePos == NULL && ( namePos = strrchr( path, '/' ) ) != NULL )
{
const int endPos = ( int ) ( namePos - path ) + 1;
/* If the executable isn't called dumpasn1, we won't be able to find
it with the above code, fall back to looking for directory
separators. This requires a system where the only separator is
the directory separator (ie it doesn't work for Windows or most
mainframe environments) */
if( endPos < FILENAME_MAX - 13 )
{
memcpy( buffer, path, endPos );
strcpy( buffer + endPos, CONFIG_NAME );
if( testConfigPath( buffer ) )
return( readConfig( buffer, TRUE ) );
}
/* That didn't work, try the absolute locations and $PATH */
namePos = NULL;
}
#endif /* __UNIX__ */
if( strlen( path ) < FILENAME_MAX - 13 && namePos != NULL )
{
strcpy( buffer, path );
strcpy( buffer + ( int ) ( namePos - ( char * ) path ), CONFIG_NAME );
if( testConfigPath( buffer ) )
return( readConfig( buffer, TRUE ) );
}
/* Now try each of the possible absolute locations for the config file */
for( i = 0; configPaths[ i ] != NULL; i++ )
{
buildConfigPath( buffer, configPaths[ i ] );
if( testConfigPath( buffer ) )
return( readConfig( buffer, TRUE ) );
}
#ifdef __UNIX__
/* On Unix systems we can also search for the config file on $PATH */
if( ( envPath = getenv( "PATH" ) ) != NULL )
{
char *pathPtr = strtok( envPath, ":" );
do
{
sprintf( buffer, "%s/%s", pathPtr, CONFIG_NAME );
if( testConfigPath( buffer ) )
return( readConfig( buffer, TRUE ) );
pathPtr = strtok( NULL, ":" );
}
while( pathPtr != NULL );
}
#endif /* __UNIX__ */
#ifdef __WIN32__
/* Under Windows we can use GetModuleFileName() to find the location of
the program */
count = GetModuleFileName ( NULL, filePath, _MAX_PATH );
if( count > 0 )
{
char *progNameStart = strrchr( filePath, '\\' );
if( progNameStart != NULL && \
( progNameStart - filePath ) < _MAX_PATH - 13 )
{
/* Replace the program name with the config file name */
strcpy( progNameStart + 1, CONFIG_NAME );
if( testConfigPath( filePath ) )
return( readConfig( filePath, TRUE ) );
}
}
#endif /*__WIN32__*/
/* Default to just the config name (which should fail as it was the
first entry in configPaths[]). readConfig() will display the
appropriate warning */
return( readConfig( CONFIG_NAME, TRUE ) );
}
/* Free the in-memory config data */
static void freeConfig( void )
{
OIDINFO *oidPtr = oidList;
while( oidPtr != NULL )
{
OIDINFO *oidCursor = oidPtr;
oidPtr = oidPtr->next;
if( oidCursor->comment != NULL )
free( oidCursor->comment );
if( oidCursor->description != NULL )
free( oidCursor->description );
free( oidCursor );
}
}
/****************************************************************************
* *
* Output/Formatting Routines *
* *
****************************************************************************/
#ifdef __OS390__
static int asciiToEbcdic( const int ch )
{
char convBuffer[ 2 ];
convBuffer[ 0 ] = ch;
convBuffer[ 1 ] = '\0';
__atoe( convBuffer ); /* Convert ASCII to EBCDIC for 390 */
return( convBuffer[ 0 ] );
}
#endif /* __OS390__ */
/* Output formatted text */
static int printString( const int level, const char *format, ... )
{
va_list argPtr;
int length;
if( level >= maxNestLevel )
return( 0 );
va_start( argPtr, format );
length = vfprintf( output, format, argPtr );
va_end( argPtr );
return( length );
}
/* Indent a string by the appropriate amount */
static void doIndent( const int level )
{
int i;
if( level >= maxNestLevel )
return;
for( i = 0; i < level; i++ )
{
fprintf( output, printDots ? ". " : \
shallowIndent ? " " : " " );
}
}
/* Complain about an error in the ASN.1 object */
static void complain( const char *message, const int messageParam,
const int level )
{
if( level < maxNestLevel )
{
if( !doPure )
fprintf( output, "%s", INDENT_STRING );
doIndent( level + 1 );
}
fputs( "Error: ", output );
fprintf( output, message, messageParam );
fputs( ".\n", output );
noErrors++;
}
static void complainLength( const ASN1_ITEM *item, const int level )
{
#if 0
/* This is a general error so we don't indent the message to the level
of the item */
#else
if( level < maxNestLevel )
{
if( !doPure )
fprintf( output, "%s", INDENT_STRING );
doIndent( level + 1 );
}
#endif /* 0 */
fprintf( output, "Error: %s has invalid length %ld.\n",
idstr( item->tag ), item->length );
noErrors++;
}
static void complainLengthCanonical( const ASN1_ITEM *item, const int level )
{
int i;
#if 0
/* This is a general error so we don't indent the message to the level
of the item */
#else
if( level < maxNestLevel )
{
if( !doPure )
fprintf( output, "%s", INDENT_STRING );
doIndent( level + 1 );
}
#endif /* 0 */
fputs( "Error: Length '", output );
for( i = item->nonCanonical; i < item->headerSize; i++ )
{
fprintf( output, "%02X", item->header[ i ] );
if( i < item->headerSize - 1 )
fputc( ' ', output );
}
fputs( "' has non-canonical encoding.\n", output );
noErrors++;
}
static void complainInt( const BYTE *intValue, const int level )
{
if( level < maxNestLevel )
{
if( !doPure )
fprintf( output, "%s", INDENT_STRING );
doIndent( level + 1 );
}
fprintf( output, "Error: Integer '%02X %02X ...' has non-DER encoding.\n",
intValue[ 0 ], intValue[ 1 ] );
noErrors++;
}
/* Adjust the nesting-level value to make sure that we don't go off the edge
of the screen via doIndent() when we're displaying a text or hex dump of
data */
static int adjustLevel( const int level, const int maxLevel )
{
/* If we've been passed a very large pseudo-level to disable output then
we don't try and override this */
if( level >= 1000 )
return( level );
/* If we've exceeded the maximum level for display, cap the value at
maxLevel to make sure that we don't end up indenting output off the
edge of the screen */
if( level > maxLevel )
return( maxLevel );
return( level );
}
#if defined( __WIN32__ ) || defined( __UNIX__ ) || defined( __OS390__ )
/* Try and display to display a Unicode character. This is pretty hit and
miss, and if it fails nothing is displayed. To try and detect this we
use wcstombs() to see if anything can be displayed, if it can't we drop
back to trying to display the data as non-Unicode */
static int displayUnicode( const wchar_t wCh, const int level )
{
char outBuf[ 8 ];
int outLen;
/* Check whether we can display this character */
outLen = wcstombs( outBuf, &wCh, 1 );
if( outLen < 1 )
{
/* Tell the caller that this can't be displayed as Unicode */
return( FALSE );
}
#if defined( __WIN32__ )
if( level < maxNestLevel )
{
int oldmode;
/* To output Unicode to the Win32 console we need to switch the
output stream to Unicode-16 mode, but the following may also
depend on which code page is currently set for the console, which
font is being used, and the phase of the moon (including the moons
for Mars and Jupiter) */
fflush( output );
oldmode = _setmode( fileno( output ), _O_U16TEXT );
fputwc( wCh, output );
_setmode( fileno( output ), oldmode );
}
#elif defined( __UNIX__ ) && !( defined( __MACH__ ) || defined( __OpenBSD__ ) )
/* Unix environments are even more broken than Win32, like Win32 the
output differentiates between char and widechar output, but there's
no easy way to deal with this. In theory fwide() can set it, but
it's a one-way function, once we've set it a particular way we can't
go back (exactly what level of braindamage it takes to have an
implementation function like this is a mystery). Other sources
suggest using setlocale() tricks, printf() with "%lc" or "%ls" as the
format specifier, and others, but none of these seem to work properly
either */
if( level < maxNestLevel )
{
#if 0
setlocale( LC_ALL, "" );
fputwc( wCh, output );
#elif 1
/* This (and the "%ls" variant below) seem to be the least broken
options */
fprintf( output, "%lc", wCh );
#elif 0
wchar_t wChString[ 2 ];
wChString[ 0 ] = wCh;
wChString[ 1 ] = 0;
fprintf( output, "%ls", wChString );
#else
if( fwide( output, 1 ) > 0 )
{
fputwc( wCh, output );
fwide( output, -1 );
}
else
fputc( wCh, output );
#endif
}
#else
#ifdef __OS390__
if( level < maxNestLevel )
{
char *p;
/* This could use some improvement */
for( p = outBuf; *p != '\0'; p++ )
*p = asciiToEbcdic( *p );
}
#endif /* IBM ASCII -> EBCDIC conversion */
printString( level, "%s", outBuf );
#endif /* OS-specific charset handling */
return( TRUE );
}
#endif /* __WIN32__ || __UNIX__ || __OS390__ */
/* Display an integer value */
static void printValue( FILE *inFile, const int valueLength,
const int level )
{
BYTE intBuffer[ 2 ];
long value;
int warnNegative = FALSE, warnNonDER = FALSE, i;
value = getc( inFile );
if( value & 0x80 )
warnNegative = TRUE;
for( i = 0; i < valueLength - 1; i++ )
{
int ch = getc( inFile );
/* Check for the first 9 bits being identical */
if( i == 0 )
{
if( ( value == 0x00 ) && ( ( ch & 0x80 ) == 0x00 ) )
warnNonDER = TRUE;
if( ( value == 0xFF ) && ( ( ch & 0x80 ) == 0x80 ) )
warnNonDER = TRUE;
if( warnNonDER )
{
intBuffer[ 0 ] = ( int ) value;
intBuffer[ 1 ] = ch;
}
}
value = ( value << 8 ) | ch;
}
fPos += valueLength;
/* Display the integer value and any associated warnings. Note that
this will display an incorrectly-encoded integer as a negative value
rather than the unsigned value that was probably intended to
emphasise that it's incorrect */
printString( level, " %ld\n", value );
if( warnNonDER )
complainInt( intBuffer, level );
if( warnNegative )
complain( "Integer is encoded as a negative value", 0, level );
}
/* Dump data as a string of hex digits up to a maximum of 128 bytes */
static void dumpHex( FILE *inFile, long length, int level,
const int isInteger )
{
const int lineLength = ( dumpText ) ? 8 : 16;
const int displayHeaderLength = ( ( doPure ) ? 0 : INDENT_SIZE ) + 2;
BYTE intBuffer[ 2 ];
char printable[ 9 ];
long noBytes = length;
int warnPadding = FALSE, warnNegative = isInteger, singleLine = FALSE;
int displayLength = displayHeaderLength, prevCh = -1, i;
memset( printable, 0, 9 );
displayLength += ( length < lineLength ) ? ( length * 3 ) : \
( lineLength * 3 );
/* Check if the size of the displayed data (LHS status info + hex data)
plus the indent-level of spaces will fit into a single line behind
the initial label, e.g. "INTEGER" */
if( displayHeaderLength + ( level * 2 ) + ( length * 3 ) < outputWidth )
singleLine = TRUE;
/* By default we only output a maximum of 128 bytes to avoid dumping
huge amounts of data, however if what's left is a partial lines'
worth then we output that as well to avoid displaying a line of text
indicating that less than a lines' worth of data remains to be
displayed */
if( noBytes >= 128 + lineLength && !printAllData )
noBytes = 128;
/* Make sure that the indent level doesn't push the text off the edge of
the screen */
level = adjustLevel( level, ( outputWidth - displayLength ) / 2 );
for( i = 0; i < noBytes; i++ )
{
int ch;
if( !( i % lineLength ) )
{
if( singleLine )
printString( level, "%c", ' ' );
else
{
if( dumpText )
{
/* If we're dumping text alongside the hex data, print
the accumulated text string */
printString( level, "%s", " " );
printString( level, "%s", printable );
}
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
}
}
ch = getc( inFile );
if( ch == EOF )
{
printString( level, "%c", '\n' );
complain( "Unexpected EOF, %d bytes missing", length - i, level );
return;
}
printString( level, "%s%02X", ( i % lineLength ) ? " " : "", ch );
printable[ i % 8 ] = ( ch >= ' ' && ch < 127 ) ? ch : '.';
fPos++;
/* If we need to check for negative values, check this now */
if( i == 0 )
{
prevCh = ch;
if( !( ch & 0x80 ) )
warnNegative = FALSE;
}
if( i == 1 )
{
/* Check for the first 9 bits being identical */
if( ( prevCh == 0x00 ) && ( ( ch & 0x80 ) == 0x00 ) )
warnPadding = TRUE;
if( ( prevCh == 0xFF ) && ( ( ch & 0x80 ) == 0x80 ) )
warnPadding = TRUE;
if( warnPadding )
{
intBuffer[ 0 ] = prevCh;
intBuffer[ 1 ] = ch;
}
}
}
if( dumpText )
{
/* Print any remaining text */
i %= lineLength;
printable[ i ] = '\0';
while( i < lineLength )
{
printString( level, "%s", " " );
i++;
}
printString( level, "%s", " " );
printString( level, "%s", printable );
}
if( length >= 128 + lineLength && !printAllData )
{
length -= 128;
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 5 );
printString( level, "[ Another %ld bytes skipped ]", length );
fPos += length;
if( useStdin )
{
while( length-- )
getc( inFile );
}
else
fseek( inFile, length, SEEK_CUR );
}
printString( level, "%c", '\n' );
if( isInteger )
{
if( warnPadding )
complainInt( intBuffer, level );
if( warnNegative )
complain( "Integer is encoded as a negative value", 0, level );
}
}
/* Convert a binary OID to its string equivalent */
static int oidToString( char *textOID, int *textOIDlength,
const BYTE *oid, const int oidLength )
{
BYTE uuidBuffer[ 32 ];
long value;
int length = 0, uuidBufPos = -1, uuidBitCount = 5, i;
int validEncoding = TRUE, isUUID = FALSE;
for( i = 0, value = 0; i < oidLength; i++ )
{
const BYTE data = oid[ i ];
const long valTmp = value << 7;
/* Pick apart the encoding. We keep going after hitting an encoding
error at the start of an arc because the overall length is
bounded and we may still be able to recover something worth
printing */
if( value == 0 && data == 0x80 )
{
/* Invalid leading zero value, 0x80 & 0x7F == 0 */
validEncoding = FALSE;
}
if( isUUID )
{
value = 1; /* Set up dummy value since we're bypassing normal read */
if( uuidBitCount == 0 )
uuidBuffer[ uuidBufPos ] = data << 1;
else
{
if( uuidBufPos >= 0 )
uuidBuffer[ uuidBufPos ] |= ( data & 0x7F ) >> ( 7 - uuidBitCount );
uuidBufPos++;
if( uuidBitCount < 7 )
uuidBuffer[ uuidBufPos ] = data << ( uuidBitCount + 1 );
}
uuidBitCount++;
if( uuidBitCount > 7 )
uuidBitCount = 0;
if( !( data & 0x80 ) )
{
/* The following check isn't completely accurate since we
could have less than 16 bytes present if there are
leading zeroes, however to handle this properly we'd
have to decode the entire value as a bignum and then
format it appropriately, and given the fact that the use
of these things is practically nonexistent it's probably
not worth the code space to deal with this */
if( uuidBufPos != 16 )
{
validEncoding = FALSE;
break;
}
length += sprintf( textOID + length,
" { %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x }",
uuidBuffer[ 0 ], uuidBuffer[ 1 ],
uuidBuffer[ 2 ], uuidBuffer[ 3 ],
uuidBuffer[ 4 ], uuidBuffer[ 5 ],
uuidBuffer[ 6 ], uuidBuffer[ 7 ],
uuidBuffer[ 8 ], uuidBuffer[ 9 ],
uuidBuffer[ 10 ], uuidBuffer[ 11 ],
uuidBuffer[ 12 ], uuidBuffer[ 13 ],
uuidBuffer[ 14 ], uuidBuffer[ 15 ] );
value = 0;
}
continue;
}
if( value >= ( LONG_MAX >> 7 ) || \
valTmp >= LONG_MAX - ( data & 0x7F ) )
{
validEncoding = FALSE;
break;
}
value = valTmp | ( data & 0x7F );
if( value < 0 || value > LONG_MAX / 2 )
{
validEncoding = FALSE;
break;
}
if( !( data & 0x80 ) )
{
if( length == 0 )
{
long x, y;
/* The first two levels are encoded into one byte since the
root level has only 3 nodes (40*x + y), however if x =
joint-iso-itu-t(2) then y may be > 39, so we have to add
special-case handling for this */
x = value / 40;
y = value % 40;
if( x > 2 )
{
/* Handle special case for large y if x == 2 */
y += ( x - 2 ) * 40;
x = 2;
}
if( x < 0 || x > 2 || y < 0 || \
( ( x < 2 && y > 39 ) || \
( x == 2 && ( y > 50 && y != 100 ) ) ) )
{
/* If x = 0 or 1 then y has to be 0...39, for x = 3
it can take any value but there are no known
assigned values over 50 except for one contrived
example in X.690 which sets y = 100, so if we see
something outside this range it's most likely an
encoding error rather than some bizarre new ID
that's just appeared */
validEncoding = FALSE;
break;
}
length = sprintf( textOID, "%ld %ld", x, y );
/* An insane ITU facility lets people register UUIDs as OIDs
(see http://www.itu.int/ITU-T/asn1/uuid.html), if we find
one of these, which live under the arc '2 25' = 0x69 we
have to continue decoding the OID as a UUID instead of a
standard OID */
if( data == 0x69 )
isUUID = TRUE;
}
else
length += sprintf( textOID + length, " %ld", value );
value = 0;
}
}
if( value != 0 )
{
/* We stopped in the middle of a continued value */
validEncoding = FALSE;
}
textOID[ length ] = '\0';
*textOIDlength = length;
return( validEncoding );
}
/* Dump a bitstring, reversing the bits into the standard order in the
process */
static void dumpBitString( FILE *inFile, const int length, const int unused,
const int level )
{
unsigned int bitString = 0, currentBitMask = 0x80, remainderMask = 0xFF;
int bitFlag, value = 0, noBits, bitNo = -1, i;
char *errorStr = NULL;
if( unused < 0 || unused > 7 )
complain( "Invalid number %d of unused bits", unused, level );
noBits = ( length * 8 ) - unused;
/* ASN.1 bitstrings start at bit 0, so we need to reverse the order of
the bits if necessary */
if( length > 0 )
{
bitString = fgetc( inFile );
if( bitString == EOF )
{
noBits = 0;
errorStr = "Truncated BIT STRING data";
}
fPos++;
}
for( i = noBits - 8; i > 0; i -= 8 )
{
const int ch = fgetc( inFile );
if( ch == EOF )
{
errorStr = "Truncated BIT STRING data";
break;
}
bitString = ( bitString << 8 ) | ch;
currentBitMask <<= 8;
remainderMask = ( remainderMask << 8 ) | 0xFF;
fPos++;
}
if( errorStr != NULL )
{
printString( level, "%c", '\n' );
complain( errorStr, 0, level );
return;
}
if( reverseBitString )
{
for( i = 0, bitFlag = 1; i < noBits; i++ )
{
if( bitString & currentBitMask )
value |= bitFlag;
if( !( bitString & remainderMask ) && errorStr != NULL )
{
/* The last valid bit should be a one bit */
errorStr = "Spurious zero bits in bitstring";
}
bitFlag <<= 1;
bitString <<= 1;
}
if( noBits < sizeof( int ) && \
( ( remainderMask << noBits ) & value ) && \
errorStr != NULL )
{
/* There shouldn't be any bits set after the last valid one. We
have to do the noBits check to avoid a fencepost error when
there's exactly 32 bits */
errorStr = "Spurious one bits in bitstring";
}
}
else
value = bitString;
/* Now that it's in the right order, dump it. If there's only one bit
set (which is often the case for bit flags) we also print the bit
number to save users having to count the zeroes to figure out which
flag is set */
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
printString( level, "%c", '\'' );
if( reverseBitString )
currentBitMask = 1 << ( noBits - 1 );
for( i = 0; i < noBits; i++ )
{
if( value & currentBitMask )
{
bitNo = ( bitNo == -1 ) ? ( noBits - 1 ) - i : -2;
printString( level, "%c", '1' );
}
else
printString( level, "%c", '0' );
currentBitMask >>= 1;
}
if( bitNo >= 0 )
printString( level, "'B (bit %d)\n", bitNo );
else
printString( level, "%s", "'B\n" );
if( errorStr != NULL )
complain( errorStr, 0, level );
}
/* Display data as a text string up to a maximum of 240 characters (8 lines
of 48 chars to match the hex limit of 8 lines of 16 bytes) with special
treatement for control characters and other odd things that can turn up
in BMPString and UniversalString types.
If the string is less than 40 chars in length, we try to print it on the
same line as the rest of the text (even if it wraps), otherwise we break
it up into 48-char chunks in a somewhat less nice text-dump format */
static void displayString( FILE *inFile, long length, int level,
const STR_OPTION strOption )
{
char timeStr[ 64 ];
long noBytes = length;
int lineLength = 48, i;
int firstTime = TRUE, doTimeStr = FALSE, warnIA5 = FALSE;
int warnPrintable = FALSE, warnTime = FALSE, warnBMP = FALSE;
if( noBytes > 384 && !printAllData )
noBytes = 384; /* Only output a maximum of 384 bytes */
if( strOption == STR_UTCTIME || strOption == STR_GENERALIZED )
{
if( ( strOption == STR_UTCTIME && length != 13 ) || \
( strOption == STR_GENERALIZED && length != 15 ) )
warnTime = TRUE;
else
doTimeStr = rawTimeString ? FALSE : TRUE;
}
if( !doTimeStr && length <= 40 )
printString( level, "%s", " '" ); /* Print string on same line */
level = adjustLevel( level, ( doPure ) ? 15 : 8 );
for( i = 0; i < noBytes; i++ )
{
int ch;
/* If the string is longer than 40 chars, break it up into multiple
sections */
if( length > 40 && !( i % lineLength ) )
{
if( !firstTime )
printString( level, "%c", '\'' );
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
printString( level, "%c", '\'' );
firstTime = FALSE;
}
ch = getc( inFile );
#if defined( __WIN32__ ) || defined( __UNIX__ ) || defined( __OS390__ )
if( strOption == STR_BMP )
{
if( i == noBytes - 1 && ( noBytes & 1 ) )
{
/* Odd-length BMP string, complain */
warnBMP = TRUE;
}
else
{
const wchar_t wCh = ( ch << 8 ) | getc( inFile );
if( displayUnicode( wCh, level ) )
{
lineLength++;
i++; /* We've read two characters for a wchar_t */
fPos += 2;
continue;
}
/* The value can't be displayed as Unicode, fall back to
displaying it as normal text */
ungetc( wCh & 0xFF, inFile );
}
}
if( strOption == STR_UTF8 && ( ch & 0x80 ) )
{
const int secondCh = getc( inFile );
wchar_t wCh;
/* It's a multibyte UTF8 character, read it as a widechar */
if( ( ch & 0xE0 ) == 0xC0 ) /* 111xxxxx -> 110xxxxx */
{
/* 2-byte character in the range 0x80...0x7FF */
wCh = ( ( ch & 0x1F ) << 6 ) | ( secondCh & 0x3F );
i++; /* We've read 2 characters */
fPos += 2;
}
else
{
if( ( ch & 0xF0 ) == 0xE0 ) /* 1111xxxx -> 1110xxxx */
{
const int thirdCh = getc( inFile );
/* 3-byte character in the range 0x800...0xFFFF */
wCh = ( ( ch & 0x1F ) << 12 ) | \
( ( secondCh & 0x3F ) << 6 ) | \
( thirdCh & 0x3F );
}
else
wCh = '.';
i += 2; /* We've read 3 characters */
fPos += 3;
}
if( !displayUnicode( wCh, level ) )
printString( level, "%c", '.' );
lineLength++;
continue;
}
#endif /* __WIN32__ || __UNIX__ || __OS390__ */
switch( strOption )
{
case STR_PRINTABLE:
case STR_IA5:
case STR_LATIN1:
if( strOption == STR_PRINTABLE && !isPrintable( ch ) )
warnPrintable = TRUE;
if( strOption == STR_IA5 && !isIA5( ch ) )
warnIA5 = TRUE;
if( strOption == STR_LATIN1 )
{
if( !isprint( ch & 0x7F ) )
ch = '.'; /* Convert non-ASCII to placeholders */
}
else
{
if( !isprint( ch ) )
ch = '.'; /* Convert non-ASCII to placeholders */
}
#ifdef __OS390__
ch = asciiToEbcdic( ch );
#endif /* __OS390__ */
break;
case STR_UTCTIME:
case STR_GENERALIZED:
if( !isdigit( ch ) && ch != 'Z' )
{
warnTime = TRUE;
if( !isprint( ch ) )
ch = '.'; /* Convert non-ASCII to placeholders */
}
#ifdef __OS390__
ch = asciiToEbcdic( ch );
#endif /* __OS390__ */
break;
case STR_BMP_REVERSED:
if( i == noBytes - 1 && ( noBytes & 1 ) )
{
/* Odd-length BMP string, complain */
warnBMP = TRUE;
}
/* Wrong-endianness BMPStrings (Microsoft Unicode) can't be
handled through the usual widechar-handling mechanism
above since the first widechar looks like an ASCII char
followed by a null terminator, so we just treat them as
ASCII chars, skipping the following zero byte. This is
safe since the code that detects reversed BMPStrings
has already checked that every second byte is zero */
getc( inFile );
i++;
fPos++;
/* Drop through */
default:
if( !isprint( ch ) )
ch = '.'; /* Convert control chars to placeholders */
#ifdef __OS390__
ch = asciiToEbcdic( ch );
#endif /* __OS390__ */
}
if( doTimeStr )
timeStr[ i ] = ch;
else
printString( level, "%c", ch );
fPos++;
}
if( length > 384 && !printAllData )
{
length -= 384;
printString( level, "%s", "'\n" );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 5 );
printString( level, "[ Another %ld characters skipped ]", length );
fPos += length;
while( length-- )
{
int ch = getc( inFile );
if( strOption == STR_PRINTABLE && !isPrintable( ch ) )
warnPrintable = TRUE;
if( strOption == STR_IA5 && !isIA5( ch ) )
warnIA5 = TRUE;
}
}
else
{
if( doTimeStr )
{
const char *timeStrPtr = ( strOption == STR_UTCTIME ) ? \
timeStr : timeStr + 2;
printString( level, " %c%c/%c%c/",
timeStrPtr[ 4 ], timeStrPtr[ 5 ],
timeStrPtr[ 2 ], timeStrPtr[ 3 ] );
if( strOption == STR_UTCTIME )
{
printString( level, "%s",
( timeStr[ 0 ] < '5' ) ? "20" : "19" );
}
else
{
printString( level, "%c%c", timeStr[ 0 ], timeStr[ 1 ] );
}
printString( level, "%c%c %c%c:%c%c:%c%c GMT",
timeStrPtr[ 0 ], timeStrPtr[ 1 ], timeStrPtr[ 6 ],
timeStrPtr[ 7 ], timeStrPtr[ 8 ], timeStrPtr[ 9 ],
timeStrPtr[ 10 ], timeStrPtr[ 11 ] );
}
else
printString( level, "%c", '\'' );
}
printString( level, "%c", '\n' );
/* Display any problems we encountered */
if( warnPrintable )
complain( "PrintableString contains illegal character(s)", 0, level );
if( warnIA5 )
complain( "IA5String contains illegal character(s)", 0, level );
if( warnTime )
complain( "Time is encoded incorrectly", 0, level );
if( warnBMP )
complain( "BMPString has missing final byte/half character", 0, level );
}
/****************************************************************************
* *
* ASN.1 Parsing Routines *
* *
****************************************************************************/
/* Get an ASN.1 object's tag and length. Returns TRUE for an item
available, FALSE for end-of-data, and a negative value for an invalid
data */
static int getItem( FILE *inFile, ASN1_ITEM *item )
{
int tag, length, index = 0;
memset( item, 0, sizeof( ASN1_ITEM ) );
item->indefinite = FALSE;
tag = item->header[ index++ ] = fgetc( inFile );
if( tag == EOF )
return( FALSE );
item->id = tag & ~TAG_MASK;
tag &= TAG_MASK;
if( tag == TAG_MASK )
{
int value;
/* Long tag encoded as sequence of 7-bit values. This doesn't try to
handle tags > INT_MAX, it'd be pretty peculiar ASN.1 if it had to
use tags this large */
tag = 0;
do
{
value = fgetc( inFile );
if( value == EOF )
return( FALSE );
tag = ( tag << 7 ) | ( value & 0x7F );
item->header[ index++ ] = value;
fPos++;
}
while( value & LEN_XTND && index < 5 && !feof( inFile ) );
if( index >= 5 )
{
fPos++; /* Tag */
return( FALSE );
}
}
item->tag = tag;
if( feof( inFile ) )
{
fPos++;
return( FALSE );
}
fPos += 2; /* Tag + length */
length = item->header[ index++ ] = fgetc( inFile );
if( length == EOF )
return( FALSE );
item->headerSize = index;
if( length & LEN_XTND )
{
const int lengthStart = index;
int i;
length &= LEN_MASK;
if( length > 4 )
{
/* Impossible length value, probably because we've run into
the weeds */
return( -1 );
}
item->headerSize += length;
item->length = 0;
if( !length )
item->indefinite = TRUE;
for( i = 0; i < length; i++ )
{
int ch = fgetc( inFile );
if( ch == EOF )
{
fPos += length - i;
return( FALSE );
}
item->length = ( item->length << 8 ) | ch;
item->header[ i + index ] = ch;
}
fPos += length;
/* Check for the length being less then 128, which means it
shouldn't be encoded as a long length */
if( item->length < 128 )
item->nonCanonical = lengthStart;
/* Check for the first 9 bits of the length being identical and
if they are, remember where the encoded non-canonical length
starts */
if( item->headerSize - lengthStart > 1 )
{
if( ( item->header[ lengthStart ] == 0x00 ) && \
( ( item->header[ lengthStart + 1 ] & 0x80 ) == 0x00 ) )
item->nonCanonical = lengthStart - 1;
if( ( item->header[ lengthStart ] == 0xFF ) && \
( ( item->header[ lengthStart + 1 ] & 0x80 ) == 0x80 ) )
item->nonCanonical = lengthStart - 1;
}
}
else
item->length = length;
return( TRUE );
}
/* Check whether a BIT STRING or OCTET STRING encapsulates another object */
static int checkEncapsulate( FILE *inFile, const int length )
{
ASN1_ITEM nestedItem;
const int currentPos = fPos;
int diffPos, status;
/* If we're not looking for encapsulated objects, return */
if( !checkEncaps )
return( FALSE );
/* Read the details of the next item in the input stream */
status = getItem( inFile, &nestedItem );
diffPos = fPos - currentPos;
fPos = currentPos;
fseek( inFile, -diffPos, SEEK_CUR );
if( status <= 0 )
return( FALSE );
/* If it's not a standard tag class, don't try and dig down into it */
if( ( nestedItem.id & CLASS_MASK ) != UNIVERSAL && \
( nestedItem.id & CLASS_MASK ) != CONTEXT )
return( FALSE );
/* There is one special-case situation that overrides the check below,
which is when the nested content is indefinite-length. This is
rather tricky to check for because we'd need to read some distance
ahead into the stream to be able to safely decide whether we've got
true nested content or a false positive, for now we require that
the nested content has to be a SEQUENCE containing valid ASN.1 at
the start, giving about 24 bits of checking. There's a small risk
of false negatives for encapsulated primitive items, but since
they're primitive it should be relatively easy to make out the
contents inside the OCTET STRING */
if( nestedItem.tag == SEQUENCE && nestedItem.indefinite )
{
/* Skip the indefinite-length SEQUENCE and make sure that it's
followed by a valid item */
status = getItem( inFile, &nestedItem );
if( status > 0 )
status = getItem( inFile, &nestedItem );
diffPos = fPos - currentPos;
fPos = currentPos;
fseek( inFile, -diffPos, SEEK_CUR );
if( status <= 0 )
return( FALSE );
/* If the tag on the nest item looks vaguely valid, assume that we've
go nested content */
if( ( nestedItem.tag <= 0 || nestedItem.tag > 0x31 ) || \
( nestedItem.length >= length ) )
return( FALSE );
return( TRUE );
}
/* If it doesn't fit exactly within the current item it's not an
encapsulated object */
if( nestedItem.length != length - diffPos )
return( FALSE );
/* If it doesn't have a valid-looking tag, don't try and go any further */
if( nestedItem.tag <= 0 || nestedItem.tag > 0x31 )
return( FALSE );
/* Now things get a bit complicated because it's possible to get some
(very rare) false positives, for example if a NUMERICSTRING of
exactly the right length is nested within an OCTET STRING, since
numeric values all look like constructed tags of some kind. To
handle this we look for nested constructed items that should really
be primitive */
if( ( nestedItem.id & FORM_MASK ) == PRIMITIVE )
return( TRUE );
/* It's constructed, make sure that it's something for which it makes
sense as a constructed object. At worst this will give some false
negatives for really wierd objects (nested constructed strings inside
OCTET STRINGs), but these should probably never occur anyway */
if( nestedItem.tag == SEQUENCE || \
nestedItem.tag == SET )
return( TRUE );
return( FALSE );
}
/* Check whether a zero-length item is OK */
static int zeroLengthOK( const ASN1_ITEM *item )
{
/* An implicitly-tagged NULL can have a zero length. An occurrence of this
type of item is almost always an error, however OCSP uses a weird status
encoding that encodes result values in tags and then has to use a NULL
value to indicate that there's nothing there except the tag that encodes
the status, so we allow this as well if zero-length content is explicitly
enabled */
if( zeroLengthAllowed && ( item->id & CLASS_MASK ) == CONTEXT )
return( TRUE );
/* If we can't recognise the type from the tag, reject it */
if( ( item->id & CLASS_MASK ) != UNIVERSAL )
return( FALSE );
/* The following types are zero-length by definition */
if( item->tag == EOC || item->tag == NULLTAG )
return( TRUE );
/* A real with a value of zero has zero length */
if( item->tag == REAL )
return( TRUE );
/* Everything after this point requires input from the user to say that
zero-length data is OK (usually it's not, so we flag it as a
problem) */
if( !zeroLengthAllowed )
return( FALSE );
/* String types can have zero length except for the Unrestricted
Character String type ([UNIVERSAL 29]) which has to have at least one
octet for the CH-A/CH-B index */
if( item->tag == OCTETSTRING || item->tag == NUMERICSTRING || \
item->tag == PRINTABLESTRING || item->tag == T61STRING || \
item->tag == VIDEOTEXSTRING || item->tag == VISIBLESTRING || \
item->tag == IA5STRING || item->tag == GRAPHICSTRING || \
item->tag == GENERALSTRING || item->tag == UNIVERSALSTRING || \
item->tag == BMPSTRING || item->tag == UTF8STRING || \
item->tag == OBJDESCRIPTOR )
return( TRUE );
/* SEQUENCE and SET can be zero if there are absent optional/default
components */
if( item->tag == SEQUENCE || item->tag == SET )
return( TRUE );
return( FALSE );
}
/* Check whether the next item looks like text */
static STR_OPTION checkForText( FILE *inFile, const int length )
{
char buffer[ 16 ];
int isBMP = FALSE, isUnicode = FALSE;
int sampleLength = min( length, 16 ), i;
/* If the sample is very short, we're more careful about what we
accept */
if( sampleLength < 4 )
{
/* If the sample size is too small, don't try anything */
if( sampleLength <= 2 )
return( STR_NONE );
/* For samples of 3-4 characters we only allow ASCII text. These
short strings are used in some places (eg PKCS #12 files) as
IDs */
sampleLength = fread( buffer, 1, sampleLength, inFile );
if( sampleLength <= 0 )
return( STR_NONE );
fseek( inFile, -sampleLength, SEEK_CUR );
for( i = 0; i < sampleLength; i++ )
{
const int ch = byteToInt( buffer[ i ] );
if( !( isalpha( ch ) || isdigit( ch ) || isspace( ch ) ) )
return( STR_NONE );
}
return( STR_IA5 );
}
/* Check for ASCII-looking text */
sampleLength = fread( buffer, 1, sampleLength, inFile );
if( sampleLength <= 0 )
return( STR_NONE );
fseek( inFile, -sampleLength, SEEK_CUR );
if( isdigit( byteToInt( buffer[ 0 ] ) ) && \
( length == 13 || length == 15 ) && \
buffer[ length - 1 ] == 'Z' )
{
/* It looks like a time string, make sure that it really is one */
for( i = 0; i < length - 1; i++ )
{
if( !isdigit( byteToInt( buffer[ i ] ) ) )
break;
}
if( i == length - 1 )
return( ( length == 13 ) ? STR_UTCTIME : STR_GENERALIZED );
}
for( i = 0; i < sampleLength; i++ )
{
/* If even bytes are zero, it could be a BMPString. Initially
we set isBMP to FALSE, if it looks like a BMPString we set it to
TRUE, if we then encounter a nonzero byte it's neither an ASCII
nor a BMPString */
if( !( i & 1 ) )
{
if( !buffer[ i ] )
{
/* If we thought we were in a Unicode string but we've found a
zero byte where it'd occur in a BMP string, it's neither a
Unicode nor BMP string */
if( isUnicode )
return( STR_NONE );
/* We've collapsed the eigenstate (in an earlier incarnation
isBMP could take values of -1, 0, or 1, with 0 being
undecided, in which case this comment made a bit more
sense) */
if( i < sampleLength - 2 )
{
/* If the last char(s) are zero but preceding ones
weren't, don't treat it as a BMP string. This can
happen when storing a null-terminated string if the
implementation gets the length wrong and stores the
null as well */
isBMP = TRUE;
}
continue;
}
else
{
/* If we thought we were in a BMPString but we've found a
nonzero byte where there should be a zero, it's neither
an ASCII nor BMP string */
if( isBMP )
return( STR_NONE );
}
}
else
{
/* Just to make it tricky, Microsoft stuff Unicode strings into
some places (to avoid having to convert them to BMPStrings,
presumably) so we have to check for these as well */
if( !buffer[ i ] )
{
if( isBMP )
return( STR_NONE );
isUnicode = TRUE;
continue;
}
else
{
if( isUnicode )
return( STR_NONE );
}
}
if( buffer[ i ] < 0x20 || buffer[ i ] > 0x7E )
return( STR_NONE );
}
/* It looks like a text string */
return( isUnicode ? STR_BMP_REVERSED : isBMP ? STR_BMP : STR_IA5 );
}
/* Dump the header bytes for an object, useful for vgrepping the original
object from a hex dump */
static void dumpHeader( FILE *inFile, const ASN1_ITEM *item, const int level )
{
int extraLen = 24 - item->headerSize, i;
/* Dump the tag and length bytes */
if( !doPure )
printString( level, "%s", " " );
printString( level, "<%02X", *item->header );
for( i = 1; i < item->headerSize; i++ )
printString( level, " %02X", item->header[ i ] );
/* If we're asked for more, dump enough extra data to make up 24 bytes.
This is somewhat ugly since it assumes we can seek backwards over the
data, which means it won't always work on streams */
if( extraLen > 0 && doDumpHeader > 1 )
{
/* Make sure that we don't print too much data. This doesn't work
for indefinite-length data, we don't try and guess the length with
this since it involves picking apart what we're printing */
if( extraLen > item->length && !item->indefinite )
extraLen = ( int ) item->length;
for( i = 0; i < extraLen; i++ )
{
const int ch = fgetc( inFile );
if( ch == EOF )
{
/* Exit loop and get fseek() offset correct */
extraLen = i;
break;
}
printString( level, " %02X", ch );
}
fseek( inFile, -extraLen, SEEK_CUR );
}
printString( level, "%s", ">\n" );
}
/* Print a constructed ASN.1 object */
static int printAsn1( FILE *inFile, const int level, long length,
const int isIndefinite );
static void printConstructed( FILE *inFile, int level, const ASN1_ITEM *item )
{
int result;
/* Special case for zero-length objects */
if( !item->length && !item->indefinite )
{
printString( level, "%s", " {}\n" );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
printString( level, "%s", " {\n" );
if( item->nonCanonical )
complainLengthCanonical( item, level );
result = printAsn1( inFile, level + 1, item->length, item->indefinite );
if( result )
{
fprintf( output, "Error: Inconsistent object length, %d byte%s "
"difference.\n", result, ( result > 1 ) ? "s" : "" );
noErrors++;
}
if( !doPure )
printString( level, "%s", INDENT_STRING );
printString( level, "%s", ( printDots ) ? ". " : " " );
doIndent( level );
printString( level, "%s", "}\n" );
}
/* Print a single ASN.1 object */
static void printASN1object( FILE *inFile, ASN1_ITEM *item, int level )
{
OIDINFO *oidInfo;
STR_OPTION stringType;
BYTE buffer[ MAX_OID_SIZE ];
const int nonOutlineObject = \
( doOutlineOnly && ( item->id & FORM_MASK ) != CONSTRUCTED ) ? \
TRUE : FALSE;
if( ( item->id & CLASS_MASK ) != UNIVERSAL )
{
static const char *const classtext[] =
{ "UNIVERSAL ", "APPLICATION ", "", "PRIVATE " };
/* Print the object type */
if( !nonOutlineObject )
{
printString( level, "[%s%d]",
classtext[ ( item->id & CLASS_MASK ) >> 6 ], item->tag );
}
/* Perform a sanity check */
if( ( item->tag != NULLTAG ) && ( item->length < 0 ) )
{
int i;
fflush( stdout );
fprintf( stderr, "\nError: Object has bad length field, tag = %02X, "
"length = %lX, value =", item->tag, item->length );
fprintf( stderr, "<%02X", *item->header );
for( i = 1; i < item->headerSize; i++ )
fprintf( stderr, " %02X", item->header[ i ] );
fputs( ">.\n", stderr );
exit( EXIT_FAILURE );
}
if( !item->length && !item->indefinite && !zeroLengthOK( item ) )
{
printString( level, "%c", '\n' );
complain( "Object has zero length", 0, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
/* If it's constructed, print the various fields in it */
if( ( item->id & FORM_MASK ) == CONSTRUCTED )
{
printConstructed( inFile, level, item );
return;
}
/* It'sprimitive, if we're only displaying the ASN.1 in outline
form, supress the display by dumping it with a nesting level that
ensures it won't get output (this clears the data from the input
without displaying it) */
if( nonOutlineObject )
{
dumpHex( inFile, item->length, 1000, FALSE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
printString( level, "%c", '\n' );
return;
}
/* It's primitive, if it's a seekable stream try and determine
whether it's text so we can display it as such */
if( !useStdin && \
( stringType = checkForText( inFile, item->length ) ) != STR_NONE )
{
/* It looks like a text string, dump it as text */
displayString( inFile, item->length, level, stringType );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
/* This could be anything, dump it as hex data */
dumpHex( inFile, item->length, level, FALSE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
/* Print the object type */
if( !doOutlineOnly || ( item->id & FORM_MASK ) == CONSTRUCTED )
printString( level, "%s", idstr( item->tag ) );
/* Perform a sanity check */
if( ( item->tag != NULLTAG ) && ( item->length < 0 ) )
{
int i;
fflush( stdout );
fprintf( stderr, "\nError: Object has bad length field, tag = %02X, "
"length = %lX, value =", item->tag, item->length );
fprintf( stderr, "<%02X", *item->header );
for( i = 1; i < item->headerSize; i++ )
fprintf( stderr, " %02X", item->header[ i ] );
fputs( ">.\n", stderr );
exit( EXIT_FAILURE );
}
/* If it's constructed, print the various fields in it */
if( ( item->id & FORM_MASK ) == CONSTRUCTED )
{
printConstructed( inFile, level, item );
return;
}
/* It's primitive */
if( doOutlineOnly )
{
/* If we're only displaying the ASN.1 in outline form, set an
artificially high nesting level that ensures it won't get output
(this clears the data from the input without displaying it) */
level = 1000;
}
if( !item->length && !zeroLengthOK( item ) )
{
printString( level, "%c", '\n' );
complain( "Object has zero length", 0, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
switch( item->tag )
{
case BOOLEAN:
{
int ch;
if( item->length != 1 )
complainLength( item, level );
ch = getc( inFile );
printString( level, " %s\n", ch ? "TRUE" : "FALSE" );
if( ch != 0 && ch != 0xFF )
{
complain( "BOOLEAN '%02X' has non-DER encoding", ch,
level );
}
if( item->nonCanonical )
complainLengthCanonical( item, level );
fPos++;
break;
}
case INTEGER:
case ENUMERATED:
if( item->length > 4 )
{
dumpHex( inFile, item->length, level, TRUE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
}
else
{
printValue( inFile, item->length, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
}
break;
case BITSTRING:
{
int ch;
if( item->length < 2 )
complainLength( item, level );
if( ( ch = getc( inFile ) ) != 0 )
{
printString( level, " %d unused bit%s",
ch, ( ch != 1 ) ? "s" : "" );
}
fPos++;
if( !--item->length && !ch )
{
printString( level, "%c", '\n' );
complain( "Object has zero length", 0, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
if( item->length <= sizeof( int ) )
{
/* It's short enough to be a bit flag, dump it as a sequence
of bits */
dumpBitString( inFile, ( int ) item->length, ch, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
}
/* Drop through to dump it as an octet string */
}
case OCTETSTRING:
if( checkEncapsulate( inFile, item->length ) )
{
/* It's something encapsulated inside the string, print it as
a constructed item */
printString( level, "%s", ", encapsulates" );
printConstructed( inFile, level, item );
break;
}
if( !useStdin && !dumpText && \
( stringType = checkForText( inFile, item->length ) ) != STR_NONE )
{
/* If we'd be doing a straight hex dump and it looks like
encapsulated text, display it as such. If the user has
overridden character set type checking and it's a string
type for which we normally perform type checking, we reset
its type to none */
displayString( inFile, item->length, level, \
( !checkCharset && ( stringType == STR_IA5 || \
stringType == STR_PRINTABLE ) ) ? \
STR_NONE : stringType );
if( item->nonCanonical )
complainLengthCanonical( item, level );
return;
}
dumpHex( inFile, item->length, level, FALSE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case OID:
{
char textOID[ 128 ];
int length, isValid;
/* Hierarchical Object Identifier */
if( item->length < 3 )
complainLength( item, level );
if( item->length > MAX_OID_SIZE )
{
fflush( stdout );
fprintf( stderr, "\nError: Object identifier length %ld too "
"large.\n", item->length );
exit( EXIT_FAILURE );
}
length = fread( buffer, 1, ( size_t ) item->length, inFile );
if( length < item->length )
{
complain( "Invalid OID data", 0, level );
break;
}
fPos += item->length;
if( ( oidInfo = getOIDinfo( buffer, ( int ) item->length ) ) != NULL )
{
/* Convert the binary OID to text form */
isValid = oidToString( textOID, &length, buffer,
( int ) item->length );
/* Check if LHS status info + indent + "OID " string + oid
name + "(" + oid value + ")" will wrap */
if( ( ( doPure ) ? 0 : INDENT_SIZE ) + ( level * 2 ) + 18 + \
strlen( oidInfo->description ) + 2 + length >= outputWidth )
{
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
}
else
printString( level, "%c", ' ' );
printString( level, "%s (%s)\n", oidInfo->description, textOID );
/* Display extra comments about the OID if required */
if( extraOIDinfo && oidInfo->comment != NULL )
{
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
printString( level, "(%s)\n", oidInfo->comment );
}
if( !isValid )
complain( "OID has invalid encoding", 0, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
/* If there's a warning associated with this OID, remember
that there was a problem */
if( oidInfo->warn )
noWarnings++;
break;
}
/* Print the OID as a text string */
isValid = oidToString( textOID, &length, buffer,
( int ) item->length );
printString( level, " '%s'\n", textOID );
if( !isValid )
complain( "OID has invalid encoding", 0, level );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
}
case EOC:
case NULLTAG:
printString( level, "%c", '\n' );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case OBJDESCRIPTOR:
case GRAPHICSTRING:
case VISIBLESTRING:
case GENERALSTRING:
case UNIVERSALSTRING:
case NUMERICSTRING:
case VIDEOTEXSTRING:
case PRINTABLESTRING:
displayString( inFile, item->length, level, STR_PRINTABLE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case UTF8STRING:
displayString( inFile, item->length, level, STR_UTF8 );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case BMPSTRING:
displayString( inFile, item->length, level, STR_BMP );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case UTCTIME:
displayString( inFile, item->length, level, STR_UTCTIME );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case GENERALIZEDTIME:
displayString( inFile, item->length, level, STR_GENERALIZED );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case IA5STRING:
displayString( inFile, item->length, level, STR_IA5 );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case T61STRING:
displayString( inFile, item->length, level, STR_LATIN1 );
if( item->nonCanonical )
complainLengthCanonical( item, level );
break;
case SEQUENCE:
printString( level, "%c", '\n' );
complain( "SEQUENCE has invalid primitive encoding", 0, level );
break;
case SET:
printString( level, "%c", '\n' );
complain( "SET has invalid primitive encoding", 0, level );
break;
default:
printString( level, "%c", '\n' );
if( !doPure )
printString( level, "%s", INDENT_STRING );
doIndent( level + 1 );
printString( level, "%s",
"Unrecognised primitive, hex value is:");
dumpHex( inFile, item->length, level, FALSE );
if( item->nonCanonical )
complainLengthCanonical( item, level );
noErrors++; /* Treat it as an error */
}
}
/* Print a complex ASN.1 object */
static int printAsn1( FILE *inFile, const int level, long length,
const int isIndefinite )
{
ASN1_ITEM item;
long lastPos = fPos;
int seenEOC = FALSE, status;
/* Special-case for zero-length objects */
if( !length && !isIndefinite )
return( 0 );
while( ( status = getItem( inFile, &item ) ) > 0 )
{
int nonOutlineObject = FALSE;
/* Perform various special checks the first time we're called */
if( length == LENGTH_MAGIC )
{
/* If the length isn't known and the item has a definite length,
set the length to the item's length */
if( !item.indefinite )
{
length = item.headerSize + item.length;
/* We can also adjust the width of the informational data
column to maximise the amount of screen real estate (for
lengths less than the default of four) or get rid of
oversized columns (for lengths greater than four) */
if( length < 1000 )
infoWidth = 3;
else
if( length > 9999999 )
infoWidth = 8;
else
if( length > 999999 )
infoWidth = 7;
else
if( length > 99999 )
infoWidth = 6;
else
if( length > 9999 )
infoWidth = 5;
}
/* If the input isn't seekable, turn off some options that
require the use of fseek(). This check isn't perfect (some
streams are slightly seekable due to buffering) but it's
better than nothing */
if( fseek( inFile, -item.headerSize, SEEK_CUR ) )
{
useStdin = TRUE;
checkEncaps = FALSE;
puts( "Warning: Input is non-seekable, some functionality "
"has been disabled." );
}
else
fseek( inFile, item.headerSize, SEEK_CUR );
}
/* Dump the header as hex data if requested */
if( doDumpHeader )
dumpHeader( inFile, &item, level );
/* If we're displaying the ASN.1 outline only and it's not a
constructed object, don't display anything */
if( doOutlineOnly && ( item.id & FORM_MASK ) != CONSTRUCTED )
nonOutlineObject = TRUE;
/* Print the offset and length, unless we're in pure ASN.1-only
output mode or we're displaying the outline only and it's not
a constructed object */
if( item.header[ 0 ] == EOC )
{
seenEOC = TRUE;
if( !isIndefinite)
complain( "Spurious EOC in definite-length item", 0, level );
}
if( !doPure && !nonOutlineObject )
{
if( item.indefinite )
printString( level, ( doHexValues ) ? \
LEN_HEX_INDEF : LEN_INDEF, lastPos );
else
{
if( !seenEOC )
printString( level, ( doHexValues ) ? \
LEN_HEX : LEN, lastPos, item.length );
}
}
/* Print details on the item */
if( !seenEOC )
{
if( !nonOutlineObject )
doIndent( level );
printASN1object( inFile, &item, level );
}
/* If it was an indefinite-length object (no length was ever set) and
we've come back to the top level, exit */
if( length == LENGTH_MAGIC )
return( 0 );
length -= fPos - lastPos;
lastPos = fPos;
if( isIndefinite )
{
if( seenEOC )
return( 0 );
}
else
{
if( length <= 0 )
{
if( length < 0 )
return( ( int ) -length );
return( 0 );
}
else
{
if( length == 1 )
{
const int ch = fgetc( inFile );
if( ch == EOF )
return( 0 );
/* No object can be one byte long, try and recover. This
only works sometimes because it can be caused by
spurious data in an OCTET STRING hole or an incorrect
length encoding. The following workaround tries to
recover from spurious data by skipping the byte if
it's zero or a non-basic-ASN.1 tag, but keeping it if
it could be valid ASN.1 */
if( ch && ch <= 0x31 )
ungetc( ch, inFile );
else
{
fPos++;
return( 1 );
}
}
}
}
}
if( status == -1 )
{
int i;
fflush( stdout );
fprintf( stderr, "\nError: Invalid data encountered at position "
"%d:", fPos );
for( i = 0; i < item.headerSize; i++ )
fprintf( stderr, " %02X", item.header[ i ] );
fprintf( stderr, ".\n" );
exit( EXIT_FAILURE );
}
/* If we see an EOF and there's supposed to be more data present,
complain */
if( length && length != LENGTH_MAGIC )
{
fprintf( output, "Error: Inconsistent object length, %ld byte%s "
"difference.\n", length, ( length > 1 ) ? "s" : "" );
noErrors++;
}
return( 0 );
}
/* Show usage and exit */
static void usageExit( void )
{
puts( "DumpASN1 - ASN.1 object dump/syntax check program." );
puts( "Copyright Peter Gutmann 1997 - 2012. Last updated " UPDATE_STRING "." );
puts( "" );
puts( "Usage: dumpasn1 [-acdefghilmoprstuvwxz] <file>" );
puts( " Input options:" );
puts( " - = Take input from stdin (some options may not work properly)" );
puts( " -<number> = Start <number> bytes into the file" );
puts( " -- = End of arg list" );
puts( " -c<file> = Read Object Identifier info from alternate config file" );
puts( " (values will override equivalents in global config file)" );
puts( "" );
puts( " Output options:" );
puts( " -f<file> = Dump object at offset -<number> to file (allows data to be" );
puts( " extracted from encapsulating objects)" );
puts( " -w<number> = Set width of output, default = 80 columns" );
puts( "" );
puts( " Display options:" );
puts( " -a = Print all data in long data blocks, not just the first 128 bytes" );
puts( " -d = Print dots to show column alignment" );
puts( " -g = Display ASN.1 structure outline only (no primitive objects)" );
puts( " -h = Hex dump object header (tag+length) before the decoded output" );
puts( " -hh = Same as -h but display more of the object as hex data" );
puts( " -i = Use shallow indenting, for deeply-nested objects" );
puts( " -l = Long format, display extra info about Object Identifiers" );
puts( " -m<number> = Maximum nesting level for which to display content" );
puts( " -p = Pure ASN.1 output without encoding information" );
puts( " -t = Display text values next to hex dump of data" );
puts( " -v = Verbose mode, equivalent to -ahlt" );
puts( "" );
puts( " Format options:" );
puts( " -e = Don't print encapsulated data inside OCTET/BIT STRINGs" );
puts( " -r = Print bits in BIT STRING as encoded in reverse order" );
puts( " -u = Don't format UTCTime/GeneralizedTime string data" );
puts( " -x = Display size and offset in hex not decimal" );
puts( "" );
puts( " Checking options:" );
puts( " -o = Don't check validity of character strings hidden in octet strings" );
puts( " -s = Syntax check only, don't dump ASN.1 structures" );
puts( " -z = Allow zero-length items" );
puts( "" );
puts( "Warnings generated by deprecated OIDs require the use of '-l' to be displayed." );
puts( "Program return code is the number of errors found or EXIT_SUCCESS." );
exit( EXIT_FAILURE );
}
int main( int argc, char *argv[] )
{
FILE *inFile, *outFile = NULL;
#ifdef __WIN32__
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
#endif /* __WIN32__ */
#ifdef __OS390__
char pathPtr[ FILENAME_MAX ];
#else
char *pathPtr = argv[ 0 ];
#endif /* __OS390__ */
long offset = 0;
int moreArgs = TRUE, doCheckOnly = FALSE;
#ifdef __OS390__
memset( pathPtr, '\0', sizeof( pathPtr ) );
getcwd( pathPtr, sizeof( pathPtr ) );
strcat( pathPtr, "/" );
#endif /* __OS390__ */
/* Skip the program name */
argv++; argc--;
/* Display usage if no args given */
if( argc < 1 )
usageExit();
output = stdout; /* Needs to be assigned at runtime */
/* Get the output width. Under Unix there's no safe way to do this, so
we default to 80 columns */
#ifdef __WIN32__
if( GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE ),
&csbiInfo ) )
outputWidth = csbiInfo.dwSize.X;
#endif /* __WIN32__ */
/* Check for arguments */
while( argc && *argv[ 0 ] == '-' && moreArgs )
{
char *argPtr = argv[ 0 ] + 1;
if( !*argPtr )
useStdin = TRUE;
while( *argPtr )
{
if( isdigit( byteToInt( *argPtr ) ) )
{
offset = atol( argPtr );
break;
}
switch( toupper( byteToInt( *argPtr ) ) )
{
case '-':
moreArgs = FALSE; /* GNU-style end-of-args flag */
break;
case 'A':
printAllData = TRUE;
break;
case 'C':
if( !readConfig( argPtr + 1, FALSE ) )
exit( EXIT_FAILURE );
while( argPtr[ 1 ] )
argPtr++; /* Skip rest of arg */
break;
case 'D':
printDots = TRUE;
break;
case 'E':
checkEncaps = FALSE;
break;
case 'F':
if( ( outFile = fopen( argPtr + 1, "wb" ) ) == NULL )
{
perror( argPtr + 1 );
exit( EXIT_FAILURE );
}
while( argPtr[ 1 ] )
argPtr++; /* Skip rest of arg */
break;
case 'G':
doOutlineOnly = TRUE;
break;
case 'H':
doDumpHeader++;
break;
case 'I':
shallowIndent = TRUE;
break;
case 'L':
extraOIDinfo = TRUE;
break;
case 'M':
maxNestLevel = atoi( argPtr + 1 );
if( maxNestLevel < 1 || maxNestLevel > 100 )
{
puts( "Invalid maximum nesting level." );
exit( EXIT_FAILURE );
}
while( argPtr[ 1 ] )
argPtr++; /* Skip rest of arg */
break;
case 'O':
checkCharset = TRUE;
break;
case 'P':
doPure = TRUE;
break;
case 'R':
reverseBitString = !reverseBitString;
break;
case 'S':
doCheckOnly = TRUE;
#if defined( __WIN32__ )
/* Under Windows we can't fclose( stdout ) because the
VC++ runtime reassigns the stdout handle to the next
open file (which is valid) but then scribbles stdout
garbage all over it for files larger than about 16K
(which isn't), so we have to make sure that the
stdout handle is pointed to something somewhere */
( void ) freopen( "nul", "w", stdout );
#elif defined( __UNIX__ )
/* Safety feature in case any Unix libc is as broken
as the Win32 version */
( void ) freopen( "/dev/null", "w", stdout );
#else
fclose( stdout );
#endif /* OS-specific bypassing of stdout */
break;
case 'T':
dumpText = TRUE;
break;
case 'U':
rawTimeString = TRUE;
break;
case 'V':
printAllData = doDumpHeader = TRUE;
extraOIDinfo = dumpText = TRUE;
break;
case 'W':
outputWidth = atoi( argPtr + 1 );
if( outputWidth < 40 || outputWidth > 500 )
{
puts( "Invalid output width." );
exit( EXIT_FAILURE );
}
while( argPtr[ 1 ] )
argPtr++; /* Skip rest of arg */
break;
case 'X':
doHexValues = TRUE;
break;
case 'Z':
zeroLengthAllowed = TRUE;
break;
default:
printf( "Unknown argument '%c'.\n", *argPtr );
return( EXIT_SUCCESS );
}
argPtr++;
}
argv++;
argc--;
}
/* We can't use options that perform an fseek() if reading from stdin */
if( useStdin && ( doDumpHeader || outFile != NULL ) )
{
puts( "Can't use -f or -h when taking input from stdin" );
exit( EXIT_FAILURE );
}
/* Check args and read the config file. We don't bother weeding out
dups during the read because (a) the linear search would make the
process n^2, (b) during the dump process the search will terminate on
the first match so dups aren't that serious, and (c) there should be
very few dups present */
if( argc != 1 && !useStdin )
usageExit();
if( !readGlobalConfig( pathPtr ) )
exit( EXIT_FAILURE );
/* Dump the given file */
if( useStdin )
inFile = stdin;
else
{
if( ( inFile = fopen( argv[ 0 ], "rb" ) ) == NULL )
{
perror( argv[ 0 ] );
freeConfig();
exit( EXIT_FAILURE );
}
}
if( useStdin )
{
while( offset-- )
getc( inFile );
}
else
fseek( inFile, offset, SEEK_SET );
if( outFile != NULL )
{
ASN1_ITEM item;
long length;
int i, status;
/* Make sure that there's something there, and that it has a
definite length */
status = getItem( inFile, &item );
if( status == -1 )
{
puts( "Non-ASN.1 data encountered." );
freeConfig();
exit( EXIT_FAILURE );
}
if( status == 0 )
{
puts( "Nothing to read." );
freeConfig();
exit( EXIT_FAILURE );
}
if( item.indefinite )
{
puts( "Cannot process indefinite-length item." );
freeConfig();
exit( EXIT_FAILURE );
}
/* Copy the item across, first the header and then the data */
for( i = 0; i < item.headerSize; i++ )
putc( item.header[ i ], outFile );
for( length = 0; length < item.length && !feof( inFile ); length++ )
putc( getc( inFile ), outFile );
fclose( outFile );
fseek( inFile, offset, SEEK_SET );
}
printAsn1( inFile, 0, LENGTH_MAGIC, 0 );
if( !useStdin && offset == 0 )
{
BYTE buffer[ 16 ];
long position = ftell( inFile );
/* If we're dumping a standalone ASN.1 object and there's further
data appended to it, warn the user of its existence. This is a
bit hit-and-miss since there may or may not be additional EOCs
present, dumpasn1 always stops once it knows that the data should
end (without trying to read any trailing EOCs) because data from
some sources has the EOCs truncated, and most apps know that they
have to stop at min( data_end, EOCs ). To avoid false positives,
we skip at least 4 EOCs worth of data and if there's still more
present, we complain */
fread( buffer, 1, 8, inFile ); /* Skip 4 EOCs */
if( !feof( inFile ) )
{
fprintf( output, "Warning: Further data follows ASN.1 data at "
"position %ld.\n", position );
noWarnings++;
}
}
fclose( inFile );
freeConfig();
/* Print a summary of warnings/errors if it's required or appropriate */
if( !doPure )
{
fflush( stdout );
if( !doCheckOnly )
fputc( '\n', stderr );
fprintf( stderr, "%d warning%s, %d error%s.\n", noWarnings,
( noWarnings != 1 ) ? "s" : "", noErrors,
( noErrors != 1 ) ? "s" : "" );
}
return( ( noErrors ) ? noErrors : EXIT_SUCCESS );
}
|
the_stack_data/145625.c | #include <stdio.h>
#define N 4
int maxfascia(int Mat[][N], int n, int k)
{
int i, j, found, tmp, res;
found = 0;
tmp = 0;
res = 0;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
if(Mat[i][j]==k) {
tmp++;
found = 1;
}
else if(found) {
if(tmp>res) {
res = tmp;
}
tmp = 0;
found = 0;
}
}
}
return res;
}
int main(void)
{
int m[N][N];
int i, j, f;
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("Inserisci elemento [%d][%d]: ", i, j);
scanf("%d", &m[i][j]);
}
}
printf("Inserisci valore: ");
scanf("%d", &f);
printf("Lunghezza fascia max: %d\n", maxfascia(m, N, f));
return 0;
}
|
the_stack_data/917800.c | /*-
* Copyright 2003-2005 Colin Percival
* Copyright 2012 Matthew Endsley
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted providing 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 ``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.
*/
#include <stdint.h>
struct bspatch_stream
{
void* opaque;
int (*read)(const struct bspatch_stream* stream, void* buffer, int length);
};
int bspatch(const uint8_t* old, int64_t oldsize, uint8_t* new, int64_t newsize, struct bspatch_stream* stream);
#if !defined(BSPATCH_HEADER_ONLY)
static int64_t offtin(uint8_t *buf)
{
int64_t y;
y=buf[7]&0x7F;
y=y*256;y+=buf[6];
y=y*256;y+=buf[5];
y=y*256;y+=buf[4];
y=y*256;y+=buf[3];
y=y*256;y+=buf[2];
y=y*256;y+=buf[1];
y=y*256;y+=buf[0];
if(buf[7]&0x80) y=-y;
return y;
}
int bspatch(const uint8_t* old, int64_t oldsize, uint8_t* new, int64_t newsize, struct bspatch_stream* stream)
{
uint8_t buf[8];
int64_t oldpos,newpos;
int64_t ctrl[3];
int64_t i;
oldpos=0;newpos=0;
while(newpos<newsize) {
/* Read control data */
for(i=0;i<=2;i++) {
if (stream->read(stream, buf, 8))
return -1;
ctrl[i]=offtin(buf);
};
/* Sanity-check */
if(newpos+ctrl[0]>newsize)
return -1;
/* Read diff string */
if (stream->read(stream, new + newpos, ctrl[0]))
return -1;
/* Add old data to diff string */
for(i=0;i<ctrl[0];i++)
if((oldpos+i>=0) && (oldpos+i<oldsize))
new[newpos+i]+=old[oldpos+i];
/* Adjust pointers */
newpos+=ctrl[0];
oldpos+=ctrl[0];
/* Sanity-check */
if(newpos+ctrl[1]>newsize)
return -1;
/* Read extra string */
if (stream->read(stream, new + newpos, ctrl[1]))
return -1;
/* Adjust pointers */
newpos+=ctrl[1];
oldpos+=ctrl[2];
};
return 0;
}
#if defined(BSPATCH_EXECUTABLE)
#include "include/bzlib.h"
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include <unistd.h>
#include <fcntl.h>
static int bz2_read(const struct bspatch_stream* stream, void* buffer, int length)
{
int n;
int bz2err;
BZFILE* bz2;
bz2 = (BZFILE*)stream->opaque;
n = BZ2_bzRead(&bz2err, bz2, buffer, length);
if (n != length)
return -1;
return 0;
}
int main(int argc,char * argv[])
{
FILE * f;
int fd;
int bz2err;
uint8_t header[24];
uint8_t *old, *new;
int64_t oldsize, newsize;
BZFILE* bz2;
struct bspatch_stream stream;
if(argc!=4) errx(1,"usage: %s oldfile newfile patchfile\n",argv[0]);
/* Open patch file */
if ((f = fopen(argv[3], "r")) == NULL)
err(1, "fopen(%s)", argv[3]);
/* Read header */
if (fread(header, 1, 16, f) != 16) {
if (feof(f))
errx(1, "Corrupt patch\n");
err(1, "fread(%s)", argv[3]);
}
/* Check for appropriate magic */
if (memcmp(header, "ENDSLEY/BSDIFF43", 16) != 0)
errx(1, "Corrupt patch\n");
/* Read lengths from header */
newsize=offtin(header+16);
if(newsize<0)
errx(1,"Corrupt patch\n");
/* Close patch file and re-open it via libbzip2 at the right places */
if(((fd=open(argv[1],O_RDONLY,0))<0) ||
((oldsize=lseek(fd,0,SEEK_END))==-1) ||
((old=malloc(oldsize+1))==NULL) ||
(lseek(fd,0,SEEK_SET)!=0) ||
(read(fd,old,oldsize)!=oldsize) ||
(close(fd)==-1)) err(1,"%s",argv[1]);
if((new=malloc(newsize+1))==NULL) err(1,NULL);
if (NULL == (bz2 = BZ2_bzReadOpen(&bz2err, f, 0, 0, NULL, 0)))
errx(1, "BZ2_bzReadOpen, bz2err=%d", bz2err);
stream.read = bz2_read;
stream.opaque = bz2;
if (bspatch(old, oldsize, new, newsize, &stream))
errx(1, "bspatch");
/* Clean up the bzip2 reads */
BZ2_bzReadClose(&bz2err, bz2);
fclose(f);
/* Write the new file */
if(((fd=open(argv[2],O_CREAT|O_TRUNC|O_WRONLY,0666))<0) ||
(write(fd,new,newsize)!=newsize) || (close(fd)==-1))
err(1,"%s",argv[2]);
free(new);
free(old);
return 0;
}
#endif
#endif
|
the_stack_data/225144113.c | #include <stdio.h>
#include <ctype.h>
int main(){
int n, in1, in2;
scanf("%d", &n);
char string[n];
scanf("%s", string);
scanf("%d %d", &in1, &in2);
int num1, num2;
num1 = (int)string[in1];
num2 = (int)string[in2];
if(num1 >= 65 && num1 <= 90){
string[in1] = tolower((char)num1);
}else{
string[in1] = toupper((char)num1);
}
if(num2 >= 65 && num2 <= 90){
string[in2] = tolower((char)num2);
}else{
string[in2] = toupper((char)num2);
}
printf("%s\n", string);
} |
the_stack_data/196196.c | //
// stack.c
// c_exercises
//
// Created by 王显朋 on 2019/3/2.
// Copyright © 2019年 wongxp. All rights reserved.
//
#include <stdio.h>
#define MAXVAL 100
static double var[MAXVAL];
static int sp = 0;
/**
* push f onto value stack
*/
void push(double f) {
if (sp >= MAXVAL) {
printf("error: stack full, can't push %g\n", f);
} else {
var[sp++] = f;
}
}
/**
* pop and return top value from stack
*/
double pop(void) {
if (sp <= 0) {
printf("error: stack empty\n");
return 0.0;
} else {
return var[--sp];
}
}
/**
* clear the stack (for 4_4)
*/
void clear_(void) {
sp = 0;
}
|
the_stack_data/1089870.c | #include<stdio.h>
int n,k,a[100];
void pat(int x, int y){
int i;
if(x>=n){
if(y==k){
for(i=0; i<n; i++)printf("%d",a[i]);
printf("\n");
}
return;
}
if(y<k){
a[x]=1;
pat(x+1,y+1);
}
a[x]=0;
pat(x+1,y);
}
int main(void){
scanf("%d %d",&n,&k);
pat(0,0);
return 0;
} |
the_stack_data/151396.c | void mergeSort(int A[], int B[], int s, int e);
void merge(int A[], int B[], int s, int m, int e);
void mergeSort(int A[], int B[], int s, int e) {
if (s < e) {
int m = (s + e) / 2;
mergeSort(A, B, s, m);
mergeSort(A, B, m + 1, e);
merge(A, B, s, m, e);
}
}
void merge(int A[], int B[], int s, int m, int e) {
int i = s;
int j = m + 1;
for (int k = 0; k < (e - s + 1); k++) {
if ((A[i] < A[j] && i <= m) || j > e) {
B[k] = A[i];
i++;
} else {
B[k] = A[j];
j++;
}
}
for (int k = 0; k < (e - s + 1); k++) {
A[s + k] = B[k];
}
} |
the_stack_data/59627.c | /**************************8
* test.c
*
* test for myprintf.c
*
* Author: Simon Lee (sijlee)
* Date Created: 01/28/2016
* Last Modified by: Simon Lee (sijlee)
* Date Last Modified: 01/28/2016
* Assignment: Lab 2
* Part of: C335
*/
#include <stdio.h>
//declare & initialize myprintf function from other c file
extern void myprintf(const char *, ...);
//running actual test
//should print out the contents
int main() {
myprintf("Nothing much\n");
myprintf("The letter %c\n", 'A');
myprintf("A string: %s\n", "Splash!");
myprintf("The number %d\n", 11);
myprintf("The number %x in hexadecimal\n", 11);
myprintf("%d is a negative number\n", -5);
myprintf("The number %d\n", 'A');
myprintf("The number %x in hexadecimal\n", 'A');
return 0;
}
|
the_stack_data/215768358.c | #include <stdio.h>
#include <stdlib.h>
int main( int ac, char *av[] )
{
long long d, n, p;
char buf[1024];
p = 0;
while( fgets( buf, 1024, stdin ) ) {
d = strtoll( buf, NULL, 10 );
n = p + d;
if( p != 0 && d == 2 )
printf( "%lld %lld\n", p, n );
p = n;
}
return( 0 );
}
|
the_stack_data/125140477.c | /**
* Reading from file and displaying on the screen
*
* Argument Constant for open() are
* O_RDONLY
* O_RDWR
* O_CREAT
* O_APPEND
* O_TRUNC
*/
#include <unistd.h>
#include <fcntl.h>
int main()
{
char str[50];
int file_descriptor = open("file.txt", O_RDONLY, 0777);
read(file_descriptor, str, 5);
write(0, str, 5);
read(file_descriptor, str, 5);
write(0, str, 5);
write(0, "\n", 1);
return 0;
}
|
the_stack_data/1720.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_iterative_factorial.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slammari <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/13 11:53:49 by slammari #+# #+# */
/* Updated: 2021/10/13 20:07:37 by slammari ### ########.fr */
/* */
/* ************************************************************************** */
int ft_iterative_factorial(int nb)
{
int n;
int i;
n = 1;
i = 1;
if (nb < 0)
return (0);
while (i <= nb)
{
n = n * i;
i++;
}
return (n);
}
|
the_stack_data/29826275.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//Precision to use for calculations
#define fptype float
typedef struct OptionData_ {
fptype s; // spot price
fptype strike; // strike price
fptype r; // risk-free interest rate
fptype divq; // dividend rate
fptype v; // volatility
fptype t; // time to maturity or option expiration in years
// (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc)
char OptionType; // Option type. "P"=PUT, "C"=CALL
fptype divs; // dividend vals (not used in this test)
fptype DGrefval; // DerivaGem Reference Value
} OptionData;
OptionData *data;
int numOptions;
int * otype;
fptype * sptprice;
fptype * strike;
fptype * rate;
fptype * volatility;
fptype * otime;
int numError = 0;
int bs_thread (fptype *prices) {
int i, j;
fptype price;
fptype priceDelta;
int start = 0;
int end = start + numOptions;
for (i=start; i<end; i++) {
prices[i] = i;
}
return 0;
}
int main (int argc, char **argv) {
FILE *file;
int i;
int loopnum;
fptype * buffer;
int * buffer2;
int rv;
//Read input data
numOptions = atoll(argv[1]) + 2;
// alloc spaces for the option data
data = (OptionData*)malloc(numOptions*sizeof(OptionData));
fptype *prices = (fptype*)malloc(numOptions*sizeof(fptype));
printf("Num of Options: %d\n", numOptions);
#define PAD 256
#define LINESIZE 64
buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD);
sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1));
strike = sptprice + numOptions;
rate = strike + numOptions;
volatility = rate + numOptions;
otime = volatility + numOptions;
buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD);
otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1));
for (i=0; i<numOptions; i++) {
otype[i] = (data[i].OptionType == 'P') ? 1 : 0;
sptprice[i] = data[i].s;
strike[i] = data[i].strike;
rate[i] = data[i].r;
volatility[i] = data[i].v;
otime[i] = data[i].t;
}
bs_thread(prices);
printf("Wow: %f\n", prices[0] + prices[1]);
return 0;
}
|
the_stack_data/76700093.c | // INFO: task hung in __get_super
// https://syzkaller.appspot.com/bug?id=9f2bd61dc53dba56d73d25464b93fa9a0a5c554e
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/futex.h>
#include <linux/loop.h>
unsigned long long procid;
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i;
for (i = 0; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct fs_image_segment {
void* data;
uintptr_t size;
uintptr_t offset;
};
#define IMAGE_MAX_SEGMENTS 4096
#define IMAGE_MAX_SIZE (129 << 20)
#define SYZ_memfd_create 319
static long syz_read_part_table(volatile unsigned long size,
volatile unsigned long nsegs,
volatile long segments)
{
char loopname[64], linkname[64];
int loopfd, err = 0, res = -1;
unsigned long i, j;
struct fs_image_segment* segs = (struct fs_image_segment*)segments;
if (nsegs > IMAGE_MAX_SEGMENTS)
nsegs = IMAGE_MAX_SEGMENTS;
for (i = 0; i < nsegs; i++) {
if (segs[i].size > IMAGE_MAX_SIZE)
segs[i].size = IMAGE_MAX_SIZE;
segs[i].offset %= IMAGE_MAX_SIZE;
if (segs[i].offset > IMAGE_MAX_SIZE - segs[i].size)
segs[i].offset = IMAGE_MAX_SIZE - segs[i].size;
if (size < segs[i].offset + segs[i].offset)
size = segs[i].offset + segs[i].offset;
}
if (size > IMAGE_MAX_SIZE)
size = IMAGE_MAX_SIZE;
int memfd = syscall(SYZ_memfd_create, "syz_read_part_table", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (ftruncate(memfd, size)) {
err = errno;
goto error_close_memfd;
}
for (i = 0; i < nsegs; i++) {
if (pwrite(memfd, segs[i].data, segs[i].size, segs[i].offset) < 0) {
}
}
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
struct loop_info64 info;
if (ioctl(loopfd, LOOP_GET_STATUS64, &info)) {
err = errno;
goto error_clear_loop;
}
info.lo_flags |= LO_FLAGS_PARTSCAN;
if (ioctl(loopfd, LOOP_SET_STATUS64, &info)) {
err = errno;
goto error_clear_loop;
}
res = 0;
for (i = 1, j = 0; i < 8; i++) {
snprintf(loopname, sizeof(loopname), "/dev/loop%llup%d", procid, (int)i);
struct stat statbuf;
if (stat(loopname, &statbuf) == 0) {
snprintf(linkname, sizeof(linkname), "./file%d", (int)j++);
if (symlink(loopname, linkname)) {
}
}
}
error_clear_loop:
ioctl(loopfd, LOOP_CLR_FD, 0);
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return res;
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void reset_loop()
{
char buf[64];
snprintf(buf, sizeof(buf), "/dev/loop%llu", procid);
int loopfd = open(buf, O_RDWR);
if (loopfd != -1) {
ioctl(loopfd, LOOP_CLR_FD, 0);
close(loopfd);
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void execute_one(void)
{
int i, call, thread;
for (call = 0; call < 5; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
event_timedwait(&th->done, 45);
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
reset_loop();
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
}
}
void execute_call(int call)
{
switch (call) {
case 0:
memcpy((void*)0x20000000, "./file0\000", 8);
syscall(__NR_mkdir, 0x20000000, 0);
break;
case 1:
syscall(__NR_request_key, 0, 0, 0, 0xfffffffd);
break;
case 2:
*(uint64_t*)0x20002740 = 0;
*(uint64_t*)0x20002748 = 0;
*(uint64_t*)0x20002750 = 0xe874;
*(uint64_t*)0x20002758 = 0;
*(uint64_t*)0x20002760 = 0;
*(uint64_t*)0x20002768 = 2;
*(uint64_t*)0x20002770 = 0;
*(uint64_t*)0x20002778 = 0;
*(uint64_t*)0x20002780 = 3;
*(uint64_t*)0x20002788 = 0x20001600;
*(uint64_t*)0x20002790 = 0;
*(uint64_t*)0x20002798 = 7;
*(uint64_t*)0x200027a0 = 0;
*(uint64_t*)0x200027a8 = 0;
*(uint64_t*)0x200027b0 = 7;
*(uint64_t*)0x200027b8 = 0;
*(uint64_t*)0x200027c0 = 0;
*(uint64_t*)0x200027c8 = 8;
syz_read_part_table(0x3ff, 6, 0x20002740);
break;
case 3:
memcpy((void*)0x20000140, "/dev/loop", 9);
*(uint8_t*)0x20000149 = 0x30;
*(uint8_t*)0x2000014a = 0;
memcpy((void*)0x20000180, "./file0\000", 8);
memcpy((void*)0x200001c0, "udf\000", 4);
syscall(__NR_mount, 0x20000140, 0x20000180, 0x200001c0, 0, 0);
break;
case 4:
syscall(__NR_mount, 0, 0, 0, 8, 0);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
loop();
return 0;
}
|
the_stack_data/126898.c | /*
Autor: root
Compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Para compilar: gcc raizcuadrara1603.c -o raizcuadrara1603
Fecha: Sun Mar 21 01:44:39 UTC 2021
Librerías:
Resumen:
Se ingresa un número positivo. El programa busca su raíz cuadrada
y le aplica la función piso, o sea, busca el entero menor a esta
raíz cuadrada.
*/
//Librerías
#include <stdio.h>
int main(){
//Iniciamos las variables globales
float N=0;
int i=0;
printf("Ingresar un número positivo: ");
scanf("%f",&N);
//Por si ingresa un número negativo
if(N<0){
printf("No existe raíz cuadrada en los reales\n");
} else if(N==0){
//Por si ingresa el cero
printf("La raíz cuadrada es: 0");
} else if(N>0){
//Busca el entero que se acerque más a la raíz cuadrada
while(i*i <= N){
i++;
}
printf("La raíz cuadrada es: %d \n", i-1);
}
return 0;
} |
the_stack_data/328446.c | // RUN: %clang -### -c -fveclib=none %s 2>&1 | FileCheck -check-prefix CHECK-NOLIB %s
// RUN: %clang -### -c -fveclib=Accelerate %s 2>&1 | FileCheck -check-prefix CHECK-ACCELERATE %s
// RUN: %clang -### -c -fveclib=MASSV %s 2>&1 | FileCheck -check-prefix CHECK-MASSV %s
// RUN: not %clang -c -fveclib=something %s 2>&1 | FileCheck -check-prefix CHECK-INVALID %s
// CHECK-NOLIB: "-fveclib=none"
// CHECK-ACCELERATE: "-fveclib=Accelerate"
// CHECK-MASSV: "-fveclib=MASSV"
// CHECK-INVALID: error: invalid value 'something' in '-fveclib=something'
// RUN: %clang -fveclib=Accelerate %s -target arm64-apple-ios8.0.0 -### 2>&1 | FileCheck --check-prefix=CHECK-LINK %s
// CHECK-LINK: "-framework" "Accelerate"
// RUN: %clang -fveclib=Accelerate %s -nostdlib -target arm64-apple-ios8.0.0 -### 2>&1 | FileCheck --check-prefix=CHECK-LINK-NOSTDLIB %s
// CHECK-LINK-NOSTDLIB-NOT: "-framework" "Accelerate"
// RUN: %clang -fveclib=Accelerate %s -nodefaultlibs -target arm64-apple-ios8.0.0 -### 2>&1 | FileCheck --check-prefix=CHECK-LINK-NODEFAULTLIBS %s
// CHECK-LINK-NODEFAULTLIBS-NOT: "-framework" "Accelerate"
|
the_stack_data/242329908.c | /* Example code for Exercises in C.
Modified version of an example from Chapter 2.5 of Head First C.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#define NUM_TRACKS 5
char tracks[][80] = {
"So What",
"Freddie Freeloader",
"Blue in Green",
"All Blues",
"Flamenco Sketches"
};
typedef regex_t Regex;
/* Returns a new Regex that matches the given pattern.
*
* pattern: string regex
* flags: flags passed to regcomp
* returns: new Regex
*/
Regex *make_regex(char *pattern, int flags) {
Regex *regex = (Regex *)malloc(sizeof(Regex));
int ret = regcomp(regex, pattern, flags);
if (ret) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
return regex;
}
/* Checks whether a regex matches a string.
*
* regex: Regex pointer
* s: string
* returns: 1 if there's a match, 0 otherwise
*/
int regex_match(Regex *regex, char *s) {
int ret = regexec(regex, s, 0, NULL, 0);
if (!ret) {
return 1;
} else if (ret == REG_NOMATCH) {
return 0;
} else {
size_t errsize = regerror(ret, regex, (char *)NULL, (size_t)0);
char *errbuf = malloc(errsize * sizeof(char));
regerror(ret, regex, errbuf, errsize);
fprintf(stderr, "Regex match failed: %s\n", errbuf);
exit(1);
}
}
/* Frees a Regex.
*
* regex: Regex pointer
*/
void regex_free(Regex *regex) {
regfree(regex);
// FILL THIS IN!
}
/* Finds all tracks that match the given pattern.
*
* Prints track number and title.
*/
void find_track_regex(char pattern[])
{
int i;
Regex *regex = make_regex(pattern, REG_EXTENDED | REG_NOSUB);
for (i=0; i<NUM_TRACKS; i++) {
if (regex_match(regex, tracks[i])) {
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
regex_free(regex);
}
int main (int argc, char *argv[])
{
char *pattern = "F.*F.*";
find_track_regex(pattern);
return 0;
}
|
the_stack_data/126702006.c | //1828 - Bazinga!
#include <stdio.h>
#include <string.h>
int main(){
int casos, i;
char sheldon[20], raj[20];
scanf("%d", &casos);
for(i = 1; i <= casos; i++){
scanf("%s %s", sheldon, raj);
if(!strcmp(sheldon, raj)){
printf("Caso #%d: De novo!\n", i);
}
//1
else if(!strcmp(sheldon, "tesoura") && !strcmp(raj, "papel")){
printf("Caso #%d: Bazinga!\n", i);
}
//2
else if(!strcmp(sheldon, "papel") && !strcmp(raj, "pedra")){
printf("Caso #%d: Bazinga!\n", i);
}
//3
else if(!strcmp(sheldon, "pedra") && !strcmp(raj, "lagarto")){
printf("Caso #%d: Bazinga!\n", i);
}
//4
else if(!strcmp(sheldon, "lagarto") && !strcmp(raj, "Spock")){
printf("Caso #%d: Bazinga!\n", i);
}
//5
else if(!strcmp(sheldon, "Spock") && !strcmp(raj, "tesoura")){
printf("Caso #%d: Bazinga!\n", i);
}
//6
else if(!strcmp(sheldon, "tesoura") && !strcmp(raj, "lagarto")){
printf("Caso #%d: Bazinga!\n", i);
}
//7
else if(!strcmp(sheldon, "lagarto") && !strcmp(raj, "papel")){
printf("Caso #%d: Bazinga!\n", i);
}
//8
else if(!strcmp(sheldon, "papel") && !strcmp(raj, "Spock")){
printf("Caso #%d: Bazinga!\n", i);
}
//9
else if(!strcmp(sheldon, "Spock") && !strcmp(raj, "pedra")){
printf("Caso #%d: Bazinga!\n", i);
}
//10
else if(!strcmp(sheldon, "pedra") && !strcmp(raj, "tesoura")){
printf("Caso #%d: Bazinga!\n", i);
}
else{
printf("Caso #%d: Raj trapaceou!\n", i);
}
}
return 0;
}
|
the_stack_data/122015569.c | int main()
{
int a = 5;
int b = 2;
int c = 6;
a /= b+2*c;
return a;
} |
the_stack_data/100140898.c | const char bar[] = "world";
|
the_stack_data/154831371.c | #include <stdio.h>
int main(void) {
int t_ct;
double time, power_of_2;
int limit;
printf("Enter the number of terms you want: ");
scanf("%d", &limit);
for (time = 0, power_of_2 = 1, t_ct = 1; t_ct <= limit; t_ct++, power_of_2 *= 2.0) {
time += 1.0 / power_of_2;
printf("time = %f when terms = %d.\n", time, t_ct);
}
return 0;
} |
the_stack_data/831517.c | #include <stdio.h>
int main() {
int n100, n50, n20, n10, n5, n2;
int m1, m50, m25, m10, m05, m01;
double n;
scanf("%lf", &n);
int notas = n;
int moedas = (n - notas) * 100;
if((moedas * 1000) % 10 == 9){
moedas++;
}
n100 = notas/100;
notas = notas%100;
n50 = notas/50;
notas = notas%50;
n20 = notas/20;
notas = notas%20;
n10 = notas/10;
notas = notas%10;
n5 = notas/5;
notas = notas%5;
n2 = notas/2;
notas = notas%2;
m1 = notas/1;
notas = notas%1;
m50 = moedas/50;
moedas = moedas%50;
m25 = moedas/25;
moedas = moedas%25;
m10 = moedas/10;
moedas = moedas%10;
m05 = moedas/5;
moedas = moedas%5;
m01 = moedas/1;
printf("NOTAS:\n");
printf("%d nota(s) de R$ 100.00\n", n100);
printf("%d nota(s) de R$ 50.00\n", n50);
printf("%d nota(s) de R$ 20.00\n", n20);
printf("%d nota(s) de R$ 10.00\n", n10);
printf("%d nota(s) de R$ 5.00\n", n5);
printf("%d nota(s) de R$ 2.00\n", n2);
printf("MOEDAS:\n");
printf("%d moeda(s) de R$ 1.00\n", m1);
printf("%d moeda(s) de R$ 0.50\n", m50);
printf("%d moeda(s) de R$ 0.25\n", m25);
printf("%d moeda(s) de R$ 0.10\n", m10);
printf("%d moeda(s) de R$ 0.05\n", m05);
printf("%d moeda(s) de R$ 0.01\n", m01);
return 0;
} |
the_stack_data/364799.c | #include<stdio.h>
int main()
{
double n;
scanf("%lf",&n);
if(n<0 || n>100){
printf("Fora de intervalo\n");
}
else if(n<=25.00){
printf("Intervalo [0,25]\n");
}
else if(n<=50.0){
printf("Intervalo (25,50]\n");
}
else if(n<=75.0){
printf("Intervalo (50,75]\n");
}
else if(n<=100.0){
printf("Intervalo (75,100]\n");
}
return 0;
}
|
the_stack_data/83838.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
//1
int *array, size, elementToDelete, i, position;
//2
printf("Enter total number of elements to add : ");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(int));
//3
for (i = 0; i < size; i++)
{
printf("Enter element for position %d : ", i);
scanf("%d", &array[i]);
}
//4
printf("You have entered : ");
for (i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
//5
printf("Enter the number you want to delete : ");
scanf("%d", &elementToDelete);
//6
position = -1;
//7
for (i = 0; i < size; i++)
{
if (array[i] == elementToDelete)
{
position = i;
break;
}
}
//8
if (position != -1)
{
//9
for (i = position; i < size - 1; i++)
{
array[i] = array[i + 1];
}
array = (int *)realloc(array, (size - 1) * sizeof(int));
//10
printf("Final array :");
for (i = 0; i < size - 1; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
else
{
//11
printf("Entered number is not found in the array.");
}
}
|
the_stack_data/92327621.c | // Arthur Henry
// COP3402 - Fall 2019
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define SIZE 16
char *expr();
char *printOp(char op);
char *newTemp();
void printList();
void exitLLVM();
int contains(char identifier);
typedef struct node
{
char var;
char *addr;
char *num;
struct node *next;
} node;
typedef struct LinkedList
{
node *head;
node *tail;
} LinkedList;
// NOTE: Variable declarations are all happening at the beginning
// of the simplec program.
// TODO: Storing the variable names will be a simple tail insertion
// into a linked list.
// TODO: Loading the variable will be a simple linked list search.
// NOTE: When searching, we will be looking for the var field in the node struct.
// NOTE: These may be slow operations, but are effective for what we need them to do.
// Global file pointer so all functions have access to it.
FILE *file;
// Keeps a pointer that's in the exact position of the file we're in.
char token;
// Keeps a pointer that's ahead of every step we make.
char lookahead;
// Controls where we will be storing our temp values.
int temp = 0;
// Helps with a program that carries a single integer.
char *numG;
// The head of our linked list that will hold our variables.
// Will allow O(1) insertion at the tail and O(n) lookup.
LinkedList *variables;
// NOTE: We don't have to add anything to the number just yet,
// because we only read declarations at the beginning.
// TODO: Make sure that the number is stored properly. (We might
// not have to actually store it.)
node *createNode(char var, char *addr)
{
node *newNode = calloc(1, sizeof(node));
// printf("%c\n", var);
newNode->var = var;
newNode->addr = addr;
return newNode;
}
// Allocating memory for our linked list.
LinkedList *createList()
{
return calloc(1, sizeof(LinkedList));
}
// Inserts a new temporary variable at the end of our linked list.
void tailInsert(char var, char *addr)
{
if (variables == NULL)
{
return;
}
else if (variables->head == NULL)
{
variables->head = variables->tail = createNode(var, addr);
}
else
{
variables->tail->next = createNode(var, addr);
variables->tail = variables->tail->next;
}
return;
}
// Returning the address of the node.
// i.e., the number of nodes we went through the list
char *lookup(char identifier)
{
node *temp = NULL;
// Identifier cannot exist in empty list.
if (variables == NULL || variables->tail == NULL)
return 0;
temp = variables->head;
while (temp != NULL)
{
if (temp->var == identifier)
return temp->addr;
temp = temp->next;
}
return NULL;
}
int isIdentifier(char identifier)
{
node *temp = NULL;
// Identifier cannot exist in empty list.
if (variables == NULL || variables->tail == NULL)
return 0;
temp = variables->head;
while (temp != NULL)
{
if (temp->var == identifier)
return 1;
temp = temp->next;
}
return 0;
}
// Updates the lookahead char.
void peek()
{
// Get character from the file and store in lookahead.
lookahead = fgetc(file);
// Going back to where the file pointer was previously.
ungetc(lookahead, file);
}
// Updates our current file pointer and lookahead.
void consume()
{
token = fgetc(file);
// Everytime we update our token, update the lookahead.
peek();
}
// Skips spaces encountered.
void spaces()
{
while (lookahead == ' ')
consume();
}
// Returns 1 if we have a print token in the simpelc file.
// Otherwise, returns 0.
int printCheck()
{
peek();
switch(lookahead)
{
case 'p':
// printf("%c\n", token);
consume();
case 'r':
// printf("%c\n", token);
consume();
case 'i':
// printf("%c\n", token);
consume();
case 'n':
// printf("%c\n", token);
consume();
case 't':
// printf("%c\n", token);
consume();
// printf("printing!\n");
return 1;
default:
return 0;
}
}
// Generates the LLVM code for printing.
void printLLVM(char var)
{
char *tempToPrint;
tempToPrint = malloc(sizeof(char) * SIZE);
if (!contains(var))
{
fprintf(stderr, "error: use of undeclared variable %c\n", var);
exitLLVM();
exit(0);
}
// Checks if there is one value passed into the program.
if (temp == 0)
{
printf(" %%t1 = %s %s, 0\n", printOp('+'), numG);
temp++;
}
// TODO: Load the value of temp onto a new variable, then print that one.
strcpy(tempToPrint, lookup(var));
consume();
printf(" %s = load i32, i32* %s\n", newTemp(), tempToPrint);
printf(" call void @print_integer(i32 %%t%d)\n\n", temp);
}
// Prints out the LLVM instruction for the operation we have to perform.
// Otherwise, if the symbol is invalid NULL is returned.
char *printOp(char op)
{
switch(op)
{
case '+':
return "add nsw i32";
case '-':
return "sub nsw i32";
case '*':
return "mul nsw i32";
case '/':
return "sdiv i32";
case '%':
return "srem i32";
default:
break;
}
return NULL;
}
// Invalid token was passed into factor().
// This is true according to project1.md specifications.
void error()
{
printf("Error(), exiting.\n");
exit(0);
}
// Assigns a new temporary variable to a result.
char *newTemp()
{
char *new = malloc(sizeof(char) * (16));
snprintf(new, 16, "%s%d", "%t", ++temp);
return new;
}
// Computes the grammar for factor.
char *factor()
{
int i = 0;
char *num = NULL, *addr = NULL, *result = NULL;
char identifier;
num = malloc(sizeof(char) * 16);
numG = malloc(sizeof(char) * 16);
// spaces();
// Nested expression encountered.
if (lookahead == '(')
{
consume(); // LPAREN
strcpy(num, expr());
consume(); // RPAREN
}
else if (isdigit(lookahead) || lookahead == '-')
{
// printf("la: %c\n", lookahead);
// Checks for negative numbers.
if (lookahead == '-')
{
consume();
num[i++] = token;
}
// Sets num to first digit encountered.
consume();
num[i++] = token;
// Allows for multidigit numbers to be passed in.
while (isdigit(lookahead))
{
consume();
num[i++] = token;
}
num[i] = '\0';
// printf("num in factor(): %s\n", num);
strcpy(numG, num);
return numG;
}
else if (isIdentifier(lookahead))
{
// printf("la: %c (supposed to be y)\n", lookahead);
consume();
identifier = token;
spaces();
// Checking to see if lookahead already exists in our linked list
addr = lookup(identifier);
// A variable that doesn't exist is trying to be accessed, return error
// to avoid compiling problems.
if (addr == NULL)
{
fprintf(stderr, "error: use of undeclared variable %c\n", identifier);
exitLLVM();
exit(0);
}
result = newTemp();
printf(" %s = load i32, i32* %s\n", result, addr);
return result;
}
else
{
fprintf(stderr, "error: use of undeclared variable %c\n", lookahead);
exitLLVM();
exit(0);
}
return num;
}
// Executes the term with a loop.
char *term()
{
char operation;
char *left = NULL, *right = NULL, *result = NULL;
left = malloc(sizeof(char) * 16);
right = malloc(sizeof(char) * 16);
result = malloc(sizeof(char) * 16);
spaces();
// NOTE: I was having issues here. Just leaving this as a
// reference for possible future problems.
strcpy(left, factor());
spaces();
// printf("lookahead: %c\n", lookahead);
while (lookahead == '*' || lookahead == '/' || lookahead == '%' || lookahead == '=')
{
spaces();
if (lookahead == '=')
printf("%s\n", variables->head->addr);
consume();
operation = token;
spaces();
strcpy(right, factor());
spaces();
strcpy(result, newTemp());
printf(" %s = %s %s, %s\n", result, printOp(operation), left, right);
strcpy(left, result);
}
// printf("lookahead in term(): %c\n", lookahead);
return left;
}
// Executes the expression with a loop.
char *expr()
{
char operation;
char *left = NULL, *right = NULL, *result = NULL;
left = malloc(sizeof(char) * 16);
right = malloc(sizeof(char) * 16);
result = malloc(sizeof(char) * 16);
spaces();
strcpy(left, term());
spaces();
while (lookahead == '+' || lookahead == '-')
{
consume();
operation = token;
spaces();
strcpy(right, term());
spaces();
strcpy(result, newTemp());
printf(" %s = %s %s, %s\n", result, printOp(operation), left, right);
strcpy(left, result);
}
return left;
}
// Opens the file if it exists. Otherwise, we exit the program.
void processInputFile(char *filename)
{
if ((file = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "File could not be opened in processInputFile().\n");
exit(0);
}
return;
}
// Consumes semi colons or new line characters.
void semi()
{
// if (print)
// printLLVM();
while (lookahead == ';' || lookahead == '\n')
consume();
}
// Checks if the linked list already contains the identifier passed in.
int contains(char identifier)
{
node *temp = NULL;
// Preventing segfault.
if (variables == NULL || variables->tail == NULL)
return 0;
temp = variables->head;
// Iterating through variable list without affecting original state.
while (temp != NULL)
{
// printf("%c -> ", temp->var);
// Identifier already exists in the list.
if (temp->var == identifier)
return 1;
temp = temp->next;
}
// printf("\n");
// Identifier has not been inserted into the list of variables.
return 0;
}
// Prints the linked list to make sure all values exist within the
// data structure. (NOTE: It's for debugging purposes.)
void printList()
{
node *temp = NULL;
temp = variables->head;
while (temp != NULL)
{
printf("%c -> ", temp->var);
temp = temp->next;
}
printf("\n");
}
// Returns 1 if the beginning on the line started with 'read'.
// Otherwise, returns 0.
int readCheck()
{
peek();
switch (lookahead)
{
case 'r':
case 'e':
case 'a':
case 'd':
consume();
consume();
consume();
consume();
return 1;
default:
return 0;
}
return 0;
}
// Reads and stores integers.
void read()
{
char identifier;
char *addr, *result;
addr = malloc(sizeof(char) * SIZE);
result = malloc(sizeof(char) * SIZE);
spaces();
// Gets identifier.
consume();
identifier = token;
spaces();
// FIXME: segfaulting here (possible another error)
strcpy(addr, lookup(identifier));
if (addr == NULL)
{
fprintf(stderr, "error: use of undeclared variable %c\n", identifier);
exitLLVM();
exit(0);
}
strcpy(result, newTemp());
printf(" %s = call i32 @read_integer()\n", result);
printf(" store i32 %s, i32* %s\n\n", result, addr);
}
// Assigns values to variables that exist within our linked
// list data structure storing all temporary variables.
void assign()
{
char identifier;
char *addr, *result;
addr = malloc(sizeof(char) * SIZE);
result = malloc(sizeof(char) * SIZE);
consume();
identifier = token;
spaces();
// printf("token: %c\n", token);
// Consumes equal sign.
consume();
spaces();
// printf("514: token: %c\n", token);
// printf("lookahead: %c\n", lookahead);
strcpy(result, expr());
spaces();
// Consumes semi colon.
semi();
strcpy(addr, lookup(identifier));
if (addr == NULL)
{
fprintf(stderr, "error: use of undeclared variable %c\n", identifier);
exitLLVM();
exit(0);
}
printf(" store i32 %s, i32* %s\n\n", result, addr);
}
// Returns 1 if there is an integer delcaration.
// Otherwise, returns 0.
int declarationCheck()
{
switch(lookahead)
{
case 'i':
consume();
case 'n':
consume();
case 't':
consume();
return 1;
default:
return 0;
}
return 0;
}
// Declares a variable by inserting it into our linked list.
void declaration()
{
char identifier;
char *result = NULL;
result = malloc(sizeof(char) * SIZE);
spaces();
// printf("la: %c\n", lookahead);
if (contains(lookahead))
{
fprintf(stderr, "error: multiple definitions of %c\n", lookahead);
exitLLVM();
exit(0);
}
if (isalpha(lookahead))
{
spaces();
// Gets identifier.
consume();
identifier = token;
consume(); // consumes semi colon
// Checking if identifier already exists in symbol table.
if (contains(identifier))
error();
strcpy(result, newTemp());
// printList();
// printf(" ; \"int %c;\"\n", identifier);
printf(" %s = alloca i32\n\n", result);
tailInsert(identifier, result);
}
semi();
}
// Depending on the value of printCheck(), we either print the
// variable the SimpleC program is asking for, or computing an expression.
void statement()
{
spaces();
peek();
if (declarationCheck())
{
// printf("Going into declaration()...\n");
declaration();
}
else if (isIdentifier(lookahead))
{
// printf("Going into assign()...\n");
assign();
}
else if (readCheck())
{
// printf("lookahead: %c\n", lookahead);
// printf("Going into read()...\n");
read();
}
else if (printCheck())
{
// printf("Going into print()...\n");
spaces();
printLLVM(lookahead);
}
semi();
return;
}
// Template code that needs to be generated before we execute our
// main function.
void boilerplate()
{
printf("target triple = \"x86_64-pc-linux-gnu\"\n"
"declare i32 @printf(i8*, ...) #1\n"
"@.str = private unnamed_addr constant [4 x i8] c\"%%d%c0A%c00\", align 1\n"
"define void @print_integer(i32) #0 {\n"
" %%2 = alloca i32, align 4\n"
" store i32 %%0, i32* %%2, align 4\n"
" %%3 = load i32, i32* %%2, align 4\n"
" %%4 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32 %%3)\n"
" ret void\n"
"}\n\n", 92, 92);
printf("%%struct._IO_FILE = type { i32, i8*, i8*, i8*, i8*, i8*, i8*, i8*, i8*, i8*, i8*, i8*, %%struct._IO_marker*, %%struct._IO_FILE*, i32, i32, i64, i16, i8, [1 x i8], i8*, i64, %%struct._IO_codecvt*, %%struct._IO_wide_data*, %%struct._IO_FILE*, i8*, i64, i32, [20 x i8] }\n"
"%%struct._IO_marker = type opaque\n"
"%%struct._IO_codecvt = type opaque\n"
"%%struct._IO_wide_data = type opaque\n\n");
printf("@stderr = external dso_local global %%struct._IO_FILE*, align 8\n"
"@.str.1 = private unnamed_addr constant [25 x i8] c\"please enter an integer\\0A\\00\", align 1\n"
"@.str.2 = private unnamed_addr constant [3 x i8] c\"%%d\\00\", align 1\n"
"@.str.3 = private unnamed_addr constant [6 x i8] c\"scanf\\00\", align 1\n"
"@.str.4 = private unnamed_addr constant [24 x i8] c\"no matching characters\\0A\\00\", align 1\n\n");
printf("declare i32* @__errno_location() #2\n"
"declare i32 @__isoc99_scanf(i8*, ...) #1\n"
"declare void @perror(i8*) #1\n"
"declare void @exit(i32) #3\n"
"declare i32 @fprintf(%%struct._IO_FILE*, i8*, ...) #1\n\n");
printf("define i32 @read_integer() #0 {\n"
" %%1 = alloca i32, align 4\n"
" %%2 = alloca i32, align 4\n"
" %%3 = call i32* @__errno_location() #4\n"
" store i32 0, i32* %%3, align 4\n"
" %%4 = load %%struct._IO_FILE*, %%struct._IO_FILE** @stderr, align 8\n"
" %%5 = call i32 (%%struct._IO_FILE*, i8*, ...) @fprintf(%%struct._IO_FILE* %%4, i8* getelementptr inbounds ([25 x i8], [25 x i8]* @.str.1, i32 0, i32 0))\n"
" %%6 = call i32 (i8*, ...) @__isoc99_scanf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str.2, i32 0, i32 0), i32* %%1)\n"
" store i32 %%6, i32* %%2, align 4\n"
" %%7 = load i32, i32* %%2, align 4\n"
" %%8 = icmp eq i32 %%7, 1\n"
" br i1 %%8, label %%9, label %%11\n"
"\n"
"; <label>:9: ; preds = %%0\n"
" %%10 = load i32, i32* %%1, align 4\n"
" ret i32 %%10\n"
"\n"
"; <label>:11: ; preds = %%0\n"
" %%12 = call i32* @__errno_location() #4\n"
" %%13 = load i32, i32* %%12, align 4\n"
" %%14 = icmp ne i32 %%13, 0\n"
" br i1 %%14, label %%15, label %%16\n"
"\n"
"; <label>:15: ; preds = %%11\n"
" call void @perror(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @.str.3, i32 0, i32 0))\n"
" call void @exit(i32 1) #5\n"
" unreachable\n"
"\n"
"; <label>:16: ; preds = %%11\n"
" %%17 = load %%struct._IO_FILE*, %%struct._IO_FILE** @stderr, align 8\n"
" %%18 = call i32 (%%struct._IO_FILE*, i8*, ...) @fprintf(%%struct._IO_FILE* %%17, i8* getelementptr inbounds ([24 x i8], [24 x i8]* @.str.4, i32 0, i32 0))\n"
" call void @exit(i32 1) #5\n"
" unreachable\n"
"}\n\n");
printf("define i32 @main() #0 {\n");
}
// Prints the exit code for LLVM file.
void exitLLVM()
{
printf(" ret i32 0\n}\n");
}
int main(int argc, char **argv)
{
char c;
// Making sure two arguments are passed in.
if (argc < 2)
{
fprintf(stderr, "Proper usage: %s <filename>.\n", argv[0]);
return 0;
}
processInputFile(argv[1]);
variables = createList();
boilerplate();
while ((token = fgetc(file)) != EOF)
{
// Ensures we start at the very beginning of the file.
ungetc(token, file);
statement();
}
exitLLVM();
fclose(file);
return 0;
}
|
the_stack_data/147014212.c | #include <math.h>
#include <stdio.h>
// 1. Addition
void calcAddition() {
printf("\nEnter two numbers: \n");
int a, b;
scanf("%d%d", &a, &b);
int result = a + b;
printf("The sum is %d\n", result);
}
// AGAIN?!?!
//hello idiot
// Fill the rest of the functionality here!
// 2. Subtraction
// 3. Multiplication
// 4. Division
// 5. Exponentiation
// 6. Sine
void calcSine() {
printf("\nEnter the angle in degrees: ");
int angle;
scanf("%d", &angle);
// Convert degrees to radians
double radians = angle / 180.0 * 3.14;
double answer = sin(radians);
printf("The sine value is %f", answer);
}
// Fill the rest of the functionality here!
// 7. Cosine
// 8. Tangent
// 9. Floor
void calcFloor() {
float num;
int result;
scanf("%f", &num);
result=floor(num);
printf("Floor integer of %.2f = %d", num,result);
}
// 10. Ceiling
// 11. Round
// 12. Absolute value
int main() {
int choice;
printf(
"Welcome to the Cool Calculator program!\n\n"
"1. Addition\n"
"2. Subtraction\n"
"3. Multiplication\n"
"4. Division-123\n"
"5. Exponentiation\n"
"6. Sine\n"
"7. Cosine\n"
"8. Tangent\n"
"9. Floor\n"
"10. Ceiling\n"
"11. Round\n"
"12. Absolute value\n\n"
"Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
// 1. Addition
case 1:
calcAddition();
break;
case 2:
case 3:
case 4:
case 5:
// 6. Sine
case 6:
calcSine();
break;
case 7:
case 8:
case 9: calcFloor();
case 10:
case 11:
case 12:
default:
printf("Invalid choice!");
}
return 0;
}
|
the_stack_data/37638323.c | /** @file snd2wlf.c
*
* Converter program that converts Wolfenstein 3D AdLib sound effects to WLF
* format files.
*
* The AdLib sound effects are stored in a format that's similar to, but not
* exactly the Wolfenstein 3D music format. The audio data was meant to be
* sent to the sound hardware in a very specific way, so only the variable
* data was stored. This converter adds the omitted information back so the
* sound can be played like a music track.
*
* The format of WLF music files is a variation of the IMF (id music format)
* specification. The only difference is that the lengh of a tick in an IMF
* file is 1/560 seconds, while it is 1/700 seconds in a WLF file.
*
* Here is the structure of the AdLib sound effect files:
*
* | Type | Name | Description |
* |--------------|------------|--------------------------------|
* | Uint32le | length | Length of the audio data |
* | Uint16le | priority | Priority of the sound effect |
* | Byte[16] | instrument | Instrument settings |
* | Byte | octave | Octave number |
* | Byte[length] | data | Actual sound data |
* | Uint8 | terminator | Unused |
* | Char[] | name | Null-terminated name, optional |
*
* The length and priority are *header* data and irrelevant to the actual
* effect, they only serve for the interpreting program to know how to play
* back the sound effect. The terminator and the name likewise are a *footer*
* and only relevant to *Muse*, the program they were created with.
*
* The original source of the program was written by Sune Mindall in Java and
* has been ported to C by HiPhish.
*/
#include <stdint.h>
#include <stdio.h>
/*-[ CONSTANTS ]--------------------------------------------------------------*/
#define MIN_DELAY 0 ///< The shortest delay that can be used.
#define TICK_DELAY 5 ///< One AdLib-sound-tick(@140hz) is 5 WLF ticks(@700Hz)
/** List of AdLib registers.
*
* The reason I don't just make the numeric value of the items the hardware
* addresses right away is so I could be able to iterate over the sequence of
* registers when reading and writing in one go.
*/
enum adlib_registers {
M_CHAR ,///< Modulator characteristics.
C_CHAR ,///< Carrier characteristics.
M_SCALE ,///< Modulator scale.
C_SCALE ,///< Carrier scale.
M_ATTACK ,///< Modulator attack/decay rate.
C_ATTACK ,///< Carrier attack/decay rate.
M_SUST ,///< Modulator sustain.
C_SUST ,///< Carrier sustain.
M_WAVE ,///< Modulator waveform.
C_WAVE ,///< Carrier waveform.
N_CONN ,///< Feedback/connection (usually ignored and set to 0).
NUMBER_OF_REGISTERS
};
/*-[ MAPPINGS ]---------------------------------------------------------------*/
/** Map an AdLib register to its hardware address */
uint8_t register_adress[NUMBER_OF_REGISTERS] = {
[M_CHAR ] = 0x20,
[C_CHAR ] = 0x23,
[M_SCALE ] = 0x40,
[C_SCALE ] = 0x43,
[M_ATTACK] = 0x60,
[C_ATTACK] = 0x63,
[M_SUST ] = 0x80,
[C_SUST ] = 0x83,
[M_WAVE ] = 0xE0,
[C_WAVE ] = 0xE3,
[N_CONN ] = 0xC0,
};
/*-[ FUNCTION DECLARATIONS ]--------------------------------------------------*/
/** Convert an AdLib sound effect file from the standard input to a WLF music
* file to the standard output.
*/
int convert_sound(void);
/** Write an IMF data element to the standard output.
*
* @param reg The OPL register to write.
* @param data Data to write to the register.
* @param delay Delay before next element, specified in ticks.
* @param counter Pointer to a counter integer to keep track up how many
* bytes we have written.
*
* An IMF data element consists of four bytes:
*
* - byte 1: OPL register
* - byte 2: Data to write to the register
* - byte 3+4: Delay before next element, specified in ticks
*
* A tick is either 1/560 sec for regular IMF or 1/700 sec for WLF.
*/
void write_imf_element(uint8_t opl, uint8_t data, uint16_t delay, uint16_t *counter);
/** Handles the arguments supplied to the program.
*
* @param argc Number of arguments passed.
* @param argv Array of argument literals passed.
*/
void handle_arguments(int argc, char *argv[]);
/** Prints usage instructions to the standard output. */
void print_usage(void);
/** Reads an unsigned 8-bit integer from file in an endian-independent way.
*
* @return The integer that was read.
*
* Reading advances the file position pointer.
*/
uint32_t read_uint8(void);
/** Reads an unsigned 16-bit integer from file in an endian-independent way.
*
* @return The integer that was read.
*
* Reading advances the file position pointer.
*/
uint32_t read_uint16(void);
/** Reads an unsigned 32-bit integer from file in an endian-independent way.
*
* @return The integer that was read.
*
* Reading advances the file position pointer.
*/
uint32_t read_uint32(void);
/** Write an unsigned 16-bit integer to the standard output.
*
* @param i The integer to write.
*/
void write_uint16(uint16_t i);
/*----------------------------------------------------------------------------*/
int main(int argc, char *argv[]) {
return convert_sound();
}
/*----------------------------------------------------------------------------*/
/*-[ FUNCTION IMPLEMENTATIONS ]-----------------------------------------------*/
int convert_sound() {
//Read length of the sound data from the header
uint32_t length = read_uint32();
// Write placeholder for the length of the output
write_uint16(0x0000);
// The real length of the WLF music data
uint16_t wlf_length = 0;
// Skip over the priority
fseek(stdin, sizeof(uint16_t), SEEK_CUR);
// Read and write instrument data
// nConn must never be set or the sound will play wrong
for (int reg = 0; reg < NUMBER_OF_REGISTERS - 1; ++reg) {
uint8_t intstrument = read_uint8();
write_imf_element(register_adress[reg], intstrument, MIN_DELAY, &wlf_length);
}
// The last six bytes of the sequence are either padding or unused, skip ahead
fseek(stdin, 6, SEEK_CUR);
// Read octave and compute block value from it
uint8_t block = (read_uint8() & 7) << 2;
// Read and write the pitch data
int note_on = 0; //boolean variable
for (unsigned int i = 0; i < length;) {
uint8_t note_value = read_uint8();
++i;
uint16_t repeated = 1;
//look ahead to see if the pitch is repeated. If so, the repetitions is counted and we skip ahead.
while (i < length && read_uint8() == note_value) {
++repeated;
++i;
}
// step back one byte (remember reading bytes moves forward through the file)
fseek(stdin, -1, SEEK_CUR);
if (note_value == 0x00) { // note not to be played
write_imf_element(0xB0, block, TICK_DELAY * repeated, &wlf_length);
note_on = 0;
}
else if (!note_on) { // note to be played and status noteOFF
write_imf_element(0xA0, note_value , MIN_DELAY , &wlf_length);
write_imf_element(0xB0, block | 0x20, TICK_DELAY * repeated, &wlf_length);
note_on = 1;
} else { // note to be played and status noteON
write_imf_element(0xA0, note_value, TICK_DELAY * repeated, &wlf_length);
note_on = 1;
}
}
// Add final note off
write_imf_element(0xB0, block, MIN_DELAY, &wlf_length);
// skip terminator (fseek has stepped one byte back, so we have to skip two bytes forward)
fseek(stdin, 2, SEEK_CUR);
// The audio data has been written, the rest is tag data that will be ignored
// by audio players. As such the data is not strictly standardised
// The purpose of this is unknown
fprintf(stdout, "%c%c", '\0', '\0');
//Read name(from footer) and write it down (the name is always 16 characters)
for (int i = 0; i < 15; ++i) {
char c = read_uint8();
fprintf(stdout, "%c", c);
// reading the null character, that's the end of the string so break out
if (c == '\0') {
// pad the rest of the string with '\0' to 16 characters
for (int j = 0; j < 15 - i - 1; ++j) {
fprintf(stdout, "%c", '\0');
}
break;
}
}
fprintf(stdout, "%c", '\0'); // terminate the string
// write comment (64 chars) and cProg (6 chars)
for (int i = 0; i < 70; ++i) {
fprintf(stdout, "%c", '\0');
}
// finally, write the WLF audio data length
fseek(stdout, 0, SEEK_SET); // seek to the beginning of the file
write_uint16(wlf_length);
return 0;
}
void write_imf_element(uint8_t opl, uint8_t data, uint16_t delay, uint16_t *counter) {
fwrite(&opl , sizeof(uint8_t), 1, stdout);
fwrite(&data, sizeof(uint8_t), 1, stdout);
write_uint16(delay);
if (counter != NULL) {*counter += 4;}
}
// In order to be able to read multi-byte value in an endian-independen manner
// we first read the individual bytes in their original order, then we OR them
// bitwise like a little-endian number.
uint32_t read_uint8() {
uint8_t byte[1] = {0x00};
fread(byte, sizeof(uint8_t), 1, stdin);
return byte[0];
}
uint32_t read_uint16() {
uint8_t byte[2] = {0x00, 0x00};
fread(byte, sizeof(uint8_t), 2, stdin);
uint32_t result = ((uint16_t)byte[0])<<0 | ((uint16_t)byte[1])<<8;
return result;
}
uint32_t read_uint32() {
uint8_t byte[4] = {0x00, 0x00, 0x00, 0x00};
fread(byte, sizeof(uint8_t), 4, stdin);
uint32_t result = ((uint32_t)byte[0])<<0 | ((uint32_t)byte[1])<<8 | ((uint32_t)byte[2])<<16| ((uint32_t)byte[3])<<24;
return result;
}
void write_uint16(uint16_t i) {
uint8_t le = i & 0x00FF; // little end
uint8_t be = i >> 8; // big end
fwrite(&le, sizeof(uint8_t), 1, stdout);
fwrite(&be, sizeof(uint8_t), 1, stdout);
}
|
the_stack_data/125643.c | /* Taxonomy Classification: 0000000100000163000010 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 1 variable
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 1 if
* LOOP STRUCTURE 6 non-standard while
* LOOP COMPLEXITY 3 two
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 0 no overflow
* CONTINUOUS/DISCRETE 1 continuous
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of software 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 set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology 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".
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.
*/
int main(int argc, char *argv[])
{
int test_value;
int inc_value;
int loop_counter;
char buf[10];
test_value = 9;
inc_value = 9 - (9 - 1);
loop_counter = 0;
while(loop_counter += inc_value)
{
/* OK */
buf[loop_counter] = 'A';
if (loop_counter >= test_value) break;
}
return 0;
}
|
the_stack_data/162643643.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
int main()
{
setlocale(LC_ALL, "pt-br");
int n;
double f;
scanf("%d", &n);
f = (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)) / sqrt(5);
printf("%.1lf\n", f);
return 0;
} |
the_stack_data/102105.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define ARRAY_SIZE 1000000
int main()
{
int array[ARRAY_SIZE];
int i;
printf("\n\nProgram : 'memory_1'\n");
printf("____________________\n");
printf ("\n\nPID : %d \n",getpid());
printf( "Size of int : %ld \n",sizeof(int));
printf("\nPress Enter Key to exit.\n");
getchar();
return 0;
} |
the_stack_data/107952841.c | #include <stdio.h>
#include <stdlib.h>
#define MAX_JOGADORES 300
void ad_jogador(int numero, int pos);
int soma_golos(int jogador);
float equilibrio(int jogador, float media);
int jogadores[MAX_JOGADORES][6];
int main()
{
int n, i = 0, j;
scanf("%d", &n);
while (n != (-1)){
ad_jogador(n, i);
i++;
scanf("%d", &n);
}
for (j = 0;j < i;j++){
float soma = soma_golos(j);
float media = (soma / 5);
float eq = equilibrio(j, media);
printf("%d\n", jogadores[j][0]);
printf("Media: %g\n", media);
printf("Equilibrio: %g\n", eq);
if (media > eq) {
printf("Classificacao: %g\n", media);
}else{
printf("Classificacao: %g\n", media / 2);
}
}
return 0;
}
void ad_jogador(int numero, int pos)
{
int j;
jogadores[pos][0] = numero;
for (j = 1;j < 6;j++){
scanf("%d\n", &jogadores[pos][j]);
}
}
int soma_golos(int jogador)
{
int soma = 0, k;
for (k = 1;k < 6;k++){
soma = soma + jogadores[jogador][k];
}
return soma;
}
float equilibrio(int jogador, float media)
{
float somatorio = 0, eq = 0, val = 0;
int k;
for (k = 1;k < 6;k++){
val = (jogadores[jogador][k] - media);
somatorio += (val * val);
}
eq = somatorio / 4;
return eq;
}
|
the_stack_data/73574763.c | /*
* Windows Service related function definitions
* By Raju Krishnappa([email protected])
*
*/
#ifdef WIN32
#include <net-snmp/net-snmp-config.h>
#include <windows.h>
#include <tchar.h>
#include <stdio.h> /* sprintf */
#include <process.h> /* beginthreadex */
#include <net-snmp/library/winservice.h>
#ifdef mingw32 /* MinGW doesn't fully support exception handling. */
#define TRY if(1)
#define LEAVE goto labelFIN
#define FINALLY do { \
labelFIN: \
; \
} while(0); if(1)
#else
#define TRY __try
#define LEAVE __leave
#define FINALLY __finally
#endif /* mingw32 */
#define CountOf(arr) ( sizeof(arr) / sizeof(arr[0]) )
#if defined(WIN32) && defined(HAVE_WIN32_PLATFORM_SDK) && !defined(mingw32)
#pragma comment(lib, "iphlpapi.lib")
#ifdef USING_WINEXTDLL_MODULE
#pragma comment(lib, "snmpapi.lib")
#pragma comment(lib, "mgmtapi.lib")
#endif
#endif
/*
* External global variables used here
*/
/*
* Application Name
* This should be declared by the application, which wants to register as
* windows service
*/
extern LPTSTR app_name_long;
/*
* Declare global variable
*/
/*
* Flag to indicate whether process is running as Service
*/
BOOL g_fRunningAsService = FALSE;
/*
* Variable to maintain Current Service status
*/
static SERVICE_STATUS ServiceStatus;
/*
* Service Handle
*/
static SERVICE_STATUS_HANDLE hServiceStatus = 0L;
/*
* Service Table Entry
*/
SERVICE_TABLE_ENTRY ServiceTableEntry[] = {
{NULL, ServiceMain}, /* Service Main function */
{NULL, NULL}
};
/*
* Handle to Thread, to implement Pause, Resume and Stop functions
*/
static HANDLE hServiceThread = NULL; /* Thread Handle */
/*
* Holds calling partys Function Entry point, that should start
* when entering service mode
*/
static INT (*ServiceEntryPoint) (INT Argc, LPTSTR Argv[]) = 0L;
/*
* To hold Stop Function address, to be called when STOP request
* received from the SCM
*/
static VOID (*StopFunction) (VOID) = 0L;
/*
* To update windows service status to SCM
*/
static BOOL UpdateServiceStatus (DWORD dwStatus, DWORD dwErrorCode,
DWORD dwWaitHint);
/*
* To Report current service status to SCM
*/
static BOOL ReportCurrentServiceStatus (VOID);
VOID
ProcessError (WORD eventLogType, LPCTSTR pszMessage, int useGetLastError, int quiet);
/*
* To register as Windows Service with SCM(Service Control Manager)
* Input - Service Name, Service Display Name,Service Description and
* Service startup arguments
*/
int
RegisterService (LPCTSTR lpszServiceName, LPCTSTR lpszServiceDisplayName,
LPCTSTR lpszServiceDescription,
InputParams * StartUpArg, int quiet) /* Startup argument to the service */
{
TCHAR szServicePath[MAX_PATH]; /* To hold module File name */
TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */
TCHAR szServiceCommand[MAX_PATH + 9]; /* Command to execute */
SC_HANDLE hSCManager = NULL;
SC_HANDLE hService = NULL;
TCHAR szRegAppLogKey[] =
_T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
TCHAR szRegKey[512];
HKEY hKey = NULL; /* Key to registry entry */
HKEY hParamKey = NULL; /* To store startup parameters */
DWORD dwData; /* Type of logging supported */
DWORD i, j; /* Loop variables */
int exitStatus = 0;
GetModuleFileName (NULL, szServicePath, MAX_PATH);
TRY
{
/*
* Open Service Control Manager handle
*/
hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCManager == NULL)
{
ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet);
exitStatus = SERVICE_ERROR_SCM_OPEN;
LEAVE;
}
/*
* Generate the command to be executed by the SCM
*/
_sntprintf (szServiceCommand, CountOf(szServiceCommand), _T("%s %s"), szServicePath, _T ("-service"));
/*
* Create the desired service
*/
hService = CreateService (hSCManager, lpszServiceName, lpszServiceDisplayName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szServiceCommand,
NULL, /* load-order group */
NULL, /* group member tag */
NULL, /* dependencies */
NULL, /* account */
NULL); /* password */
if (hService == NULL)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("Can't create service"), lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_SERVICE;
LEAVE;
}
/*
* Create registry entries for the event log
*/
/*
* Create registry Application event log key
*/
_tcscpy (szRegKey, szRegAppLogKey);
_tcscat (szRegKey, lpszServiceName);
/*
* Create registry key
*/
if (RegCreateKey (HKEY_LOCAL_MACHINE, szRegKey, &hKey) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"), lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
}
/*
* Add Event ID message file name to the 'EventMessageFile' subkey
*/
RegSetValueEx (hKey, _T("EventMessageFile"), 0, REG_EXPAND_SZ,
(CONST BYTE *) szServicePath,
_tcslen (szServicePath) + sizeof (TCHAR));
/*
* Set the supported types flags.
*/
dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
RegSetValueEx (hKey, _T("TypesSupported"), 0, REG_DWORD,
(CONST BYTE *) & dwData, sizeof (DWORD));
/*
* Close Registry key
*/
RegCloseKey (hKey);
/*
* Set Service Description String and save startup parameters if present
*/
if (lpszServiceDescription != NULL || StartUpArg->Argc > 2)
{
/*
* Create Registry Key path
*/
_tcscpy (szRegKey, _T ("SYSTEM\\CurrentControlSet\\Services\\"));
_tcscat (szRegKey, app_name_long);
hKey = NULL;
/*
* Open Registry key using Create and Set access.
*/
if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_WRITE,
&hKey) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"),
lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
}
/*
* Create description subkey and the set value
*/
if (lpszServiceDescription != NULL)
{
if (RegSetValueEx (hKey, _T("Description"), 0, REG_SZ,
(CONST BYTE *) lpszServiceDescription,
_tcslen (lpszServiceDescription) +
sizeof (TCHAR)) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"),
lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
};
}
/*
* Save startup arguments if they are present
*/
if (StartUpArg->Argc > 2)
{
/*
* Create Subkey parameters
*/
if (RegCreateKeyEx
(hKey, _T("Parameters"), 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,
&hParamKey, NULL) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"),
lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
}
/*
* Save parameters
*/
/*
* Loop through arguments
*/
if (quiet) /* Make sure we don't store -quiet arg */
i = 3;
else
i = 2;
for (j = 1; i < StartUpArg->Argc; i++, j++)
{
_sntprintf (szRegKey, CountOf(szRegKey), _T("%s%d"), _T ("Param"), j);
/*
* Create registry key
*/
if (RegSetValueEx
(hParamKey, szRegKey, 0, REG_SZ,
(CONST BYTE *) StartUpArg->Argv[i],
_tcslen (StartUpArg->Argv[i]) +
sizeof (TCHAR)) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"),
lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
};
}
}
/*
* Everything is set, delete hKey
*/
RegCloseKey (hParamKey);
RegCloseKey (hKey);
}
/*
* Ready to log messages
*/
/*
* Successfully registered as service
*/
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), lpszServiceName,
_T ("successfully registered as a service"));
/*
* Log message to eventlog
*/
ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet);
}
FINALLY
{
if (hSCManager)
CloseServiceHandle (hSCManager);
if (hService)
CloseServiceHandle (hService);
if (hKey)
RegCloseKey (hKey);
if (hParamKey)
RegCloseKey (hParamKey);
}
return (exitStatus);
}
/*
* Unregister the service with the Windows SCM
* Input - ServiceName
*/
int
UnregisterService (LPCTSTR lpszServiceName, int quiet)
{
TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */
SC_HANDLE hSCManager = NULL; /* SCM handle */
SC_HANDLE hService = NULL; /* Service Handle */
SERVICE_STATUS sStatus;
TCHAR szRegAppLogKey[] =
_T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
TCHAR szRegKey[512];
int exitStatus = 0;
/* HKEY hKey = NULL; ?* Key to registry entry */
TRY
{
/*
* Open Service Control Manager
*/
hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCManager == NULL)
{
ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet);
exitStatus = SERVICE_ERROR_SCM_OPEN;
LEAVE;
}
/*
* Open registered service
*/
hService = OpenService (hSCManager, lpszServiceName, SERVICE_ALL_ACCESS);
if (hService == NULL)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("Can't open service"),
lpszServiceName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_OPEN_SERVICE;
LEAVE;
}
/*
* Query service status
* If running stop before deleting
*/
if (QueryServiceStatus (hService, &sStatus))
{
if (sStatus.dwCurrentState == SERVICE_RUNNING
|| sStatus.dwCurrentState == SERVICE_PAUSED)
{
ControlService (hService, SERVICE_CONTROL_STOP, &sStatus);
}
};
/*
* Delete the service
*/
if (DeleteService (hService) == FALSE)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("Can't delete service"),
lpszServiceName);
/*
* Log message to eventlog
*/
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 0, quiet);
LEAVE;
}
/*
* Log "Service deleted successfully " message to eventlog
*/
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), lpszServiceName, _T ("service deleted"));
ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet);
/*
* Delete registry entries for EventLog
*/
_tcscpy (szRegKey, szRegAppLogKey);
_tcscat (szRegKey, lpszServiceName);
RegDeleteKey (HKEY_LOCAL_MACHINE, szRegKey);
}
/*
* Delete the handles
*/
FINALLY
{
if (hService)
CloseServiceHandle (hService);
if (hSCManager)
CloseServiceHandle (hSCManager);
}
return (exitStatus);
}
/*
* Write a message to the Windows event log.
*/
VOID
WriteToEventLog (WORD wType, LPCTSTR pszFormat, ...)
{
TCHAR szMessage[512];
LPCTSTR LogStr[1];
va_list ArgList;
HANDLE hEventSource = NULL;
va_start (ArgList, pszFormat);
_vsntprintf (szMessage, CountOf(szMessage), pszFormat, ArgList);
va_end (ArgList);
LogStr[0] = szMessage;
hEventSource = RegisterEventSource (NULL, app_name_long);
if (hEventSource == NULL)
return;
ReportEvent (hEventSource, wType, 0,
DISPLAY_MSG,
NULL, 1, 0, LogStr, NULL);
DeregisterEventSource (hEventSource);
}
/*
* Pre-process the second command-line argument from the user.
* Service related options are:
* -register - registers the service
* -unregister - unregisters the service
* -service - run as service
* other command-line arguments are ignored here.
*
* Return: Type indicating the option specified
*/
INT
ParseCmdLineForServiceOption (int argc, TCHAR * argv[], int *quiet)
{
int nReturn = RUN_AS_CONSOLE; /* default is to run as a console application */
if (argc >= 2)
{
/*
* second argument present
*/
if (lstrcmpi (_T ("-register"), argv[1]) == 0)
{
nReturn = REGISTER_SERVICE;
}
else if (lstrcmpi (_T ("-unregister"), argv[1]) == 0)
{
nReturn = UN_REGISTER_SERVICE;
}
else if (lstrcmpi (_T ("-service"), argv[1]) == 0)
{
nReturn = RUN_AS_SERVICE;
}
}
if (argc >= 3)
{
/*
* third argument present
*/
if (lstrcmpi (_T ("-quiet"), argv[2]) == 0)
{
*quiet = 1;
}
}
return nReturn;
}
/*
* Write error message to event log, console or pop-up window.
*
* If useGetLastError is 1, the last error returned from GetLastError()
* is appended to pszMessage, separated by a ": ".
*
* eventLogType: MessageBox equivalent:
*
* EVENTLOG_INFORMATION_TYPE MB_ICONASTERISK
* EVENTLOG_WARNING_TYPE MB_ICONEXCLAMATION
* EVENTLOG_ERROR_TYPE MB_ICONSTOP
*
*/
VOID
ProcessError (WORD eventLogType, LPCTSTR pszMessage, int useGetLastError, int quiet)
{
HANDLE hEventSource = NULL;
TCHAR pszMessageFull[MAX_STR_SIZE]; /* Combined pszMessage and GetLastError */
/*
* If useGetLastError enabled, generate text from GetLastError() and append to
* pszMessageFull
*/
if (useGetLastError) {
LPTSTR pErrorMsgTemp = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) & pErrorMsgTemp, 0, NULL);
_sntprintf (pszMessageFull, CountOf(pszMessageFull), _T("%s: %s"), pszMessage, pErrorMsgTemp);
if (pErrorMsgTemp) {
LocalFree (pErrorMsgTemp);
pErrorMsgTemp = NULL;
}
}
else {
_sntprintf (pszMessageFull, CountOf(pszMessageFull), _T("%s"), pszMessage);
}
hEventSource = RegisterEventSource (NULL, app_name_long);
if (hEventSource != NULL) {
LPCTSTR LogStr[1];
LogStr[0] = pszMessageFull;
if (ReportEvent (hEventSource,
eventLogType,
0,
DISPLAY_MSG, /* just output the text to the event log */
NULL,
1,
0,
LogStr,
NULL)) {
}
else {
LPTSTR pErrorMsgTemp = NULL;
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) & pErrorMsgTemp, 0, NULL);
_ftprintf(stderr,_T("Could NOT lot to Event Log. Error returned from ReportEvent(): %s\n"),pErrorMsgTemp);
if (pErrorMsgTemp) {
LocalFree (pErrorMsgTemp);
pErrorMsgTemp = NULL;
}
}
DeregisterEventSource (hEventSource);
}
if (quiet) {
_ftprintf(stderr,_T("%s\n"),pszMessageFull);
}
else {
switch (eventLogType) {
case EVENTLOG_INFORMATION_TYPE:
MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONASTERISK);
break;
case EVENTLOG_WARNING_TYPE:
MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONEXCLAMATION);
break;
case EVENTLOG_ERROR_TYPE:
MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONSTOP);
break;
default:
MessageBox (NULL, pszMessageFull, app_name_long, EVENTLOG_WARNING_TYPE);
break;
}
}
}
/*
* Update current service status.
* Sends the current service status to the SCM. Also updates
* the global service status structure.
*/
static BOOL
UpdateServiceStatus (DWORD dwStatus, DWORD dwErrorCode, DWORD dwWaitHint)
{
DWORD static dwCheckpoint = 1;
DWORD dwControls = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
if (g_fRunningAsService == FALSE)
return FALSE;
ZeroMemory (&ServiceStatus, sizeof (ServiceStatus));
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = dwStatus;
ServiceStatus.dwWaitHint = dwWaitHint;
if (dwErrorCode)
{
ServiceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
ServiceStatus.dwServiceSpecificExitCode = dwErrorCode;
}
/*
* special cases that depend on the new state
*/
switch (dwStatus)
{
case SERVICE_START_PENDING:
dwControls = 0;
break;
case SERVICE_RUNNING:
case SERVICE_STOPPED:
dwCheckpoint = 0;
break;
}
ServiceStatus.dwCheckPoint = dwCheckpoint++;
ServiceStatus.dwControlsAccepted = dwControls;
return ReportCurrentServiceStatus ();
}
/*
* Reports current service status to SCM
*/
static BOOL
ReportCurrentServiceStatus ()
{
return SetServiceStatus (hServiceStatus, &ServiceStatus);
}
/*
* ServiceMain function.
*/
VOID WINAPI
ServiceMain (DWORD argc, LPTSTR argv[])
{
SECURITY_ATTRIBUTES SecurityAttributes;
unsigned threadId;
/*
* Input arguments
*/
DWORD ArgCount = 0;
LPTSTR *ArgArray = NULL;
TCHAR szRegKey[512];
HKEY hParamKey = NULL;
DWORD TotalParams = 0;
DWORD i;
InputParams ThreadInputParams;
/*
* Build the Input parameters to pass to worker thread
*/
/*
* SCM sends Service Name as first arg, increment to point
* arguments user specified while starting control agent
*/
/*
* Read registry parameter
*/
ArgCount = 1;
/*
* Create registry key path
*/
_sntprintf (szRegKey, CountOf(szRegKey), _T("%s%s\\%s"),
_T ("SYSTEM\\CurrentControlSet\\Services\\"), app_name_long,
_T("Parameters"));
if (RegOpenKeyEx
(HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_ALL_ACCESS, &hParamKey) == ERROR_SUCCESS)
{
/*
* Read startup configuration information
*/
/*
* Find number of subkeys inside parameters
*/
if (RegQueryInfoKey (hParamKey, NULL, NULL, 0,
NULL, NULL, NULL, &TotalParams,
NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
{
if (TotalParams != 0)
{
ArgCount += TotalParams;
/*
* Allocate memory to hold strings
*/
ArgArray = calloc(ArgCount, sizeof(ArgArray[0]));
if (ArgArray == 0)
{
WriteToEventLog (EVENTLOG_ERROR_TYPE,
_T ("Resource failure"));
return;
}
/*
* Copy first argument
*/
ArgArray[0] = _tcsdup (argv[0]);
for (i = 1; i <= TotalParams; i++)
{
DWORD dwErrorcode;
DWORD nSize;
DWORD nRegkeyType;
TCHAR *szValue;
/*
* Create Subkey value name
*/
_sntprintf (szRegKey, CountOf(szRegKey), _T("%s%d"), _T("Param"), i);
/*
* Query subkey.
*/
nSize = 0;
dwErrorcode = RegQueryValueEx(hParamKey, szRegKey, NULL,
&nRegkeyType, NULL, &nSize);
if (dwErrorcode == ERROR_SUCCESS) {
if (nRegkeyType == REG_SZ || nRegkeyType == REG_EXPAND_SZ) {
szValue = malloc(nSize + sizeof(szValue[0]));
if (szValue) {
dwErrorcode = RegQueryValueEx(hParamKey, szRegKey, NULL,
&nRegkeyType, (LPBYTE)szValue, &nSize);
if (dwErrorcode == ERROR_SUCCESS) {
szValue[nSize] = 0;
ArgArray[i] = szValue;
} else {
free(szValue);
WriteToEventLog(EVENTLOG_ERROR_TYPE, _T("Querying registry key %s failed: error code %ld"), szRegKey, dwErrorcode);
}
} else
WriteToEventLog(EVENTLOG_ERROR_TYPE, _T("Querying registry key %s failed: out of memory"), szRegKey);
} else
WriteToEventLog(EVENTLOG_ERROR_TYPE, _T("Type %ld of registry key %s is incorrect"), nRegkeyType, szRegKey);
} else
WriteToEventLog(EVENTLOG_ERROR_TYPE, _T("Querying registry key %s failed: error code %ld"), szRegKey, dwErrorcode);
if (!ArgArray[i]) {
TotalParams = ArgCount = i;
break;
}
}
}
}
RegCloseKey (hParamKey);
}
if (ArgCount == 1)
{
/*
* No startup args are given
*/
ThreadInputParams.Argc = argc;
ThreadInputParams.Argv = argv;
}
else
{
ThreadInputParams.Argc = ArgCount;
ThreadInputParams.Argv = ArgArray;
}
/*
* Register Service Control Handler
*/
hServiceStatus = RegisterServiceCtrlHandler (app_name_long, ControlHandler);
if (hServiceStatus == 0)
{
WriteToEventLog (EVENTLOG_ERROR_TYPE,
_T ("RegisterServiceCtrlHandler failed"));
return;
}
/*
* Update the service status to START_PENDING.
*/
UpdateServiceStatus (SERVICE_START_PENDING, NO_ERROR, SCM_WAIT_INTERVAL);
/*
* Start the worker thread, which does the majority of the work .
*/
TRY
{
if (SetSimpleSecurityAttributes (&SecurityAttributes) == FALSE)
{
WriteToEventLog (EVENTLOG_ERROR_TYPE,
_T ("Couldn't init security attributes"));
LEAVE;
}
hServiceThread =
(void *) _beginthreadex (&SecurityAttributes, 0,
ThreadFunction,
(void *) &ThreadInputParams, 0, &threadId);
if (hServiceThread == NULL)
{
WriteToEventLog (EVENTLOG_ERROR_TYPE, _T ("Couldn't start worker thread"));
LEAVE;
}
/*
* Set service status to SERVICE_RUNNING.
*/
UpdateServiceStatus (SERVICE_RUNNING, NO_ERROR, SCM_WAIT_INTERVAL);
/*
* Wait until the worker thread finishes.
*/
WaitForSingleObject (hServiceThread, INFINITE);
}
FINALLY
{
/*
* Release resources
*/
UpdateServiceStatus (SERVICE_STOPPED, NO_ERROR, SCM_WAIT_INTERVAL);
if (hServiceThread)
CloseHandle (hServiceThread);
FreeSecurityAttributes (&SecurityAttributes);
/*
* Free allocated argument list
*/
if (ArgCount > 1 && ArgArray != NULL)
{
/*
* Free all strings
*/
for (i = 0; i < ArgCount; i++)
{
free (ArgArray[i]);
}
free (ArgArray);
}
}
}
/*
* Function to start as Windows service
* The calling party should specify their entry point as input parameter
* Returns TRUE if the Service is started successfully
*/
BOOL
RunAsService (INT (*ServiceFunction) (INT, LPTSTR *))
{
/*
* Set the ServiceEntryPoint
*/
ServiceEntryPoint = ServiceFunction;
/*
* By default, mark as Running as a service
*/
g_fRunningAsService = TRUE;
/*
* Initialize ServiceTableEntry table
*/
ServiceTableEntry[0].lpServiceName = app_name_long; /* Application Name */
/*
* Call SCM via StartServiceCtrlDispatcher to run as Service
* * If the function returns TRUE we are running as Service,
*/
if (StartServiceCtrlDispatcher (ServiceTableEntry) == FALSE)
{
g_fRunningAsService = FALSE;
/*
* Some other error has occurred.
*/
WriteToEventLog (EVENTLOG_ERROR_TYPE,
_T ("Couldn't start service - %s"), app_name_long);
}
return g_fRunningAsService;
}
/*
* Service control handler function
* Responds to SCM commands/requests
* This service handles 4 commands
* - interrogate, pause, continue and stop.
*/
VOID WINAPI
ControlHandler (DWORD dwControl)
{
switch (dwControl)
{
case SERVICE_CONTROL_INTERROGATE:
ProcessServiceInterrogate ();
break;
case SERVICE_CONTROL_PAUSE:
ProcessServicePause ();
break;
case SERVICE_CONTROL_CONTINUE:
ProcessServiceContinue ();
break;
case SERVICE_CONTROL_STOP:
ProcessServiceStop ();
break;
}
}
/*
* To stop the service.
* If a stop function was registered, invoke it,
* otherwise terminate the worker thread.
* After stopping, Service status is set to STOP in
* main loop
*/
VOID
ProcessServiceStop (VOID)
{
UpdateServiceStatus (SERVICE_STOP_PENDING, NO_ERROR, SCM_WAIT_INTERVAL);
if (StopFunction != NULL)
{
(*StopFunction) ();
}
else
{
TerminateThread (hServiceThread, 0);
}
}
/*
* Returns the current state of the service to the SCM.
*/
VOID
ProcessServiceInterrogate (VOID)
{
ReportCurrentServiceStatus ();
}
/*
* To Create a security descriptor with a NULL ACL, which
* allows unlimited access. Returns a SECURITY_ATTRIBUTES
* structure that contains the security descriptor.
* The structure contains a dynamically allocated security
* descriptor that must be freed either manually, or by
* calling FreeSecurityAttributes
*/
BOOL
SetSimpleSecurityAttributes (SECURITY_ATTRIBUTES * pSecurityAttr)
{
BOOL fReturn = FALSE;
SECURITY_DESCRIPTOR *pSecurityDesc = NULL;
/*
* If an invalid address is passed as a parameter, return
* FALSE right away.
*/
if (!pSecurityAttr)
return FALSE;
pSecurityDesc =
(SECURITY_DESCRIPTOR *) LocalAlloc (LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!pSecurityDesc)
return FALSE;
fReturn =
InitializeSecurityDescriptor (pSecurityDesc, SECURITY_DESCRIPTOR_REVISION);
if (fReturn != FALSE)
{
fReturn = SetSecurityDescriptorDacl (pSecurityDesc, TRUE, NULL, FALSE);
}
if (fReturn != FALSE)
{
pSecurityAttr->nLength = sizeof (SECURITY_ATTRIBUTES);
pSecurityAttr->lpSecurityDescriptor = pSecurityDesc;
pSecurityAttr->bInheritHandle = TRUE;
}
else
{
/*
* Couldn't initialize or set security descriptor.
*/
LocalFree (pSecurityDesc);
}
return fReturn;
}
/*
* This function Frees the security descriptor, if any was created.
*/
VOID
FreeSecurityAttributes (SECURITY_ATTRIBUTES * pSecurityAttr)
{
if (pSecurityAttr && pSecurityAttr->lpSecurityDescriptor)
LocalFree (pSecurityAttr->lpSecurityDescriptor);
}
/*
* This function runs in the worker thread
* until an exit is forced, or until the SCM issues the STOP command.
* Invokes registered service function
* Returns when called registered function returns
*
* Input:
* lpParam contains argc and argv, pass to service main function
*/
unsigned WINAPI
ThreadFunction (LPVOID lpParam)
{
InputParams * pInputArg = (InputParams *) lpParam;
return (*ServiceEntryPoint) (pInputArg->Argc, pInputArg->Argv);
}
/*
* This function is called to register an application-specific function
* which is invoked when the SCM stops the worker thread.
*/
VOID
RegisterStopFunction (VOID (*StopFunc) (VOID))
{
StopFunction = StopFunc;
}
/*
* SCM pause command invokes this function
* If the service is not running, this function does nothing.
* Otherwise, suspend the worker thread and update the status.
*/
VOID
ProcessServicePause (VOID)
{
if (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
UpdateServiceStatus (SERVICE_PAUSE_PENDING, NO_ERROR, SCM_WAIT_INTERVAL);
if (SuspendThread (hServiceThread) != -1)
{
UpdateServiceStatus (SERVICE_PAUSED, NO_ERROR, SCM_WAIT_INTERVAL);
}
}
}
/*
* SCM resume command invokes this function
* If the service is not paused, this function does nothing.
* Otherwise, resume the worker thread and update the status.
*/
VOID
ProcessServiceContinue (VOID)
{
if (ServiceStatus.dwCurrentState == SERVICE_PAUSED)
{
UpdateServiceStatus (SERVICE_CONTINUE_PENDING, NO_ERROR, SCM_WAIT_INTERVAL);
if (ResumeThread (hServiceThread) != -1)
{
UpdateServiceStatus (SERVICE_RUNNING, NO_ERROR, SCM_WAIT_INTERVAL);
}
}
}
#endif /* WIN32 */
|
the_stack_data/33136.c | #include <stdio.h>
int main(void)
{
printf(" *\f\b\b* *\f\b\b\b* *\f\b\b\b\b\b\b*******\n");
printf("********************\n");
printf("********************\n");
printf("********************\n");
printf("********************\n");
printf("BBBBBBBBB\f");
printf("DD\r");
printf("AAA\f");
printf("CC***\n");
printf(" *\f");
printf("\r * *\f");
printf("\r * *\f");
printf("\r*******\n");
printf("********************\n");
return 0;
} |
the_stack_data/14670.c | /* Program to work with system calls related to directories */
/* to execute o/p => ./a.out filePath */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]){
if (2 != argc){
printf("\n Please pass in the directory name \n");
return 1;
}
DIR *dp = NULL;
struct dirent *dptr = NULL;
// Buffer for storing the directory path
char buff[128];
memset(buff, 0, sizeof(buff));
//copy the path set by the user
strcpy(buff, argv[1]);
// Open the directory stream
if (NULL == (dp = opendir(argv[1]))){
printf("\n Cannot open Input directory [%s]\n", argv[1]);
exit(1);
}
else{
// Check if user supplied '/' at the end of directory name.
// Based on it create a buffer containing path to new directory name 'newDir'
if (buff[strlen(buff) - 1] == '/'){
strncpy(buff + strlen(buff), "newDir/", 7);
}
else{
strncpy(buff + strlen(buff), "/newDir/", 8);
}
printf("\n Creating a new directory [%s]\n", buff);
// create a new directory
mkdir(buff, S_IRWXU | S_IRWXG | S_IRWXO);
printf("\n The contents of directory [%s] are as follows \n", argv[1]);
// Read the directory contents
while (NULL != (dptr = readdir(dp))){
printf(" [%s] ", dptr->d_name);
}
// Close the directory stream
closedir(dp);
// Remove the new directory created by us
rmdir(buff);
printf("\n");
}
return 0;
}
|
the_stack_data/808095.c |
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
//使用select实现精确到1微秒(0.000001秒)的sleep
void sleep_us(unsigned int nusecs)
{
struct timeval tval;
tval.tv_sec = nusecs / 1000000;
tval.tv_usec = nusecs % 1000000;
select(0, NULL, NULL, NULL, &tval);
}
int Add(int a, int b) {
while(1) {
sleep_us(1000000);
}
return a + b;
} |
the_stack_data/45449776.c | /*numPass=7, numTotal=7
Verdict:ACCEPTED, Visibility:1, Input:"0 0 4
1 1 3", ExpOutput:"YES
", Output:"YES"
Verdict:ACCEPTED, Visibility:1, Input:"0 0 4
10 10 3", ExpOutput:"NO
", Output:"NO"
Verdict:ACCEPTED, Visibility:1, Input:"-1 -1 5
6 6 5", ExpOutput:"YES
", Output:"YES"
Verdict:ACCEPTED, Visibility:0, Input:"-1 -1 1
5 -1 1", ExpOutput:"NO
", Output:"NO"
Verdict:ACCEPTED, Visibility:0, Input:"2 2 2
2 2 1", ExpOutput:"YES
", Output:"YES"
Verdict:ACCEPTED, Visibility:0, Input:"3 0 3
-4 0 3", ExpOutput:"NO
", Output:"NO"
Verdict:ACCEPTED, Visibility:0, Input:"1 0 1
3 0 3", ExpOutput:"YES
", Output:"YES"
*/
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct circle{
int x;
int y;
int r;
}c1,c2;
int main(){
int d;
scanf("%d %d %d\n",&c1.x,&c1.y,&c1.r);
scanf("%d %d %d",&c2.x,&c2.y,&c2.r);
d=sqrt(pow(c1.x-c2.x,2)+pow(c1.y-c2.y,2));
if(d<=abs(c1.r+c2.r))
printf("YES");
else
printf("NO");
return 0;
} |
the_stack_data/1203567.c | struct Point {
int x;
int y;
};
int main(void) {
struct Point p = {
.y = 2,
.x = 1,
};
return !(p.x == 1 && p.y == 2);
}
|
the_stack_data/200142446.c | // Function with VLA parameter using var ref in array dimension
// (allowed, but normalized to "int array[*]").
void foobar2 ( int size, int array[size] );
void foobar2 ( int size, int array[size] )
{
}
|
the_stack_data/1064073.c | /* Generate assembler source containing symbol information
*
* Copyright 2002 by Kai Germaschewski
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* Usage: nm -n vmlinux | scripts/symbols [--all-symbols] > symbols.S
*
* ChangeLog:
*
* (25/Aug/2004) Paulo Marques <[email protected]>
* Changed the compression method from stem compression to "table lookup"
* compression
*
* Table compression uses all the unused char codes on the symbols and
* maps these to the most used substrings (tokens). For instance, it might
* map char code 0xF7 to represent "write_" and then in every symbol where
* "write_" appears it can be replaced by 0xF7, saving 5 bytes.
* The used codes themselves are also placed in the table so that the
* decompresion can work without "special cases".
* Applied to kernel symbols, this usually produces a compression ratio
* of about 50%.
*
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#define KSYM_NAME_LEN 127
struct sym_entry {
unsigned long long addr;
unsigned int len;
unsigned char *sym;
};
static struct sym_entry *table;
static unsigned int table_size, table_cnt;
static unsigned long long _stext, _etext, _sinittext, _einittext, _sextratext, _eextratext;
static int all_symbols = 0;
static char symbol_prefix_char = '\0';
int token_profit[0x10000];
/* the table that holds the result of the compression */
unsigned char best_table[256][2];
unsigned char best_table_len[256];
static void usage(void)
{
fprintf(stderr, "Usage: symbols [--all-symbols] [--symbol-prefix=<prefix char>] < in.map > out.S\n");
exit(1);
}
/*
* This ignores the intensely annoying "mapping symbols" found
* in ARM ELF files: $a, $t and $d.
*/
static inline int is_arm_mapping_symbol(const char *str)
{
return str[0] == '$' && strchr("atd", str[1])
&& (str[2] == '\0' || str[2] == '.');
}
static int read_symbol(FILE *in, struct sym_entry *s)
{
char str[500];
char *sym, stype;
int rc;
rc = fscanf(in, "%llx %c %499s\n", &s->addr, &stype, str);
if (rc != 3) {
if (rc != EOF) {
/* skip line */
if (fgets(str, 500, in) == NULL)
return -1; /* must check fgets result */
}
return -1;
}
sym = str;
/* skip prefix char */
if (symbol_prefix_char && str[0] == symbol_prefix_char)
sym++;
/* Ignore most absolute/undefined (?) symbols. */
if (strcmp(sym, "_stext") == 0)
_stext = s->addr;
else if (strcmp(sym, "_etext") == 0)
_etext = s->addr;
else if (strcmp(sym, "_sinittext") == 0)
_sinittext = s->addr;
else if (strcmp(sym, "_einittext") == 0)
_einittext = s->addr;
else if (strcmp(sym, "_sextratext") == 0)
_sextratext = s->addr;
else if (strcmp(sym, "_eextratext") == 0)
_eextratext = s->addr;
else if (toupper((uint8_t)stype) == 'A')
{
/* Keep these useful absolute symbols */
if (strcmp(sym, "__gp"))
return -1;
}
else if (toupper((uint8_t)stype) == 'U' ||
is_arm_mapping_symbol(sym))
return -1;
/* exclude also MIPS ELF local symbols ($L123 instead of .L123) */
else if (str[0] == '$')
return -1;
/* include the type field in the symbol name, so that it gets
* compressed together */
s->len = strlen(str) + 1;
s->sym = malloc(s->len + 1);
strcpy((char *)s->sym + 1, str);
s->sym[0] = stype;
return 0;
}
static int symbol_valid(struct sym_entry *s)
{
int offset = 1;
/* skip prefix char */
if (symbol_prefix_char && *(s->sym + 1) == symbol_prefix_char)
offset++;
/* if --all-symbols is not specified, then symbols outside the text
* and inittext sections are discarded */
if (!all_symbols) {
if ((s->addr < _stext || s->addr > _etext)
&& (s->addr < _sinittext || s->addr > _einittext)
&& (s->addr < _sextratext || s->addr > _eextratext))
return 0;
/* Corner case. Discard any symbols with the same value as
* _etext _einittext or _eextratext; they can move between pass
* 1 and 2 when the symbols data are added. If these symbols
* move then they may get dropped in pass 2, which breaks the
* symbols rules.
*/
if ((s->addr == _etext && strcmp((char*)s->sym + offset, "_etext")) ||
(s->addr == _einittext && strcmp((char*)s->sym + offset, "_einittext")) ||
(s->addr == _eextratext && strcmp((char*)s->sym + offset, "_eextratext")))
return 0;
}
/* Exclude symbols which vary between passes. */
if (strstr((char *)s->sym + offset, "_compiled."))
return 0;
return 1;
}
static void read_map(FILE *in)
{
while (!feof(in)) {
if (table_cnt >= table_size) {
table_size += 10000;
table = realloc(table, sizeof(*table) * table_size);
if (!table) {
fprintf(stderr, "out of memory\n");
exit (1);
}
}
if (read_symbol(in, &table[table_cnt]) == 0)
table_cnt++;
}
}
static void output_label(char *label)
{
if (symbol_prefix_char)
printf(".globl %c%s\n", symbol_prefix_char, label);
else
printf(".globl %s\n", label);
printf("\tALGN\n");
if (symbol_prefix_char)
printf("%c%s:\n", symbol_prefix_char, label);
else
printf("%s:\n", label);
}
/* uncompress a compressed symbol. When this function is called, the best table
* might still be compressed itself, so the function needs to be recursive */
static int expand_symbol(unsigned char *data, int len, char *result)
{
int c, rlen, total=0;
while (len) {
c = *data;
/* if the table holds a single char that is the same as the one
* we are looking for, then end the search */
if (best_table[c][0]==c && best_table_len[c]==1) {
*result++ = c;
total++;
} else {
/* if not, recurse and expand */
rlen = expand_symbol(best_table[c], best_table_len[c], result);
total += rlen;
result += rlen;
}
data++;
len--;
}
*result=0;
return total;
}
static void write_src(void)
{
unsigned int i, k, off;
unsigned int best_idx[256];
unsigned int *markers;
char buf[KSYM_NAME_LEN+1];
printf("#include <xen/config.h>\n");
printf("#include <asm/types.h>\n");
printf("#if BITS_PER_LONG == 64 && !defined(SYMBOLS_ORIGIN)\n");
printf("#define PTR .quad\n");
printf("#define ALGN .align 8\n");
printf("#else\n");
printf("#define PTR .long\n");
printf("#define ALGN .align 4\n");
printf("#endif\n");
printf("\t.section .rodata, \"a\"\n");
printf("#ifndef SYMBOLS_ORIGIN\n");
printf("#define SYMBOLS_ORIGIN 0\n");
output_label("symbols_addresses");
printf("#else\n");
output_label("symbols_offsets");
printf("#endif\n");
for (i = 0; i < table_cnt; i++) {
printf("\tPTR\t%#llx - SYMBOLS_ORIGIN\n", table[i].addr);
}
printf("\n");
output_label("symbols_num_syms");
printf("\t.long\t%d\n", table_cnt);
printf("\n");
/* table of offset markers, that give the offset in the compressed stream
* every 256 symbols */
markers = (unsigned int *) malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
output_label("symbols_names");
off = 0;
for (i = 0; i < table_cnt; i++) {
if ((i & 0xFF) == 0)
markers[i >> 8] = off;
printf("\t.byte 0x%02x", table[i].len);
for (k = 0; k < table[i].len; k++)
printf(", 0x%02x", table[i].sym[k]);
printf("\n");
off += table[i].len + 1;
}
printf("\n");
output_label("symbols_markers");
for (i = 0; i < ((table_cnt + 255) >> 8); i++)
printf("\t.long\t%d\n", markers[i]);
printf("\n");
free(markers);
output_label("symbols_token_table");
off = 0;
for (i = 0; i < 256; i++) {
best_idx[i] = off;
expand_symbol(best_table[i], best_table_len[i], buf);
printf("\t.asciz\t\"%s\"\n", buf);
off += strlen(buf) + 1;
}
printf("\n");
output_label("symbols_token_index");
for (i = 0; i < 256; i++)
printf("\t.short\t%d\n", best_idx[i]);
printf("\n");
}
/* table lookup compression functions */
/* count all the possible tokens in a symbol */
static void learn_symbol(unsigned char *symbol, int len)
{
int i;
for (i = 0; i < len - 1; i++)
token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
}
/* decrease the count for all the possible tokens in a symbol */
static void forget_symbol(unsigned char *symbol, int len)
{
int i;
for (i = 0; i < len - 1; i++)
token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
}
/* remove all the invalid symbols from the table and do the initial token count */
static void build_initial_tok_table(void)
{
unsigned int i, pos;
pos = 0;
for (i = 0; i < table_cnt; i++) {
if ( symbol_valid(&table[i]) ) {
if (pos != i)
table[pos] = table[i];
learn_symbol(table[pos].sym, table[pos].len);
pos++;
}
}
table_cnt = pos;
}
static void *memmem_pvt(void *h, size_t hlen, void *n, size_t nlen)
{
char *p;
for (p = h; (p - (char *)h) <= (long)(hlen - nlen); p++)
if (!memcmp(p, n, nlen)) return p;
return NULL;
}
/* replace a given token in all the valid symbols. Use the sampled symbols
* to update the counts */
static void compress_symbols(unsigned char *str, int idx)
{
unsigned int i, len, size;
unsigned char *p1, *p2;
for (i = 0; i < table_cnt; i++) {
len = table[i].len;
p1 = table[i].sym;
/* find the token on the symbol */
p2 = memmem_pvt(p1, len, str, 2);
if (!p2) continue;
/* decrease the counts for this symbol's tokens */
forget_symbol(table[i].sym, len);
size = len;
do {
*p2 = idx;
p2++;
size -= (p2 - p1);
memmove(p2, p2 + 1, size);
p1 = p2;
len--;
if (size < 2) break;
/* find the token on the symbol */
p2 = memmem_pvt(p1, size, str, 2);
} while (p2);
table[i].len = len;
/* increase the counts for this symbol's new tokens */
learn_symbol(table[i].sym, len);
}
}
/* search the token with the maximum profit */
static int find_best_token(void)
{
int i, best, bestprofit;
bestprofit=-10000;
best = 0;
for (i = 0; i < 0x10000; i++) {
if (token_profit[i] > bestprofit) {
best = i;
bestprofit = token_profit[i];
}
}
return best;
}
/* this is the core of the algorithm: calculate the "best" table */
static void optimize_result(void)
{
int i, best;
/* using the '\0' symbol last allows compress_symbols to use standard
* fast string functions */
for (i = 255; i >= 0; i--) {
/* if this table slot is empty (it is not used by an actual
* original char code */
if (!best_table_len[i]) {
/* find the token with the breates profit value */
best = find_best_token();
/* place it in the "best" table */
best_table_len[i] = 2;
best_table[i][0] = best & 0xFF;
best_table[i][1] = (best >> 8) & 0xFF;
/* replace this token in all the valid symbols */
compress_symbols(best_table[i], i);
}
}
}
/* start by placing the symbols that are actually used on the table */
static void insert_real_symbols_in_table(void)
{
unsigned int i, j, c;
memset(best_table, 0, sizeof(best_table));
memset(best_table_len, 0, sizeof(best_table_len));
for (i = 0; i < table_cnt; i++) {
for (j = 0; j < table[i].len; j++) {
c = table[i].sym[j];
best_table[c][0]=c;
best_table_len[c]=1;
}
}
}
static void optimize_token_table(void)
{
build_initial_tok_table();
insert_real_symbols_in_table();
/* When valid symbol is not registered, exit to error */
if (!table_cnt) {
fprintf(stderr, "No valid symbol.\n");
exit(1);
}
optimize_result();
}
int main(int argc, char **argv)
{
if (argc >= 2) {
int i;
for (i = 1; i < argc; i++) {
if(strcmp(argv[i], "--all-symbols") == 0)
all_symbols = 1;
else if (strncmp(argv[i], "--symbol-prefix=", 16) == 0) {
char *p = &argv[i][16];
/* skip quote */
if ((*p == '"' && *(p+2) == '"') || (*p == '\'' && *(p+2) == '\''))
p++;
symbol_prefix_char = *p;
} else
usage();
}
} else if (argc != 1)
usage();
read_map(stdin);
optimize_token_table();
write_src();
return 0;
}
|
the_stack_data/1043735.c | /*
* dropcaches.c
*
* COPYRIGHT (C) 2012 AND ALL RIGHTS RESERVED BY
* MARC WEIDLER, ULRICHSTR. 12/1, 71672 MARBACH, GERMANY ([email protected]).
*
* ALL RIGHTS RESERVED. THIS SOFTWARE AND RELATED DOCUMENTATION ARE PROTECTED BY
* COPYRIGHT RESTRICTING ITS USE, COPYING, DISTRIBUTION, AND DECOMPILATION. NO PART
* OF THIS PRODUCT OR RELATED DOCUMENTATION MAY BE REPRODUCED IN ANY FORM BY ANY
* MEANS WITHOUT PRIOR WRITTEN AUTHORIZATION OF MARC WEIDLER OR HIS PARTNERS, IF ANY.
* UNLESS OTHERWISE ARRANGED, THIRD PARTIES MAY NOT HAVE ACCESS TO THIS PRODUCT OR
* RELATED DOCUMENTATION. SEE LICENSE FILE FOR DETAILS.
*
* 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. THE ENTIRE RISK AS TO THE QUALITY AND
* PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
* YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define RC_OK 0
#define RC_ERROR 1
#define TARGET "/proc/sys/vm/drop_caches"
int main (int argc, char *argv[])
{
int fd, ret;
int rc= RC_OK;
(void)argc;
(void)argv;
sync();
fd= open(TARGET, O_WRONLY);
if (fd >= 0)
{
ret= write(fd, "3", 1);
if (ret <= 0)
{
perror("Write to "TARGET);
rc= RC_ERROR;
}
close(fd);
}
else
{
perror("Opening "TARGET);
rc= RC_ERROR;
}
return rc;
}
|
the_stack_data/135719.c | struct s {
int a;
int b;
int c;
};
int test_struct(void)
{
struct s s = { .a = 1, .c = 3, };
return s.b;
}
/*
* check-name: default-init-struct
* check-command: test-linearize -Wno-decl -fdump-ir $file
*
* check-output-ignore
* check-output-contains: phisrc\\..*return.*\\$0
* check-output-excludes: load\\.
*/
|
the_stack_data/75139121.c | // SPDX-License-Identifier: GPL-2.0
/*
* video_device_test - Video Device Test
*
* Copyright (c) 2016 Shuah Khan <[email protected]>
* Copyright (c) 2016 Samsung Electronics Co., Ltd.
*
*/
/*
* This file adds a test for Video Device. This test should not be included
* in the Kselftest run. This test should be run when hardware and driver
* that makes use of V4L2 API is present.
*
* This test opens user specified Video Device and calls video ioctls in a
* loop once every 10 seconds.
*
* Usage:
* sudo ./video_device_test -d /dev/videoX
*
* While test is running, remove the device or unbind the driver and
* ensure there are no use after free errors and other Oops in the
* dmesg.
* When possible, enable KaSan kernel config option for use-after-free
* error detection.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <time.h>
#include <linux/videodev2.h>
int main(int argc, char **argv)
{
int opt;
char video_dev[256];
int count;
struct v4l2_tuner vtuner;
struct v4l2_capability vcap;
int ret;
int fd;
if (argc < 2) {
printf("Usage: %s [-d </dev/videoX>]\n", argv[0]);
exit(-1);
}
/* Process arguments */
while ((opt = getopt(argc, argv, "d:")) != -1) {
switch (opt) {
case 'd':
strncpy(video_dev, optarg, sizeof(video_dev) - 1);
video_dev[sizeof(video_dev)-1] = '\0';
break;
default:
printf("Usage: %s [-d </dev/videoX>]\n", argv[0]);
exit(-1);
}
}
/* Generate random number of interations */
srand((unsigned int) time(NULL));
count = rand();
/* Open Video device and keep it open */
fd = open(video_dev, O_RDWR);
if (fd == -1) {
printf("Video Device open errno %s\n", strerror(errno));
exit(-1);
}
printf("\nNote:\n"
"While test is running, remove the device or unbind\n"
"driver and ensure there are no use after free errors\n"
"and other Oops in the dmesg. When possible, enable KaSan\n"
"kernel config option for use-after-free error detection.\n\n");
while (count > 0) {
ret = ioctl(fd, VIDIOC_QUERYCAP, &vcap);
if (ret < 0)
printf("VIDIOC_QUERYCAP errno %s\n", strerror(errno));
else
printf("Video device driver %s\n", vcap.driver);
ret = ioctl(fd, VIDIOC_G_TUNER, &vtuner);
if (ret < 0)
printf("VIDIOC_G_TUNER, errno %s\n", strerror(errno));
else
printf("type %d rangelow %d rangehigh %d\n",
vtuner.type, vtuner.rangelow, vtuner.rangehigh);
sleep(10);
count--;
}
}
|
the_stack_data/134491.c | /*----------------------------------------------------------------------------
* Copyright (c) <2016-2018>, <Huawei Technologies Co., Ltd>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Notice of Export Control Law
* ===============================================
* Huawei LiteOS may be subject to applicable export control laws and regulations, which might
* include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
* Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
* applicable export control laws and regulations.
*---------------------------------------------------------------------------*/
#ifdef LWM2M_BOOTSTRAP
#ifdef LWM2M_CLIENT_MODE
#include "util_timer.h"
#include "liblwm2m.h"
void timer_init(util_timer_t *timer, time_t interval, void(*callback)(void *param), void *param)
{
timer->expireTime = lwm2m_gettime() + interval;
timer->interval = interval;
timer->startFlag = false;
timer->callback = callback;
timer->param = param;
}
void timer_start(util_timer_t *timer)
{
timer->startFlag = true;
}
void timer_stop(util_timer_t *timer)
{
timer->startFlag = false;
}
void timer_step(util_timer_t *timer)
{
time_t current;
if (!timer->startFlag)
{
return;
}
current = lwm2m_gettime();
if (current < timer->expireTime)
{
return;
}
if (timer->callback)
{
timer->callback(timer->param);
}
timer->expireTime = current + timer->interval;
}
#endif // LWM2M_CLIENT_MODE
#endif // LWM2M_BOOTSTRAP
|
the_stack_data/93962.c | #include <alloca.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static char const dump_lookup_table[256u*2u] = {
'0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7',
'0', '8', '0', '9', '0', 'A', '0', 'B', '0', 'C', '0', 'D', '0', 'E', '0', 'F',
'1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7',
'1', '8', '1', '9', '1', 'A', '1', 'B', '1', 'C', '1', 'D', '1', 'E', '1', 'F',
'2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7',
'2', '8', '2', '9', '2', 'A', '2', 'B', '2', 'C', '2', 'D', '2', 'E', '2', 'F',
'3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7',
'3', '8', '3', '9', '3', 'A', '3', 'B', '3', 'C', '3', 'D', '3', 'E', '3', 'F',
'4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7',
'4', '8', '4', '9', '4', 'A', '4', 'B', '4', 'C', '4', 'D', '4', 'E', '4', 'F',
'5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7',
'5', '8', '5', '9', '5', 'A', '5', 'B', '5', 'C', '5', 'D', '5', 'E', '5', 'F',
'6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7',
'6', '8', '6', '9', '6', 'A', '6', 'B', '6', 'C', '6', 'D', '6', 'E', '6', 'F',
'7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7',
'7', '8', '7', '9', '7', 'A', '7', 'B', '7', 'C', '7', 'D', '7', 'E', '7', 'F',
'8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7',
'8', '8', '8', '9', '8', 'A', '8', 'B', '8', 'C', '8', 'D', '8', 'E', '8', 'F',
'9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7',
'9', '8', '9', '9', '9', 'A', '9', 'B', '9', 'C', '9', 'D', '9', 'E', '9', 'F',
'A', '0', 'A', '1', 'A', '2', 'A', '3', 'A', '4', 'A', '5', 'A', '6', 'A', '7',
'A', '8', 'A', '9', 'A', 'A', 'A', 'B', 'A', 'C', 'A', 'D', 'A', 'E', 'A', 'F',
'B', '0', 'B', '1', 'B', '2', 'B', '3', 'B', '4', 'B', '5', 'B', '6', 'B', '7',
'B', '8', 'B', '9', 'B', 'A', 'B', 'B', 'B', 'C', 'B', 'D', 'B', 'E', 'B', 'F',
'C', '0', 'C', '1', 'C', '2', 'C', '3', 'C', '4', 'C', '5', 'C', '6', 'C', '7',
'C', '8', 'C', '9', 'C', 'A', 'C', 'B', 'C', 'C', 'C', 'D', 'C', 'E', 'C', 'F',
'D', '0', 'D', '1', 'D', '2', 'D', '3', 'D', '4', 'D', '5', 'D', '6', 'D', '7',
'D', '8', 'D', '9', 'D', 'A', 'D', 'B', 'D', 'C', 'D', 'D', 'D', 'E', 'D', 'F',
'E', '0', 'E', '1', 'E', '2', 'E', '3', 'E', '4', 'E', '5', 'E', '6', 'E', '7',
'E', '8', 'E', '9', 'E', 'A', 'E', 'B', 'E', 'C', 'E', 'D', 'E', 'E', 'E', 'F',
'F', '0', 'F', '1', 'F', '2', 'F', '3', 'F', '4', 'F', '5', 'F', '6', 'F', '7',
'F', '8', 'F', '9', 'F', 'A', 'F', 'B', 'F', 'C', 'F', 'D', 'F', 'E', 'F', 'F',
};
void
dump(void const* pobj, size_t size)
{
if (size == 0) {
fputc('\n', stderr);
return;
}
// .setup
// Allocate a buffer large enough to hold size number of three-byte
// triples. For each three-byte triple, x, bytes x[0:1] will contain the
// two-byte hex representation of a single byte of obj, and byte x[2] will
// contain a whitespace separator (either ' ' or '\n').
char* const buf = alloca(size * 3u); // Locally allocated buffer.
char* ptr = buf; // Write pointer into the locally allocated buffer.
// .loop
uint8_t const* cur = pobj;
uint8_t const* const end = (uint8_t const*)pobj + size;
while (cur != end) {
char const* const repr = dump_lookup_table + (*cur * 2u);
ptr[0u] = repr[0u];
ptr[1u] = repr[1u];
ptr[2u] = ' ';
ptr += 3u;
cur += 1u;
}
// .write
ptr[-1] = '\n';
fprintf(stderr, "%.*s", (int)(size * 3u), buf);
}
int
main()
{
dump((uint8_t[]){0xAA}, sizeof(uint8_t));
dump((uint16_t[]){0xABCD}, sizeof(uint8_t));
dump((uint16_t[]){0xABCD}, sizeof(uint16_t));
dump((uint32_t[]){0x76543210u}, sizeof(uint32_t));
dump((uint32_t[]){0xDEADBEEFu}, sizeof(uint32_t));
dump((uint64_t[]){0xBADCAFE01DC0FFEEu}, sizeof(uint64_t));
dump((uint64_t[]){0xBADCAFE01DC0FFEEu}, 0u);
dump((bool[]){true}, sizeof(bool));
dump((bool[]){false}, sizeof(bool));
dump((char[]){' '}, sizeof(char));
dump((char[]){'x'}, sizeof(char));
return 0;
}
|
the_stack_data/263472.c | #include<stdio.h>
int main(void)
{
int j,n=1,number;
scanf("%d",&number);
for(;n<=number;n++)
{
for(j=1;j<=n;j++)
{
printf("*");
}
printf("\n");
}
for(n=number;n>=1;n--)
{
for(j=1;j<=n;j++)
printf("*");
printf("\n");
}
return 0;
}
|
the_stack_data/182953650.c | #include <stdio.h>
int main()
{
int numbers[5];
int impar = 0;
int positivo = 0;
int negativo = 0;
int i;
for(i=0;i<5;i++)
{
scanf("%d", &numbers[i]);
if(numbers[i] % 2)
impar++;
if(numbers[i] > 0)
positivo++;
else
if(numbers[i]<0)
negativo++;
}
printf("%d valor(es) par(es)\n", 5 - impar);
printf("%d valor(es) impar(es)\n",impar);
printf("%d valor(es) positivo(s)\n", positivo);
printf("%d valor(es) negativo(s)\n", negativo);
return 0;
} |
the_stack_data/11074823.c | /**
******************************************************************************
* @file stm32l4xx_ll_tim.c
* @author MCD Application Team
* @brief TIM LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx_ll_tim.h"
#include "stm32l4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32L4xx_LL_Driver
* @{
*/
#if defined (TIM1) || defined (TIM8) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM15) || defined (TIM16) || defined (TIM17) || defined (TIM6) || defined (TIM7)
/** @addtogroup TIM_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup TIM_LL_Private_Macros
* @{
*/
#define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \
|| ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \
|| ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \
|| ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \
|| ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN))
#define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \
|| ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \
|| ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4))
#define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \
|| ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \
|| ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \
|| ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \
|| ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \
|| ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \
|| ((__VALUE__) == LL_TIM_OCMODE_PWM1) \
|| ((__VALUE__) == LL_TIM_OCMODE_PWM2) \
|| ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM1) \
|| ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM2) \
|| ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM1) \
|| ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM2) \
|| ((__VALUE__) == LL_TIM_OCMODE_ASSYMETRIC_PWM1) \
|| ((__VALUE__) == LL_TIM_OCMODE_ASSYMETRIC_PWM2))
#define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \
|| ((__VALUE__) == LL_TIM_OCSTATE_ENABLE))
#define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \
|| ((__VALUE__) == LL_TIM_OCPOLARITY_LOW))
#define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \
|| ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH))
#define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \
|| ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \
|| ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC))
#define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \
|| ((__VALUE__) == LL_TIM_ICPSC_DIV2) \
|| ((__VALUE__) == LL_TIM_ICPSC_DIV4) \
|| ((__VALUE__) == LL_TIM_ICPSC_DIV8))
#define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \
|| ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8))
#define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \
|| ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING) \
|| ((__VALUE__) == LL_TIM_IC_POLARITY_BOTHEDGE))
#define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \
|| ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \
|| ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12))
#define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \
|| ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING))
#define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \
|| ((__VALUE__) == LL_TIM_OSSR_ENABLE))
#define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \
|| ((__VALUE__) == LL_TIM_OSSI_ENABLE))
#define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \
|| ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \
|| ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \
|| ((__VALUE__) == LL_TIM_LOCKLEVEL_3))
#define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \
|| ((__VALUE__) == LL_TIM_BREAK_ENABLE))
#define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \
|| ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH))
#define IS_LL_TIM_BREAK_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N2) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N4) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N8) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N6) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N8) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N6) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N8) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N6) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N8) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N5) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N6) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N8) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N5) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N6) \
|| ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N8))
#define IS_LL_TIM_BREAK2_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_DISABLE) \
|| ((__VALUE__) == LL_TIM_BREAK2_ENABLE))
#define IS_LL_TIM_BREAK2_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_POLARITY_LOW) \
|| ((__VALUE__) == LL_TIM_BREAK2_POLARITY_HIGH))
#define IS_LL_TIM_BREAK2_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N2) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N4) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N8) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N6) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N8) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N6) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N8) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N6) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N8) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N5) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N6) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N8) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N5) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N6) \
|| ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N8))
#define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \
|| ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup TIM_LL_Private_Functions TIM Private Functions
* @{
*/
static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC5Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus OC6Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct);
static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup TIM_LL_Exported_Functions
* @{
*/
/** @addtogroup TIM_LL_EF_Init
* @{
*/
/**
* @brief Set TIMx registers to their reset values.
* @param TIMx Timer instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: invalid TIMx instance
*/
ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx)
{
ErrorStatus result = SUCCESS;
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(TIMx));
if (TIMx == TIM1)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1);
}
else if (TIMx == TIM2)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2);
}
#if defined(TIM3)
else if (TIMx == TIM3)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3);
}
#endif
#if defined(TIM4)
else if (TIMx == TIM4)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4);
}
#endif
#if defined(TIM5)
else if (TIMx == TIM5)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5);
}
#endif
else if (TIMx == TIM6)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6);
}
#if defined (TIM7)
else if (TIMx == TIM7)
{
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7);
}
#endif
#if defined(TIM8)
else if (TIMx == TIM8)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM8);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM8);
}
#endif
else if (TIMx == TIM15)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15);
}
else if (TIMx == TIM16)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16);
}
#if defined(TIM17)
else if (TIMx == TIM17)
{
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17);
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17);
}
#endif
else
{
result = ERROR;
}
return result;
}
/**
* @brief Set the fields of the time base unit configuration data structure
* to their default values.
* @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure)
* @retval None
*/
void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct)
{
/* Set the default configuration */
TIM_InitStruct->Prescaler = (uint16_t)0x0000;
TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct->Autoreload = 0xFFFFFFFFU;
TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
TIM_InitStruct->RepetitionCounter = (uint8_t)0x00;
}
/**
* @brief Configure the TIMx time base unit.
* @param TIMx Timer Instance
* @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (TIMx time base unit configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct)
{
uint32_t tmpcr1;
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(TIMx));
assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode));
assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision));
tmpcr1 = LL_TIM_ReadReg(TIMx, CR1);
if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx))
{
/* Select the Counter Mode */
MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode);
}
if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx))
{
/* Set the clock division */
MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision);
}
/* Write to TIMx CR1 */
LL_TIM_WriteReg(TIMx, CR1, tmpcr1);
/* Set the Autoreload value */
LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload);
/* Set the Prescaler value */
LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler);
if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx))
{
/* Set the Repetition Counter value */
LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter);
}
/* Generate an update event to reload the Prescaler
and the repetition counter value (if applicable) immediately */
LL_TIM_GenerateEvent_UPDATE(TIMx);
return SUCCESS;
}
/**
* @brief Set the fields of the TIMx output channel configuration data
* structure to their default values.
* @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (the output channel configuration data structure)
* @retval None
*/
void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct)
{
/* Set the default configuration */
TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN;
TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct->CompareValue = 0x00000000U;
TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH;
TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH;
TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW;
TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW;
}
/**
* @brief Configure the TIMx output channel.
* @param TIMx Timer Instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @arg @ref LL_TIM_CHANNEL_CH5
* @arg @ref LL_TIM_CHANNEL_CH6
* @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx output channel is initialized
* - ERROR: TIMx output channel is not initialized
*/
ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct)
{
ErrorStatus result = ERROR;
switch (Channel)
{
case LL_TIM_CHANNEL_CH1:
result = OC1Config(TIMx, TIM_OC_InitStruct);
break;
case LL_TIM_CHANNEL_CH2:
result = OC2Config(TIMx, TIM_OC_InitStruct);
break;
case LL_TIM_CHANNEL_CH3:
result = OC3Config(TIMx, TIM_OC_InitStruct);
break;
case LL_TIM_CHANNEL_CH4:
result = OC4Config(TIMx, TIM_OC_InitStruct);
break;
case LL_TIM_CHANNEL_CH5:
result = OC5Config(TIMx, TIM_OC_InitStruct);
break;
case LL_TIM_CHANNEL_CH6:
result = OC6Config(TIMx, TIM_OC_InitStruct);
break;
default:
break;
}
return result;
}
/**
* @brief Set the fields of the TIMx input channel configuration data
* structure to their default values.
* @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration data structure)
* @retval None
*/
void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct)
{
/* Set the default configuration */
TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING;
TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI;
TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1;
TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1;
}
/**
* @brief Configure the TIMx input channel.
* @param TIMx Timer Instance
* @param Channel This parameter can be one of the following values:
* @arg @ref LL_TIM_CHANNEL_CH1
* @arg @ref LL_TIM_CHANNEL_CH2
* @arg @ref LL_TIM_CHANNEL_CH3
* @arg @ref LL_TIM_CHANNEL_CH4
* @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx output channel is initialized
* - ERROR: TIMx output channel is not initialized
*/
ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct)
{
ErrorStatus result = ERROR;
switch (Channel)
{
case LL_TIM_CHANNEL_CH1:
result = IC1Config(TIMx, TIM_IC_InitStruct);
break;
case LL_TIM_CHANNEL_CH2:
result = IC2Config(TIMx, TIM_IC_InitStruct);
break;
case LL_TIM_CHANNEL_CH3:
result = IC3Config(TIMx, TIM_IC_InitStruct);
break;
case LL_TIM_CHANNEL_CH4:
result = IC4Config(TIMx, TIM_IC_InitStruct);
break;
default:
break;
}
return result;
}
/**
* @brief Fills each TIM_EncoderInitStruct field with its default value
* @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface configuration data structure)
* @retval None
*/
void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct)
{
/* Set the default configuration */
TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1;
TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING;
TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI;
TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1;
TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1;
TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING;
TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI;
TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1;
TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1;
}
/**
* @brief Configure the encoder interface of the timer instance.
* @param TIMx Timer Instance
* @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct)
{
uint32_t tmpccmr1;
uint32_t tmpccer;
/* Check the parameters */
assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx));
assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode));
assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter));
assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter));
/* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */
TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E);
/* Get the TIMx CCMR1 register value */
tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Configure TI1 */
tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U);
/* Configure TI2 */
tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U);
tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U);
/* Set TI1 and TI2 polarity and enable TI1 and TI2 */
tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP);
tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity);
tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U);
tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E);
/* Set encoder mode */
LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode);
/* Write to TIMx CCMR1 */
LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Set the fields of the TIMx Hall sensor interface configuration data
* structure to their default values.
* @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface configuration data structure)
* @retval None
*/
void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct)
{
/* Set the default configuration */
TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING;
TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1;
TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1;
TIM_HallSensorInitStruct->CommutationDelay = 0U;
}
/**
* @brief Configure the Hall sensor interface of the timer instance.
* @note TIMx CH1, CH2 and CH3 inputs connected through a XOR
* to the TI1 input channel
* @note TIMx slave mode controller is configured in reset mode.
Selected internal trigger is TI1F_ED.
* @note Channel 1 is configured as input, IC1 is mapped on TRC.
* @note Captured value stored in TIMx_CCR1 correspond to the time elapsed
* between 2 changes on the inputs. It gives information about motor speed.
* @note Channel 2 is configured in output PWM 2 mode.
* @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay.
* @note OC2REF is selected as trigger output on TRGO.
* @note LL_TIM_IC_POLARITY_BOTHEDGE must not be used for TI1 when it is used
* when TIMx operates in Hall sensor interface mode.
* @param TIMx Timer Instance
* @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor interface configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct)
{
uint32_t tmpcr2;
uint32_t tmpccmr1;
uint32_t tmpccer;
uint32_t tmpsmcr;
/* Check the parameters */
assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx));
assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity));
assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter));
/* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */
TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E);
/* Get the TIMx CR2 register value */
tmpcr2 = LL_TIM_ReadReg(TIMx, CR2);
/* Get the TIMx CCMR1 register value */
tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx SMCR register value */
tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR);
/* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */
tmpcr2 |= TIM_CR2_TI1S;
/* OC2REF signal is used as trigger output (TRGO) */
tmpcr2 |= LL_TIM_TRGO_OC2REF;
/* Configure the slave mode controller */
tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS);
tmpsmcr |= LL_TIM_TS_TI1F_ED;
tmpsmcr |= LL_TIM_SLAVEMODE_RESET;
/* Configure input channel 1 */
tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC);
tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U);
tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U);
tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U);
/* Configure input channel 2 */
tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE);
tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U);
/* Set Channel 1 polarity and enable Channel 1 and Channel2 */
tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP);
tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity);
tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E);
/* Write to TIMx CR2 */
LL_TIM_WriteReg(TIMx, CR2, tmpcr2);
/* Write to TIMx SMCR */
LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr);
/* Write to TIMx CCMR1 */
LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
/* Write to TIMx CCR2 */
LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay);
return SUCCESS;
}
/**
* @brief Set the fields of the Break and Dead Time configuration data structure
* to their default values.
* @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure)
* @retval None
*/
void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct)
{
/* Set the default configuration */
TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE;
TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE;
TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF;
TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00;
TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE;
TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW;
TIM_BDTRInitStruct->BreakFilter = LL_TIM_BREAK_FILTER_FDIV1;
TIM_BDTRInitStruct->Break2State = LL_TIM_BREAK2_DISABLE;
TIM_BDTRInitStruct->Break2Polarity = LL_TIM_BREAK2_POLARITY_LOW;
TIM_BDTRInitStruct->Break2Filter = LL_TIM_BREAK2_FILTER_FDIV1;
TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE;
}
/**
* @brief Configure the Break and Dead Time feature of the timer instance.
* @note As the bits BK2P, BK2E, BK2F[3:0], BKF[3:0], AOE, BKP, BKE, OSSI, OSSR
* and DTG[7:0] can be write-locked depending on the LOCK configuration, it
* can be necessary to configure all of them during the first write access to
* the TIMx_BDTR register.
* @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a break input.
* @note Macro @ref IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not
* a timer instance provides a second break input.
* @param TIMx Timer Instance
* @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure)
* @retval An ErrorStatus enumeration value:
* - SUCCESS: Break and Dead Time is initialized
* - ERROR: not applicable
*/
ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct)
{
uint32_t tmpbdtr = 0;
/* Check the parameters */
assert_param(IS_TIM_BREAK_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState));
assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState));
assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel));
assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState));
assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity));
assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput));
/* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State,
the OSSI State, the dead time value and the Automatic Output Enable Bit */
/* Set the BDTR bits */
MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime);
MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel);
MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState);
MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState);
MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState);
MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity);
MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput);
MODIFY_REG(tmpbdtr, TIM_BDTR_MOE, TIM_BDTRInitStruct->AutomaticOutput);
if (IS_TIM_ADVANCED_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_BREAK_FILTER(TIM_BDTRInitStruct->BreakFilter));
MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, TIM_BDTRInitStruct->BreakFilter);
}
if (IS_TIM_BKIN2_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_BREAK2_STATE(TIM_BDTRInitStruct->Break2State));
assert_param(IS_LL_TIM_BREAK2_POLARITY(TIM_BDTRInitStruct->Break2Polarity));
assert_param(IS_LL_TIM_BREAK2_FILTER(TIM_BDTRInitStruct->Break2Filter));
/* Set the BREAK2 input related BDTR bit-fields */
MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (TIM_BDTRInitStruct->Break2Filter));
MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, TIM_BDTRInitStruct->Break2State);
MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, TIM_BDTRInitStruct->Break2Polarity);
}
/* Set TIMx_BDTR */
LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr);
return SUCCESS;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup TIM_LL_Private_Functions TIM Private Functions
* @brief Private functions
* @{
*/
/**
* @brief Configure the TIMx output channel 1.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr1;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Check the parameters */
assert_param(IS_TIM_CC1_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
/* Disable the Channel 1: Reset the CC1E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CR2 register value */
tmpcr2 = LL_TIM_ReadReg(TIMx, CR2);
/* Get the TIMx CCMR1 register value */
tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1);
/* Reset Capture/Compare selection Bits */
CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S);
/* Set the Output Compare Mode */
MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the complementary output Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U);
/* Set the complementary output State */
MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U);
/* Set the Output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState);
/* Set the complementary output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U);
}
/* Write to TIMx CR2 */
LL_TIM_WriteReg(TIMx, CR2, tmpcr2);
/* Write to TIMx CCMR1 */
LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx output channel 2.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr1;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
/* Disable the Channel 2: Reset the CC2E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CR2 register value */
tmpcr2 = LL_TIM_ReadReg(TIMx, CR2);
/* Get the TIMx CCMR1 register value */
tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1);
/* Reset Capture/Compare selection Bits */
CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S);
/* Select the Output Compare Mode */
MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the complementary output Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U);
/* Set the complementary output State */
MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U);
/* Set the Output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U);
/* Set the complementary output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U);
}
/* Write to TIMx CR2 */
LL_TIM_WriteReg(TIMx, CR2, tmpcr2);
/* Write to TIMx CCMR1 */
LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx output channel 3.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr2;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Check the parameters */
assert_param(IS_TIM_CC3_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
/* Disable the Channel 3: Reset the CC3E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CR2 register value */
tmpcr2 = LL_TIM_ReadReg(TIMx, CR2);
/* Get the TIMx CCMR2 register value */
tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2);
/* Reset Capture/Compare selection Bits */
CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S);
/* Select the Output Compare Mode */
MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the complementary output Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U);
/* Set the complementary output State */
MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U);
/* Set the Output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U);
/* Set the complementary output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U);
}
/* Write to TIMx CR2 */
LL_TIM_WriteReg(TIMx, CR2, tmpcr2);
/* Write to TIMx CCMR2 */
LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx output channel 4.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr2;
uint32_t tmpccer;
uint32_t tmpcr2;
/* Check the parameters */
assert_param(IS_TIM_CC4_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
/* Disable the Channel 4: Reset the CC4E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CR2 register value */
tmpcr2 = LL_TIM_ReadReg(TIMx, CR2);
/* Get the TIMx CCMR2 register value */
tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2);
/* Reset Capture/Compare selection Bits */
CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S);
/* Select the Output Compare Mode */
MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the Output Idle state */
MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U);
}
/* Write to TIMx CR2 */
LL_TIM_WriteReg(TIMx, CR2, tmpcr2);
/* Write to TIMx CCMR2 */
LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx output channel 5.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 5 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC5Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr3;
uint32_t tmpccer;
/* Check the parameters */
assert_param(IS_TIM_CC5_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
/* Disable the Channel 5: Reset the CC5E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC5E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CCMR3 register value */
tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3);
/* Select the Output Compare Mode */
MODIFY_REG(tmpccmr3, TIM_CCMR3_OC5M, TIM_OCInitStruct->OCMode);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC5P, TIM_OCInitStruct->OCPolarity << 16U);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC5E, TIM_OCInitStruct->OCState << 16U);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the Output Idle state */
MODIFY_REG(TIMx->CR2, TIM_CR2_OIS5, TIM_OCInitStruct->OCIdleState << 8U);
}
/* Write to TIMx CCMR3 */
LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH5(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx output channel 6.
* @param TIMx Timer Instance
* @param TIM_OCInitStruct pointer to the the TIMx output channel 6 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus OC6Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct)
{
uint32_t tmpccmr3;
uint32_t tmpccer;
/* Check the parameters */
assert_param(IS_TIM_CC6_INSTANCE(TIMx));
assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity));
assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity));
assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState));
/* Disable the Channel 5: Reset the CC6E Bit */
CLEAR_BIT(TIMx->CCER, TIM_CCER_CC6E);
/* Get the TIMx CCER register value */
tmpccer = LL_TIM_ReadReg(TIMx, CCER);
/* Get the TIMx CCMR3 register value */
tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3);
/* Select the Output Compare Mode */
MODIFY_REG(tmpccmr3, TIM_CCMR3_OC6M, TIM_OCInitStruct->OCMode << 8U);
/* Set the Output Compare Polarity */
MODIFY_REG(tmpccer, TIM_CCER_CC6P, TIM_OCInitStruct->OCPolarity << 20U);
/* Set the Output State */
MODIFY_REG(tmpccer, TIM_CCER_CC6E, TIM_OCInitStruct->OCState << 20U);
if (IS_TIM_BREAK_INSTANCE(TIMx))
{
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState));
assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState));
/* Set the Output Idle state */
MODIFY_REG(TIMx->CR2, TIM_CR2_OIS6, TIM_OCInitStruct->OCIdleState << 10U);
}
/* Write to TIMx CCMR3 */
LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3);
/* Set the Capture Compare Register value */
LL_TIM_OC_SetCompareCH6(TIMx, TIM_OCInitStruct->CompareValue);
/* Write to TIMx CCER */
LL_TIM_WriteReg(TIMx, CCER, tmpccer);
return SUCCESS;
}
/**
* @brief Configure the TIMx input channel 1.
* @param TIMx Timer Instance
* @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct)
{
/* Check the parameters */
assert_param(IS_TIM_CC1_INSTANCE(TIMx));
assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter));
/* Disable the Channel 1: Reset the CC1E Bit */
TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E;
/* Select the Input and set the filter and the prescaler value */
MODIFY_REG(TIMx->CCMR1,
(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC),
(TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U);
/* Select the Polarity and set the CC1E Bit */
MODIFY_REG(TIMx->CCER,
(TIM_CCER_CC1P | TIM_CCER_CC1NP),
(TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E));
return SUCCESS;
}
/**
* @brief Configure the TIMx input channel 2.
* @param TIMx Timer Instance
* @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct)
{
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(TIMx));
assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter));
/* Disable the Channel 2: Reset the CC2E Bit */
TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E;
/* Select the Input and set the filter and the prescaler value */
MODIFY_REG(TIMx->CCMR1,
(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC),
(TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U);
/* Select the Polarity and set the CC2E Bit */
MODIFY_REG(TIMx->CCER,
(TIM_CCER_CC2P | TIM_CCER_CC2NP),
((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E));
return SUCCESS;
}
/**
* @brief Configure the TIMx input channel 3.
* @param TIMx Timer Instance
* @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct)
{
/* Check the parameters */
assert_param(IS_TIM_CC3_INSTANCE(TIMx));
assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter));
/* Disable the Channel 3: Reset the CC3E Bit */
TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E;
/* Select the Input and set the filter and the prescaler value */
MODIFY_REG(TIMx->CCMR2,
(TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC),
(TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U);
/* Select the Polarity and set the CC3E Bit */
MODIFY_REG(TIMx->CCER,
(TIM_CCER_CC3P | TIM_CCER_CC3NP),
((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E));
return SUCCESS;
}
/**
* @brief Configure the TIMx input channel 4.
* @param TIMx Timer Instance
* @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: TIMx registers are de-initialized
* - ERROR: not applicable
*/
static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct)
{
/* Check the parameters */
assert_param(IS_TIM_CC4_INSTANCE(TIMx));
assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity));
assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput));
assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler));
assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter));
/* Disable the Channel 4: Reset the CC4E Bit */
TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E;
/* Select the Input and set the filter and the prescaler value */
MODIFY_REG(TIMx->CCMR2,
(TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC),
(TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U);
/* Select the Polarity and set the CC2E Bit */
MODIFY_REG(TIMx->CCER,
(TIM_CCER_CC4P | TIM_CCER_CC4NP),
((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E));
return SUCCESS;
}
/**
* @}
*/
/**
* @}
*/
#endif /* TIM1 || TIM8 || TIM2 || TIM3 || TIM4 || TIM5 || TIM15 || TIM16 || TIM17 || TIM6 || TIM7 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/37637335.c | typedef struct Factorization{
long int *mlt;
long int *exp;
long int dim;
} Factorization;
int foo(Factorization **fctlist, int genexp){
int lexp = 0;
for(int k = 0; k < fctlist[genexp]->dim; k++){
lexp -= fctlist[genexp]->exp[k];
}
return lexp;
}
|
the_stack_data/92328637.c | #include <stdio.h>
#include <time.h>
#include <stdarg.h>
void logger(char *char_format, ...)
{
va_list valist;
va_start(valist, char_format);
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("\033[0;32m");
printf("%s", asctime(tm));
printf("\033[0m");
printf("--->");
vprintf(char_format, valist);
printf("\n\n");
} |
the_stack_data/181392760.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test_one(int x) {
#pragma omp target parallel for
for (int i = 0; i < x; i++)
;
}
void test_two(int x, int y) {
#pragma omp target parallel for
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_three(int x, int y) {
#pragma omp target parallel for collapse(1)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_four(int x, int y) {
#pragma omp target parallel for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_five(int x, int y, int z) {
#pragma omp target parallel for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
for (int i = 0; i < z; i++)
;
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target-parallel-for.c:3:1, line:7:1> line:3:6 test_one 'void (int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:4:1, col:32>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:5:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:10:1, col:32>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:17:1, col:44>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:42> 'int' 1
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:24:1, col:44>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:42> 'int' 2
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1>
// CHECK-NEXT: `-OMPTargetParallelForDirective {{.*}} <line:31:1, col:44>
// CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:42> 'int' 2
// CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
|
the_stack_data/11076570.c | #include <stdio.h>
#include <stdlib.h>
//
#define SIZE 5
//
int pilha[SIZE], topo = -1;
//
//Add elemento no topo
void push(int Elemento);
//Remover elemento do topo
void pop();
//Imprimir elemento do topo
void print();
//Main
void main()
{
int comando;
int valor;
char info[] = "1-Push\n2-Pop\n3-Print\n4-Sair";
do
{
printf("*********\n");
puts(info);
printf("Insira o Comando: ");
scanf("%i", &comando);
switch (comando)
{
case 1:
printf("digite o valor desejado: ");
scanf("%i", &valor);
push(valor);
break;
case 2:
pop();
break;
case 3:
print();
break;
case 4:
printf("Volte Sempre, Bye!!!!\n");
break;
default:
printf("Comando Invalido\n");
//scanf("%i", &comando);
break;
}
} while (comando != 4);
}
//Implementacao
//Add elemento no topo
void push(int Elemento)
{
if (topo < 5)
{
topo++;
pilha[topo] = Elemento;
printf("*'%i' foi adicionado\n", Elemento);
}
else
{
printf("pilha cheia\n");
}
}
//Remover elemento do topo
void pop()
{
if (topo == -1)
{
printf("pilha vazia\n");
}
else if (topo > -1 && topo < 5)
{
topo--;
}
}
//Imprimir elemento do topo
void print()
{
if (topo > -1 && topo < 5)
{
printf("***%i\n**", pilha[topo]);
}
else
{
printf("Pilha vazia\n");
}
}
|
the_stack_data/669281.c | #include<stdio.h>
#include<stdlib.h>
#define MAX 1000
struct node{
int priority;
struct node *prev,*next;
};
int BiggestOfThree(int a,int b,int c){return a>b?a>c?a:c:b>c?b:c;}
void nodex(struct node *n1,struct node *n2){
if(n1==NULL||n2==NULL){return;}
int t=n1->priority;
n1->priority=n2->priority;
n2->priority=t;
}
int sizeOfQueue(struct node *pq){
int l=0;
while(pq!=NULL){
l++;
pq=pq->next;
}
return l;
}
struct node * getNodeAtIndex(struct node *pq,int i){
int l;
for(l=0;l<i;l++){
if(pq==NULL){return NULL;}
pq=pq->next;
}
return pq;
}
void addAtEnd(struct node **pq,int pri){
struct node *nod=(struct node *)malloc(sizeof(struct node));
nod->priority=pri;nod->next=NULL;nod->prev=NULL;
if((*pq)==NULL){(*pq)=nod;return;}
struct node *head=*pq;
while (head->next!=NULL){head=head->next;}
head->next=nod;
nod->prev=head;
}
void heapify(struct node *pq,int index){
struct node
*a=getNodeAtIndex(pq,index),
*b=getNodeAtIndex(pq,(2*(index+1))-1),
*c=getNodeAtIndex(pq,(2*(index+1)));
if(b==NULL&&c==NULL){return;}
if(c==NULL){
if(a->priority>b->priority){return;}
nodex(a,b);
}
else{
int big=BiggestOfThree(
a->priority,
b->priority,
c->priority
);
if(big==a->priority){return;}
else if(big==b->priority){nodex(a,b);}
else if(big==c->priority){nodex(a,c);}
}
if(index==0){return;}
heapify(pq,index/2);
}
void buildHeap(struct node **pq){
int size=sizeOfQueue(*pq);
int i;
for(i=(size/2);i>=0;i--){
heapify(*pq,i);
}
}
void display(struct node *pq){
while (pq!=NULL){
printf("%d ",pq->priority);
pq=pq->next;
}
}
void insert(struct node **pq,int pri){
addAtEnd(pq,pri);
buildHeap(pq);
}
void extractMax(struct node **pq){
struct node *temp=*pq;
temp->next->prev=NULL;
*pq=temp->next;
free(temp);
buildHeap(pq);
}
void changeKey(struct node **pq,int oldk,int newk){
int i=0;
struct node *k=*pq;
while(k->priority!=oldk){
if(k==NULL){
printf("ERR:ELEMENT NOT FOUND");
}
k=k->next;
i++;
}
k->priority=newk;
buildHeap(pq);
}
void deletion(struct node **pq,int key){
changeKey(pq,key,MAX);
extractMax(pq);
}
void message(){
printf("1-insert(key)\n2-extractMax()\n3-changeKey(old,new)\n4-delete(key):");
}
int main(){
struct node *PQ=NULL;
int op;
while(1){
message();
scanf("%d",&op);
switch (op)
{
case 1:
int key;
scanf("%d",&key);
insert(&PQ,key);
break;
case 2:
extractMax(&PQ);
break;
case 3:
int k1,k2;
scanf("%d %d",&k1,&k2);
changeKey(&PQ,k1,k2);
break;
case 4:
int k;
scanf("%d",&key);
deletion(&PQ,key);
break;
default:
printf("no-op");
break;
}
display(PQ);
printf("\n");
}
return 0;
}
|
the_stack_data/93889033.c | #include<stdio.h>
#include<stdlib.h>
FILE *fp,*fs;
struct first_node{
struct first_node *parent1;
int data1;
};
//==================================================
struct second_node{
struct second_node *parent2;
int data2;
int rank;
};
//==========================
struct data_set1{
struct first_node *head1;
};
struct data_set2{
struct second_node *head2;
};
struct data_set1 *a, *c;
struct data_set2 *b, *d;
int n1=0, n2=0, n3=0, n4=0, c1=0, c2=0, c3=0, c4=0;
struct first_node* get1(int p)
{
for(int i=0;i<n1;i++)
if(a[i].head1->data1==p)
return a[i].head1;
return NULL;
}
struct second_node* get2(int p)
{
for(int i=0;i<n2;i++)
if(b[i].head2->data2==p)
return b[i].head2;
return NULL;
}
struct first_node* get3(int p)
{
for(int i=0;i<n3;i++)
if(c[i].head1->data1==p)
return c[i].head1;
return NULL;
}
struct second_node* get4(int p)
{
for(int i=0;i<n4;i++)
if(d[i].head2->data2==p)
return d[i].head2;
return NULL;
}
void makedata_set1(int p)
{
struct first_node* x;
x=(struct first_node*)malloc(sizeof(struct first_node));
x->data1=p;
x->parent1=x;
a = (struct data_set1 *) realloc(a, (n1+1)*sizeof(struct data_set1));
a[n1].head1=x;
n1++;
}
void makedata_set2(int p)
{
struct second_node* x;
x=(struct second_node*)malloc(sizeof(struct second_node));
x->data2=p;
x->rank=0;
x->parent2=x;
b= (struct data_set2 *) realloc(b, (n2+1)*sizeof(struct data_set2));
b[n2].head2=x;
n2++;
}
void makeset3(int p)
{
struct first_node* x;
x=(struct first_node*)malloc(sizeof(struct first_node));
x->data1=p;
x->parent1=x;
c = (struct data_set1 *) realloc(c, (n3+1)*sizeof(struct data_set1));
c[n3].head1=x;
n3++;
}
void makeset4(int p)
{
struct second_node* x;
x=(struct second_node*)malloc(sizeof(struct second_node));
x->data2=p;
x->rank=0;
x->parent2=x;
d = (struct data_set2 *) realloc(d, (n4+1)*sizeof(struct data_set2));
d[n4].head2=x;
n4++;
}
struct first_node* finddata_set1(int p)
{
c1++;
struct first_node* x;
x=get1(p);
while(x->parent1!=x)
{
x=x->parent1;
c1++;
}
return x;
}
struct second_node* finddata_set2(int p)
{
c2++;
struct second_node* x;
x=get2(p);
while(x->parent2!=x)
{
x=x->parent2;
c2++;
}
return x;
}
struct first_node* findset3(int p)
{
c3++;
struct first_node* x;
x=get3(p);
if(x->parent1!=x)
{
x->parent1=findset3(x->parent1->data1);
}
return x->parent1;
}
struct second_node* findset4(int p)
{
c4++;
struct second_node* x;
x=get4(p);
if(x->parent2!=x)
{
x->parent2=findset4(x->parent2->data2);
}
return x->parent2;
}
void union1(int p, int q){
struct first_node *x, *y;
x = finddata_set1(p);
y = finddata_set1(q);
if(x == y)
fprintf(fp,"%d ", x->data1);
else{
if(x != y)
y->parent1 = x;
fprintf(fp,"%d ", x->data1);
}
}
//union two
void union2(int p, int q){
struct second_node *x, *y;
x = finddata_set2(p);
y = finddata_set2(q);
if(x == y)
fprintf(fp,"%d ", x->data2);
else{
if(x->rank >= y->rank)
{y->parent2 = x;
fprintf(fp,"%d ", x->data2);
}
else
{x->parent2 = y;
fprintf(fp,"%d ", y->data2);
}
if(x->rank == y->rank)
x->rank = x->rank + 1;
}
}
//=======================================================
void union3(int p, int q){
struct first_node *x, *y;
x = findset3(p);
y = findset3(q);
if(x == y)
fprintf(fp,"%d ", x->data1);
else{
if(x != y)
y->parent1 = x;
fprintf(fp,"%d ", x->data1);
}
}
void union4(int p, int q){
struct second_node *x, *y;
x = findset4(p);
y = findset4(q);
if(x == y)
fprintf(fp,"%d\n", x->data2);
else{
if(x->rank >= y->rank)
{y->parent2 = x;
fprintf(fp,"%d\n", x->data2);
}
else
{x->parent2 = y;
fprintf(fp,"%d\n", y->data2);
}
if(x->rank == y->rank)
x->rank = x->rank + 1;
}
}
//==================================================================
int main()
{
fs=fopen("input.txt","r");
fp=fopen("output.txt","w");
if(fs==NULL)
{
printf("error opening the file\n");
exit(0);
}
struct first_node *g1, *g3;
struct second_node *g2, *g4;
a = (struct data_set1 *) malloc(sizeof(struct data_set1));
b = (struct data_set2 *) malloc(sizeof(struct data_set2));
c = (struct data_set1 *) malloc(sizeof(struct data_set1));
d = (struct data_set2 *) malloc(sizeof(struct data_set2));
int key,key1,key2;
char ch;
int i;
while(1)
{
fscanf(fs,"%c",&ch);
if(ch=='m')
{
fscanf(fs,"%d",&key);
for( i=0; i<n1; i++)
if(a[i].head1->data1 == key)
break;
if(i!= n1)
fprintf(fp,"PRESENT\n");
else
{makedata_set1(key);
makedata_set2(key);
makeset3(key);
makeset4(key);
fprintf(fp,"%d\n", key);
}
}
else if(ch=='f')
{
fscanf(fs,"%d", &key);
for(i=0; i<n1; i++)
if(a[i].head1->data1 == key)
break;
if(i!= n1)
{
g1 = finddata_set1(key);
fprintf(fp,"%d ", g1->data1);
g2 = finddata_set2(key);
fprintf(fp,"%d ", g2->data2);
g3 = findset3(key);
fprintf(fp,"%d ", g3->data1);
g4 = findset4(key);
fprintf(fp,"%d\n", g4->data2);
}
else
fprintf(fp,"NOT FOUND\n");
}
else if(ch=='u')
{
fscanf(fs,"%d %d", &key1, &key2);
for(i=0; i<n1; i++)
if(a[i].head1->data1 == key1)
break;
if(i==n1)
{
fprintf(fp,"ERROR ERROR ERROR ERROR\n");
continue;
}
for(i=0; i<n1; i++)
if(a[i].head1->data1 == key2)
break;
if(i== n1 )
{
fprintf(fp,"ERROR ERROR ERROR ERROR\n");
continue;
}
union1(key1, key2);
union2(key1, key2);
union3(key1, key2);
union4(key1, key2);
}
else if(ch=='s')
{
fprintf(fp,"%d ", c1);
fprintf(fp,"%d ", c2);
fprintf(fp,"%d ", c3);
fprintf(fp,"%d\n", c4);
break;
}
}
fclose(fp);
fclose(fs);
return 0;
}
|
the_stack_data/140144.c | //*****************************************************************************
//
// startup_gcc.c - Startup code for use with GNU tools.
//
// Copyright (c) 2008-2013 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 10636 of the RDK-BLDC Firmware Package.
//
//*****************************************************************************
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void IntDefaultHandler(void);
extern void ADC0IntHandler(void);
extern void CANIntHandler(void);
extern void lwIPEthernetIntHandler(void);
extern void GPIOBIntHandler(void);
extern void GPIOCIntHandler(void);
extern void FaultISR(void);
extern void NmiSR(void);
extern void PWM0IntHandler(void);
extern void MainWaveformTick(void);
extern void MainMillisecondTick(void);
extern void QEIIntHandler(void);
extern void SysTickIntHandler(void);
extern void Timer0AIntHandler(void);
extern void Timer1AIntHandler(void);
extern void WatchdogIntHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static unsigned long pulStack[1024];
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((unsigned long)pulStack + sizeof(pulStack)),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
SysTickIntHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
GPIOBIntHandler, // GPIO Port B
GPIOCIntHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
IntDefaultHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
PWM0IntHandler, // PWM Generator 0
MainWaveformTick, // PWM Generator 1
MainMillisecondTick, // PWM Generator 2
QEIIntHandler, // Quadrature Encoder 0
ADC0IntHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
WatchdogIntHandler, // Watchdog timer
Timer0AIntHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
Timer1AIntHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
CANIntHandler, // CAN0
IntDefaultHandler, // CAN1
IntDefaultHandler, // CAN2
lwIPEthernetIntHandler, // Ethernet
IntDefaultHandler // Hibernate
};
//*****************************************************************************
//
// The following are constructs created by the linker, indicating where the
// the "data" and "bss" segments reside in memory. The initializers for the
// for the "data" segment resides immediately following the "text" segment.
//
//*****************************************************************************
extern unsigned long _etext;
extern unsigned long _data;
extern unsigned long _edata;
extern unsigned long _bss;
extern unsigned long _ebss;
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
unsigned long *pulSrc, *pulDest;
//
// Copy the data segment initializers from flash to SRAM.
//
pulSrc = &_etext;
for(pulDest = &_data; pulDest < &_edata; )
{
*pulDest++ = *pulSrc++;
}
//
// Zero fill the bss segment.
//
__asm(" ldr r0, =_bss\n"
" ldr r1, =_ebss\n"
" mov r2, #0\n"
" .thumb_func\n"
"zero_loop:\n"
" cmp r0, r1\n"
" it lt\n"
" strlt r2, [r0], #4\n"
" blt zero_loop");
//
// Call the application's entry point.
//
main();
}
|
the_stack_data/300316.c | /* File : strcmp.c
Author : Richard A. O'Keefe.
Updated: 10 April 1984
Defines: strcmp()
strcmp(s, t) returns > 0, = 0, or < 0 when s > t, s = t, or s < t
according to the ordinary lexicographical order. To test for
equality, the macro streql(s,t) is clearer than !strcmp(s,t). Note
that if the string contains characters outside the range 0..127 the
result is machine-dependent; PDP-11s and VAXen use signed bytes,
some other machines use unsigned bytes.
*/
#include "strings.h"
int strcmp(register const char *s, register const char *t)
{
while (*s == *t++) if (!*s++) return 0;
return s[0]-t[-1];
}
|
the_stack_data/855198.c | //
// 編號:19-0502N0v0Lx_Struct+Fprintf-Homework.c
//
// Copyright: Oracragron.Waylon.Yuen
//
/*標頭文件*/
#include <stdio.h>
#include <string.h>
/*定義*/
#define MemberSIZE 5 //資料筆數
#define FILE_PATH "save.txt" //文件路徑
/*定義 結構 & 名稱為account*/
typedef struct account{
int account_number; // 帳戶編號
char firstname[50]; // 姓
char lastname[50]; // 名
double balance; // 帳戶餘額
}account;
/*副程式宣告*/
void acount_sort(struct account *p);
int main(void){
struct account Member[MemberSIZE], *p; //宣告 結構型 Member陣列 & 指標p
p = Member; //將指標p指向Member陣列開頭位置
int i;
printf("請分別輸入 帳戶編號、 姓、 名、 帳戶餘額\n");
for(i=0; i<MemberSIZE; i++){
/*輸入結構資料*/
scanf(
"%d%s%s%lf", // lf: double
&(p+i)->account_number,
(p+i)->firstname,
(p+i)->lastname,
&(p+i)->balance
);
}
/*以帳戶排序-副程式*/
acount_sort(p); //呼叫副程式 並傳遞 p指標參數於副程式
puts("\n");
/*輸出並保存至外部文件*/
FILE *fptr; //文件指標宣告
if( (fptr = fopen("FILE_PATH", "w")) != NULL){ //判斷路徑是否存在文件
//成功讀取文件
puts("File open Success!");
puts("**************************");
/*逐筆資料保存至外部文件*/
for(i=1; i<MemberSIZE; i++){
fprintf(
fptr,"%d\t%s\t%s\t%lf\n",
(p+i)->account_number,
(p+i)->firstname,
(p+i)->lastname,
(p+i)->balance
);
}
fflush(fptr); //刷新緩衝區, 將緩衝區內容寫入文件
rewind(fptr); //重置文件內部指標位置,讓指標位置指向文件開頭
fclose(fptr); //關閉文件
printf("......File Save Success!\n");
}else{
//文件打開失敗
printf("File open Fail! Plz check the file!\n"); //錯誤提示語
puts("......End of run");
return 0;
}
/*在cmd中顯示結果*/
printf("\n輸出結構內容:\n帳戶編號\t姓\t名\t帳戶餘額\n");
/*逐筆資料輸出至螢幕*/
for(i=1; i<=MemberSIZE; i++){
printf(
"%d\t\t%s\t%s\t%lf\n",
(p+i)->account_number,
(p+i)->firstname,
(p+i)->lastname,
(p+i)->balance
);
}
return 0;
}
/*帳戶排序-副程式*/
void acount_sort(struct account *p){
int i, j;
struct account temp; //宣告結構型 的account名稱為 temp:用途為交換次序所必要第三個保存位置
/*泡沫排序法*/
for(i=0; i<MemberSIZE; i++){
for(j=0; j<MemberSIZE-i; j++){
if( (p+j)->account_number > (p+j+1)->account_number ){ //決定排序:由小到大 or 有大到小
/*交換*/
temp = *(p + j);
*(p + j) = *(p + j + 1);
*(p + j + 1) = temp;
}
}
}
}
|
the_stack_data/56631.c | /* print_int.c -- 打印输入的整数信息 */
#include <stdio.h>
int main(void)
{
int even_count = 0, odd_count = 0;
float even_sum = 0, odd_sum = 0;
int x;
while (scanf("%d", &x) && x != 0) {
if (x % 2 == 0) {
even_count ++;
even_sum += x;
} else {
odd_count ++;
odd_sum += x;
}
}
printf("even_count is %d, even_aver is %.2f\n", even_count, even_count > 0 ? even_sum / even_count : 0);
printf("odd_count is %d, odd_aver is %.2f\n", odd_count, odd_count > 0 ? odd_sum / odd_count : 0);
printf("\n---------------------------------------------\n");
return 0;
} |
the_stack_data/71177.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int codigo;
char nome[40];
double preco;
int qtd;
} Pessoa;
void menu() {
printf(" --- Cadastra Pessoas --- \n");
printf("1 - Cadastrar Pessoas\n");
printf("2 - Vizualizar Pessoas\n");
printf("0 - Exit Programa\n");
}
// Void porque não preciso retornar nada na main e sim só na memória
void cadastrarPessoas(Pessoa **ptrAux, int *qtd) {
Pessoa aux; // Essa estrutura é local, a partir daí é que inserimos no ponteiro
/**
* 1. ler para uma memoria aux
* 2. Alocar a Memoria
* 3. Passar da Memoria aux para a memoria alocada
**/
/**
p = &a -> P está recebendo o endereço de a
(*p) = 100; -> quem está sendo apontado por p recebe o valor de 100
**/
// 1. Lendo e inserindo em uma memoria aux
while ( scanf("%d", &aux.codigo) && (aux.codigo != 0))
{
printf("Nome: ");
scanf(" %39[^\n]", aux.nome);
printf("Preço: ");
scanf("%lf", &aux.preco);
printf("Qtd: ");
scanf("%d", &aux.qtd);
// 2. Realizando a alocação -> vamos usar quem ptrAux está apontando, nesse caso ptrPessoa(main).
(*ptrAux) = (Pessoa *) realloc((*ptrAux), (*qtd + 1) * sizeof(Pessoa));
if ((*ptrAux) == NULL) {
printf("Error for alocation\n");
exit(-1);
}
// 3. Passando da memoria aux para memoria do main
(*ptrAux)[*qtd] = aux; // na posicao inserindo uma pessoa
(*qtd)++; // Incrementou a quantidade de pessoa
}
}
int main()
{
Pessoa *ptrPessoa = NULL;
int qtd = 0; // Por ser uma estrutura dinâmica, precisamos usar um contador => aumenta o diminui
int i;
// Mostrando as opções aos usuarios
menu();
// Cadastrando pessoas em um ponteiro dinamico
cadastrarPessoas(&ptrPessoa, &qtd); // Sempre que passar o endereço de algo, usar um * na funcao
// Mostrando as pessoas que foram cadastradas (aloc dinamica)
printf("%d pessoas foram lidas\n", qtd);
for (i = 0; i < qtd; i++) {
printf("Nome: %s\n", ptrPessoa[i].nome);
printf("Codigo: %d\n", ptrPessoa[i].codigo);
printf("Preco: %.2lf\n", ptrPessoa[i].preco);
printf("QTD: %d\n", ptrPessoa[i].qtd);
}
free(ptrPessoa);
return 0;
} |
the_stack_data/556820.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include <omp.h>
/*
* This test would hang when level instead of active level
* used to push task state.
*/
int main()
{
// If num_threads is changed to a value greater than 1, then the test passes
#pragma omp parallel num_threads(1)
{
#pragma omp parallel
printf("Hello World from thread %d\n", omp_get_thread_num());
}
printf("omp_num_threads: %d\n", omp_get_max_threads());
#pragma omp parallel
{
#pragma omp master
#pragma omp task default(none)
{
printf("%d is executing this task\n", omp_get_thread_num());
}
}
printf("pass\n");
return 0;
}
|
the_stack_data/20449385.c |
#include<stdio.h>
main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same location" ) ;
}
|
the_stack_data/1120051.c | /*******************************************************************
* Copyright (C) 2017-2018 Xilinx, 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
* XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
*******************************************************************************/
/*****************************************************************************/
/**
*
* @file xrfdc_g.c
* @addtogroup rfdc_v5_0
* @{
*
* This file contains a configuration table that specifies the configuration of
* RFdc devices in the system.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.0 sk 05/16/17 Initial release
*
* </pre>
*
******************************************************************************/
#ifdef __BAREMETAL__
/***************************** Include Files ********************************/
#include "xparameters.h"
#include "xrfdc.h"
/************************** Constant Definitions ****************************/
/**************************** Type Definitions ******************************/
/***************** Macros (Inline Functions) Definitions ********************/
/************************** Variable Definitions ****************************/
/**
* The configuration table for devices
*/
XRFdc_Config XRFdc_ConfigTable[XPAR_XRFDC_NUM_INSTANCES] =
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DEVICE_ID,
XPAR_USP_RF_DATA_CONVERTER_0_BASEADDR,
XPAR_USP_RF_DATA_CONVERTER_0_HIGH_SPEED_ADC,
XPAR_USP_RF_DATA_CONVERTER_0_SYSREF_MASTER,
XPAR_USP_RF_DATA_CONVERTER_0_SYSREF_MASTER,
XPAR_USP_RF_DATA_CONVERTER_0_SYSREF_SOURCE,
XPAR_USP_RF_DATA_CONVERTER_0_SYSREF_SOURCE,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC0_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE00_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL00,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE00,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE00,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE01_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL01,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE01,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE01,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE02_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL02,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE02,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE02,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE03_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL03,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE03,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE03,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE00,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH00,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE00,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO00_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER00_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE00,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE01,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH01,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE01,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO01_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER01_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE01,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE02,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH02,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE02,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO02_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER02_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE02,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE03,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH03,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE03,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO03_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER03_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE03,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC1_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE10_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL10,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE10,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE10,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE11_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL11,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE11,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE11,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE12_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL12,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE12,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE12,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE13_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL13,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE13,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE13,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE10,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH10,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE10,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO10_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER10_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE10,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE11,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH11,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE11,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO11_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER11_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE11,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE12,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH12,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE12,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO12_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER12_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE12,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE13,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH13,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE13,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO13_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER13_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE13,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC2_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE20_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL20,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE20,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE20,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE21_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL21,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE21,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE21,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE22_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL22,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE22,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE22,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE23_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL23,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE23,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE23,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE20,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH20,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE20,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO20_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER20_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE20,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE21,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH21,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE21,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO21_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER21_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE21,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE22,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH22,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE22,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO22_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER22_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE22,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE23,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH23,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE23,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO23_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER23_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE23,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_DAC3_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE30_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL30,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE30,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE30,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE31_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL31,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE31,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE31,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE32_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL32,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE32,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE32,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_SLICE33_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INVSINC_CTRL33,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_MODE33,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DECODER_MODE33,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE30,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH30,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE30,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO30_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER30_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE30,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE31,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH31,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE31,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO31_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER31_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE31,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE32,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH32,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE32,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO32_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER32_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE32,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_TYPE33,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_DATA_WIDTH33,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_INTERPOLATION_MODE33,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_FIFO33_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_ADDER33_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_DAC_MIXER_TYPE33,
},
},
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC0_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE00_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE00,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE01_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE01,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE02_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE02,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE03_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE03,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE00,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH00,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE00,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO00_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE00,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE01,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH01,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE01,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO01_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE01,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE02,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH02,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE02,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO02_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE02,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE03,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH03,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE03,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO03_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE03,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC1_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE10_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE10,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE11_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE11,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE12_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE12,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE13_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE13,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE10,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH10,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE10,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO10_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE10,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE11,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH11,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE11,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO11_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE11,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE12,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH12,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE12,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO12_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE12,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE13,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH13,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE13,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO13_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE13,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC2_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE20_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE20,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE21_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE21,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE22_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE22,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE23_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE23,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE20,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH20,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE20,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO20_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE20,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE21,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH21,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE21,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO21_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE21,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE22,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH22,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE22,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO22_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE22,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE23,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH23,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE23,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO23_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE23,
},
},
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_PLL_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_SAMPLING_RATE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_REFCLK_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_FABRIC_FREQ,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_FBDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_OUTDIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_REFCLK_DIV,
XPAR_USP_RF_DATA_CONVERTER_0_ADC3_BAND,
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE30_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE30,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE31_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE31,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE32_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE32,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_SLICE33_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_MODE33,
},
},
{
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE30,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH30,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE30,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO30_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE30,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE31,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH31,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE31,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO31_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE31,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE32,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH32,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE32,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO32_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE32,
},
{
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_TYPE33,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DATA_WIDTH33,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_DECIMATION_MODE33,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_FIFO33_ENABLE,
XPAR_USP_RF_DATA_CONVERTER_0_ADC_MIXER_TYPE33,
},
},
},
}
}
};
#endif
/** @} */
|
the_stack_data/389.c | #include <stdio.h>
#define SIZE 4
typedef struct
{
char name[20];
char species[20];
int length;
int weight;
char naturalHabitat[20];
}Animal;
void fill_struct_array(Animal[]);
void length_info(Animal[],int*,int*,double*);
void filter_mammals(Animal[],Animal[]);
void change_weight(Animal*);
void print_animals(Animal[]);
void fill(Animal*,char*,char*,int,int,char*);
int getInt(const char*);
void strCpy(char*,char*);
int strCmp(char*,char*);
int main(void)
{
Animal animal[SIZE];
Animal filtered_animals[SIZE];
int min=0,max=0;
double average=0.;
fill_struct_array(animal);
length_info(animal,&max,&min,&average);
filter_mammals(animal,filtered_animals);
print_animals(animal);
change_weight(&animal[0]);
printf("Min : %d Max : %d Ave : %.2lf\n",min,max,average);
print_animals(animal);
print_animals(filtered_animals);
return 0;
}
void fill_struct_array(Animal table[])
{
fill(&table[0],"Lion","Mammals",200,130,"Savannah");
fill(&table[1],"Dolphin","Mammals",300,180,"Oceans");
fill(&table[2],"Shark","Fish",450,250,"Oceans");
fill(&table[3],"Wolf","Mammals",160,60,"Forest");
}
void fill(Animal* animal, char* name, char* species, int length, int weight, char* naturalHabitat)
{
strCpy(animal->name,name);
strCpy(animal->species,species);
strCpy(animal->naturalHabitat,naturalHabitat);
animal->length = length;
animal->weight = weight;
}
void length_info(Animal table[], int* max, int* min, double* average)
{
*max = *min = table[0].length;
for(int i=0 ; i < SIZE ; ++i)
{
if(table[i].length > *max)
*max = table[i].length;
if(table[i].length < *min)
*min = table[i].length;
*average += table[i].length;
}
*average /= SIZE;
}
void filter_mammals(Animal table[], Animal filtered_animals[])
{
int index=0;
for(int i=0 ; i < SIZE ; ++i)
if(strCmp(table[i].species,"Mammals") == 0 && table[i].weight > 100 && strCmp(table[i].naturalHabitat,"Oceans") != 0)
filtered_animals[index++] = table[i];
for(int i = index ; i < SIZE ; ++i)
filtered_animals[i].length = -1;
}
void change_weight(Animal* animal_to_change)
{
int weight=0;
printf("Current weight : %d\n",animal_to_change->weight);
weight = getInt("Weight : ");
animal_to_change->weight = weight;
}
void print_animals(Animal table[])
{
for(int i=0 ; i < SIZE ; ++i)
if(table[i].length != -1)
printf("Name : %s\nSpecies : %s\nLenght(cm) : %d\nWeight(kg) : %d\nNatural Habitat : %s\n",table[i].name,table[i].species,table[i].length,table[i].weight,table[i].naturalHabitat);
}
int getInt(const char* text)
{
int var=0;
printf("%s",text);
scanf("%d",&var);
return var;
}
void strCpy(char* s1, char* s2)
{
while(*s1++ = *s2++);
}
int strCmp(char* s1, char* s2)
{
while(*s1 && *s2 && *s1 == *s2)
++s1,++s2;
return *s1 - *s2;
} |
the_stack_data/91431.c | #include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>
static const char MESSAGE[] = "Hello, World!\n";
static const int PORT = 9995;
static void listener_cb(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *);
static void conn_writecb(struct bufferevent *, void *);
static void conn_eventcb(struct bufferevent *, short, void *);
static void signal_cb(evutil_socket_t, short, void *);
int main()
{
struct event_base* base;
struct evconnlistener* listener;
struct event* signal_event;
struct sockaddr_in sin;
base = event_base_new(); //分配b
if (!base) {
fprintf(stderr, "Could not initialize libevent!\n");
return 1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&sin, sizeof(sin));
if (!listener) {
fprintf(stderr, "Could not create a listener!\n");
return 1;
}
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
if (!signal_event || event_add(signal_event, NULL)<0) {
fprintf(stderr, "Could not create/add a signal event!\n");
return 1;
}
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(signal_event);
event_base_free(base);
printf("done\n");
return 0;
}
static void listener_cb(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr* sa, int socklen, void* user_data) {
struct event_base* base = user_data;
struct bufferevent *bev;
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); //
if (!bev) {
fprintf(stderr, "Error constructing bufferevent!");
event_base_loopbreak(base);
return;
}
bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL); //设置bev的回调
bufferevent_enable(bev, EV_WRITE); //启用bev写
bufferevent_disable(bev, EV_READ); //禁用bev读 PS这两行可以省略
bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
}
static void conn_writecb(struct bufferevent *bev, void *user_data) {
struct evbuffer *output = bufferevent_get_output(bev);
if (evbuffer_get_length(output) == 0) {
printf("flushed answer\n");
bufferevent_free(bev);
}
}
//bev结束或异常处理
static void conn_eventcb(struct bufferevent *bev, short events, void *user_data) {
if (events & BEV_EVENT_EOF) {
printf("Connection closed.\n");
} else if (events & BEV_EVENT_ERROR) {
printf("Got an error on the connection: %s\n",
strerror(errno));/*XXX win32*/
}
/* None of the other events can happen here, since we haven't enabled
* timeouts */
bufferevent_free(bev);
}
static void signal_cb(evutil_socket_t sig, short events, void *user_data) {
struct event_base* base = user_data;
struct timeval delay = { 2, 0 };
printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
event_base_loopexit(base, &delay); //eb在2s后停止
}
|
the_stack_data/206393677.c | int main() {
int a = 3;
int b = 4;
return a + b;
}
|
the_stack_data/1269276.c | /*
* Copyright 2010 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
* Stub routine for `pselect' for porting support.
*/
#include <sys/time.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <unistd.h>
#include <errno.h>
int pselect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
const struct timespec *timeout, const sigset_t *sigmask) {
errno = ENOSYS;
return -1;
}
|
the_stack_data/93829.c | /*
* Program: program_3_2.c
* Function Title: Main
* Summary: display english representation of two digit integer
*
* input: None
* output: None
* Pseudocode
* Begin
* define variables
* Ask for two digit number
* scan in number
* divide by 10 to get 10 place digit (b)
* find remainder to get 1 place digit (c)
* print "The English representation of # is "
* If b equals 0
* Then
* switch looking at c
* case 0 print "zero"
* case 1 print "one"
* case 2 print "two"
* case 3 print "three"
* case 4 print "four"
* case 5 print "five"
* case 6 print "six"
* case 7 print "seven"
* case 8 print "eight"
* case 9 print "nine"
* Else
If b equals 1
* Then
* switch looking at c
* case 0 print "ten"
* case 1 print "eleven"
* case 2 print "twelve"
* case 3 print "thirteen"
* case 4 print "fourteen"
* case 5 print "fifteen"
* case 6 print "sixteen"
* case 7 print "seventeen"
* case 8 print "eighteen"
* case 9 print "nineteen"
Else
If b equals 2
Then
print "twenty"
switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b equals 3
* Then
* print "thirty"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b equals 4
* Then
print "fourty"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b equals 5
* Then
print "fifty"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b equals 6
* Then
print "sixty"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b eqauls 7
* Then
print "seventy"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
If b equals 8
* Then
print "eighty"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* Else
* print "ninety"
* switch looking at c
case 0: do nothing
case 1: print "-one"
case 2 print "-two"
* case 3 print "-three"
* case 4 print "-four"
* case 5 print "-five"
* case 6 print "-six"
* case 7 print "-seven"
* case 8 print "-eight"
* case 9 print "-nine"
* EndIf
EndIf
* EndIf
* EndIf
* EndIf
* EndIf
* EndIf
* EndIf
* EndIf
*
* print "."
*
* End
*/
#include <stdio.h>
int main() { //Begin
int a, b, c, d; //define variables
printf("Enter a two-digit number (1-99): "); //Ask for two digit number
scanf("%d", &a); //scan in number
b = a / 10; //divide by 10 to get 10 place digit (b)
c = a % 10; //find remainder to get 1 place digit (c)
printf("The English representation of %d is "
, a); //print "The English representation of # is "
if (b == 0) //If b equals 0
{ //Then
switch (c) { //switch looking at c
case 0: printf("zero"); //case 0 print "zero"
break;
case 1: printf("one"); //case 1 print "one"
break;
case 2: printf("two"); //case 2 print "two"
break;
case 3: printf("three"); //case 3 print "three"
break;
case 4: printf("four"); //case 4 print "four"
break;
case 5: printf("five"); //case 5 print "five"
break;
case 6: printf("six"); //case 6 print "six"
break;
case 7: printf("seven"); //case 7 print "seven"
break;
case 8: printf("eight"); //case 8 print "eight"
break;
case 9: printf("nine"); //case 9 print "nine"
break;
}
}
else //Else
if (b == 1) //If b equals 1
{ //Then
switch (c) { //switch looking at c
case 0: printf("ten"); //case 0 print "ten"
break;
case 1: printf("eleven"); //case 1 print "eleven"
break;
case 2: printf("twelve"); //case 2 print "twelve"
break;
case 3: printf("thirteen"); //case 3 print "thirteen"
break;
case 4: printf("fourteen"); //case 4 print "fourteen"
break;
case 5: printf("fifteen"); //case 5 print "fifteen"
break;
case 6: printf("sixteen"); //case 6 print "sixteen"
break;
case 7: printf("seventeen"); //case 7 print "seventeen"
break;
case 8: printf("eighteen"); //case 8 print "eighteen"
break;
case 9: printf("nineteen"); //case 9 print "nineteen"
break;
}
}
else //Else
if (b == 2) //If b equals 2
{ //Then
printf("twenty"); //print "twenty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 3) //If b equals 3
{ //Then
printf("thirty"); //print "thirty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 4) //If b equals 4
{ //Then
printf("forty"); //print "forty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 5) //If b equals 5
{ //Then
printf("fifty"); //print "fifty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 6) //If b equals 6
{ //Then
printf("sixty"); //print "sixty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 7) //If b equals 7
{ //Then
printf("seventy"); //print "seventy"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else //Else
if (b == 8) //If b equals 8
{ //Then
printf("eighty"); //print "eighty"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
}
}
else { //Else
printf("ninety"); //print "ninety"
switch (c) { //switch looking at c
case 0: break; //case 0 do nothing
case 1: printf("-one"); //case 1 print "-one"
break;
case 2: printf("-two"); //case 2 print "-two"
break;
case 3: printf("-three"); //case 3 print "-three"
break;
case 4: printf("-four"); //case 4 print "-four"
break;
case 5: printf("-five"); //case 5 print "-five"
break;
case 6: printf("-six"); //case 6 print "-six"
break;
case 7: printf("-seven"); //case 7 print "-seven"
break;
case 8: printf("-eight"); //case 8 print "-eight"
break;
case 9: printf("-nine"); //case 9 print "-nine"
break;
} //EndIf
} //EndIf
//EndIf
//EndIf
//EndIf
//EndIf
//EndIf
//EndIf
//EndIf
printf("."); //print "."
return 0;
} //End |
the_stack_data/821506.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_str_is_lowercase.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ayip <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/15 16:34:07 by ayip #+# #+# */
/* Updated: 2017/08/15 16:35:02 by ayip ### ########.fr */
/* */
/* ************************************************************************** */
int ft_str_is_lowercase(char *str)
{
char *tmp;
tmp = str;
while (*tmp)
{
if (*tmp < 'a' || *tmp > 'z')
return (0);
tmp++;
}
return (1);
}
|
the_stack_data/200143685.c |
// > cd …/Rom
// > zasm -c sdcc -L lib -I include EMUF.asm
#include <stdio.h>
static int n;
extern unsigned long int system_time;
static float f = 0x842;
void foo(){ f=0x421; }
void main()
{
unsigned long int i;
char c;
f = 0.0;
foo();
f = 1.0;
foo();
f = 2.0;
foo();
f = 3.0;
foo();
f = 4.0;
foo();
f = 5.0;
foo();
f = -1.0;
foo();
f = 1.0e30;
foo();
f = 1.0e-30;
foo();
f = 1.5e-30;
printf("\n\rZ80EMUF booting...\n\r");
printf("press any key to continue");
c = getchar();
printf("\n\r");
if(c>' ' && c<='~')
{
printf("your key of choice was '%c'\n\r",c);
}
for(;;)
{
// printf("\rsystem time: %lu",system_time);
printf("\rsystem time: %.2f seconds",system_time/100.0);
for(i=0;i<65000UL;i++){n+=1;}
}
}
|
the_stack_data/103266170.c | #ifdef HAVE_X11_ICE
# include <X11/ICE/ICElib.h>
static Status test_ICE(void)
{
return IceInitThreads();
}
#endif
#ifdef HAVE_X11_SM
# include <X11/SM/SMlib.h>
# include <stdlib.h>
static void test_SM(void)
{
SmcProtocolVersion(NULL);
}
#endif
#ifdef HAVE_X11_X11
# include <X11/Xlib.h>
static Status test_X11(void)
{
return XInitThreads();
}
#endif
#ifdef HAVE_X11_Xau
# include <X11/Xauth.h>
static char* test_Xau(void)
{
return XauFileName();
}
#endif
#ifdef HAVE_X11_Xcomposite
# include <X11/extensions/Xcomposite.h>
static int test_Xcomposite(void)
{
return XCompositeVersion();
}
#endif
#ifdef HAVE_X11_Xdamage
# include <X11/extensions/Xdamage.h>
static Bool test_Xdamage(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XDamageQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xdmcp
# include <X11/Xdmcp.h>
static int test_Xdmcp(void)
{
BYTE data[1024];
XdmcpBuffer buf = { data, sizeof(data), 0, 0 };
return XdmcpReadRemaining(&buf);
}
#endif
#ifdef HAVE_X11_Xext
# include <X11/Xlib.h>
# include <X11/extensions/Xext.h>
static int test_Xext(void)
{
Display* dpy = XOpenDisplay(NULL);
int ret = XMissingExtension(dpy, "cmake");
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xxf86misc
# include <X11/Xlib.h>
# include <X11/extensions/xf86misc.h>
static Bool test_Xxf86misc(void)
{
Display* dpy = XOpenDisplay(NULL);
Bool ret = XF86MiscSetClientVersion(dpy);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xxf86vm
# include <X11/Xlib.h>
# include <X11/extensions/xf86vmode.h>
static Bool test_Xxf86vm(void)
{
Display* dpy = XOpenDisplay(NULL);
Bool ret = XF86VidModeSetClientVersion(dpy);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xfixes
# include <X11/extensions/Xfixes.h>
static Bool test_Xfixes(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XFixesQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xft
# include <X11/Xft/Xft.h>
static FcBool test_Xft(void)
{
return XftInitFtLibrary();
}
#endif
#ifdef HAVE_X11_Xi
# include <X11/extensions/XInput.h>
static XExtensionVersion* test_Xi(void)
{
Display* dpy = XOpenDisplay(NULL);
XExtensionVersion* ret = XGetExtensionVersion(dpy, "cmake");
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xinerama
# include <X11/extensions/Xinerama.h>
static Bool test_Xinerama(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XineramaQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xkb
# include <X11/XKBlib.h>
static Bool test_Xkb(void)
{
return XkbIgnoreExtension(0);
}
#endif
#ifdef HAVE_X11_xkbfile
// clang-format off
# include <stdio.h>
# include <X11/XKBlib.h>
# include <X11/extensions/XKBfile.h>
# include <stdlib.h>
// clang-format on
static void test_xkbfile(void)
{
Display* dpy = XOpenDisplay(NULL);
XkbInitAtoms(dpy);
XCloseDisplay(dpy);
}
#endif
#ifdef HAVE_X11_Xmu
# include <X11/Xmu/Xmu.h>
# include <stdlib.h>
static Bool test_Xmu(void)
{
return XmuValidArea(NULL);
}
#endif
#ifdef HAVE_X11_Xpm
# include <X11/xpm.h>
static int test_Xpm(void)
{
return XpmAttributesSize();
}
#endif
#ifdef HAVE_X11_Xtst
# include <X11/extensions/XTest.h>
static Status test_Xtst(void)
{
Display* dpy = XOpenDisplay(NULL);
Status ret = XTestDiscard(dpy);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xrandr
# include <X11/extensions/Xrandr.h>
static Bool test_Xrandr(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XRRQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xrender
# include <X11/extensions/Xrender.h>
static Bool test_Xrender(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XRenderQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_XRes
# include <X11/Xlib.h>
# include <X11/extensions/XRes.h>
static Bool test_XRes(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XResQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xss
# include <X11/extensions/scrnsaver.h>
static Bool test_Xss(void)
{
Display* dpy = XOpenDisplay(NULL);
int ev_base;
int err_base;
Bool ret = XScreenSaverQueryExtension(dpy, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xt
# include <X11/Intrinsic.h>
static void test_Xt(void)
{
return XtToolkitInitialize();
}
#endif
#ifdef HAVE_X11_Xutil
# include <X11/Xutil.h>
static int test_Xutil(void)
{
Region r = XCreateRegion();
return XDestroyRegion(r);
}
#endif
#ifdef HAVE_X11_Xv
# include <X11/Xlib.h>
# include <X11/extensions/Xvlib.h>
static int test_Xv(void)
{
Display* dpy = XOpenDisplay(NULL);
unsigned int version;
unsigned int revision;
unsigned int req_base;
unsigned int ev_base;
unsigned int err_base;
int ret =
XvQueryExtension(dpy, &version, &revision, &req_base, &ev_base, &err_base);
XCloseDisplay(dpy);
return ret;
}
#endif
#ifdef HAVE_X11_Xaw
# include <X11/Intrinsic.h>
# include <X11/Xaw/Box.h>
static void test_Xaw(void)
{
XrmOptionDescRec opt_table[] = { { NULL } };
Widget toplevel;
toplevel =
XtInitialize("test", "test", opt_table, XtNumber(opt_table), NULL, NULL);
Widget box =
XtCreateManagedWidget("testbox", boxWidgetClass, toplevel, NULL, 0);
return;
}
#endif
#ifdef HAVE_xcb
# include <xcb/xcb.h>
static void test_xcb(void)
{
int screen_nbr;
xcb_connection_t* connection = xcb_connect(NULL, &screen_nbr);
xcb_disconnect(connection);
}
# ifdef HAVE_xcb_util
# include <xcb/xcb_aux.h>
static void test_xcb_util(void)
{
int screen_nbr;
xcb_connection_t* connection = xcb_connect(NULL, &screen_nbr);
xcb_screen_t* screen = xcb_aux_get_screen(connection, screen_nbr);
xcb_disconnect(connection);
}
# endif
# ifdef HAVE_xcb_xfixes
# include <xcb/xcb_xfixes.h>
static void test_xcb_xfixes(void)
{
int screen_nbr;
xcb_connection_t* connection = xcb_connect(NULL, &screen_nbr);
xcb_xfixes_query_version(connection, 1, 0);
xcb_disconnect(connection);
}
# endif
#endif
#include <stddef.h>
int main(int argc, char* argv[])
{
(void)argv;
void* fptrs[] = {
#ifdef HAVE_X11_ICE
test_ICE,
#endif
#ifdef HAVE_X11_SM
test_SM,
#endif
#ifdef HAVE_X11_X11
test_X11,
#endif
#ifdef HAVE_X11_Xau
test_Xau,
#endif
#ifdef HAVE_X11_Xcomposite
test_Xcomposite,
#endif
#ifdef HAVE_X11_Xdamage
test_Xdamage,
#endif
#ifdef HAVE_X11_Xdmcp
test_Xdmcp,
#endif
#ifdef HAVE_X11_Xext
test_Xext,
#endif
#ifdef HAVE_X11_Xxf86misc
test_Xxf86misc,
#endif
#ifdef HAVE_X11_Xxf86vm
test_Xxf86vm,
#endif
#ifdef HAVE_X11_Xfixes
test_Xfixes,
#endif
#ifdef HAVE_X11_Xft
test_Xft,
#endif
#ifdef HAVE_X11_Xi
test_Xi,
#endif
#ifdef HAVE_X11_Xinerama
test_Xinerama,
#endif
#ifdef HAVE_X11_Xkb
test_Xkb,
#endif
#ifdef HAVE_X11_xkbfile
test_xkbfile,
#endif
#ifdef HAVE_X11_Xmu
test_Xmu,
#endif
#ifdef HAVE_X11_Xpm
test_Xpm,
#endif
#ifdef HAVE_X11_Xtst
test_Xtst,
#endif
#ifdef HAVE_X11_Xrandr
test_Xrandr,
#endif
#ifdef HAVE_X11_Xrender
test_Xrender,
#endif
#ifdef HAVE_X11_XRes
test_XRes,
#endif
#ifdef HAVE_X11_Xss
test_Xss,
#endif
#ifdef HAVE_X11_Xt
test_Xt,
#endif
#ifdef HAVE_X11_Xutil
test_Xutil,
#endif
#ifdef HAVE_X11_Xv
test_Xv,
#endif
#ifdef HAVE_X11_Xaw
test_Xaw,
#endif
#ifdef HAVE_xcb
test_xcb,
#endif
#ifdef HAVE_xcb_util
test_xcb_util,
#endif
#ifdef HAVE_xcb_xfixes
test_xcb_xfixes,
#endif
NULL,
};
// The code here is to convince the compiler to keep the static functions but
// without calling them. This ends up always being "0" because `argc` is
// always 1 in the test harness which always returns the sentinel at the end
// of the array. The array logic is there to ensure that the contents of
// `fptrs` is not optimized out.
return (int)fptrs[(sizeof(fptrs) / sizeof(*fptrs)) - argc];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.