file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/504414.c | #include <stdio.h>
int main()
{
int X,Y;
float price;
scanf("%d %d",&X,&Y);
if (X ==1)
price=Y*4.00;
else if (X==2)
price = Y*4.50;
else if (X == 3)
price = Y*5.00;
else if (X== 4)
price = Y*2.00;
else if (X== 5)
price = Y*1.50;
printf("Total: R$ %.2f\n",price);
return 0;
}
|
the_stack_data/1034114.c | // SPDX-License-Identifier: GPL-2.0+
/*
* Copyright 2013 Albert ARIBAUD <[email protected]>
*/
/**
* These two symbols are declared in a C file so that the linker
* uses R_ARM_RELATIVE relocation, rather than the R_ARM_ABS32 one
* it would use if the symbols were defined in the linker file.
* Using only R_ARM_RELATIVE relocation ensures that references to
* the symbols are correct after as well as before relocation.
*
* We need a 0-byte-size type for these symbols, and the compiler
* does not allow defining objects of C type 'void'. Using an empty
* struct is allowed by the compiler, but causes gcc versions 4.4 and
* below to complain about aliasing. Therefore we use the next best
* thing: zero-sized arrays, which are both 0-byte-size and exempt from
* aliasing warnings.
*/
char __bss_start__[0] __attribute__((section(".__bss_start__")));
char __bss_end__[0] __attribute__((section(".__bss_end__")));
char __image_copy_start[0] __attribute__((section(".__image_copy_start")));
char __image_copy_end[0] __attribute__((section(".__image_copy_end")));
char __rel_dyn_start[0] __attribute__((section(".__rel_dyn_start")));
char __rel_dyn_end[0] __attribute__((section(".__rel_dyn_end")));
char __secure_start[0] __attribute__((section(".__secure_start")));
char __secure_end[0] __attribute__((section(".__secure_end")));
char __secure_stack_start[0] __attribute__((section(".__secure_stack_start")));
char __secure_stack_end[0] __attribute__((section(".__secure_stack_end")));
char __efi_runtime_start[0] __attribute__((section(".__efi_runtime_start")));
char __efi_runtime_stop[0] __attribute__((section(".__efi_runtime_stop")));
char __efi_runtime_rel_start[0] __attribute__((section(".__efi_runtime_rel_start")));
char __efi_runtime_rel_stop[0] __attribute__((section(".__efi_runtime_rel_stop")));
char _end[0] __attribute__((section(".__end")));
|
the_stack_data/1203848.c | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("Oi, mundo!\n");
exit(EXIT_SUCCESS);
} |
the_stack_data/200142969.c | /*
** EPITECH PROJECT, 2017
** my_str_isnum.c
** File description:
** my_str_isnum.c
*/
int my_str_isnum(char const *str)
{
int i = 0;
while (str[i] != '\0') {
if ((str[i] < 48) || (str[i] > 57)) {
return (0);
}
i = i + 1;
}
return (1);
}
|
the_stack_data/72283.c | #include "stdio.h"
int main()
{
FILE *stream;
char str[50] = {0};
int a = 15;
int b = a/2;
float c,d;
printf("%d\n",b); //print the value of b
printf("%3d\n",b); //print the value of b after 3rd position
printf("%03d\n",b); //print the value of b after 3rd position and fill the first two positions with 0's
c = 185460.3;
d = c/3;
printf("%0.4f\n", d); //print the string with precision of 4 characters after the decimal
stream = fopen("test.text", "a");
fprintf(stream , "appending this message with integer %d\n", b); // add the formatted string to the sream
sprintf(str, "adding the integer %d to this buffer", a);
snprintf(str, 4, "adding the integer %d to this buffer", a); // add one less than the size to the string
puts(str); // No check on buffer overrun
fclose(stream);
return 0;
}
|
the_stack_data/218893097.c | /*
* Copyright (c) 2014 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.
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char **argv) {
if (argc == 2) {
long func_arg = strtol(argv[1], NULL, 0);
/* Run sbrk(), return the new program break or (-1) if sbrk() failed. */
if (!strcmp(argv[0], "sbrk")) {
if (sbrk(func_arg) == (void*) -1)
return -1;
return (int) sbrk(0); /* get the new program break */
}
/* Allocate the given amount of memory with malloc. */
if (!strcmp(argv[0], "malloc"))
return (int) malloc(func_arg);
}
return EXIT_FAILURE;
}
|
the_stack_data/72013027.c | #if 0
extern int *pcre_compile(const char *, int, const char **, int *,
const unsigned char *);
#endif
// int pcre_compile(const char *, int, const char **, int *,const unsigned char *);
// This function declaration's parameters are not named, so no source position information
// will be available in EDG.
void foobar(int,int);
// The use of this declaration is not enough in EDG to define source position information to the
// function parameters (because the previous declaration's function parameters were not named).
void foobar(int x,int y);
// The use of this defining declaration will cause source position information to be generated
// for the function parameters.
// void foobar(int x,int y) {}
|
the_stack_data/332359.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static doublecomplex c_b1 = {1.,0.};
static integer c__1 = 1;
static integer c_n1 = -1;
/* > \brief \b ZHETRS_AA_2STAGE */
/* @generated from SRC/dsytrs_aa_2stage.f, fortran d -> c, Mon Oct 30 11:59:02 2017 */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZHETRS_AA_2STAGE + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zhetrs_
aa_2stage.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zhetrs_
aa_2stage.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zhetrs_
aa_2stage.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZHETRS_AA_2STAGE( UPLO, N, NRHS, A, LDA, TB, LTB, IPIV, */
/* IPIV2, B, LDB, INFO ) */
/* CHARACTER UPLO */
/* INTEGER N, NRHS, LDA, LTB, LDB, INFO */
/* INTEGER IPIV( * ), IPIV2( * ) */
/* COMPLEX*16 A( LDA, * ), TB( * ), B( LDB, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZHETRS_AA_2STAGE solves a system of linear equations A*X = B with a */
/* > hermitian matrix A using the factorization A = U**H*T*U or */
/* > A = L*T*L**H computed by ZHETRF_AA_2STAGE. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > Specifies whether the details of the factorization are stored */
/* > as an upper or lower triangular matrix. */
/* > = 'U': Upper triangular, form is A = U**H*T*U; */
/* > = 'L': Lower triangular, form is A = L*T*L**H. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right hand sides, i.e., the number of columns */
/* > of the matrix B. NRHS >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] A */
/* > \verbatim */
/* > A is COMPLEX*16 array, dimension (LDA,N) */
/* > Details of factors computed by ZHETRF_AA_2STAGE. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] TB */
/* > \verbatim */
/* > TB is COMPLEX*16 array, dimension (LTB) */
/* > Details of factors computed by ZHETRF_AA_2STAGE. */
/* > \endverbatim */
/* > */
/* > \param[in] LTB */
/* > \verbatim */
/* > LTB is INTEGER */
/* > The size of the array TB. LTB >= 4*N. */
/* > \endverbatim */
/* > */
/* > \param[in] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > Details of the interchanges as computed by */
/* > ZHETRF_AA_2STAGE. */
/* > \endverbatim */
/* > */
/* > \param[in] IPIV2 */
/* > \verbatim */
/* > IPIV2 is INTEGER array, dimension (N) */
/* > Details of the interchanges as computed by */
/* > ZHETRF_AA_2STAGE. */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is COMPLEX*16 array, dimension (LDB,NRHS) */
/* > On entry, the right hand side matrix B. */
/* > On exit, the solution matrix X. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2017 */
/* > \ingroup complex16SYcomputational */
/* ===================================================================== */
/* Subroutine */ int zhetrs_aa_2stage_(char *uplo, integer *n, integer *nrhs,
doublecomplex *a, integer *lda, doublecomplex *tb, integer *ltb,
integer *ipiv, integer *ipiv2, doublecomplex *b, integer *ldb,
integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, i__1;
/* Local variables */
integer ldtb;
extern logical lsame_(char *, char *);
logical upper;
extern /* Subroutine */ int ztrsm_(char *, char *, char *, char *,
integer *, integer *, doublecomplex *, doublecomplex *, integer *,
doublecomplex *, integer *);
integer nb;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen), zgbtrs_(
char *, integer *, integer *, integer *, integer *, doublecomplex
*, integer *, integer *, doublecomplex *, integer *, integer *), zlaswp_(integer *, doublecomplex *, integer *, integer *,
integer *, integer *, integer *);
/* -- LAPACK computational routine (version 3.8.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2017 */
/* ===================================================================== */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--tb;
--ipiv;
--ipiv2;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
/* Function Body */
*info = 0;
upper = lsame_(uplo, "U");
if (! upper && ! lsame_(uplo, "L")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*nrhs < 0) {
*info = -3;
} else if (*lda < f2cmax(1,*n)) {
*info = -5;
} else if (*ltb < *n << 2) {
*info = -7;
} else if (*ldb < f2cmax(1,*n)) {
*info = -11;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("ZHETRS_AA_2STAGE", &i__1, (ftnlen)16);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *nrhs == 0) {
return 0;
}
/* Read NB and compute LDTB */
nb = (integer) tb[1].r;
ldtb = *ltb / *n;
if (upper) {
/* Solve A*X = B, where A = U**H*T*U. */
if (*n > nb) {
/* Pivot, P**T * B -> B */
i__1 = nb + 1;
zlaswp_(nrhs, &b[b_offset], ldb, &i__1, n, &ipiv[1], &c__1);
/* Compute (U**H \ B) -> B [ (U**H \P**T * B) ] */
i__1 = *n - nb;
ztrsm_("L", "U", "C", "U", &i__1, nrhs, &c_b1, &a[(nb + 1) *
a_dim1 + 1], lda, &b[nb + 1 + b_dim1], ldb);
}
/* Compute T \ B -> B [ T \ (U**H \P**T * B) ] */
zgbtrs_("N", n, &nb, &nb, nrhs, &tb[1], &ldtb, &ipiv2[1], &b[b_offset]
, ldb, info);
if (*n > nb) {
/* Compute (U \ B) -> B [ U \ (T \ (U**H \P**T * B) ) ] */
i__1 = *n - nb;
ztrsm_("L", "U", "N", "U", &i__1, nrhs, &c_b1, &a[(nb + 1) *
a_dim1 + 1], lda, &b[nb + 1 + b_dim1], ldb);
/* Pivot, P * B -> B [ P * (U \ (T \ (U**H \P**T * B) )) ] */
i__1 = nb + 1;
zlaswp_(nrhs, &b[b_offset], ldb, &i__1, n, &ipiv[1], &c_n1);
}
} else {
/* Solve A*X = B, where A = L*T*L**H. */
if (*n > nb) {
/* Pivot, P**T * B -> B */
i__1 = nb + 1;
zlaswp_(nrhs, &b[b_offset], ldb, &i__1, n, &ipiv[1], &c__1);
/* Compute (L \ B) -> B [ (L \P**T * B) ] */
i__1 = *n - nb;
ztrsm_("L", "L", "N", "U", &i__1, nrhs, &c_b1, &a[nb + 1 + a_dim1]
, lda, &b[nb + 1 + b_dim1], ldb);
}
/* Compute T \ B -> B [ T \ (L \P**T * B) ] */
zgbtrs_("N", n, &nb, &nb, nrhs, &tb[1], &ldtb, &ipiv2[1], &b[b_offset]
, ldb, info);
if (*n > nb) {
/* Compute (L**H \ B) -> B [ L**H \ (T \ (L \P**T * B) ) ] */
i__1 = *n - nb;
ztrsm_("L", "L", "C", "U", &i__1, nrhs, &c_b1, &a[nb + 1 + a_dim1]
, lda, &b[nb + 1 + b_dim1], ldb);
/* Pivot, P * B -> B [ P * (L**H \ (T \ (L \P**T * B) )) ] */
i__1 = nb + 1;
zlaswp_(nrhs, &b[b_offset], ldb, &i__1, n, &ipiv[1], &c_n1);
}
}
return 0;
/* End of ZHETRS_AA_2STAGE */
} /* zhetrs_aa_2stage__ */
|
the_stack_data/68886770.c | #include <stdio.h>
#define PI 3.14159
int main(){
double a, b, c;
scanf("%lf %lf %lf", &a, &b, &c);
printf("TRIANGULO: %.3lf\n", a*c/2);
printf("CIRCULO: %.3lf\n", PI*c*c );
printf("TRAPEZIO: %.3lf\n", ((a+b)*c)/2);
printf("QUADRADO: %.3lf\n", b*b);
printf("RETANGULO: %.3lf\n", a*b);
return 0;
} |
the_stack_data/4173.c | #include<stdio.h>
void main()
{
int n,j,k;
printf("enter the length\n");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
printf(" ");
for(k=0;k<=i;k++)
printf("#");
printf("\n");
}
} |
the_stack_data/887491.c | #include <stdio.h>
int main()
{
printf("Hello World!\n");
return 0;
}
|
the_stack_data/159514915.c |
/*Este codigo usa el modelo de montecarlo para estimar el valor de la constante PI */
/* este codigo es original de http://stackoverflow.com/questions/17659652/calculating-pi-using-monte-carlo-method-gives-imprecise-answer*/
/* Ha sido modificado por Alejandro Parra Briones para fines academicos*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <unistd.h>
#define sqr2(x) ((x)*(x))
#define frand() ((double) rand() / (RAND_MAX))
#define MAXLEN (atoi(argv[1]))
#define SLEEP (argc == 3 && argv[2] == "sleep")
// Funcion para verificar si cayo dentro del circulo
int circumscribed(int radius)
{
float xcoord = frand();
float ycoord = frand();
float coord = sqr2(xcoord) + sqr2(ycoord);
return coord <= radius ? 1 : -1;
}
int main(int argc, char *argv[])
{
int i, j, circles = 0, rect = 0;
float pi;
srand(time(NULL));
for(i = 0; i < MAXLEN; i++)
{
if(circumscribed(1) > 0) // What?
circles++;
if(SLEEP)
usleep(rand() % 3); // Sleep from 0-2 seconds
}
pi = 4 * ((float) circles/(float) MAXLEN);
printf("After %d iterations circles is %d PI is %2.4f : \n", MAXLEN, circles, pi);
return 0;
}
|
the_stack_data/84338.c | /*Mouse simulation using uinput kernel module
* Mouse Operations Supported:
* 1. Mouse left/right click
* 2. Mouse Cursor Movement Up/Down/Left/Right
* 3. Press and Hold Mouse left click
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <time.h>
#include <stdbool.h>
#define ERROR(str, args...) \
do \
{ \
perror(str); \
exit(EXIT_FAILURE); \
} while (0)
typedef enum
{
RELEASE_KEY = 0,
PRESS_KEY
} KEY_ACTION;
int report_input_event(int fd)
{
struct input_event report_ev;
report_ev.type = EV_SYN;
report_ev.code = SYN_REPORT;
report_ev.value = 0;
int ret = write(fd, &report_ev, sizeof(struct input_event));
return ret;
}
int hold_mouse_button_pressed(int fd, bool left, bool right)
{
int ret;
struct input_event mouse_ev;
mouse_ev.type = EV_KEY;
mouse_ev.code = left ? BTN_LEFT : BTN_RIGHT;
mouse_ev.value = PRESS_KEY;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse click press");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
return ret;
}
/* set left/right value to true/false for left/right button click */
int click_mouse_button(int fd, bool left, bool right)
{
int ret;
struct input_event mouse_ev;
mouse_ev.type = EV_KEY;
mouse_ev.code = left ? BTN_LEFT : BTN_RIGHT;
mouse_ev.value = PRESS_KEY;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse click press");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
mouse_ev.value = RELEASE_KEY;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse click release");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
return ret;
}
int move_cursor_rel(int fd, int rel_x, int rel_y)
{
int ret;
struct input_event mouse_ev;
mouse_ev.type = EV_REL;
mouse_ev.code = rel_x ? REL_X : REL_Y;
mouse_ev.value = rel_x ? rel_x : rel_y;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
return ret;
}
int move_cursor_abs(int fd, int abs_x, int abs_y)
{
int ret;
struct input_event mouse_ev;
mouse_ev.type = EV_ABS;
mouse_ev.code = ABS_X;
mouse_ev.value = abs_x;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
mouse_ev.code = ABS_Y;
mouse_ev.value = abs_y;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
mouse_ev.type = EV_KEY;
mouse_ev.code = BTN_TOUCH;
mouse_ev.value = 1;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
mouse_ev.value = 0;
ret = write(fd, &mouse_ev, sizeof(struct input_event));
if (ret < 0)
ERROR("write error: mouse");
if (report_input_event(fd) < 0)
ERROR("write error: report event");
return ret;
}
int main(void)
{
int fd_mouse;
struct uinput_user_dev uidev;
struct input_event ev;
struct timeval timeval_t;
char ch = 0;
int mouse_sensitivity_default = 20;
fd_mouse = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd_mouse < 0)
ERROR("error: open mouse fd");
if (ioctl(fd_mouse, UI_SET_EVBIT, EV_KEY) < 0)
ERROR("error: ioctl: UI_SET_EVBIT");
if (ioctl(fd_mouse, UI_SET_KEYBIT, BTN_LEFT) < 0)
ERROR("error: ioctl: UI_SET_KEYBIT");
if (ioctl(fd_mouse, UI_SET_KEYBIT, BTN_RIGHT) < 0)
ERROR("error: ioctl: UI_SET_KEYBIT");
if (ioctl(fd_mouse, UI_SET_EVBIT, EV_REL) < 0)
ERROR("error: ioctl: UI_SET_EVBIT");
if (ioctl(fd_mouse, UI_SET_RELBIT, REL_X) < 0)
ERROR("error: ioctl: UI_SET_RELBIT");
if (ioctl(fd_mouse, UI_SET_RELBIT, REL_Y) < 0)
ERROR("error: ioctl: UI_SET_RELBIT");
/* for touch input with x,y coordinate */
if (ioctl(fd_mouse, UI_SET_EVBIT, EV_ABS) < 0)
ERROR("error: ioctl: UI_SET_RELBIT");
if (ioctl(fd_mouse, UI_SET_EVBIT, ABS_X) < 0)
ERROR("error: ioctl: UI_SET_RELBIT");
if (ioctl(fd_mouse, UI_SET_EVBIT, ABS_Y) < 0)
ERROR("error: ioctl: UI_SET_RELBIT");
memset(&uidev, 0, sizeof(uidev));
snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "virtual mouse device");
uidev.id.bustype = BUS_USB;
uidev.id.vendor = 0x1;
uidev.id.product = 0x2;
uidev.id.version = 1;
if (write(fd_mouse, &uidev, sizeof(uidev)) < 0)
ERROR("error: write");
if (ioctl(fd_mouse, UI_DEV_CREATE) < 0)
ERROR("error: ioctl");
while (ch != 'q')
{
printf("\n\nselect operation: \
\n w:cursor up \n d:cursor right \n a:cursor left \n z:cursor down \
\n l:left click \n r:right click \n h: hold left mouse button pressed \n q:quit \n");
scanf("%c", &ch);
switch (ch)
{
case 'w':
{
move_cursor_rel(fd_mouse, 0, -(mouse_sensitivity_default));
break;
}
case 'd':
{
move_cursor_rel(fd_mouse, mouse_sensitivity_default, 0);
break;
}
case 'a':
{
move_cursor_rel(fd_mouse, -(mouse_sensitivity_default), 0);
break;
}
case 'z':
{
move_cursor_rel(fd_mouse, 0, mouse_sensitivity_default);
break;
}
case 'l':
{
click_mouse_button(fd_mouse, 1, 0);
break;
}
case 'r':
{
click_mouse_button(fd_mouse, 0, 1);
break;
}
case 'h':
{
hold_mouse_button_pressed(fd_mouse, 1, 0);
break;
}
case 'q':
{
break;
}
default:
{
break;
}
}
}
sleep(1);
if (ioctl(fd_mouse, UI_DEV_DESTROY) < 0)
ERROR("error: ioctl");
close(fd_mouse);
return 0;
}
|
the_stack_data/957420.c | #include <stdio.h>
void f2(int d)
{
d = d + 1;
}
void f(int *c)
{
*c = *c - 2;
f2(*c);
}
int main()
{
int a = 32, b = 27;
int *p = &a;
int *q;
*p = *p + a;
q = &b;
*q = *q + b;
f(&a);
f(&b);
if (a > b)
{
*q = *q + b;
}
else
{
*p = *p - a;
}
printf("%d\n", a);
printf("%d\n", b);
return 0;
} |
the_stack_data/43138.c | /*
A basic test suite for Portland State University CS333 Operating Systems Project 2.
Created by Joe Coleman
*/
#ifdef CS333_P2
#include "types.h"
#include "user.h"
// comment out tests for features the student doesn't have implemented
// Note the CPUTIME_TEST requires GETPROCS_TEST
#define GETPROCS_TEST
#ifdef GETPROCS_TEST
#include "uproc.h"
#endif
#ifdef GETPROCS_TEST
// Fork to 64 process and then make sure we get all when passing table array
// of sizes 1, 16, 64, 72. NOTE: caller does all forks.
static int
testprocarray(int max, int expected_ret){
struct uproc * table;
int ret, success = 0;
table = malloc(sizeof(struct uproc) * max); // bad code, assumes success
if (!table) {
printf(2, "Error: malloc() call failed. %s at line %d\n", __FUNCTION__, __LINE__);
exit();
}
ret = getprocs(max, table);
sleep(2000);
if (ret != expected_ret){
printf(2, "FAILED: getprocs(%d) returned %d, expected %d\n", max, ret, expected_ret);
success = -1;
}
else{
printf(2, "getprocs() was asked for %d processes and returned %d. SUCCESS\n", max, expected_ret);
}
free(table);
return success;
}
static int
testinvalidarray(void){
struct uproc * table;
int ret;
table = malloc(sizeof(struct uproc));
if (!table) {
printf(2, "Error: malloc() call failed. %s at line %d\n", __FUNCTION__, __LINE__);
exit();
}
ret = getprocs(1024, table);
free(table);
if(ret >= 0){
printf(2, "FAILED: called getprocs with max way larger than table and returned %d, not error\n", ret);
return -1;
}
return 0;
}
static void
testgetprocs(){
int ret, success;
printf(1, "\n----------\nRunning GetProcs Test\n----------\n");
printf(1, "Filling the proc[] array with dummy processes\n");
// Fork until no space left in ptable
ret = fork();
if (ret == 0){
while((ret = fork()) == 0);
if(ret > 0){
wait();
exit();
}
// Only return left is -1, which is no space left in ptable
success = testinvalidarray();
success |= testprocarray( 1, 1);
success |= testprocarray(16, 16);
success |= testprocarray(64, 64);
success |= testprocarray(72, 64);
if (success == 0)
printf(1, "** All Tests Passed **\n");
exit();
}
wait();
}
#endif
int
main(int argc, char *argv[])
{
#ifdef GETPROCS_TEST
testgetprocs(); // no need to pass argv[0]
#endif
printf(1, "\n** End of Tests **\n");
exit();
}
#endif
|
the_stack_data/70449417.c | #include <stdio.h>
int main(){
for(int row=1;row<10;row++){
for(int column=1;column<=row;column++){
printf("%d*%d=%d\t",column,row,row*column);
}
printf("\n");
}
return 0;
}
|
the_stack_data/57949110.c | /* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-tailc-details" } */
/* LLVM LOCAL test not applicable */
/* { dg-require-fdump "" } */
extern void *alloca (__SIZE_TYPE__);
int q(int a);
int *v;
int
t(int a)
{
int r,r1;
if (a)
r1=r = q(a-1);
else
return 0;
/* Dead alloca should not disturb us. */
if (r!=r1)
v=alloca(r);
return r;
}
/* { dg-final { scan-tree-dump-times "Found tail call" 1 "tailc"} } */
/* { dg-final { cleanup-tree-dump "tailc" } } */
|
the_stack_data/165766753.c | /*
* sr_replicate.c: ipv6 segment routing replicator for multicast
*
* Copyright (c) 2016 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if DPDK > 0 /* Cannot run replicate without DPDK */
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/pg/pg.h>
#include <vnet/sr/sr.h>
#include <vnet/devices/dpdk/dpdk.h>
#include <vnet/dpdk_replication.h>
#include <vnet/ip/ip.h>
#include <vppinfra/hash.h>
#include <vppinfra/error.h>
#include <vppinfra/elog.h>
typedef struct {
/* convenience */
vlib_main_t * vlib_main;
vnet_main_t * vnet_main;
} sr_replicate_main_t;
sr_replicate_main_t sr_replicate_main;
typedef struct {
ip6_address_t src, dst;
u16 length;
u32 next_index;
u32 tunnel_index;
u8 sr[256];
} sr_replicate_trace_t;
/* packet trace format function */
static u8 * format_sr_replicate_trace (u8 * s, va_list * args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
sr_replicate_trace_t * t = va_arg (*args, sr_replicate_trace_t *);
ip6_main_t * im = &ip6_main;
ip6_sr_main_t * sm = &sr_main;
ip6_sr_tunnel_t *tun = pool_elt_at_index (sm->tunnels, t->tunnel_index);
ip6_fib_t * rx_fib, * tx_fib;
rx_fib = find_ip6_fib_by_table_index_or_id (im, tun->rx_fib_index,
IP6_ROUTE_FLAG_FIB_INDEX);
tx_fib = find_ip6_fib_by_table_index_or_id (im, tun->tx_fib_index,
IP6_ROUTE_FLAG_FIB_INDEX);
s = format
(s, "SR-REPLICATE: next %s ip6 src %U dst %U len %u\n"
" rx-fib-id %d tx-fib-id %d\n%U",
"ip6-lookup",
format_ip6_address, &t->src,
format_ip6_address, &t->dst, t->length,
rx_fib->table_id, tx_fib->table_id,
format_ip6_sr_header, t->sr, 0 /* print_hmac */);
return s;
}
#define foreach_sr_replicate_error \
_(REPLICATED, "sr packets replicated") \
_(NO_BUFFERS, "error allocating buffers for replicas") \
_(NO_REPLICAS, "no replicas were needed") \
_(NO_BUFFER_DROPS, "sr no buffer drops")
typedef enum {
#define _(sym,str) SR_REPLICATE_ERROR_##sym,
foreach_sr_replicate_error
#undef _
SR_REPLICATE_N_ERROR,
} sr_replicate_error_t;
static char * sr_replicate_error_strings[] = {
#define _(sym,string) string,
foreach_sr_replicate_error
#undef _
};
typedef enum {
SR_REPLICATE_NEXT_IP6_LOOKUP,
SR_REPLICATE_N_NEXT,
} sr_replicate_next_t;
static uword
sr_replicate_node_fn (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
u32 n_left_from, * from, * to_next;
sr_replicate_next_t next_index;
int pkts_replicated = 0;
ip6_sr_main_t * sm = &sr_main;
int no_buffer_drops = 0;
vlib_buffer_free_list_t * fl;
unsigned socket_id = rte_socket_id();
vlib_buffer_main_t * bm = vm->buffer_main;
from = vlib_frame_vector_args (frame);
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
fl = vlib_buffer_get_free_list (vm, VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index,
to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0, hdr_bi0;
vlib_buffer_t * b0, * orig_b0;
struct rte_mbuf * orig_mb0 = 0, * hdr_mb0 = 0, * clone0 = 0;
struct rte_mbuf ** hdr_vec = 0, ** rte_mbuf_vec = 0;
ip6_sr_policy_t * pol0 = 0;
ip6_sr_tunnel_t * t0 = 0;
ip6_sr_header_t * hdr_sr0 = 0;
ip6_header_t * ip0 = 0, * hdr_ip0 = 0;
int num_replicas = 0;
int i;
bi0 = from[0];
b0 = vlib_get_buffer (vm, bi0);
orig_b0 = b0;
pol0 = pool_elt_at_index (sm->policies,
vnet_buffer(b0)->ip.save_protocol);
ip0 = vlib_buffer_get_current (b0);
/* Skip forward to the punch-in point */
vlib_buffer_advance (b0, sizeof(*ip0));
orig_mb0 = rte_mbuf_from_vlib_buffer (b0);
i16 delta0 = vlib_buffer_length_in_chain (vm, orig_b0)
- (i16) orig_mb0->pkt_len;
u16 new_data_len0 = (u16)((i16) orig_mb0->data_len + delta0);
u16 new_pkt_len0 = (u16)((i16) orig_mb0->pkt_len + delta0);
orig_mb0->data_len = new_data_len0;
orig_mb0->pkt_len = new_pkt_len0;
orig_mb0->data_off = (u16)(RTE_PKTMBUF_HEADROOM + b0->current_data);
/*
Before entering loop determine if we can allocate:
- all the new HEADER RTE_MBUFs and assign them to a vector
- all the clones
if successful, then iterate over vectors of resources
*/
num_replicas = vec_len (pol0->tunnel_indices);
if (PREDICT_FALSE(num_replicas == 0))
{
b0->error = node->errors[SR_REPLICATE_ERROR_NO_REPLICAS];
goto do_trace0;
}
vec_reset_length (hdr_vec);
vec_reset_length (rte_mbuf_vec);
for (i=0; i < num_replicas; i++)
{
hdr_mb0 = rte_pktmbuf_alloc(bm->pktmbuf_pools[socket_id]);
if (i < (num_replicas - 1) )
/* Not the last tunnel to process */
clone0 = rte_pktmbuf_clone
(orig_mb0, bm->pktmbuf_pools[socket_id]);
else
/* Last tunnel to process, use original MB */
clone0 = orig_mb0;
if (PREDICT_FALSE( !clone0 || !hdr_mb0 ))
{
b0->error = node->errors[SR_REPLICATE_ERROR_NO_BUFFERS];
vec_foreach_index (i, rte_mbuf_vec)
{
rte_pktmbuf_free(rte_mbuf_vec[i]);
}
vec_free (rte_mbuf_vec);
vec_foreach_index (i, hdr_vec)
{
rte_pktmbuf_free(hdr_vec[i]);
}
vec_free (hdr_vec);
goto do_trace0;
}
vec_add1 (hdr_vec, hdr_mb0);
vec_add1 (rte_mbuf_vec, clone0);
}
for (i=0; i < num_replicas; i++)
{
vlib_buffer_t * hdr_b0;
t0 = vec_elt_at_index (sm->tunnels, pol0->tunnel_indices[i]);
/* Our replicas */
hdr_mb0 = hdr_vec[i];
clone0 = rte_mbuf_vec[i];
hdr_mb0->data_len = sizeof (*ip0) + vec_len (t0->rewrite);
hdr_mb0->pkt_len = hdr_mb0->data_len +
vlib_buffer_length_in_chain (vm, orig_b0);
hdr_b0 = vlib_buffer_from_rte_mbuf (hdr_mb0);
vlib_buffer_init_for_free_list (hdr_b0, fl);
memcpy (hdr_b0->data, ip0, sizeof (*ip0));
memcpy (hdr_b0->data + sizeof (*ip0), t0->rewrite,
vec_len (t0->rewrite));
hdr_b0->current_data = 0;
hdr_b0->current_length = sizeof (*ip0) + vec_len (t0->rewrite);
hdr_b0->flags = orig_b0->flags | VLIB_BUFFER_NEXT_PRESENT;
hdr_b0->total_length_not_including_first_buffer =
hdr_mb0->pkt_len - hdr_b0->current_length;
hdr_ip0 = (ip6_header_t *) hdr_b0->data;
hdr_ip0->payload_length = clib_host_to_net_u16(hdr_mb0->data_len);
hdr_sr0 = (ip6_sr_header_t *) (hdr_ip0+1);
hdr_sr0->protocol = hdr_ip0->protocol;
hdr_ip0->protocol = 43;
/* Rewrite the ip6 dst address */
hdr_ip0->dst_address.as_u64[0] = t0->first_hop.as_u64[0];
hdr_ip0->dst_address.as_u64[1] = t0->first_hop.as_u64[1];
sr_fix_hmac (sm, hdr_ip0, hdr_sr0);
/* prepend new header to invariant piece */
hdr_mb0->next = clone0;
hdr_b0->next_buffer = vlib_get_buffer_index (vm, vlib_buffer_from_rte_mbuf (clone0));
/* update header's fields */
hdr_mb0->pkt_len = (uint16_t)(hdr_mb0->data_len + clone0->pkt_len);
hdr_mb0->nb_segs = (uint8_t)(clone0->nb_segs + 1);
/* copy metadata from source packet*/
hdr_mb0->port = clone0->port;
hdr_mb0->vlan_tci = clone0->vlan_tci;
hdr_mb0->vlan_tci_outer = clone0->vlan_tci_outer;
hdr_mb0->tx_offload = clone0->tx_offload;
hdr_mb0->hash = clone0->hash;
hdr_mb0->ol_flags = clone0->ol_flags;
__rte_mbuf_sanity_check(hdr_mb0, 1);
hdr_bi0 = vlib_get_buffer_index (vm, hdr_b0);
to_next[0] = hdr_bi0;
to_next += 1;
n_left_to_next -= 1;
if (n_left_to_next == 0)
{
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
vlib_get_next_frame (vm, node, next_index,
to_next, n_left_to_next);
}
pkts_replicated++;
}
from += 1;
n_left_from -= 1;
do_trace0:
if (PREDICT_FALSE(b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_replicate_trace_t *tr = vlib_add_trace (vm, node,
b0, sizeof (*tr));
tr->tunnel_index = t0 - sm->tunnels;
if (hdr_ip0)
{
memcpy (tr->src.as_u8, hdr_ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
memcpy (tr->dst.as_u8, hdr_ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (hdr_ip0->payload_length)
tr->length = clib_net_to_host_u16(hdr_ip0->payload_length);
else
tr->length = 0;
tr->next_index = next_index;
memcpy (tr->sr, hdr_sr0, sizeof (tr->sr));
}
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
vlib_node_increment_counter (vm, sr_replicate_node.index,
SR_REPLICATE_ERROR_REPLICATED, pkts_replicated);
vlib_node_increment_counter (vm, sr_replicate_node.index,
SR_REPLICATE_ERROR_NO_BUFFER_DROPS, no_buffer_drops);
return frame->n_vectors;
}
VLIB_REGISTER_NODE (sr_replicate_node) = {
.function = sr_replicate_node_fn,
.name = "sr-replicate",
.vector_size = sizeof (u32),
.format_trace = format_sr_replicate_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = ARRAY_LEN(sr_replicate_error_strings),
.error_strings = sr_replicate_error_strings,
.n_next_nodes = SR_REPLICATE_N_NEXT,
.next_nodes = {
[SR_REPLICATE_NEXT_IP6_LOOKUP] = "ip6-lookup",
},
};
VLIB_NODE_FUNCTION_MULTIARCH (sr_replicate_node, sr_replicate_node_fn)
clib_error_t *sr_replicate_init (vlib_main_t *vm)
{
sr_replicate_main_t *msm = &sr_replicate_main;
msm->vlib_main = vm;
msm->vnet_main = vnet_get_main();
return 0;
}
VLIB_INIT_FUNCTION(sr_replicate_init);
#endif /* DPDK */
|
the_stack_data/231392815.c |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXARGS 10
struct commands
{
char *arg[4];
};
int
main()
{
char *line = NULL;
size_t bufsize = 0;
char ** chArray = malloc(128 * sizeof(char*));
char *pch;
int pos = 0;
int pos2 = 0;
/*int arPos;
int wc;
int rc;*/
struct commands com[5];
char osh[4] = "osh>";
while(1){
printf("%s", osh);
/*com = malloc(sizeof(MAXARGS/2));*/
getline(&line, &bufsize, stdin);
if(strcmp(line, "exit\n")==0){
return 0;
}
pch = strtok( line, " \n");
int i ;
int x;
for (i = 0 ; i <= 3 ; i++ ) {
for (x =0; x<= 3; x++){
if(com[i].arg[x] !=NULL){
com[i].arg[x] = NULL;
}
}
}
while(pch != NULL) {
if(strcmp(pch,"|")==0){
pos++;
pos2=0;
pch=strtok(NULL, " \n");
}
com[pos].arg[pos2]= pch;
pos2 = pos2 + 1;
pch = strtok( NULL, "|\n ");
}
int a;
int b;
for ( a = 0 ; a <= 2 ; a++ ) {
for ( b = 0; b <= 3; b++){
if(com[a].arg[b] != NULL){
printf("%s", com[a].arg[b]);
}
}
printf("\n");
}
chArray[pos] = NULL;
/*execvp(chArray[0], chArray);*/
}
/*
arPos = pos-1;
while(arPos>0 ){
if(*chArray[arPos] == '|'){
int pip[2];
pipe(pip);
rc = fork();
if (rc<0){
fprintf(stderr, "fork Failed\n");
exit(1);
}
else if (rc ==0) {
dup2(pip[1],0);
close(pip[1]);
execvp(chArray[arPos +1], chArray);
printf(" shouldnt hit here");
}
else {
wc = wait(NULL);
dup2(pip[0], 1);
close(pip[0]);
}
chArray[arPos] =NULL;
}
arPos--;
}
if(pipeDelim == 0){
execvp(chArray[0], chArray);
}
*/
return 0;
}
|
the_stack_data/82951157.c | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/time.h>
struct chunk {
int size;
int used;
struct chunk *next;
};
extern struct chunk* flist;
void check(int expr, const char* message) {
if (!expr) {
printf("%s\n", message);
exit(1);
}
}
int main (int argc, char* argv[]) {
void *current;
void *init = sbrk(0);
free(0); // shouldn't crash
void* empty = malloc(0); // should return null
check(empty == 0, "test1: size 0 does not return NULL");
check(flist == 0, "test2: flist should be NULL to start");
void *request1 = malloc(sizeof(char)*32);
current = sbrk(0);
check(flist == 0, "test 3: flist should be empty after first malloc");
check((current-init) == 32+16, "test 4: wrong amount allocated");
struct chunk* header1 = (struct chunk*) ((struct chunk*) request1 - 1);
check(header1->size == 32, "test 5: header size wrong");
check(header1->used == 32, "test 6: header used wrong");
free(request1);
check(flist != 0, "test 7: flist should be non-empty after free");
request1 = malloc(sizeof(char) * 16);
current = sbrk(0);
check(flist == 0, "test 8: flist should be empty");
check((current-init) == 32+16, "test9: wrong amount allocated");
header1 = (struct chunk*) ((struct chunk*) request1 - 1);
check(header1->size == 32, "test 10: header size wrong");
check(header1->used == 16, "test 11: header used wrong");
free(request1);
void* request2 = malloc(sizeof(char) * 64);
current = sbrk(0);
check(flist != 0, "test 12: flist should not be empty");
check((current-init) == 32+2*16+64, "test 13: current-init wrong size");
struct chunk* header2 = (struct chunk*) ((struct chunk*) request2 - 1);
check(header2->size == 64, "test 14: header size wrong");
check(header2->used == 64, "test 15: header used wrong");
free(request2);
check(flist->size == 64, "test 16: flist first node size");
check(flist->next != 0, "test 17: flist empty");
check(flist->next->size == 32, "test 18: flist second node size");
return 0 ;
}
|
the_stack_data/165765988.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int l1,l2, i, j, t, k;
char s1[1000], s2[1000];
scanf("%d", &t);
for(k=1; k<=t; k++)
{
scanf("%s%s", s1, s2);
for(l1=1; s1[l1]!='\0'; l1++);
for(l2=1; s2[l2]!='\0'; l2++);
if(l1!=l2)
{
printf("NO\n");
exit(0);
}
for(i=0; i<=l1; i++)
{
for(j=0; j<=l1; j++)
{
if(s1[i]==s2[j])
{
s1[i]='\0';
s2[j]='\0';
}
else
{
continue;
}
}
}
if(strlen(s1)==0 && strlen(s2)==0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
} |
the_stack_data/529838.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strequ.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmorer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/02 12:20:15 by gmorer #+# #+# */
/* Updated: 2016/01/04 16:41:40 by gmorer ### ########.fr */
/* */
/* ************************************************************************** */
int ft_strequ(char const *s1, char const *s2)
{
unsigned int i;
i = 0;
while (s1[i] != '\0' || s2[i] != '\0')
{
if (s1[i] != s2[i])
return (0);
i++;
}
if (s1[i] != s2[i])
return (0);
else
return (1);
}
|
the_stack_data/153267421.c |
/*
* Date : 2015. 4. 28.
* Author : Kate
* Purpose: structure
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
typedef struct complexNum{
double x;
double y;
//x is real number and y is imaginary number
}Complex;
void addComplex(Complex c1, Complex c2){
printf("The result is %3.2f + %3.2fi\n", c1.x + c2.x , c1.y + c2.y);
return;
}
void subtractComplex(Complex c1, Complex c2){
printf("The result is %3.2f + %3.2fi\n", c1.x - c2.x, c1.y - c2.y);
return;
}
void timeComplex(Complex c1, Complex c2){
printf("The result is %3.2f + %3.2fi\n", c1.x *c2.x - c1.y * c2.y, c1.y*c2.x + c2.y*c1.x);
return;
}
double absoluteNum(Complex c1){
return sqrt(c1.x*c1.x + c1.y*c1.y);
}
int main(void){
Complex c1, c2;
puts("enter the first x, y ( x + yi ) :");
scanf("%lf %lf", &c1.x, &c1.y);
puts("enter the second x, y (x + yi) :");
scanf("%lf %lf", &c2.x, &c2.y);
addComplex(c1, c2);
subtractComplex(c1, c2);
timeComplex(c1, c2);
printf("The absolute number of first is %3.2f\n", absoluteNum(c1));
printf("The absolute number of second is %3.2f\n", absoluteNum(c2));
return 0;
}
|
the_stack_data/9513957.c | // strncpy(s1, s2, n) copies the first ‘n’ characters of the second string s2 to the first string s1.
#include <string.h>
#include <stdio.h>
int main()
{
char s2[] = "Hello";
char s1[10];
strncpy(s1, s2, 2);
s1[2] = '\0'; /* null character manually added */
printf("Source string = %s\n", s2);
printf("Target string = %s\n", s1);
return 0;
}
|
the_stack_data/48576585.c | /* make the lookup table for output.asm */
#define TABLESIZE ('x' - ' ' + 1)
/* possible states to be in */
#define NORMAL 0 /* normal character to be output */
#define PERCENT 1 /* just read percent sign */
#define FLAG 2 /* just read a flag character */
#define WIDTH 3 /* just read a width specification character */
#define DOT 4 /* just read a dot between width and precision */
#define PRECIS 5 /* just read a precision specification character */
#define SIZE 6 /* just read a size specification character */
#define TYPE 7 /* just read a conversion specification character */
#define BOGUS 0 /* bogus state - print the character literally */
#define NUMSTATES 8
/* possible types of characters to read */
#define CH_OTHER 0 /* character with no special meaning */
#define CH_PERCENT 1 /* '%' */
#define CH_DOT 2 /* '.' */
#define CH_STAR 3 /* '*' */
#define CH_ZERO 4 /* '0' */
#define CH_DIGIT 5 /* '1'..'9' */
#define CH_FLAG 6 /* ' ', '+', '-', '#' */
#define CH_SIZE 7 /* 'h', 'l', 'L', 'N', 'F', 'w' */
#define CH_TYPE 8 /* conversion specified character */
#define NUMCHARS 9
unsigned char table[TABLESIZE]; /* the table we build */
/* this is the state table */
int statetable[NUMSTATES][NUMCHARS] = {
/* state, other % . * 0 digit flag size type */
/* NORMAL */ { NORMAL, PERCENT, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL },
/* PERCENT */ { BOGUS, NORMAL, DOT, WIDTH, FLAG, WIDTH, FLAG, SIZE, TYPE },
/* FLAG */ { BOGUS, BOGUS, DOT, WIDTH, FLAG, WIDTH, FLAG, SIZE, TYPE },
/* WIDTH */ { BOGUS, BOGUS, DOT, BOGUS, WIDTH, WIDTH, BOGUS, SIZE, TYPE },
/* DOT */ { BOGUS, BOGUS, BOGUS, PRECIS, PRECIS, PRECIS, BOGUS, SIZE, TYPE },
/* PRECIS */ { BOGUS, BOGUS, BOGUS, BOGUS, PRECIS, PRECIS, BOGUS, SIZE, TYPE },
/* SIZE */ { BOGUS, BOGUS, BOGUS, BOGUS, BOGUS, BOGUS, BOGUS, SIZE, TYPE },
/* TYPE */ { NORMAL, PERCENT, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL, NORMAL }
};
/* this determines what type of character ch is */
static int chartype (
int ch
)
{
if (ch < ' ' || ch > 'z')
return CH_OTHER;
if (ch == '%')
return CH_PERCENT;
if (ch == '.')
return CH_DOT;
if (ch == '*')
return CH_STAR;
if (ch == '0')
return CH_ZERO;
if (strchr("123456789", ch))
return CH_DIGIT;
if (strchr(" +-#", ch))
return CH_FLAG;
if (strchr("hlLNFw", ch))
return CH_SIZE;
if (strchr("diouxXfeEgGcspnCSZ", ch))
return CH_TYPE;
return CH_OTHER;
}
main()
{
int ch;
int state, class;
int i;
for (ch = ' '; ch <= 'x'; ++ch) {
table[ch-' '] = chartype(ch);
}
for (state = NORMAL; state <= TYPE; ++state)
for (class = CH_OTHER; class <= CH_TYPE; ++class)
table[class*8+state] |= statetable[state][class]<<4;
for (i = 0; i < TABLESIZE; ++i) {
if (i % 8 == 0)
printf("\ndb\t %.2xh", table[i]);
else
printf(", %.2xh", table[i]);
}
return 0;
}
|
the_stack_data/121398.c | #include <stdio.h>
int main(){
char c;
for(c = 0;c<120;c++){
printf("%c",c);
}
} |
the_stack_data/29629.c | /* match.c Gathering of Sec. 21.2 code snippets (thanks to Robert Lynch). */
#include <sys/types.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void do_regerror(int errcode, const regex_t *preg);
int main() {
regex_t p;
regmatch_t *pmatch;
int rcomp_err, rexec_err;
char string[BUFSIZ+1];
int i;
rcomp_err = regcomp(&p, "(^(.*[^\\])#.*$)|(^[^#]+$)",
REG_EXTENDED | REG_NEWLINE);
if(rcomp_err) {
do_regerror(rcomp_err, &p);
}
pmatch = alloca(sizeof(regmatch_t) * (p.re_nsub+1));
if(!pmatch) {
perror("alloca");
}
printf("Input a string: ");
fgets(string, sizeof(string), stdin);
rexec_err = regexec(&p, string, p.re_nsub+1, pmatch, 0);
if(rexec_err) {
do_regerror(rexec_err, &p);
} else {
/* match succeeded */
for(i = 0; i <= p.re_nsub; i++) {
/* print the matching portion(s) of the string */
if(pmatch[i].rm_so != -1) {
char * submatch;
size_t matchlen = pmatch[i].rm_eo - pmatch[i].rm_so;
submatch = malloc(matchlen+1);
strncpy(submatch, string+pmatch[i].rm_so, matchlen);
submatch[matchlen] = '\0';
printf("match %i: %s\n", i, submatch);
free(submatch);
}
}
}
exit(0);
}
void do_regerror(int errcode, const regex_t *preg) {
char *errbuf;
size_t errbuf_size;
errbuf_size = regerror(errcode, preg, NULL, 0); /* missing ; */
errbuf = alloca(errbuf_size);
if(!errbuf) {
perror("alloca");
return;
}
regerror(errcode, preg, errbuf, errbuf_size);
fprintf(stderr, "%s\n", errbuf);
}
|
the_stack_data/90766686.c | #include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(0);
struct tm *l;
puts(ctime(&t));
l = localtime(&t);
printf ("%d %d %d -- %d:%d:%d, %d/w %d/y, isdst %d\n",
l->tm_year, l->tm_mon + 1, l->tm_mday,
l->tm_hour, l->tm_min, l->tm_sec,
l->tm_wday, l->tm_yday, l->tm_isdst);
puts(asctime(l));
return 0;
}
|
the_stack_data/449187.c | /*
* Phoenix-RTOS
*
* libphoenix
*
* net/inet_ntop.c
*
* Copyright 2021 Phoenix Systems
* Author: Maciej Purski
*
* This file is part of Phoenix-RTOS.
*
* %LICENSE%
*/
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
static const char *inet_ntop4(const void *src, char *dst, socklen_t size)
{
if (size < INET_ADDRSTRLEN) {
errno = ENOSPC;
return NULL;
}
snprintf(dst, size, "%u.%u.%u.%u",
(unsigned int)((unsigned char *)src)[0],
(unsigned int)((unsigned char *)src)[1],
(unsigned int)((unsigned char *)src)[2],
(unsigned int)((unsigned char *)src)[3]);
return dst;
}
static const char *inet_ntop6(const void *src, char *dst, socklen_t size)
{
const struct in6_addr *addr;
const int n_hextets = sizeof(addr->s6_addr16) / sizeof(addr->s6_addr16[0]);
int i, zero_idx = -1, tmp_len, zero_len = 0, tmp_idx = -1;
char *dst_ptr = dst;
if (size < INET6_ADDRSTRLEN) {
errno = ENOSPC;
return NULL;
}
memset(dst, 0, size);
addr = (const struct in6_addr *) src;
if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) {
snprintf(dst, INET6_ADDRSTRLEN, "::%s%u.%u.%u.%u",
addr->s6_addr16[5] == 0xFFFF ? "ffff:" : "",
addr->s6_addr[12],
addr->s6_addr[13],
addr->s6_addr[14],
addr->s6_addr[15]);
return dst;
}
/* Find the longest all-zero string */
for (i = 0; i < n_hextets; i++) {
if (addr->s6_addr16[i] == 0) {
if (tmp_idx == -1) {
/* Found new all-zero string */
tmp_idx = i;
tmp_len = 1;
}
else {
tmp_len++;
}
}
/* Check if, all-zero string is over */
if (tmp_idx != -1 && (addr->s6_addr16[i] != 0 || i == n_hextets - 1)) {
if (tmp_len > 1 && tmp_len > zero_len) {
zero_len = tmp_len;
zero_idx = tmp_idx;
}
tmp_idx = -1;
}
}
i = 0;
/* Leading zeros */
if (zero_idx == 0) {
*(dst_ptr++) = ':';
i += zero_len;
}
while (i < n_hextets) {
if (i != 0)
*(dst_ptr++) = ':';
/* Zeros inside */
if (i == zero_idx) {
i += zero_len;
} else {
dst_ptr += snprintf(dst_ptr, 5, "%x", ntohs(addr->s6_addr16[i]));
i++;
}
}
/* Trailing zeros */
if (zero_idx + zero_len == n_hextets)
*(dst_ptr++) = ':';
return dst;
}
const char *inet_ntop(int af, const void *src,
char *dst, socklen_t size)
{
if (dst == NULL || src == NULL)
return NULL;
if (af == AF_INET)
return inet_ntop4(src, dst, size);
else if (af == AF_INET6)
return inet_ntop6(src, dst, size);
errno = EAFNOSUPPORT;
return NULL;
}
|
the_stack_data/173579072.c | #include <omp.h>
#include <stdio.h>
#define ITERS 4096
int main() {
int failed = 0;
#pragma omp target map(tofrom: failed)
{
int globalized[256];
#pragma omp parallel for
for (int i = 0; i < 256; i++) {
globalized[i] = 0;
}
#pragma omp parallel for reduction(+:globalized)
for (int i = 0; i < ITERS; i++) {
globalized[i % 256] += i;
}
printf("%d", globalized[0]);
for (int i = 1; i < 256; i++) {
printf(" %d", globalized[i]);
if (globalized[i] != (30720 + i*16))
failed = 1;
}
printf("\n");
if (failed) printf("Failed\n");
else printf("Passed\n");
}
return failed;
}
|
the_stack_data/107756.c | /* Copyright (C) 2005-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <unistd.h>
#include <sys/param.h>
ssize_t
__pread_chk (int fd, void *buf, size_t nbytes, off_t offset, size_t buflen)
{
if (nbytes > buflen)
__chk_fail ();
return __pread (fd, buf, nbytes, offset);
}
|
the_stack_data/95449018.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define FILE "/dev/my_misc_device"
int main(void)
{
char buff[20] ;
memset(buff, 0, 20);
int fd = open(FILE, O_RDONLY);
if (fd < 0) {
perror("open\n");
exit(1);
}
read(fd, buff, 20);
printf("%s\n", buff);
close(fd);
return 0;
}
|
the_stack_data/120010.c | /*Nome: Bruno Rossi Carmo N: 11236289
Nome: Carlos Eduardo Capellini N: 11280140*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //Biblioteca de strings
struct cadastro_Netflix {
char titulo[50];
int faixa_etaria_sugerida;
char faixa_etaria_restricao[100];
int faixa_escala_numerica;
int ano_lancamento;
int nota_user;
int tamanho_amostra;
};
typedef struct cadastro_Netflix cadnet;
int main()
{
cadnet x;
FILE *arq;
int i;
arq=fopen("netflix_all.csv", "wb");
}
|
the_stack_data/140765567.c | /*
* created by Jaakko
*/
#ifdef CHANGED_1
#include "lib/types.h"
#include "kernel/config.h"
#include "kernel/assert.h"
#include "kernel/spinlock.h"
#include "kernel/thread.h"
#include "kernel/interrupt.h"
#include "kernel/sleepq.h"
#include "kernel/panic.h"
#include "kernel/lock_cond.h"
/* definitions for the locks and condition variables */
/* spinlocks and tables they cover */
spinlock_t lock_table_slock;
static lock_t lock_table[CONFIG_MAX_LOCKS];
spinlock_t cond_table_slock;
static cond_t cond_table[CONFIG_MAX_CONDITION_VARIABLES];
/**
* These helper functions are meant for spinlock locking (so that interrupt disabling
* won't forgot).
* Proper compilers will optimize these function calls away for performance.
*/
/*
static interrupt_status_t s_acquire(spinlock_t* spin_lock) {
interrupt_status_t prev_int_stat;
prev_int_stat = _interrupt_disable();
spinlock_acquire(spin_lock);
return prev_int_stat;
}
*/
static void s_release(spinlock_t* spin_lock, interrupt_status_t prev_status) {
spinlock_release(spin_lock);
_interrupt_set_state(prev_status);
}
/* init functions */
void lock_table_init(void) {
uint32_t i;
/* Start by acquiring the lock_table_slock.
* Interrupts need to be disabled and the lock initialized.
*/
interrupt_status_t prev_int_stat;
prev_int_stat = _interrupt_disable();
spinlock_reset(&lock_table_slock);
spinlock_acquire(&lock_table_slock);
/* initialize all locks unused */
for (i = 0; i < CONFIG_MAX_LOCKS; i++) {
spinlock_reset(&(lock_table[i].slock));
lock_table[i].locked_id = LOCK_NO_THREAD;
lock_table[i].nested_locking_count = 0;
lock_table[i].waiting_thread_count = 0;
lock_table[i].is_used = 0;
}
/* release spinlock and set interrupt to previous state */
s_release(&lock_table_slock, prev_int_stat);
}
void cond_table_init(void) {
int i;
/* Start by acquiring the cond_table_slock.
* Interrupts need to be disabled and the lock initialized.
*/
interrupt_status_t prev_int_stat;
prev_int_stat = _interrupt_disable();
spinlock_reset(&cond_table_slock);
spinlock_acquire(&cond_table_slock);
/* initialize all conds unused */
for (i = 0; i < CONFIG_MAX_CONDITION_VARIABLES; i++) {
spinlock_reset(&cond_table[i].slock);
cond_table[i].waiting_thread_count = 0;
cond_table[i].is_used = 0;
}
/* release spinlock and set interrupt to previous state */
spinlock_release(&cond_table_slock);
_interrupt_set_state(prev_int_stat);
}
/* ********************************************* */
/* lock functions */
lock_t *lock_create(void) {
int i;
/* this changes the lock_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&lock_table_slock);
lock_t* lock_to_return;
/* critical section: find next unused lock and set it used and
* return the address
*/
for (i = 0; i < CONFIG_MAX_LOCKS; i++) {
if (!(lock_table[i].is_used)) {
lock_table[i].is_used = 1;
/* found unused, release lock and return interrupt status
* back to original */
lock_to_return = lock_table + i;
spinlock_release(&lock_table_slock);
_interrupt_set_state(prev_int_stat);
return lock_to_return;
}
}
/* Here all locks were used which is bad: panic*/
KERNEL_PANIC("lock_create(): no free locks");
return 0; /* need to return something to prevent compiler error */
}
void lock_destroy(lock_t *lock) {
/* this changes the lock_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&lock_table_slock);
spinlock_acquire(&lock->slock);
/* critical section: check that lock is open if not panic*/
KERNEL_ASSERT(lock->locked_id == LOCK_NO_THREAD);
/* mark lock unused */
lock->is_used = 0;
spinlock_release(&lock->slock);
spinlock_release(&lock_table_slock);
_interrupt_set_state(prev_int_stat);
}
void lock_acquire(lock_t *lock) {
/* this changes the lock_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&lock->slock);
/* if lock was open */
if (lock->locked_id == LOCK_NO_THREAD) {
lock->locked_id = thread_get_current_thread();
//kprintf("acquire %d", lock->locked_id);
lock->nested_locking_count = 1;
/* lock is now acquired and spinlock can be released
* and interrupts returned to original state
*/
spinlock_release(&lock->slock);
_interrupt_set_state(prev_int_stat);
return;
} else if (lock->locked_id == thread_get_current_thread()) {
lock->nested_locking_count++;
/* same thread tried to lock, so function returns and
* releases the locks after increasing nesting
*/
spinlock_release(&lock->slock);
_interrupt_set_state(prev_int_stat);
return;
}
/* Now the thread trying to lock must be suspended.
* When using sleepq interrupts must be disabled and
* they are at this point.
*/
lock->waiting_thread_count++;
sleepq_add(&lock->slock);
/* before leaving execution of this thread release
* lock and interrupts can be left as they are.
*/
spinlock_release(&lock->slock);
thread_switch();
/* Here the thread has been woken up.
* The spinlock must be acquired again
*/
spinlock_acquire(&lock->slock);
lock->waiting_thread_count--;
lock->locked_id = thread_get_current_thread();
lock->nested_locking_count = 1;
spinlock_release(&lock->slock);
_interrupt_set_state(prev_int_stat);
}
void lock_release(lock_t *lock) {
/* this changes the lock_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&lock->slock);
//kprintf("release %d . %d", lock->locked_id, thread_get_current_thread());
/* releasing some other threads lock is not allowed */
KERNEL_ASSERT(lock->locked_id == thread_get_current_thread());
if (lock->nested_locking_count > 1) {
/* nested locking, do nothing when releasing except
* decrease nesting and release spinlock and return
* interrupt status back to original
*/
lock->nested_locking_count--;
spinlock_release(&lock->slock);
_interrupt_set_state(prev_int_stat);
return;
}
// set to zero if lock is about to be released
lock->nested_locking_count = 0;
/* Here we need to release the lock and wake up a thread if any */
if (lock->waiting_thread_count > 0) {
sleepq_wake(&lock->slock);
/* set locked thread to LOCK_RESERVED_THREAD instead of
* LOCK_NO_THREAD to prevent jumping the sleep queue
*/
lock->locked_id = LOCK_RESERVED_THREAD;
} else { /* lock->waiting_thread_count == 0 */
/* there are no threads in queue */
lock->locked_id = LOCK_NO_THREAD;
}
/* release and return again */
spinlock_release(&lock->slock);
_interrupt_set_state(prev_int_stat);
return;
}
/* condition variable functions */
cond_t *condition_create(void) {
int i;
/* this changes the cond_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&cond_table_slock);
cond_t* cond_to_return;
/* critical section: find next unused cond and set it used and
* return the address
*/
for (i = 0; i < CONFIG_MAX_LOCKS; i++) {
if (!(cond_table[i].is_used)) {
cond_table[i].is_used = 1;
/* found unused, release cond and return interrupt status
* back to original */
cond_to_return = cond_table + i;
spinlock_release(&cond_table_slock);
_interrupt_set_state(prev_int_stat);
return cond_to_return;
}
}
/* Here all conds were used which is bad: panic*/
KERNEL_PANIC("cond_create(): no free condition variables");
return 0;
}
void condition_destroy(cond_t *cond) {
KERNEL_ASSERT(cond);
/* this changes the lock_table and thus
* requires aquiring a spinlock and disabling interrupts.
*/
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&cond_table_slock);
spinlock_acquire(&cond->slock);
/* test that no threads are waiting condition */
KERNEL_ASSERT(cond->waiting_thread_count == 0);
/* mark lock unused */
cond->is_used = 0;
spinlock_release(&cond->slock);
spinlock_release(&cond_table_slock);
_interrupt_set_state(prev_int_stat);
}
void condition_wait(cond_t *cond, lock_t *condition_lock) {
KERNEL_ASSERT(cond && condition_lock);
// lock cond variable
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&cond->slock);
// add this thread to sleepq
cond->waiting_thread_count++;
sleepq_add(&cond->slock);
// release lock for condition
lock_release(condition_lock);
// release spinlock and put thread to sleep
spinlock_release(&cond->slock);
thread_switch();
// zzzZZzzz
// now thread wakes up, it means that it is singaled
// restore interrupts and try to acquire lock
_interrupt_set_state(prev_int_stat);
lock_acquire(condition_lock);
}
void condition_signal(cond_t *cond, lock_t *condition_lock) {
KERNEL_ASSERT(cond && condition_lock);
// lock cond variable
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&cond->slock);
// check that we have threads waiting for signal
if (cond->waiting_thread_count > 0) {
// we have 1..n, wake the first one
cond->waiting_thread_count--;
sleepq_wake(&cond->slock);
}
// we dont need to release condition lock because this is non-blocking cond var
// just restore interrupts
spinlock_release(&cond->slock);
_interrupt_set_state(prev_int_stat);
}
void condition_broadcast(cond_t *cond, lock_t *condition_lock) {
KERNEL_ASSERT(cond && condition_lock);
// lock cond variable
interrupt_status_t prev_int_stat = _interrupt_disable();
spinlock_acquire(&cond->slock);
// check that we have threads waiting for signal
if (cond->waiting_thread_count > 0) {
// we have 1..n, wake all!
cond->waiting_thread_count = 0;
sleepq_wake_all(&cond->slock);
}
// we dont need to release condition lock because this is non-blocking cond var
// just restore interrupts
spinlock_release(&cond->slock);
_interrupt_set_state(prev_int_stat);
}
#endif
|
the_stack_data/490143.c | #include <strings.h>
#include <string.h>
/**
* @brief Compare memory s1 and s2 by n characters
*
* @param s1
* @param s2
* @param n Size of the area to compare
* @return int Zero if equal, non-zero otherwise
*/
int bcmp(const void *s1, const void *s2, size_t n)
{
return memcmp(s1, s2, n);
}
/**
* @brief Copies n bytes from s1 into s2
*
* @param s1 Source
* @param s2 Destination
* @param n Size of the area
*/
void bcopy(const void *s1, void *s2, size_t n)
{
return memmove(s1, s2, n);
}
/**
* @brief Zeroes out a piece of the storage
* Reference: https://man7.org/linux/man-pages/man3/bzero.3.html
*
* @param s Area to zero out
* @param n Size of the area
*/
void bzero(void *s, size_t n)
{
memset(s, 0, n);
}
/**
* @brief Same as bzero, but guarantees that the operation won't be
* optimized away by the compiler if deemed unescesary
*
* @param s Area to zero out
* @param n Size of the area
*/
void explicit_bzero(void *s, size_t n)
{
memset(s, 0, n);
}
/**
* @brief Finds the first bit that is set on the specified bitset i
* and returns the index of said bit
*
* TODO: Is it 1 or zero based?
* @param i Bitset
* @return int
*/
int ffs(int i)
{
int idx = 0;
if(i == 0) {
return 0;
}
/* Find until bit is set */
while(i & 1 == 0) {
i >>= 1;
idx++;
}
return idx;
}
/**
* @brief Equivalent to strchr(s, c)
*
* @param s
* @param c
* @return char*
*/
char *index(const char *s, int c)
{
return strchr(s, c);
}
/**
* @brief Equivalent to strrchr(s, c)
*
* @param s
* @param c
* @return char*
*/
char *rindex(const char *s, int c)
{
return strrchr(s, c);
}
/** @todo strcasecmp() */
int strcasecmp(const char *s1, const char *s2)
{
return 0;
}
/** @todo strncasecmp() */
int strncasecmp(const char *s1, const char *s2, size_t n)
{
return 0;
}
|
the_stack_data/11023.c | /*******************************************************************************
* Copyright (c) 2012-2017, Kim Grasman <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Kim Grasman nor the
* names of 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 KIM GRASMAN 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 <assert.h>
#include <stddef.h>
#include "getopt.h"
/* Just to test if it compiles as C */
struct option opts[] = {
{"first", no_argument, 0, 'f'},
{"second", required_argument, 0, 's'},
{"third", optional_argument, 0, 't'},
{0, 0, 0, 0}
};
int main(int argc, char* argv[]) {
int opt;
while ((opt = getopt_long(argc, argv, "fs:t::", opts, NULL)) != -1) {
switch (opt) {
case 'f':
case 's':
case 't':
break;
default:
assert(0);
break;
}
}
return 0;
}
|
the_stack_data/97013428.c | #include <stdio.h>
int main()
{
int N;
scanf("%d", &N);
printf("%02d:%02d:%02d\n", N/3600, (N%3600)/60, N%60);
return 0;
}
|
the_stack_data/36765.c | #define R_NO_REMAP
void sum_c(
double *input, // Input vector
int *n, // Length of 'input'
double *na_flag, // 'NA' flag
double *result // Result (length 1)
) {
int i;
int n_valid = 0; // Number of non-'NA' elements
result[0] = 0;
for(i = 0; i < *n; i++) {
if(input[i] != *na_flag) {
result[0] += input[i];
n_valid++;
}
}
if(n_valid == 0) {
result[0] = *na_flag;
}
}
|
the_stack_data/119592.c | //
#include <stdio.h>
long long int check(long long int a, long long int b);
int main(){
long long int in,num,digit,temp,lost,value;
int a=0;
printf("\nEnter an ingteger > ");
scanf("%lld",&in);
printf("\n");
if(in >0){
num=10;
while (a <=12){
value = in%num;
if(lost==value){
digit = 0;
}
else{
digit = check(value,(num/10));
}
lost = value;
num = num*10;
temp = in%num;
temp = check(temp,(num/10));
if(temp ==in){
printf("%lld\n",digit);
break;
}
else{
printf("%lld\n",digit);
}
a++;
}}
else if(in == 0){
printf("0\n");
}
else{
num=(-10);
while( a<=12){
value = in%(num);
if(lost==value){
digit = 0;
}
else{
digit = check((-value),(-(num/10)));
}
lost = value;
num = num*10;
temp = in%num;
temp = check((-temp),(-(num/10)));
if(temp == (-in)){
printf("-%lld\n",digit);
break;
}
else{
printf("%lld\n",digit);
}
a++;
}}
printf("That's all, have a nice day!\n");
return 0;
}
long long int check(long long int a, long long int b){
if(a >= b){
a = a/b;
return a;
}
else{
return a;
}
}
|
the_stack_data/242331344.c | /* { dg-do compile } */
unsigned a, b, c[1];
void __assert_fail() __attribute__((__noreturn__));
void fn1()
{
int d;
unsigned e;
for (;;)
{
d = 0;
for (; d <= 6; d++)
c[d] || a ? 0 : __assert_fail();
for (; e <= 5; e++)
a = b;
}
}
|
the_stack_data/243892813.c | /*!
* \file dragondev_test.c
* \brief
*
* \author sabertazimi, <[email protected]>
* \version 1.0
* \date 2017
* \license MIT
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void) {
int dragondev;
char buf[11];
dragondev = open("/dev/dragondev", O_RDWR);
if (dragondev == -1) {
perror("Test failed.\n");
exit(0);
}
for (int i = 1; i <= 127; i++) {
buf[0] = i;
printf("write_size = %d\t", (int)write(dragondev, buf, 1));
}
close(dragondev);
printf("\n\n");
dragondev = open("/dev/dragondev", O_RDWR);
if (dragondev == -1) {
perror("Test failed.\n");
exit(0);
}
for (int i = 1; i <= 12; i++) {
printf("read_size = %d, ", (int)read(dragondev, buf, 10));
printf("%s\n", buf);
}
close(dragondev);
return 0;
}
|
the_stack_data/159516446.c | #include <stdio.h>
int main(){
int num,reminder, temp,sum=0;
printf("Enter a Number: ");
scanf("%d",&num);
temp = num;
while(temp!=0){
reminder = temp%10;
sum = sum*10+reminder;
temp = temp/10;
}
if(num==sum){
printf("%d is Palindrome Number",num);
}else {
printf("%d is not Palindrome Number",num);
}
}
|
the_stack_data/3262930.c | #include <math.h>
long double remquol(long double x, long double y, int *quo)
{
signed char *cx = (void *)&x, *cy = (void *)&y;
/* By ensuring that addresses of x and y cannot be discarded,
* this empty asm guides GCC into representing extraction of
* their sign bits as memory loads rather than making x and y
* not-address-taken internally and using bitfield operations,
* which in the end wouldn't work out, as extraction from FPU
* registers needs to go through memory anyway. This way GCC
* should manage to use incoming stack slots without spills. */
__asm__ ("" :: "X"(cx), "X"(cy));
long double t = x;
unsigned fpsr;
do __asm__ ("fprem1; fnstsw %%ax" : "+t"(t), "=a"(fpsr) : "u"(y));
while (fpsr & 0x400);
/* C0, C1, C3 flags in x87 status word carry low bits of quotient:
* 15 14 13 12 11 10 9 8
* . C3 . . . C2 C1 C0
* . b1 . . . 0 b0 b2 */
unsigned char i = fpsr >> 8;
i = i>>4 | i<<4;
/* i[5:2] is now {b0 b2 ? b1}. Retrieve {0 b2 b1 b0} via
* in-register table lookup. */
unsigned qbits = 0x7575313164642020 >> (i & 60);
qbits &= 7;
*quo = (cx[9]^cy[9]) < 0 ? -qbits : qbits;
return t;
}
|
the_stack_data/630657.c | #include "stdlib.h"
#include "stdio.h"
typedef struct list {
// A doubly-linked list in under 3 minutes :D
struct list* prev;
struct list* next;
int value;
} list;
// Insert as first element, return pointer to head.
list* insert(list* head, int value) {
list* new_head = (list*)malloc(sizeof(list));
new_head->value = value;
new_head->prev = NULL;
if (head) {
new_head->next = head;
head->prev = new_head;
} else {
new_head->next = NULL;
}
return new_head;
}
list* find(list* l, int value) {
while (l) {
if (l->value == value) {
return l;
} else {
l = l->next;
}
}
return NULL;
}
// Need the double pointer?
list* delete(list* head, int elem) {
if (!head) return NULL;
list* ptr = find(head, elem);
if (ptr) {
if (ptr == head) {
// removing head
list* new_head = head->next;
free(head);
return new_head;
} else {
list* prev = ptr->prev;
prev->next = ptr->next;
free(ptr);
return head;
}
}
// element not found
return head;
}
void print_list(list* l) {
while (l) {
printf("%i ", l->value);
l = l->next;
}
printf("\n");
}
int main() {
list* l = insert(NULL, 5);
l = insert(l, 6);
print_list(l);
list* five = find(l, 5);
if (five) printf("%i found!\n", five->value);
for (int i = 0; i < 10; i++) {
l = insert(l, i);
}
l = delete(l, 4);
print_list(l);
l = delete(l, 0);
print_list(l);
l = delete(l, 9);
print_list(l);
return 0;
}
|
the_stack_data/150142259.c | #include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void * thread1(void *arg)
{
pthread_cleanup_push (pthread_mutex_unlock,&mutex);
while(1)
{
printf("thread1 is running\n");
pthread_mutex_lock (&mutex);
pthread_cond_wait(&cond,&mutex);
printf("thread1 applied the condition\n");
pthread_mutex_unlock(&mutex);
sleep(4);
}
pthread_cleanup_pop(0);
}
void * thread2(void *arg)
{
while(1)
{
printf("thread2 is running\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
printf("thread2 applied the condition\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(void)
{
pthread_t tid1,tid2;
printf("condition variable study!\n");
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_create (&tid1,NULL,(void *)thread1,NULL);
pthread_create (&tid2,NULL,(void *)thread2,NULL);
do
{
pthread_cond_signal (&cond);
}while(1);
sleep(30);
pthread_exit(0);
}
|
the_stack_data/40762433.c | /*
Author : Jack Walker
Company : Staffordshire University
Date : 10th April 2019
Function: Resistor Analysis
Version 2.0
Modifications : Added data logging and review functionality
Software : Dev C/C++
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct shipmentInfo {
char company[18], date[8];
double nominalValue, tolerance, meanResistance;
float failureRate, standDevResistance, varianceResistance;
};
typedef struct shipmentInfo data;
int operation();
int menu();
void dateInput(data*);
int toInt(char[]);
int supplierSelect(const char**);
void fourBands(const char**, const char**, const char**, int, int, int, data*);
void fiveBands(const char**, const char**, const char**, int, int, int, data*);
void sixBands(const char**, const char**, const char**, const char**, int, int, int, int, data*);
int bandInput(const char**, int, int);
double actualValInp(int);
double idealVal(int, int, int, int, int);
double multVal(int);
double tolVal(int);
int tempVal(int);
double sampleMean(double[]);
float sampleStandDev(double[], double);
double minTolVal(double, float);
double maxTolVal(double, float);
FILE* fileHandling();
/*
Purpose: Resistor Analysis
- Input a supplier name and date of shipment
- Select the amount of bands the resistor has (4, 5 or 6)
- Input the band colours that the batch consists of
- Input the actual ohm resistance value for each resistor in the sample
- Calculate the mean, standard deviation and variance of these inputs
- Calculate the nominal value based on the colours input by the user
- Using the tolerance, compare the actual resistance values to the nominal (using the tolerance as min and max values)
- Record the failure rate of the batch
- Output this data from a structure
- Store this data to a log (user selected text file)
- Output the log
- Output log items with a specified supplier
Main variables:
const char* suppliers[] - Constant array of character arrays (strings) for supplier names
const char* bandColours[] - Constant array of character arrays (strings) for band colours
const char* multiplierColours[] - Constant array of character arrays (strings) for multiplier colours
const char* toleranceColours[] - Constant array of character arrays (strings) for tolerance colours
const char* temperatureColours[] - Constant array of character arrays (strings) for temperature colours
data output - Structure storing the date, supplier name, nominal value, tolerance, mean, standard deviation, variance and failure rate for the sample
Functions:
supplierSelect() - Menu system for selecting the supplier that the batch is from
dateInput() - Input system for the date
menu() - Menu screen for selecting the amount of bands the resistor has
fourBands(), fiveBands() & sixBands() - Record the colours of the batch's bands through a text based selection
bandInput() - Request an input based on the values passed to the function
idealVal() - Calculate the nominal value based on the input provided
actualValInp() - Input the actual resistance for each of the 10 resistors in the sample
minTolVal() & maxTolVal() - Calculate the minimum and maximum acceptable resistance values
sampleMean() - Calculates the mean of the sample
sampleStandDev() - Calculates the standard deviation of the sample
*/
void main() {
const char* suppliers[4] = {"Farnell", "RSComponents", "Rapid Electronics", "DigiKey"};
const char* bandColours[10] = {"Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Grey", "White"};
const char* multiplierColours[10] = {"Silver", "Gold", "Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet"};
const char* toleranceColours[7] = {"Silver", "Gold", "Brown", "Red", "Green", "Blue", "Violet"};
const char* temperatureColours[4] = {"Brown", "Red", "Orange", "Yellow"};
int i, fail = 0, trigger = 0, index;
double arr[10];
data output;
FILE *fp;
char fileName[30], buffer[30];
switch (operation()) {
case 1:
strcpy(output.company, suppliers[supplierSelect(suppliers) - 1]);
dateInput(&output);
output.failureRate = 0;
switch (menu()) {
case 1:
fourBands(bandColours, multiplierColours, toleranceColours, 10, 10, 7, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(sampleStandDev(arr, sampleMean(arr)));
output.failureRate = fail;
break;
case 2:
fiveBands(bandColours, multiplierColours, toleranceColours, 10, 10, 7, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(output.varianceResistance);
output.failureRate = fail;
break;
case 3:
sixBands(bandColours, multiplierColours, toleranceColours, temperatureColours, 10, 10, 7, 4, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(output.varianceResistance);
output.failureRate = fail;
break;
case 4:
exit(0);
}
printf("Company - %s\nDate - %s\nFailure Rate - %f\n", output.company, output.date, output.failureRate);
printf("Nominal Value - %lf\nTolerance - %f\n", output.nominalValue, output.tolerance);
printf("Mean Resistance - %lf\nStandard Deviation - %lf\nVariance - %lf\n", output.meanResistance, output.standDevResistance, output.varianceResistance);
break;
case 2:
printf("Please input the name of the text file for the application to use (if the file can't be found, one will be created using that name): ");
scanf("%s", &fileName);
strcat(fileName, ".txt");
fp = fopen(fileName, "a");
strcpy(output.company, suppliers[supplierSelect(suppliers) - 1]);
dateInput(&output);
output.failureRate = 0;
switch (menu()) {
case 1:
fourBands(bandColours, multiplierColours, toleranceColours, 10, 10, 7, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(sampleStandDev(arr, sampleMean(arr)));
output.failureRate = fail;
break;
case 2:
fiveBands(bandColours, multiplierColours, toleranceColours, 10, 10, 7, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(output.varianceResistance);
output.failureRate = fail;
break;
case 3:
sixBands(bandColours, multiplierColours, toleranceColours, temperatureColours, 10, 10, 7, 4, &output);
for (i = 0; i < 10; i++) {
arr[i] = actualValInp(i);
if ((arr[i] > maxTolVal(output.nominalValue, output.tolerance)) || (arr[i] < minTolVal(output.nominalValue, output.tolerance))) {
fail += 10;
}
}
output.meanResistance = sampleMean(arr);
output.standDevResistance = sampleStandDev(arr, output.meanResistance);
output.varianceResistance = sqrt(output.varianceResistance);
output.failureRate = fail;
break;
case 4:
exit(0);
}
fprintf(fp, "%s\n%s\n%f\n%lf\n%f\n%lf\n%lf\n%lf\n", output.company, output.date, output.failureRate, output.nominalValue, output.tolerance, output.meanResistance, output.standDevResistance, output.varianceResistance);
fclose(fp);
break;
case 3:
fp = fileHandling();
printf("%-20s\t%-8s\t%-3s\t%-20s\t%-11s\t%-16s\t%-8s\t%-8s\n", "Company", "Date", "Failure Rate (%)", "Nominal Value (Ohms)", "Tolerance", "Mean (Ohms)", "Standard Deviation", "Variance");
while (fgets(buffer, 30, fp) != NULL) {
strtok(buffer, "\n"); /*Removes a token from a string and returns a pointer to the new form, in this case removing newline*/
printf("%-20s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-8s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-3s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("\t%-20s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-9s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-16s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-8s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("\t%-8s\n", buffer);
}
fclose(fp);
break;
case 4:
fp = fileHandling();
index = supplierSelect(suppliers) - 1;
printf("%-20s\t%-8s\t%-3s\t%-20s\t%-11s\t%-16s\t%-8s\t%-8s\n", "Company", "Date", "Failure Rate (%)", "Nominal Value (Ohms)", "Tolerance", "Mean (Ohms)", "Standard Deviation", "Variance");
while (fgets(buffer, 30, fp) != NULL) {
strtok(buffer, "\n"); /*Removes a token from a string and returns a pointer to the new form, in this case removing newline*/
if (strcmp(buffer, suppliers[index]) == 0) {
printf("%-20s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-8s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-3s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("\t%-20s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-9s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-16s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("%-8s\t", buffer);
fgets(buffer, 30, fp);
strtok(buffer, "\n");
printf("\t%-8s\n", buffer);
trigger = 1;
}
else if (trigger = 1) {
trigger = 0;
}
}
fclose(fp);
break;
case 5:
exit(0);
}
}
FILE* fileHandling(){
/*
Name: FileHandling
Function: To allow the user to input a file name and open it if valid, returning an error message and exiting if it is not
Variables: fp, fileName
Function will only return the file pointer if the file is found, otherwise the program will report this issue and exit processing
*/
FILE *fp;
char fileName[30];
printf("Please input the name of the text file for the application to use: ");
scanf("%s", &fileName);
strcat(fileName, ".txt");
fp = fopen(fileName, "r");
if (fp == NULL) {
printf("File not found. Exiting program.");
exit(0);
}else{
return fp;
}
}
int operation() {
/*
Name: Operation
Function: To provide a validated menu system for selecting the operation wanted by the user
Variables: Choice, Valid, valueRead, followChar
Function will only return the value of choice when valid = 1, otherwise it will loop until valid input is given
*/
int choice, valid = 0, valueRead;
char followChar;
do {
printf("======================================================\n");
printf("1 - Input resistor batch\n2 - Input batch and store data in log\n3 - View data log\n4 - View data log (flitered by supplier)\n5 - Exit\n");
printf("======================================================\n\r");
valueRead = scanf("%d%c", &choice, &followChar);
if (valueRead == 2) {
if (isspace(followChar) && choice > 0 && choice < 6) {
/*Integer followed by whitespace*/
valid = 1;
} else {
/*Integer followed by character*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} else if (valueRead == 1 && choice > 0 && choice < 6) {
/*Integer followed by nothing*/
valid = 1;
} else {
/*Not an integer*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} while (valid == 0);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4) {
return choice;
} else {
exit(0);
}
}
int menu() {
/*
Name: Menu
Function: To provide a validated menu system for selecting the amount of bands on the resistor batch being input
Variables: choice, valid, valueRead, followChar
Function will only return the value of choice when valid = 1, otherwise it will loop until valid input is given
*/
int choice, valid = 0, valueRead;
char followChar;
do {
printf("======================================================\n");
printf("1 - 4 Band Resistors\n2 - 5 Band Resistors\n3 - 6 Band Resistors\n4 - Exit Program\n");
printf("======================================================\n\r");
valueRead = scanf("%d%c", &choice, &followChar);
if (valueRead == 2) {
if (isspace(followChar) && choice > 0 && choice < 4) {
/*Integer followed by whitespace*/
valid = 1;
} else {
/*Integer followed by character*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} else if (valueRead == 1 && choice > 0 && choice < 4) {
/*Integer followed by nothing*/
valid = 1;
} else {
/*Not an integer*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} while (valid == 0);
if (choice == 1 || choice == 2 || choice == 3) {
return choice;
} else {
exit(0);
}
}
void dateInput(data* q) {
/*
Name: dateInput
Function: To allow the user to input a date as a string, validate the input and return the string to a structure if valid, looping if not
Paramaters: data* q - A pointer to a structure of type data
Variables: daysPerMonth[], valid, d, m, y, dateInt
Function will prompt the user to input a date in the form ddMMyyyy.
This input will then be validated by being cast to an integer using the toInt() function, after which the integer is checked to ensure the date is valid
If valid, the string form is set to the date of the data structure, else, the function loops
*/
int daysPerMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int valid = 0, d, m, y, dateInt;
char dateArr[8];
while (valid != 1) {
fflush(stdin);
printf("Please input the date in form ddMMyyyy (e.g. 07062020 is 7 June 2020): ");
scanf("%s", dateArr);
dateInt = toInt(dateArr);
d = dateInt / 1000000;
m = dateInt / 10000 - d * 100;
y = dateInt - d * 1000000 - m * 10000;
if (y % 400 == 0 || (y % 100 != 0 && y % 4 == 0)) {
daysPerMonth[1] = 29;
}
if (d < 1 || daysPerMonth[m - 1] < d || m < 1 || m > 12) {
printf("Invalid date, please try again (format ddMMyyyy)\n\r");
} else {
valid = 1;
}
}
strcpy(q->date, dateArr);
}
int toInt(char a[]) {
/*
Name: toInt
Function: Convert a string value to an integer
Paramaters: char a[] - Array of characters
Variables: i, num
Function will convert a character array to an integer and return it (Validation of char array occurs in dateInput so isn't needed here)
*/
int i, num;
num = 0;
for (i = 0; a[i] != '\0'; i++) {
num = num * 10 + a[i] - '0';
}
return num;
}
int supplierSelect(const char** suppliers) {
/*
Name: supplierSelect
Function: Provide a menu system for selecting the supplier whose batch is being sampled
Paramaters: const char** suppliers - Constant array of strings (passed as a pointer)
Variables: choice, valid, valueRead, followChar
Function will only return the value of choice when valid = 1, otherwise it will loop until valid input is given
*/
int choice, valid = 0, valueRead;
char followChar;
do {
printf("======================================================\n");
printf("1 - %s\n2 - %s\n3 - %s\n4 - %s\n5 - Exit\n", suppliers[0], suppliers[1], suppliers[2], suppliers[3]);
printf("======================================================\n\r");
valueRead = scanf("%d%c", &choice, &followChar);
if (valueRead == 2) {
if (isspace(followChar) && choice > 0 && choice < 6) {
/*Integer followed by whitespace*/
valid = 1;
} else {
/*Integer followed by character*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} else if (valueRead == 1 && choice > 0 && choice < 6) {
/*Integer followed by nothing*/
valid = 1;
} else {
/*Not an integer*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} while (valid == 0);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4) {
return choice;
} else {
exit(0);
}
}
void fourBands(const char** bandColours, const char** multiplierColours, const char** toleranceColours, int bCLen, int mCLen, int tCLen, data* d) {
/*
Name: fourBands
Function: To prompt and accept user input for the colours of a 4 band resistor and set these values to a structure
Paramaters: const char** bandColours, const char** multiplierColours, const char** toleranceColours - Arrays of strings (colour names)
int bCLen, int mCLen, int tCLen - Length of each array
data* d - Pointer to structure
Variables: i, bandOne, bandTwo, bandThree, bandFour
Function will read in values for each bands colour using bandInput to validate the selection. These values will be used to calculate the nominal value and tolerance of the resistor.
These values will be stored in the structure that has been passed in as a pointer.
*/
int i, bandOne, bandTwo, bandThree, bandFour;
bandOne = bandInput(bandColours, bCLen, 1);
bandTwo = bandInput(bandColours, bCLen, 2);
bandThree = bandInput(multiplierColours, mCLen, 3);
bandFour = bandInput(toleranceColours, tCLen, 4);
d->nominalValue = idealVal(bandOne, bandTwo, bandThree, bandFour, 4);
d->tolerance = tolVal(bandFour);
}
void fiveBands(const char** bandColours, const char** multiplierColours, const char** toleranceColours, int bCLen, int mCLen, int tCLen, data* d) {
/*
Name: fiveBands
Function: To prompt and accept user input for the colours of a 5 band resistor and set these values to a structure
Paramaters: const char** bandColours, const char** multiplierColours, const char** toleranceColours - Arrays of strings (colour names)
int bCLen, int mCLen, int tCLen - Length of each array
data* d - Pointer to structure
Variables: i, bandOne, bandTwo, bandThree, bandFour
Function will read in values for each bands colour using bandInput to validate the selection. These values will be used to calculate the nominal value and tolerance of the resistor.
These values will be stored in the structure that has been passed in as a pointer.
*/
int i, bandOne, bandTwo, bandThree, bandFour, bandFive;
bandOne = bandInput(bandColours, bCLen, 1);
bandTwo = bandInput(bandColours, bCLen, 2);
bandThree = bandInput(bandColours, bCLen, 3);
bandFour = bandInput(multiplierColours, mCLen, 4);
bandFive = bandInput(toleranceColours, tCLen, 5);
d->nominalValue = idealVal(bandOne, bandTwo, bandThree, bandFour, 5);
d->tolerance = tolVal(bandFive);
}
void sixBands(const char** bandColours, const char** multiplierColours, const char** toleranceColours, const char** temperatureColours, int bCLen, int mCLen, int tCLen, int teCLen, data* d) {
/*
Name: sixBands
Function: To prompt and accept user input for the colours of a 6 band resistor and set these values to a structure
Paramaters: const char** bandColours, const char** multiplierColours, const char** toleranceColours, const char** temperatureColours - Arrays of strings (colour names)
int bCLen, int mCLen, int tCLen, int teCLen - Length of each array
data* d - Pointer to structure
Variables: i, bandOne, bandTwo, bandThree, bandFour
Function will read in values for each bands colour using bandInput to validate the selection. These values will be used to calculate the nominal value and tolerance of the resistor.
These values will be stored in the structure that has been passed in as a pointer.
*/
int i, bandOne, bandTwo, bandThree, bandFour, bandFive, bandSix;
bandOne = bandInput(bandColours, bCLen, 1);
bandTwo = bandInput(bandColours, bCLen, 2);
bandThree = bandInput(bandColours, bCLen, 3);
bandFour = bandInput(multiplierColours, mCLen, 4);
bandFive = bandInput(toleranceColours, tCLen, 5);
bandSix = bandInput(temperatureColours, teCLen, 6);
d->nominalValue = idealVal(bandOne, bandTwo, bandThree, bandFour, 6);
d->tolerance = tolVal(bandFive);
}
int bandInput(const char** colours, int arrLen, int bandNum) {
/*
Name: bandInput
Function: To prompt user for input based on a given array
Paramaters: const char** colours - Array of strings (colours)
int arrLen, int bandNum
Variables: userInput, i, valueRead, pass, followChar
Function will return userInput if it is valid, else it will loop asking for the user to try again
*/
int userInput, i, valueRead, pass = 0;
char followChar;
do {
for (i = 0; i < arrLen; i++) {
printf("%d - %s\n\r", i, colours[i]);
}
printf("Please input a colour value of band %d using the table provided: ", bandNum);
valueRead = scanf("%d%c", &userInput, &followChar);
if (valueRead == 2) {
if (isspace(followChar) && (userInput >= 0 || userInput <= arrLen)) {
/*nteger followed by whitespace*/
pass = 1;
} else {
/*Integer followed by character*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} else if (valueRead == 1 && (userInput >= 0 || userInput <= arrLen)) {
/*Integer followed by nothing*/
pass = 1;
} else {
/*Not an integer*/
printf("Only defined integer values will be accepted, please try again.\n\r");
fflush(stdin);
}
} while (pass == 0);
return userInput;
}
double actualValInp(int i) {
/*
Name: actualValueInp
Function: To input the actual resistance (in ohms) of the resistors in the batch
Paramaters: i
Variables: userInput
Function will return userInput so long as the value is valid
*/
double userInput;
do {
printf("Please input the actual resistance for resistor %d: ", i + 1);
if (scanf("%lf", &userInput) != 1) {
fflush(stdin);
printf("Invalid value given, please try again\n\r");
}
} while (userInput < 0);
return userInput;
}
double idealVal(int bandOne, int bandTwo, int bandThree, int bandFour, int bands) {
/*
Name: idealVal
Function: to return the nominal value based on the number of bands and the colours given
Paramaters: int bandOne, int bandTwo, int bandThree, int bandFout, int bands
Variables: ideal
Function will return the nominal value based on the colours of the bands input by using one of two cases (4 or 5/6 bands)
If 4 bands is the case, the program will use multVal on band 3 to find its multiplier value and will use this in the calculation, otherwise, band 4 will be passed to multVal
*/
double ideal;
switch (bands) {
case 4:
ideal = (bandOne * 10 + bandTwo) * multVal(bandThree);
return ideal;
break;
case 5:
ideal = ((bandOne * 100) + (bandTwo * 10) + bandThree) * multVal(bandFour);
return ideal;
break;
case 6:
ideal = ((bandOne * 100) + (bandTwo * 10) + bandThree) * multVal(bandFour);
return ideal;
break;
}
}
double multVal(int value) {
/*
Name: multVal
Function: Return the value of the multiplier band
Paramaters: int value
Variables: -
Function will return the value of the multiplier based on an integer input that would represent the index of a colour in the multiplierColours array
*/
switch (value) {
case 0:
return 0.01;
break;
case 1:
return 0.1;
break;
case 2:
return 1;
break;
case 3:
return 10;
break;
case 4:
return 100;
break;
case 5:
return 1000;
break;
case 6:
return 10000;
break;
case 7:
return 100000;
break;
case 8:
return 1000000;
break;
case 9:
return 10000000;
break;
default:
printf("Invalid value, cannot determine the multipier\n\r");
}
}
double tolVal(int value) {
/*
Name: tolVal
Function: Return the value of the tolerance band
Paramaters: int value
Variables: -
Function will return the value of the tolerance based on an integer input that would represent the index of a colour in the toleranceColours array
*/
switch (value) {
case 0:
return 0.1;
break;
case 1:
return 0.05;
break;
case 2:
return 0.01;
break;
case 3:
return 0.02;
break;
case 4:
return 0.005;
break;
case 5:
return 0.0025;
break;
case 6:
return 0.001;
break;
default:
printf("Invalid value, cannot determine the tolerance\n\r");
}
}
int tempVal(int value) {
/*
Name: tempVal
Function: Return the value of the temperature band
Paramaters: int value
Variables: -
Function will return the value of the temperature based on an integer inpur that would represent the index of a colour in the temperatureColours array
*/
switch (value) {
case 0:
return 100;
break;
case 1:
return 50;
break;
case 2:
return 15;
break;
case 3:
return 25;
break;
default:
printf("Invalid value, cannot determine the temperature tolerance\n\r");
}
}
double minTolVal(double a, float b) {
/*
Name: minTolVal
Function: Return the minimum tolerance value of the batch
Paramaters: double a, double b
Variables: -
Function will calulate and return the minimum tolerance value
*/
return a - a * b;
}
double maxTolVal(double a, float b) {
/*
Name: maxTolVal
Function: Return the maximum tolerance value of the batch
Paramaters: double a, double b
Variables: -
Function will calculate and return the maximum tolerance value
*/
return a + a * b;
}
double sampleMean(double a[10]) {
/*
Name: sampleMean
Function: Return the mean for the batch
Paramaters: double a[]
Variables: i
Function will calculate and return the mean value for the 10 actual values that have been input
*/
int i;
double mean, tot = 0;
for (i = 0; i < 10; i++) {
tot += a[i];
}
mean = tot / 10;
return mean;
}
float sampleStandDev(double a[10], double mean) {
/*
Name: sampleStandDev
Function: Return the standard deviation for the batch
Paramaters: double a[], double mean
Variables: i, tot
Function will calculate and return the standard deviation for the 10 actual values that have been input
*/
int i;
double tot = 0;
float standDev;
for (i = 0; i < 10; i++) {
tot += pow(a[i] - mean, 2);
}
standDev = tot / 10;
return standDev;
}
|
the_stack_data/7949006.c | //
// Created by Michal on 02-11-2016.
//
#include <stdio.h>
int NWD(int g_First, int g_Second)
{
int g_Third;
while(g_Second != 0)
{
g_Third = g_First % g_Second;
g_First = g_Second;
g_Second = g_Third;
}
return g_First;
}
int main(){
int g_First, g_Second, g_Result;
printf("Podaj pierwsza liczbe:\n");
scanf("%d", &g_First);
printf("\nPodaj druga liczbe:\n");
scanf("%d", &g_Second);
g_Result = NWD(g_First, g_Second);
printf("\nNWD: %d", g_Result);
return 0;
} |
the_stack_data/59511512.c | #include <stdio.h>
int main()
{
printf("hello world!\n");
return 0;
}
|
the_stack_data/23575379.c | #include <stdio.h>
int ternarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int midFirst = (start + (end - start) /3);
int midSecond = (midFirst + (end - start) /3);
if(array[midFirst] == key)
return midFirst;
if(array[midSecond] == key)
return midSecond;
if(key < array[midFirst])
return ternarySearch(array, start, midFirst-1, key);
if(key > array[midSecond])
return ternarySearch(array, midSecond+1, end, key);
return ternarySearch(array, midFirst+1, midSecond-1, key);
}
return -1;
}
int main() {
int n, searchKey, loc;
printf("Enter number of items: ");
scanf("%d", &n);
int arr[n];
printf("Enter items: ");
for(int i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter search key to search in the list: ");
scanf("%d", &searchKey);
if((loc = ternarySearch(arr, 0, n, searchKey)) >= 0)
printf("Item found at location: %d", loc);
else
printf("Item is not found in the list.");
}
/*
Input:
Enter number of items: 8
Enter items:
12 25 48 52 67 79 88 93
Enter search key to search in the list: 52
Output:
Item found at location: 3
*/
/*
Time Complexity: O(log_3 n)
Space Complexity: O(1)
*/
|
the_stack_data/371090.c | /*3:*/
#line 42 "./gb_graph.w"
#ifdef SYSV
#include <string.h>
#else
#include <strings.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#define gb_typed_alloc(n,t,s) (t*) gb_alloc((long) ((n) *sizeof(t) ) ,s) \
#define n_1 uu.I \
#define arcs_per_block 102 \
#define gb_new_graph gb_nugraph
#define gb_new_arc gb_nuarc
#define gb_new_edge gb_nuedge \
#define string_block_size 1016 \
#define hash_link u.V
#define hash_head v.V \
#define HASH_MULT 314159
#define HASH_PRIME 516595003 \
#line 50 "./gb_graph.w"
/*8:*/
#line 136 "./gb_graph.w"
typedef union{
struct vertex_struct*V;
struct arc_struct*A;
struct graph_struct*G;
char*S;
long I;
}util;
/*:8*//*9:*/
#line 162 "./gb_graph.w"
typedef struct vertex_struct{
struct arc_struct*arcs;
char*name;
util u,v,w,x,y,z;
}Vertex;
/*:9*//*10:*/
#line 181 "./gb_graph.w"
typedef struct arc_struct{
struct vertex_struct*tip;
struct arc_struct*next;
long len;
util a,b;
}Arc;
/*:10*//*12:*/
#line 234 "./gb_graph.w"
#define init_area(s) *s= NULL
struct area_pointers{
char*first;
struct area_pointers*next;
};
typedef struct area_pointers*Area[1];
/*:12*//*20:*/
#line 377 "./gb_graph.w"
#define ID_FIELD_SIZE 161
typedef struct graph_struct{
Vertex*vertices;
long n;
long m;
char id[ID_FIELD_SIZE];
char util_types[15];
Area data;
Area aux_data;
util uu,vv,ww,xx,yy,zz;
}Graph;
/*:20*//*34:*/
#line 670 "./gb_graph.w"
typedef unsigned long siz_t;
/*:34*/
#line 51 "./gb_graph.w"
/*28:*/
#line 521 "./gb_graph.w"
static Arc*next_arc;
static Arc*bad_arc;
static char*next_string;
static char*bad_string;
static Arc dummy_arc[2];
static Graph dummy_graph;
static Graph*cur_graph= &dummy_graph;
/*:28*/
#line 52 "./gb_graph.w"
/*5:*/
#line 79 "./gb_graph.w"
long verbose= 0;
long panic_code= 0;
/*:5*//*14:*/
#line 289 "./gb_graph.w"
long gb_trouble_code= 0;
/*:14*//*24:*/
#line 470 "./gb_graph.w"
long extra_n= 4;
char null_string[1];
/*:24*//*32:*/
#line 654 "./gb_graph.w"
siz_t edge_trick= sizeof(Arc)-(sizeof(Arc)&(sizeof(Arc)-1));
/*:32*/
#line 53 "./gb_graph.w"
/*13:*/
#line 267 "./gb_graph.w"
char*gb_alloc(n,s)
long n;
Area s;
{long m= sizeof(char*);
Area t;
char*loc;
if(n<=0||n> 0xffff00-2*m){
gb_trouble_code|= 2;
return NULL;
}
n= ((n+m-1)/m)*m;
loc= (char*)calloc((unsigned)((n+2*m+255)/256),256);
if(loc){
*t= (struct area_pointers*)(loc+n);
(*t)->first= loc;
(*t)->next= *s;
*s= *t;
}else gb_trouble_code|= 1;
return loc;
}
/*:13*//*16:*/
#line 298 "./gb_graph.w"
void gb_free(s)
Area s;
{Area t;
while(*s){
*t= (*s)->next;
free((*s)->first);
*s= *t;
}
}
/*:16*//*23:*/
#line 443 "./gb_graph.w"
Graph*gb_new_graph(n)
long n;
{
cur_graph= (Graph*)calloc(1,sizeof(Graph));
if(cur_graph){
cur_graph->vertices= gb_typed_alloc(n+extra_n,Vertex,cur_graph->data);
if(cur_graph->vertices){Vertex*p;
cur_graph->n= n;
for(p= cur_graph->vertices+n+extra_n-1;p>=cur_graph->vertices;p--)
p->name= null_string;
sprintf(cur_graph->id,"gb_new_graph(%ld)",n);
strcpy(cur_graph->util_types,"ZZZZZZZZZZZZZZ");
}else{
free((char*)cur_graph);
cur_graph= NULL;
}
}
next_arc= bad_arc= NULL;
next_string= bad_string= NULL;
gb_trouble_code= 0;
return cur_graph;
}
/*:23*//*26:*/
#line 486 "./gb_graph.w"
void make_compound_id(g,s1,gg,s2)
Graph*g;
char*s1;
Graph*gg;
char*s2;
{int avail= ID_FIELD_SIZE-strlen(s1)-strlen(s2);
char tmp[ID_FIELD_SIZE];
strcpy(tmp,gg->id);
if(strlen(tmp)<avail)sprintf(g->id,"%s%s%s",s1,tmp,s2);
else sprintf(g->id,"%s%.*s...)%s",s1,avail-5,tmp,s2);
}
/*:26*//*27:*/
#line 499 "./gb_graph.w"
void make_double_compound_id(g,s1,gg,s2,ggg,s3)
Graph*g;
char*s1;
Graph*gg;
char*s2;
Graph*ggg;
char*s3;
{int avail= ID_FIELD_SIZE-strlen(s1)-strlen(s2)-strlen(s3);
if(strlen(gg->id)+strlen(ggg->id)<avail)
sprintf(g->id,"%s%s%s%s%s",s1,gg->id,s2,ggg->id,s3);
else sprintf(g->id,"%s%.*s...)%s%.*s...)%s",s1,avail/2-5,gg->id,
s2,(avail-9)/2,ggg->id,s3);
}
/*:27*//*29:*/
#line 550 "./gb_graph.w"
Arc*gb_virgin_arc()
{register Arc*cur_arc= next_arc;
if(cur_arc==bad_arc){
cur_arc= gb_typed_alloc(arcs_per_block,Arc,cur_graph->data);
if(cur_arc==NULL)
cur_arc= dummy_arc;
else{
next_arc= cur_arc+1;
bad_arc= cur_arc+arcs_per_block;
}
}
else next_arc++;
return cur_arc;
}
/*:29*//*30:*/
#line 582 "./gb_graph.w"
void gb_new_arc(u,v,len)
Vertex*u,*v;
long len;
{register Arc*cur_arc= gb_virgin_arc();
cur_arc->tip= v;cur_arc->next= u->arcs;cur_arc->len= len;
u->arcs= cur_arc;
cur_graph->m++;
}
/*:30*//*31:*/
#line 627 "./gb_graph.w"
void gb_new_edge(u,v,len)
Vertex*u,*v;
long len;
{register Arc*cur_arc= gb_virgin_arc();
if(cur_arc!=dummy_arc)next_arc++;
if(u<v){
cur_arc->tip= v;cur_arc->next= u->arcs;
(cur_arc+1)->tip= u;(cur_arc+1)->next= v->arcs;
u->arcs= cur_arc;v->arcs= cur_arc+1;
}else{
(cur_arc+1)->tip= v;(cur_arc+1)->next= u->arcs;
u->arcs= cur_arc+1;
cur_arc->tip= u;cur_arc->next= v->arcs;
v->arcs= cur_arc;
}
cur_arc->len= (cur_arc+1)->len= len;
cur_graph->m+= 2;
}
/*:31*//*35:*/
#line 690 "./gb_graph.w"
char*gb_save_string(s)
register char*s;
{register char*p= s;
register long len;
while(*p++);
len= p-s;
p= next_string;
if(p+len> bad_string){
long size= string_block_size;
if(len> size)
size= len;
p= gb_alloc(size,cur_graph->data);
if(p==NULL)
return null_string;
bad_string= p+size;
}
while(*s)*p++= *s++;
*p++= '\0';
next_string= p;
return p-len;
}
/*:35*//*39:*/
#line 773 "./gb_graph.w"
void switch_to_graph(g)
Graph*g;
{
cur_graph->ww.A= next_arc;cur_graph->xx.A= bad_arc;
cur_graph->yy.S= next_string;cur_graph->zz.S= bad_string;
cur_graph= (g?g:&dummy_graph);
next_arc= cur_graph->ww.A;bad_arc= cur_graph->xx.A;
next_string= cur_graph->yy.S;bad_string= cur_graph->zz.S;
cur_graph->ww.A= NULL;
cur_graph->xx.A= NULL;
cur_graph->yy.S= NULL;
cur_graph->zz.S= NULL;
}
/*:39*//*40:*/
#line 791 "./gb_graph.w"
void gb_recycle(g)
Graph*g;
{
if(g){
gb_free(g->data);
gb_free(g->aux_data);
free((char*)g);
}
}
/*:40*//*44:*/
#line 856 "./gb_graph.w"
void hash_in(v)
Vertex*v;
{register char*t= v->name;
register Vertex*u;
/*45:*/
#line 884 "./gb_graph.w"
{register long h;
for(h= 0;*t;t++){
h+= (h^(h>>1))+HASH_MULT*(unsigned char)*t;
while(h>=HASH_PRIME)h-= HASH_PRIME;
}
u= cur_graph->vertices+(h%cur_graph->n);
}
/*:45*/
#line 861 "./gb_graph.w"
;
v->hash_link= u->hash_head;
u->hash_head= v;
}
/*:44*//*46:*/
#line 899 "./gb_graph.w"
Vertex*hash_out(s)
char*s;
{register char*t= s;
register Vertex*u;
/*45:*/
#line 884 "./gb_graph.w"
{register long h;
for(h= 0;*t;t++){
h+= (h^(h>>1))+HASH_MULT*(unsigned char)*t;
while(h>=HASH_PRIME)h-= HASH_PRIME;
}
u= cur_graph->vertices+(h%cur_graph->n);
}
/*:45*/
#line 904 "./gb_graph.w"
;
for(u= u->hash_head;u;u= u->hash_link)
if(strcmp(s,u->name)==0)return u;
return NULL;
}
/*:46*//*47:*/
#line 910 "./gb_graph.w"
void hash_setup(g)
Graph*g;
{Graph*save_cur_graph;
if(g&&g->n> 0){register Vertex*v;
save_cur_graph= cur_graph;
cur_graph= g;
for(v= g->vertices;v<g->vertices+g->n;v++)v->hash_head= NULL;
for(v= g->vertices;v<g->vertices+g->n;v++)hash_in(v);
g->util_types[0]= g->util_types[1]= 'V';
cur_graph= save_cur_graph;
}
}
/*:47*//*48:*/
#line 925 "./gb_graph.w"
Vertex*hash_lookup(s,g)
char*s;
Graph*g;
{Graph*save_cur_graph;
if(g&&g->n> 0){register Vertex*v;
save_cur_graph= cur_graph;
cur_graph= g;
v= hash_out(s);
cur_graph= save_cur_graph;
return v;
}
else return NULL;
}
/*:48*/
#line 54 "./gb_graph.w"
/*:3*/
|
the_stack_data/220456910.c | #include <stdio.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
int getint(int *pn);
int main()
{
int n;
while (getint(&n) > 0) {
printf("%d\n", n);
}
return 0;
}
/* getint: get next integer from input to *pn */
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch()));
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch();
if (!isdigit(c)) {
if (c != EOF) {
ungetch(c);
ungetch(sign > 0 ? '+' : '-');
return 0;
} else {
return c;
}
}
}
for (*pn = 0; isdigit(c); c = getch())
*pn = *pn * 10 + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
#define BUFSIZE 100
static char buf[BUFSIZE];
static int bufp = 0;
static int eof_encountered = 0;
int getch(void)
{
if (eof_encountered)
return EOF;
int val = (bufp > 0) ? buf[--bufp] : getchar();
if (val == EOF) {
eof_encountered = 1;
}
return val;
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
|
the_stack_data/116584.c | #include <stdio.h>
#include <stdlib.h>
int main() {
double r;
scanf("%lf", &r);
double vesfera = (4.0 / 3.0) * 3.14159 * (r * r * r) ;
printf("VOLUME = %.3lf\n", vesfera);
return 0;
}
|
the_stack_data/39773.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
static logical c_false = FALSE_;
static integer c__2 = 2;
static real c_b21 = 1.f;
static real c_b25 = 0.f;
static logical c_true = TRUE_;
/* > \brief \b SLAQTR solves a real quasi-triangular system of equations, or a complex quasi-triangular system
of special form, in real arithmetic. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download SLAQTR + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slaqtr.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slaqtr.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slaqtr.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE SLAQTR( LTRAN, LREAL, N, T, LDT, B, W, SCALE, X, WORK, */
/* INFO ) */
/* LOGICAL LREAL, LTRAN */
/* INTEGER INFO, LDT, N */
/* REAL SCALE, W */
/* REAL B( * ), T( LDT, * ), WORK( * ), X( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > SLAQTR solves the real quasi-triangular system */
/* > */
/* > op(T)*p = scale*c, if LREAL = .TRUE. */
/* > */
/* > or the complex quasi-triangular systems */
/* > */
/* > op(T + iB)*(p+iq) = scale*(c+id), if LREAL = .FALSE. */
/* > */
/* > in real arithmetic, where T is upper quasi-triangular. */
/* > If LREAL = .FALSE., then the first diagonal block of T must be */
/* > 1 by 1, B is the specially structured matrix */
/* > */
/* > B = [ b(1) b(2) ... b(n) ] */
/* > [ w ] */
/* > [ w ] */
/* > [ . ] */
/* > [ w ] */
/* > */
/* > op(A) = A or A**T, A**T denotes the transpose of */
/* > matrix A. */
/* > */
/* > On input, X = [ c ]. On output, X = [ p ]. */
/* > [ d ] [ q ] */
/* > */
/* > This subroutine is designed for the condition number estimation */
/* > in routine STRSNA. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] LTRAN */
/* > \verbatim */
/* > LTRAN is LOGICAL */
/* > On entry, LTRAN specifies the option of conjugate transpose: */
/* > = .FALSE., op(T+i*B) = T+i*B, */
/* > = .TRUE., op(T+i*B) = (T+i*B)**T. */
/* > \endverbatim */
/* > */
/* > \param[in] LREAL */
/* > \verbatim */
/* > LREAL is LOGICAL */
/* > On entry, LREAL specifies the input matrix structure: */
/* > = .FALSE., the input is complex */
/* > = .TRUE., the input is real */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > On entry, N specifies the order of T+i*B. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] T */
/* > \verbatim */
/* > T is REAL array, dimension (LDT,N) */
/* > On entry, T contains a matrix in Schur canonical form. */
/* > If LREAL = .FALSE., then the first diagonal block of T must */
/* > be 1 by 1. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the matrix T. LDT >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] B */
/* > \verbatim */
/* > B is REAL array, dimension (N) */
/* > On entry, B contains the elements to form the matrix */
/* > B as described above. */
/* > If LREAL = .TRUE., B is not referenced. */
/* > \endverbatim */
/* > */
/* > \param[in] W */
/* > \verbatim */
/* > W is REAL */
/* > On entry, W is the diagonal element of the matrix B. */
/* > If LREAL = .TRUE., W is not referenced. */
/* > \endverbatim */
/* > */
/* > \param[out] SCALE */
/* > \verbatim */
/* > SCALE is REAL */
/* > On exit, SCALE is the scale factor. */
/* > \endverbatim */
/* > */
/* > \param[in,out] X */
/* > \verbatim */
/* > X is REAL array, dimension (2*N) */
/* > On entry, X contains the right hand side of the system. */
/* > On exit, X is overwritten by the solution. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is REAL array, dimension (N) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > On exit, INFO is set to */
/* > 0: successful exit. */
/* > 1: the some diagonal 1 by 1 block has been perturbed by */
/* > a small number SMIN to keep nonsingularity. */
/* > 2: the some diagonal 2 by 2 block has been perturbed by */
/* > a small number in SLALN2 to keep nonsingularity. */
/* > NOTE: In the interests of speed, this routine does not */
/* > check the inputs for errors. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup realOTHERauxiliary */
/* ===================================================================== */
/* Subroutine */ int slaqtr_(logical *ltran, logical *lreal, integer *n, real
*t, integer *ldt, real *b, real *w, real *scale, real *x, real *work,
integer *info)
{
/* System generated locals */
integer t_dim1, t_offset, i__1, i__2;
real r__1, r__2, r__3, r__4, r__5, r__6;
/* Local variables */
integer ierr;
real smin;
extern real sdot_(integer *, real *, integer *, real *, integer *);
real xmax, d__[4] /* was [2][2] */;
integer i__, j, k;
real v[4] /* was [2][2] */, z__;
extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *);
integer jnext;
extern real sasum_(integer *, real *, integer *);
integer j1, j2;
real sminw;
integer n1, n2;
real xnorm;
extern /* Subroutine */ int saxpy_(integer *, real *, real *, integer *,
real *, integer *), slaln2_(logical *, integer *, integer *, real
*, real *, real *, integer *, real *, real *, real *, integer *,
real *, real *, real *, integer *, real *, real *, integer *);
real si, xj, scaloc, sr;
extern real slamch_(char *), slange_(char *, integer *, integer *,
real *, integer *, real *);
real bignum;
extern integer isamax_(integer *, real *, integer *);
extern /* Subroutine */ int sladiv_(real *, real *, real *, real *, real *
, real *);
logical notran;
real smlnum, rec, eps, tjj, tmp;
/* -- 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 */
/* ===================================================================== */
/* Do not test the input parameters for errors */
/* Parameter adjustments */
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
--b;
--x;
--work;
/* Function Body */
notran = ! (*ltran);
*info = 0;
/* Quick return if possible */
if (*n == 0) {
return 0;
}
/* Set constants to control overflow */
eps = slamch_("P");
smlnum = slamch_("S") / eps;
bignum = 1.f / smlnum;
xnorm = slange_("M", n, n, &t[t_offset], ldt, d__);
if (! (*lreal)) {
/* Computing MAX */
r__1 = xnorm, r__2 = abs(*w), r__1 = f2cmax(r__1,r__2), r__2 = slange_(
"M", n, &c__1, &b[1], n, d__);
xnorm = f2cmax(r__1,r__2);
}
/* Computing MAX */
r__1 = smlnum, r__2 = eps * xnorm;
smin = f2cmax(r__1,r__2);
/* Compute 1-norm of each column of strictly upper triangular */
/* part of T to control overflow in triangular solver. */
work[1] = 0.f;
i__1 = *n;
for (j = 2; j <= i__1; ++j) {
i__2 = j - 1;
work[j] = sasum_(&i__2, &t[j * t_dim1 + 1], &c__1);
/* L10: */
}
if (! (*lreal)) {
i__1 = *n;
for (i__ = 2; i__ <= i__1; ++i__) {
work[i__] += (r__1 = b[i__], abs(r__1));
/* L20: */
}
}
n2 = *n << 1;
n1 = *n;
if (! (*lreal)) {
n1 = n2;
}
k = isamax_(&n1, &x[1], &c__1);
xmax = (r__1 = x[k], abs(r__1));
*scale = 1.f;
if (xmax > bignum) {
*scale = bignum / xmax;
sscal_(&n1, scale, &x[1], &c__1);
xmax = bignum;
}
if (*lreal) {
if (notran) {
/* Solve T*p = scale*c */
jnext = *n;
for (j = *n; j >= 1; --j) {
if (j > jnext) {
goto L30;
}
j1 = j;
j2 = j;
jnext = j - 1;
if (j > 1) {
if (t[j + (j - 1) * t_dim1] != 0.f) {
j1 = j - 1;
jnext = j - 2;
}
}
if (j1 == j2) {
/* Meet 1 by 1 diagonal block */
/* Scale to avoid overflow when computing */
/* x(j) = b(j)/T(j,j) */
xj = (r__1 = x[j1], abs(r__1));
tjj = (r__1 = t[j1 + j1 * t_dim1], abs(r__1));
tmp = t[j1 + j1 * t_dim1];
if (tjj < smin) {
tmp = smin;
tjj = smin;
*info = 1;
}
if (xj == 0.f) {
goto L30;
}
if (tjj < 1.f) {
if (xj > bignum * tjj) {
rec = 1.f / xj;
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
x[j1] /= tmp;
xj = (r__1 = x[j1], abs(r__1));
/* Scale x if necessary to avoid overflow when adding a */
/* multiple of column j1 of T. */
if (xj > 1.f) {
rec = 1.f / xj;
if (work[j1] > (bignum - xmax) * rec) {
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
}
}
if (j1 > 1) {
i__1 = j1 - 1;
r__1 = -x[j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
k = isamax_(&i__1, &x[1], &c__1);
xmax = (r__1 = x[k], abs(r__1));
}
} else {
/* Meet 2 by 2 diagonal block */
/* Call 2 by 2 linear system solve, to take */
/* care of possible overflow by scaling factor. */
d__[0] = x[j1];
d__[1] = x[j2];
slaln2_(&c_false, &c__2, &c__1, &smin, &c_b21, &t[j1 + j1
* t_dim1], ldt, &c_b21, &c_b21, d__, &c__2, &
c_b25, &c_b25, v, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 2;
}
if (scaloc != 1.f) {
sscal_(n, &scaloc, &x[1], &c__1);
*scale *= scaloc;
}
x[j1] = v[0];
x[j2] = v[1];
/* Scale V(1,1) (= X(J1)) and/or V(2,1) (=X(J2)) */
/* to avoid overflow in updating right-hand side. */
/* Computing MAX */
r__1 = abs(v[0]), r__2 = abs(v[1]);
xj = f2cmax(r__1,r__2);
if (xj > 1.f) {
rec = 1.f / xj;
/* Computing MAX */
r__1 = work[j1], r__2 = work[j2];
if (f2cmax(r__1,r__2) > (bignum - xmax) * rec) {
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
}
}
/* Update right-hand side */
if (j1 > 1) {
i__1 = j1 - 1;
r__1 = -x[j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
r__1 = -x[j2];
saxpy_(&i__1, &r__1, &t[j2 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
k = isamax_(&i__1, &x[1], &c__1);
xmax = (r__1 = x[k], abs(r__1));
}
}
L30:
;
}
} else {
/* Solve T**T*p = scale*c */
jnext = 1;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
if (j < jnext) {
goto L40;
}
j1 = j;
j2 = j;
jnext = j + 1;
if (j < *n) {
if (t[j + 1 + j * t_dim1] != 0.f) {
j2 = j + 1;
jnext = j + 2;
}
}
if (j1 == j2) {
/* 1 by 1 diagonal block */
/* Scale if necessary to avoid overflow in forming the */
/* right-hand side element by inner product. */
xj = (r__1 = x[j1], abs(r__1));
if (xmax > 1.f) {
rec = 1.f / xmax;
if (work[j1] > (bignum - xj) * rec) {
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
i__2 = j1 - 1;
x[j1] -= sdot_(&i__2, &t[j1 * t_dim1 + 1], &c__1, &x[1], &
c__1);
xj = (r__1 = x[j1], abs(r__1));
tjj = (r__1 = t[j1 + j1 * t_dim1], abs(r__1));
tmp = t[j1 + j1 * t_dim1];
if (tjj < smin) {
tmp = smin;
tjj = smin;
*info = 1;
}
if (tjj < 1.f) {
if (xj > bignum * tjj) {
rec = 1.f / xj;
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
x[j1] /= tmp;
/* Computing MAX */
r__2 = xmax, r__3 = (r__1 = x[j1], abs(r__1));
xmax = f2cmax(r__2,r__3);
} else {
/* 2 by 2 diagonal block */
/* Scale if necessary to avoid overflow in forming the */
/* right-hand side elements by inner product. */
/* Computing MAX */
r__3 = (r__1 = x[j1], abs(r__1)), r__4 = (r__2 = x[j2],
abs(r__2));
xj = f2cmax(r__3,r__4);
if (xmax > 1.f) {
rec = 1.f / xmax;
/* Computing MAX */
r__1 = work[j2], r__2 = work[j1];
if (f2cmax(r__1,r__2) > (bignum - xj) * rec) {
sscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
i__2 = j1 - 1;
d__[0] = x[j1] - sdot_(&i__2, &t[j1 * t_dim1 + 1], &c__1,
&x[1], &c__1);
i__2 = j1 - 1;
d__[1] = x[j2] - sdot_(&i__2, &t[j2 * t_dim1 + 1], &c__1,
&x[1], &c__1);
slaln2_(&c_true, &c__2, &c__1, &smin, &c_b21, &t[j1 + j1 *
t_dim1], ldt, &c_b21, &c_b21, d__, &c__2, &c_b25,
&c_b25, v, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 2;
}
if (scaloc != 1.f) {
sscal_(n, &scaloc, &x[1], &c__1);
*scale *= scaloc;
}
x[j1] = v[0];
x[j2] = v[1];
/* Computing MAX */
r__3 = (r__1 = x[j1], abs(r__1)), r__4 = (r__2 = x[j2],
abs(r__2)), r__3 = f2cmax(r__3,r__4);
xmax = f2cmax(r__3,xmax);
}
L40:
;
}
}
} else {
/* Computing MAX */
r__1 = eps * abs(*w);
sminw = f2cmax(r__1,smin);
if (notran) {
/* Solve (T + iB)*(p+iq) = c+id */
jnext = *n;
for (j = *n; j >= 1; --j) {
if (j > jnext) {
goto L70;
}
j1 = j;
j2 = j;
jnext = j - 1;
if (j > 1) {
if (t[j + (j - 1) * t_dim1] != 0.f) {
j1 = j - 1;
jnext = j - 2;
}
}
if (j1 == j2) {
/* 1 by 1 diagonal block */
/* Scale if necessary to avoid overflow in division */
z__ = *w;
if (j1 == 1) {
z__ = b[1];
}
xj = (r__1 = x[j1], abs(r__1)) + (r__2 = x[*n + j1], abs(
r__2));
tjj = (r__1 = t[j1 + j1 * t_dim1], abs(r__1)) + abs(z__);
tmp = t[j1 + j1 * t_dim1];
if (tjj < sminw) {
tmp = sminw;
tjj = sminw;
*info = 1;
}
if (xj == 0.f) {
goto L70;
}
if (tjj < 1.f) {
if (xj > bignum * tjj) {
rec = 1.f / xj;
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
sladiv_(&x[j1], &x[*n + j1], &tmp, &z__, &sr, &si);
x[j1] = sr;
x[*n + j1] = si;
xj = (r__1 = x[j1], abs(r__1)) + (r__2 = x[*n + j1], abs(
r__2));
/* Scale x if necessary to avoid overflow when adding a */
/* multiple of column j1 of T. */
if (xj > 1.f) {
rec = 1.f / xj;
if (work[j1] > (bignum - xmax) * rec) {
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
}
}
if (j1 > 1) {
i__1 = j1 - 1;
r__1 = -x[j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
r__1 = -x[*n + j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[*
n + 1], &c__1);
x[1] += b[j1] * x[*n + j1];
x[*n + 1] -= b[j1] * x[j1];
xmax = 0.f;
i__1 = j1 - 1;
for (k = 1; k <= i__1; ++k) {
/* Computing MAX */
r__3 = xmax, r__4 = (r__1 = x[k], abs(r__1)) + (
r__2 = x[k + *n], abs(r__2));
xmax = f2cmax(r__3,r__4);
/* L50: */
}
}
} else {
/* Meet 2 by 2 diagonal block */
d__[0] = x[j1];
d__[1] = x[j2];
d__[2] = x[*n + j1];
d__[3] = x[*n + j2];
r__1 = -(*w);
slaln2_(&c_false, &c__2, &c__2, &sminw, &c_b21, &t[j1 +
j1 * t_dim1], ldt, &c_b21, &c_b21, d__, &c__2, &
c_b25, &r__1, v, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 2;
}
if (scaloc != 1.f) {
i__1 = *n << 1;
sscal_(&i__1, &scaloc, &x[1], &c__1);
*scale = scaloc * *scale;
}
x[j1] = v[0];
x[j2] = v[1];
x[*n + j1] = v[2];
x[*n + j2] = v[3];
/* Scale X(J1), .... to avoid overflow in */
/* updating right hand side. */
/* Computing MAX */
r__1 = abs(v[0]) + abs(v[2]), r__2 = abs(v[1]) + abs(v[3])
;
xj = f2cmax(r__1,r__2);
if (xj > 1.f) {
rec = 1.f / xj;
/* Computing MAX */
r__1 = work[j1], r__2 = work[j2];
if (f2cmax(r__1,r__2) > (bignum - xmax) * rec) {
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
}
}
/* Update the right-hand side. */
if (j1 > 1) {
i__1 = j1 - 1;
r__1 = -x[j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
r__1 = -x[j2];
saxpy_(&i__1, &r__1, &t[j2 * t_dim1 + 1], &c__1, &x[1]
, &c__1);
i__1 = j1 - 1;
r__1 = -x[*n + j1];
saxpy_(&i__1, &r__1, &t[j1 * t_dim1 + 1], &c__1, &x[*
n + 1], &c__1);
i__1 = j1 - 1;
r__1 = -x[*n + j2];
saxpy_(&i__1, &r__1, &t[j2 * t_dim1 + 1], &c__1, &x[*
n + 1], &c__1);
x[1] = x[1] + b[j1] * x[*n + j1] + b[j2] * x[*n + j2];
x[*n + 1] = x[*n + 1] - b[j1] * x[j1] - b[j2] * x[j2];
xmax = 0.f;
i__1 = j1 - 1;
for (k = 1; k <= i__1; ++k) {
/* Computing MAX */
r__3 = (r__1 = x[k], abs(r__1)) + (r__2 = x[k + *
n], abs(r__2));
xmax = f2cmax(r__3,xmax);
/* L60: */
}
}
}
L70:
;
}
} else {
/* Solve (T + iB)**T*(p+iq) = c+id */
jnext = 1;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
if (j < jnext) {
goto L80;
}
j1 = j;
j2 = j;
jnext = j + 1;
if (j < *n) {
if (t[j + 1 + j * t_dim1] != 0.f) {
j2 = j + 1;
jnext = j + 2;
}
}
if (j1 == j2) {
/* 1 by 1 diagonal block */
/* Scale if necessary to avoid overflow in forming the */
/* right-hand side element by inner product. */
xj = (r__1 = x[j1], abs(r__1)) + (r__2 = x[j1 + *n], abs(
r__2));
if (xmax > 1.f) {
rec = 1.f / xmax;
if (work[j1] > (bignum - xj) * rec) {
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
i__2 = j1 - 1;
x[j1] -= sdot_(&i__2, &t[j1 * t_dim1 + 1], &c__1, &x[1], &
c__1);
i__2 = j1 - 1;
x[*n + j1] -= sdot_(&i__2, &t[j1 * t_dim1 + 1], &c__1, &x[
*n + 1], &c__1);
if (j1 > 1) {
x[j1] -= b[j1] * x[*n + 1];
x[*n + j1] += b[j1] * x[1];
}
xj = (r__1 = x[j1], abs(r__1)) + (r__2 = x[j1 + *n], abs(
r__2));
z__ = *w;
if (j1 == 1) {
z__ = b[1];
}
/* Scale if necessary to avoid overflow in */
/* complex division */
tjj = (r__1 = t[j1 + j1 * t_dim1], abs(r__1)) + abs(z__);
tmp = t[j1 + j1 * t_dim1];
if (tjj < sminw) {
tmp = sminw;
tjj = sminw;
*info = 1;
}
if (tjj < 1.f) {
if (xj > bignum * tjj) {
rec = 1.f / xj;
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
r__1 = -z__;
sladiv_(&x[j1], &x[*n + j1], &tmp, &r__1, &sr, &si);
x[j1] = sr;
x[j1 + *n] = si;
/* Computing MAX */
r__3 = (r__1 = x[j1], abs(r__1)) + (r__2 = x[j1 + *n],
abs(r__2));
xmax = f2cmax(r__3,xmax);
} else {
/* 2 by 2 diagonal block */
/* Scale if necessary to avoid overflow in forming the */
/* right-hand side element by inner product. */
/* Computing MAX */
r__5 = (r__1 = x[j1], abs(r__1)) + (r__2 = x[*n + j1],
abs(r__2)), r__6 = (r__3 = x[j2], abs(r__3)) + (
r__4 = x[*n + j2], abs(r__4));
xj = f2cmax(r__5,r__6);
if (xmax > 1.f) {
rec = 1.f / xmax;
/* Computing MAX */
r__1 = work[j1], r__2 = work[j2];
if (f2cmax(r__1,r__2) > (bignum - xj) / xmax) {
sscal_(&n2, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
i__2 = j1 - 1;
d__[0] = x[j1] - sdot_(&i__2, &t[j1 * t_dim1 + 1], &c__1,
&x[1], &c__1);
i__2 = j1 - 1;
d__[1] = x[j2] - sdot_(&i__2, &t[j2 * t_dim1 + 1], &c__1,
&x[1], &c__1);
i__2 = j1 - 1;
d__[2] = x[*n + j1] - sdot_(&i__2, &t[j1 * t_dim1 + 1], &
c__1, &x[*n + 1], &c__1);
i__2 = j1 - 1;
d__[3] = x[*n + j2] - sdot_(&i__2, &t[j2 * t_dim1 + 1], &
c__1, &x[*n + 1], &c__1);
d__[0] -= b[j1] * x[*n + 1];
d__[1] -= b[j2] * x[*n + 1];
d__[2] += b[j1] * x[1];
d__[3] += b[j2] * x[1];
slaln2_(&c_true, &c__2, &c__2, &sminw, &c_b21, &t[j1 + j1
* t_dim1], ldt, &c_b21, &c_b21, d__, &c__2, &
c_b25, w, v, &c__2, &scaloc, &xnorm, &ierr);
if (ierr != 0) {
*info = 2;
}
if (scaloc != 1.f) {
sscal_(&n2, &scaloc, &x[1], &c__1);
*scale = scaloc * *scale;
}
x[j1] = v[0];
x[j2] = v[1];
x[*n + j1] = v[2];
x[*n + j2] = v[3];
/* Computing MAX */
r__5 = (r__1 = x[j1], abs(r__1)) + (r__2 = x[*n + j1],
abs(r__2)), r__6 = (r__3 = x[j2], abs(r__3)) + (
r__4 = x[*n + j2], abs(r__4)), r__5 = f2cmax(r__5,
r__6);
xmax = f2cmax(r__5,xmax);
}
L80:
;
}
}
}
return 0;
/* End of SLAQTR */
} /* slaqtr_ */
|
the_stack_data/729778.c | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char * filepath;
FILE * fp;
fp = (argc == 2) ? fopen(argv[1], "r") : stdin ;
double sum = .0, tmp = .0;
int count = 0, num;
if (argc != 2)
puts("Enter numbers (q to finish):");
while((num = fscanf(fp, "%lf", &tmp)) > 0){
sum += tmp;
count ++;
}
fclose(fp);
printf("The average of array is %.3lf\n", sum/count);
return 0;
} |
the_stack_data/86075737.c | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h> // int8_t, etc., intmax_t , uintmax_t,
#include <inttypes.h> // uint8_t, ..., uintmax_t i = UINTMAX_MAX; // this type always exists
#include <stddef.h> // offsetof(type, member-designator)
#include <stdio.h> // remove, int rename(const char *old, const char *new); ,
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <math.h> // cosf, ..., int signbit(real-floating x); , isnormal(neither zero, subnormal, infinite, nor NaN)., int isnan(real-floating x); , int isinf(real-floating x); int isfinite(real-floating x);
#include <ctype.h> // tolower, toupper
#include <assert.h> // dépend de la valeur de la macro NDEBUG
#ifndef __TINYC__ // For some reasons, TCC fails to read this file.
#include <complex.h> // types «complex», «double complex», «long double complex», «float complex»
#endif
#include <ctype.h>
#include <errno.h>
#include <float.h> // limits
#include <iso646.h> // Alternative spellings: and &&, xor ^, etc.
#include <limits.h>
#include <setjmp.h>
#include <signal.h>
#include <time.h> // clock & time ---
#ifndef __PCC__ // For some reasons, PCC fails to read these files.
#include <wchar.h>
#include <wctype.h>
#endif
#include <locale.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h> // time_t, time(), ctime() ; ("man 3 time") donne la date d'ajd
#ifndef ctime_r
# define ctime_r(a,b) ((b == NULL ? 0 : strcpy(b, "FAILED ")), *a = time(NULL), ctime(a))
#endif
enum bool {true = (0 == 0), false = (0 != 0)};
typedef enum bool bool;
static char * string_replace(const char * text, const char * old_str, const char * new_str);
static int nb_occurrences(const char * text, const char * old_str);
int main(const int argc, const char * argv[]) {
if (1 != argc) {
printf("usage: %s (without any arguments)\n", argv[0]);
printf("Turn text on stdin into upper case.\n");
return -1;
}
#define BUF_SIZE 4096
ssize_t nb_read;
// ll /dev/std*
// 2: stderr
// 1: stdout
// 0: stdin
char buf[BUF_SIZE];
for (;;) {
//ssize_t read(int fildes, void *buf, size_t nbyte);
nb_read = read(0, buf, BUF_SIZE);
if (nb_read <= 0) return 0;
for (int i = 0; i < nb_read; i++)
buf[i] = toupper(buf[i]);
write(1, buf, nb_read);
}
assert(false);
return -1;
}
char * string_replace(const char * text, const char * old_str, const char * new_str) {
const size_t text_len = strlen(text);
const size_t old_str_len = strlen(old_str);
const size_t new_str_len = strlen(new_str);
const int nb_occ = nb_occurrences(text, old_str);
const size_t new_len = text_len + nb_occ * (new_str_len - old_str_len);
#if 0
fprintf(stderr, "nb occ: %d\n", nb_occ);
printf("old len: %lu\n", old_str_len);
printf("new len: %lu\n", new_str_len);
printf("text len: %lu\n", text_len);
printf("new len: %lu\n", new_len);
#endif
char * nv_text = (char *) malloc((new_len + 1) * (sizeof (char)));
nv_text[new_len] = '\0';
const char c = old_str[0];
size_t old_pos = 0;
size_t new_pos = 0;
while (text[old_pos] != '\0') {
if ((text[old_pos] == c) && ((text_len - old_pos) >= old_str_len) && (0 == memcmp(&(text[old_pos]), old_str, old_str_len))) {
memcpy(nv_text + new_pos, new_str, new_str_len);
new_pos += new_str_len;
//text += old_str_len;
old_pos += old_str_len;
}
else {
nv_text[new_pos] = text[old_pos];
new_pos++;
old_pos++;
}
assert(new_pos <= new_len);
assert(old_pos <= text_len);
}
assert(new_pos == new_len);
nv_text[new_pos] = '\0';
return nv_text;
}
int nb_occurrences(const char * text, const char * old_str) {
const size_t text_len = strlen(text);
const size_t len = strlen(old_str);
const char c = old_str[0];
int nb = 0;
size_t pos = 0;
while (text[pos] != '\0') {
if ((text[pos] == c) && ((text_len - pos) >= len) && (0 == memcmp(&(text[pos]), old_str, len))) {
nb++;
pos += len;
}
else {
pos++;
}
}
assert(pos == text_len);
return nb;
}
|
the_stack_data/108740.c | #include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
typedef struct stack
{
node *top;
}stack;
stack *init()
{
stack *t=(stack *)malloc(sizeof(stack));
t->top=NULL;
return t;
}
stack *push(stack *s,int x)
{
node *p=(node *)malloc(sizeof(node));
p->data=x;
p->next=s->top;
s->top=p;
return s;
}
stack *pop(stack *s)
{
node *p=s->top;
if(p==NULL)return s;
s->top=s->top->next;
free(p);
return s;
}
int main()
{int n;stack *s=init();
scanf("%d",&n);
int price[n],k,span[n],i;
for(i=0;i<n;i++)
{
scanf("%d",&price[i]);
}
span[0]=1;
s=push(s,0);
for(i=1,k=1;i<n;i++,k++)
{
if(price[i]< price[s->top->data] )
{
s=push(s,i);span[k]=1;
}
else
{
while(s->top!=NULL)
{if(price[i] > price[s->top->data])
s=pop(s);
else
break;
}
if(s->top!=NULL)
{
s=push(s,i);span[k]=(s->top->data)- (s->top->next->data);
}
else
{span[k]=i+1;s=push(s,i);}
}
}
for(i=0;i<n;i++)
{
printf("%d",span[i]);
}
}
|
the_stack_data/153268437.c | /*
* @f ccnl-nfnkrivine.c
* @b CCN-lite, Krivine's lazy Lambda-Calculus reduction engine
*
* Copyright (C) 2013-14, Christian Tschudin, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2013-05-10 created
* 2014-07-31 CCN-lite integration <[email protected]>
*/
#ifdef USE_NFN
#include "ccnl-nfn-krivine.h"
#include "ccnl-nfn-common.h"
#include "ccnl-nfn-parse.h"
#include "ccnl-nfn-ops.h"
#include "ccnl-os-time.h"
#include "ccnl-malloc.h"
#include "ccnl-logging.h"
#ifndef CCNL_LINUXKERNEL
#include "ccnl-os-includes.h"
enum { // abstract machine instruction set
ZAM_UNKNOWN,
ZAM_ACCESS,
ZAM_APPLY,
ZAM_CALL,
ZAM_CLOSURE,
ZAM_FOX,
ZAM_GRAB,
ZAM_HALT,
ZAM_RESOLVENAME,
ZAM_TAILAPPLY
};
// ------------------------------------------------------------------
// Machine state functions
struct closure_s *
new_closure(char *term, struct environment_s *env)
{
struct closure_s *ret = ccnl_calloc(1, sizeof(struct closure_s));
ret->term = term;
ret->env = env;
ccnl_nfn_reserveEnvironment(env);
return ret;
}
void
push_to_stack(struct stack_s **top, void *content, int type)
{
struct stack_s *h;
if (!top)
return;
h = ccnl_calloc(1, sizeof(struct stack_s));
if (h) {
DEBUGMSG(TRACE, "push_to_stack: %p\n", (void*)h);
h->next = *top;
h->content = content;
h->type = type;
*top = h;
}
}
struct stack_s *
pop_from_stack(struct stack_s **top)
{
struct stack_s *res;
if (top == NULL || *top == NULL)
return NULL;
res = *top;
*top = res->next;
res->next = NULL;
return res;
}
struct stack_s *
pop_or_resolve_from_result_stack(struct ccnl_relay_s *ccnl,
struct configuration_s *config)
// , int *restart)
{
struct stack_s *elm = pop_from_stack(&config->result_stack);
(void)ccnl;
if (!elm)
return NULL;
DEBUGMSG(TRACE, "pop_or_resolve_from_RS: conf=%p, elm=%p, type=%d\n",
(void*)config, (void*)elm, elm->type);
return elm;
}
int
stack_len(struct stack_s *s)
{
int cnt;
for (cnt = 0; s; s = s->next)
cnt++;
return cnt;
}
// #ifdef XXX
void
print_environment(struct environment_s *env)
{
int num = 0;
printf(" env addr %p (refcount=%d)\n",
(void*) env, env ? env->refcount : -1);
while (env) {
printf(" #%d %s %p\n", num++, env->name, (void*) env->closure);
env = env->next;
}
}
void
print_result_stack(struct stack_s *stack)
{
int num = 0;
while (stack) {
printf("Res element #%d: type=%d\n", num++, stack->type);
stack = stack -> next;
}
}
void
print_argument_stack(struct stack_s *stack)
{
int num = 0;
while (stack){
struct closure_s *c = stack->content;
printf("Arg element #%d: %s\n", num++, c ? c->term : "<mark>");
if (c)
print_environment(c->env);
stack = stack->next;
}
}
// #endif
void
add_to_environment(struct environment_s **env, char *name,
struct closure_s *closure)
{
struct environment_s *e;
if (!env)
return;
e = ccnl_calloc(1, sizeof(struct environment_s));
e->name = name;
e->closure = closure;
e->next = *env;
*env = e;
ccnl_nfn_reserveEnvironment(*env);
}
struct closure_s*
search_in_environment(struct environment_s *env, char *name)
{
for (; env; env = env->next)
if (!strcmp(name, env->name))
return env->closure;
return NULL;
}
int
iscontentname(char *cp)
{
return cp[0] == '/';
}
// ----------------------------------------------------------------------
//choose the it_routable_param
int choose_parameter(struct configuration_s *config){
int num, param_to_choose = config->fox_state->it_routable_param;
DEBUGMSG(DEBUG, "choose_parameter(%d)\n", param_to_choose);
for(num = config->fox_state->num_of_params-1; num >=0; --num){
if(!config->fox_state->params[num]) { break;}
if(config->fox_state->params[num]->type == STACK_TYPE_PREFIX){
--param_to_choose;
if(param_to_choose <= 0){
return num;
}
}
}
return -1;
}
struct ccnl_prefix_s *
create_namecomps(struct ccnl_relay_s *ccnl, struct configuration_s *config,
int parameter_number, struct ccnl_prefix_s *prefix)
{
DEBUGMSG(TRACE, "create_namecomps\n");
if (config->start_locally ||
ccnl_nfn_local_content_search(ccnl, config, prefix)) {
//local computation name components
DEBUGMSG(DEBUG, "content local available\n");
struct ccnl_prefix_s *pref = ccnl_nfnprefix_mkComputePrefix(config, prefix->suite);
DEBUGMSG(DEBUG, "LOCAL PREFIX: %s\n", ccnl_prefix_to_path(pref));
return pref;
}
return ccnl_nfnprefix_mkCallPrefix(prefix, config, parameter_number);
}
// ----------------------------------------------------------------------
// return a positive integer if ZAM instuction, or
// return a negative integer if a builtin op, otherwise return 0
int
ZAM_nextToken(char *prog, char **argdup, char **cont)
{
char *cp = prog, *cp2;
int len;
int token = ZAM_UNKNOWN;
// TODO: count opening/closing parentheses when hunting for ';' ?
while (*cp && *cp != '(' && *cp != ';')
cp++;
len = cp - prog;
if (!strncmp(prog, "ACCESS", len))
token = ZAM_ACCESS;
else if (!strncmp(prog, "APPLY", len))
token = ZAM_APPLY;
else if (!strncmp(prog, "CALL", len))
token = ZAM_CALL;
else if (!strncmp(prog, "CLOSURE", len))
token = ZAM_CLOSURE;
else if (!strncmp(prog, "FOX", len))
token = ZAM_FOX;
else if (!strncmp(prog, "GRAB", len))
token = ZAM_GRAB;
else if (!strncmp(prog, "HALT", len))
token = ZAM_HALT;
else if (!strncmp(prog, "RESOLVENAME", len))
token = ZAM_RESOLVENAME;
else if (!strncmp(prog, "TAILAPPLY", len))
token = ZAM_TAILAPPLY;
else {
for (len = 0; bifs[len].name; len++)
if (!strncmp(prog, bifs[len].name, strlen(bifs[len].name))) {
token = -(len+1);
break;
}
if (token == ZAM_UNKNOWN)
DEBUGMSG(INFO, " ** DID NOT find %s\n", prog);
}
if (*cp == '(') {
int nesting = 0;
cp2 = ++cp;
while (*cp2 && (*cp2 != ')' || nesting > 0)) {
if (*cp2 == '(')
nesting++;
else if (*cp2 == ')')
nesting--;
cp2++;
}
len = cp2 - cp;
*argdup = ccnl_malloc(len + 1);
memcpy(*argdup, cp, len);
(*argdup)[len] = '\0';
if (*cp2)
cp = cp2 + 1;
} else
*argdup = NULL;
if (*cp == ';')
*cont = cp + 1;
else
*cont = NULL;
return token;
}
char*
ZAM_fox(struct ccnl_relay_s *ccnl, struct configuration_s *config,
int *restart, int *halt, char *prog, char *arg, char *contd)
{
int local_search = 0, i;
int parameter_number = 0;
struct ccnl_content_s *c = NULL;
struct ccnl_prefix_s *pref;
struct ccnl_interest_s *interest;
DEBUGMSG(DEBUG, "---to do: FOX <%s>\n", arg);
ccnl_free(arg);
if (*restart) {
*restart = 0;
local_search = 1;
goto recontinue;
}
{
struct stack_s *h;
h = pop_or_resolve_from_result_stack(ccnl, config);
assert(h);
//TODO CHECK IF INT
config->fox_state->num_of_params = *(int*)h->content;
h->next = NULL;
ccnl_nfn_freeStack(h);
}
DEBUGMSG(DEBUG, "NUM OF PARAMS: %d\n", config->fox_state->num_of_params);
config->fox_state->params = ccnl_malloc(sizeof(struct ccnl_stack_s *) *
config->fox_state->num_of_params);
for (i = 0; i < config->fox_state->num_of_params; ++i) {
//pop parameter from stack
config->fox_state->params[i] = pop_from_stack(&config->result_stack);
if(!config->fox_state->params[i]) { break ; }
switch (config->fox_state->params[i]->type) {
case STACK_TYPE_INT:
DEBUGMSG(DEBUG, " info: Parameter %d %d\n", i,
*(int *)config->fox_state->params[i]->content);
break;
case STACK_TYPE_PREFIX:
DEBUGMSG(DEBUG, " info: Parameter %d %s\n", i,
ccnl_prefix_to_path((struct ccnl_prefix_s*)
config->fox_state->params[i]->content));
break;
default:
DEBUGMSG(DEBUG, " info: Parameter %d %s %p\n", i,
(char *)config->fox_state->params[i]->content,
config->fox_state->params[i]->content);
break;
}
}
//as long as there is a routable parameter: try to find a result
config->fox_state->it_routable_param = 0;
//check if last result is now available
recontinue: //loop by reentering after timeout of the interest...
if (local_search) {
DEBUGMSG(DEBUG, "Checking if result was received\n");
parameter_number = choose_parameter(config);
pref = create_namecomps(ccnl, config, parameter_number,
config->fox_state->params[parameter_number]->content);
// search for a result
c = ccnl_nfn_local_content_search(ccnl, config, pref);
set_propagate_of_interests_to_1(ccnl, pref);
ccnl_prefix_free(pref);
//TODO Check? //TODO remove interest here?
if (c) {
DEBUGMSG(DEBUG, "Result was found\n");
DEBUGMSG_CFWD(INFO, "data after result was found %.*s\n", c->pkt->contlen, c->pkt->content);
goto handlecontent;
}
}
//result was not delivered --> choose next parameter
++config->fox_state->it_routable_param;
parameter_number = choose_parameter(config);
if (parameter_number < 0)
//no more parameter --> no result found, can try a local computation
goto local_compute;
// create new prefix with name components!!!!
pref = create_namecomps(ccnl, config, parameter_number,
config->fox_state->params[parameter_number]->content);
c = ccnl_nfn_local_content_search(ccnl, config, pref);
if (c) {
ccnl_prefix_free(pref);
goto handlecontent;
}
// Result not in cache, search over the network
// pref2 = ccnl_prefix_dup(pref);
interest = ccnl_nfn_query2interest(ccnl, &pref, config);
if (pref)
ccnl_prefix_free(pref);
if (interest) {
ccnl_interest_propagate(ccnl, interest);
DEBUGMSG(DEBUG, " new interest's face is %d\n", interest->from->faceid);
}
// wait for content, return current program to continue later
*halt = -1; //set halt to -1 for async computations
return ccnl_strdup(prog);
local_compute:
if (config->local_done)
return NULL;
config->local_done = 1;
pref = ccnl_nfnprefix_mkComputePrefix(config, config->suite);
DEBUGMSG(DEBUG, "Prefix local computation: %s\n",
ccnl_prefix_to_path(pref));
interest = ccnl_nfn_query2interest(ccnl, &pref, config);
if (pref)
ccnl_prefix_free(pref);
if (interest)
ccnl_interest_propagate(ccnl, interest);
handlecontent: //if result was found ---> handle it
if (c) {
#ifdef USE_NACK
if (!strncmp((char*)c->pkt->content, ":NACK", 5)) {
DEBUGMSG(DEBUG, "NACK RECEIVED, going to next parameter\n");
++config->fox_state->it_routable_param;
return prog ? ccnl_strdup(prog) : NULL;
}
#endif
int isANumber = 1, i = 0;
for(i = 0; i < c->pkt->contlen; ++i){
if(!isdigit(c->pkt->content[i])){
isANumber = 0;
break;
}
}
if (isANumber){
int *integer = ccnl_malloc(sizeof(int));
*integer = strtol((char*)c->pkt->content, 0, 0);
push_to_stack(&config->result_stack, integer, STACK_TYPE_INT);
} else {
struct prefix_mapping_s *mapping;
struct ccnl_prefix_s *name =
create_prefix_for_content_on_result_stack(ccnl, config);
push_to_stack(&config->result_stack, name, STACK_TYPE_PREFIX);
mapping = ccnl_malloc(sizeof(struct prefix_mapping_s));
mapping->key = ccnl_prefix_dup(name); //TODO COPY
mapping->value = ccnl_prefix_dup(c->pkt->pfx);
DBL_LINKED_LIST_ADD(config->fox_state->prefix_mapping, mapping);
DEBUGMSG(DEBUG, "Created a mapping %s - %s\n",
ccnl_prefix_to_path(mapping->key),
ccnl_prefix_to_path(mapping->value));
}
}
DEBUGMSG(DEBUG, " FOX continuation: %s\n", contd);
return ccnl_strdup(contd);
}
char*
ZAM_resolvename(struct configuration_s *config, char *dummybuf,
char *arg, char *contd)
{
struct ccnl_lambdaTerm_s *t;
char res[1000], *cp = arg;
int len;
DEBUGMSG(DEBUG, "---to do: resolveNAME <%s>\n", arg);
//function definition
if (!strncmp(cp, "let", 3)) {
int i, end = 0, cp2len, namelength, lambdalen;
char *h, *cp2, *name, *lambda_expr, *resolveterm;
DEBUGMSG(DEBUG, " fct definition: %s\n", cp);
strcpy(res, cp+3);
for (i = 0; i < (int)strlen(res); ++i) {
if (!strncmp(res+i, "endlet", 6)) {
end = i;
break;
}
}
cp2len = strlen(res+end) + strlen("RESOLVENAME()");
h = strchr(cp, '=');
namelength = h - cp;
lambda_expr = ccnl_malloc(strlen(h));
name = ccnl_malloc(namelength);
cp2 = ccnl_malloc(cp2len);
memset(cp2, 0, cp2len);
memset(name, 0, namelength);
memset(lambda_expr, 0, strlen(h));
sprintf(cp2, "RESOLVENAME(%s)", res+end+7); //add 7 to overcome endlet
memcpy(name, cp+3, namelength-3); //copy name without let and endlet
trim(name);
lambdalen = strlen(h)-strlen(cp2)+11-6;
memcpy(lambda_expr, h+1, lambdalen); //copy lambda expression without =
trim(lambda_expr);
resolveterm = ccnl_malloc(strlen("RESOLVENAME()")+strlen(lambda_expr));
sprintf(resolveterm, "RESOLVENAME(%s)", lambda_expr);
add_to_environment(&config->env, name, new_closure(resolveterm, NULL));
ccnl_free(cp);
return ccnl_strdup(contd);
}
//check if term can be made available, if yes enter it as a var
//try with searching in global env for an added term!
t = ccnl_lambdaStrToTerm(0, &cp, NULL);
ccnl_free(arg);
if (term_is_var(t)) {
char *end = 0;
cp = t->v;
if (isdigit(*cp)) {
// is disgit...
int *integer = ccnl_malloc(sizeof(int));
*integer = strtol(cp, &end, 0);
if (end && *end)
end = 0;
if (end)
push_to_stack(&config->result_stack, integer, STACK_TYPE_INT);
else
ccnl_free(integer);
} else if (*cp == '\'') { // quoted name (constant)
//determine size
struct const_s *con = ccnl_nfn_krivine_str2const(cp);
push_to_stack(&config->result_stack, con, STACK_TYPE_CONST);
end = (char*)1;
} else if (iscontentname(cp)) { // is content...
struct ccnl_prefix_s *prefix;
prefix = ccnl_URItoPrefix(cp, config->suite, NULL, NULL);
push_to_stack(&config->result_stack, prefix, STACK_TYPE_PREFIX);
end = (char*)1;
}
if (end) {
if (contd)
sprintf(res, "TAILAPPLY;%s", contd);
else
sprintf(res, "TAILAPPLY");
} else {
if (contd)
sprintf(res, "ACCESS(%s);TAILAPPLY;%s", t->v, contd);
else
sprintf(res, "ACCESS(%s);TAILAPPLY", t->v);
}
ccnl_lambdaFreeTerm(t);
return ccnl_strdup(res);
}
if (term_is_lambda(t)) {
char *var;
var = t->v;
ccnl_lambdaTermToStr(dummybuf, t->m, 0);
if (contd)
sprintf(res, "GRAB(%s);RESOLVENAME(%s);%s", var, dummybuf, contd);
else
sprintf(res, "GRAB(%s);RESOLVENAME(%s)", var, dummybuf);
ccnl_lambdaFreeTerm(t);
return ccnl_strdup(res);
}
if (term_is_app(t)) {
ccnl_lambdaTermToStr(dummybuf, t->n, 0);
len = sprintf(res, "CLOSURE(RESOLVENAME(%s));", dummybuf);
ccnl_lambdaTermToStr(dummybuf, t->m, 0);
len += sprintf(res+len, "RESOLVENAME(%s)", dummybuf);
if (contd)
len += sprintf(res+len, ";%s", contd);
ccnl_lambdaFreeTerm(t);
return ccnl_strdup(res);
}
return NULL;
}
// executes a ZAM instruction, returns the term to continue working on
char*
ZAM_term(struct ccnl_relay_s *ccnl, struct configuration_s *config,
int *halt, char *dummybuf, int *restart)
{
// struct ccnl_lambdaTerm_s *t;
// char *pending, *p, *cp, *prog = config->prog;
// int len;
char *prog = config->prog;
struct builtin_s *bp;
char *arg, *contd;
int tok;
//pop closure
if (!prog || strlen(prog) == 0) {
if (config->result_stack) {
prog = ccnl_malloc(strlen((char*)config->result_stack->content)+1);
strcpy(prog, config->result_stack->content);
return prog;
}
DEBUGMSG(DEBUG, "no result returned\n");
return NULL;
}
tok = ZAM_nextToken(prog, &arg, &contd);
// TODO: count opening/closing parentheses when hunting for ';' ?
/*
pending = strchr(prog, ';');
p = strchr(prog, '(');
*/
switch (tok) {
case ZAM_ACCESS:
{
struct closure_s *closure = search_in_environment(config->env, arg);
DEBUGMSG(DEBUG, "---to do: access <%s>\n", arg);
if (!closure) {
// TODO: is the following needed? Above search should have
// visited global_dict, already!
closure = search_in_environment(config->global_dict, arg);
if (!closure) {
DEBUGMSG(WARNING, "?? could not lookup var %s\n", arg);
ccnl_free(arg);
return NULL;
}
}
ccnl_free(arg);
closure = new_closure(ccnl_strdup(closure->term), closure->env);
push_to_stack(&config->argument_stack, closure, STACK_TYPE_CLOSURE);
return ccnl_strdup(contd);
}
case ZAM_APPLY:
{
struct stack_s *fct = pop_from_stack(&config->argument_stack);
struct stack_s *par = pop_from_stack(&config->argument_stack);
struct closure_s *fclosure, *aclosure;
char *code;
DEBUGMSG(DEBUG, "---to do: apply\n");
if (!fct || !par)
return NULL;
fclosure = (struct closure_s *) fct->content;
aclosure = (struct closure_s *) par->content;
if (!fclosure || !aclosure)
return NULL;
ccnl_free(fct);
ccnl_free(par);
code = aclosure->term;
if (config->env)
ccnl_nfn_releaseEnvironment(&config->env);
config->env = aclosure->env;
ccnl_free(aclosure);
push_to_stack(&config->argument_stack, fclosure, STACK_TYPE_CLOSURE);
if (contd)
sprintf(dummybuf, "%s;%s", code, contd);
else
strcat(dummybuf, code);
ccnl_free(code);
return ccnl_strdup(dummybuf);
}
case ZAM_CALL:
{
struct stack_s *h = pop_or_resolve_from_result_stack(ccnl, config);
int i, offset, num_params = *(int *)h->content;
char name[5];
DEBUGMSG(DEBUG, "---to do: CALL <%s>\n", arg);
ccnl_free(h->content);
ccnl_free(h);
sprintf(dummybuf, "CLOSURE(FOX);RESOLVENAME(@op(");
// ... @x(@y y x 2 op)));TAILAPPLY";
offset = strlen(dummybuf);
for (i = 0; i < num_params; ++i) {
sprintf(name, "x%d", i);
offset += sprintf(dummybuf+offset, "@%s(", name);
}
for (i = num_params - 1; i >= 0; --i) {
sprintf(name, "x%d", i);
offset += sprintf(dummybuf+offset, " %s", name);
}
offset += sprintf(dummybuf + offset, " %d", num_params);
offset += sprintf(dummybuf+offset, " op");
for (i = 0; i < num_params+2; ++i)
offset += sprintf(dummybuf + offset, ")");
if (contd)
sprintf(dummybuf + offset, ";%s", contd);
return ccnl_strdup(dummybuf);
}
case ZAM_CLOSURE:
{
struct closure_s *closure;
DEBUGMSG(DEBUG, "---to do: closure <%s> (contd=%s)\n", arg, contd);
if (!config->argument_stack && !strncmp(arg, "RESOLVENAME(", 12)) {
char v[500], *c;
int len;
c = strchr(arg+12, ')');
if (!c)
goto normal;
len = c - (arg+12);
memcpy(v, arg+12, len);
v[len] = '\0';
closure = search_in_environment(config->env, v);
if (!closure)
goto normal;
if (!strcmp(closure->term, arg)) {
DEBUGMSG(WARNING, "** detected tail recursion case %s/%s\n",
closure->term, arg);
} else
goto normal;
} else {
normal:
closure = new_closure(arg, config->env);
//configuration->env = NULL;//FIXME new environment?
push_to_stack(&config->argument_stack, closure, STACK_TYPE_CLOSURE);
arg = NULL;
}
if (contd) {
ccnl_free(arg);
return ccnl_strdup(contd);
}
DEBUGMSG(ERROR, "** not implemented, see line %d\n", __LINE__);
return arg;
}
case ZAM_FOX:
return ZAM_fox(ccnl, config, restart, halt, prog, arg, contd);
case ZAM_GRAB:
{
struct stack_s *stack = pop_from_stack(&config->argument_stack);
DEBUGMSG(DEBUG, "---to do: grab <%s>\n", arg);
add_to_environment(&config->env, arg, stack->content);
ccnl_free(stack);
return ccnl_strdup(contd);
}
case ZAM_HALT:
ccnl_nfn_freeStack(config->argument_stack);
//ccnl_nfn_freeStack(config->result_stack);
config->argument_stack = /*config->result_stack =*/ NULL;
*halt = 1;
if(contd == NULL) {
return NULL;
}
return ccnl_strdup(contd);
case ZAM_RESOLVENAME:
return ZAM_resolvename(config, dummybuf, arg, contd);
case ZAM_TAILAPPLY:
{
struct stack_s *stack = pop_from_stack(&config->argument_stack);
struct closure_s *closure = (struct closure_s *) stack->content;
char *code = closure->term;
DEBUGMSG(DEBUG, "---to do: tailapply\n");
ccnl_free(stack);
if (contd) //build new term
sprintf(dummybuf, "%s;%s", code, contd);
else
strcpy(dummybuf, code);
if (config->env)
ccnl_nfn_releaseEnvironment(&config->env);
config->env = closure->env; //set environment from closure
ccnl_free(code);
ccnl_free(closure);
return ccnl_strdup(dummybuf);
}
case ZAM_UNKNOWN:
break;
default:
DEBUGMSG(DEBUG, "builtin: %s (%s/%s)\n", bifs[-tok - 1].name, prog, contd);
return bifs[-tok - 1].fct(ccnl, config, restart, halt, prog,
contd, &config->result_stack);
}
ccnl_free(arg);
// iterate through all extension operations
for (bp = op_extensions; bp; bp = bp->next)
if (!strncmp(prog, bp->name, strlen(bp->name)))
return (bp->fct)(ccnl, config, restart, halt, prog,
contd, &config->result_stack);
DEBUGMSG(INFO, "unknown (built-in) command <%s>\n", prog);
return NULL;
}
//----------------------------------------------------------------
void
allocAndAdd(struct environment_s **env, char *name, char *cmd)
{
struct closure_s *closure;
closure = new_closure(ccnl_strdup(cmd), NULL);
add_to_environment(env, ccnl_strdup(name), closure);
}
void
setup_global_environment(struct environment_s **env)
{
//Operator on Church numbers
allocAndAdd(env, "true_church",
"RESOLVENAME(@x@y x)");
allocAndAdd(env, "false_church",
"RESOLVENAME(@x@y y)");
allocAndAdd(env, "eq_church",
"CLOSURE(OP_CMPEQ_CHURCH);RESOLVENAME(@op(@x(@y x y op)))");
allocAndAdd(env, "leq_church",
"CLOSURE(OP_CMPLEQ_CHURCH);RESOLVENAME(@op(@x(@y x y op)))");
allocAndAdd(env, "ifelse_church",
"RESOLVENAME(@expr@yes@no(expr yes no))");
//Operator on integer numbers
allocAndAdd(env, "eq",
"CLOSURE(OP_CMPEQ);RESOLVENAME(@op(@x(@y x y op)))");
allocAndAdd(env, "leq",
"CLOSURE(OP_CMPLEQ);RESOLVENAME(@op(@x(@y x y op)))");
allocAndAdd(env, "ifelse",
"CLOSURE(OP_IFELSE);RESOLVENAME(@op(@x x op));TAILAPPLY");
allocAndAdd(env, "add",
"CLOSURE(OP_ADD);RESOLVENAME(@op(@x(@y x y op)));TAILAPPLY");
allocAndAdd(env, "sub",
"CLOSURE(OP_SUB);RESOLVENAME(@op(@x(@y x y op)));TAILAPPLY");
allocAndAdd(env, "mult",
"CLOSURE(OP_MULT);RESOLVENAME(@op(@x(@y x y op)));TAILAPPLY");
allocAndAdd(env, "call",
"CLOSURE(CALL);RESOLVENAME(@op(@x x op));TAILAPPLY");
allocAndAdd(env, "raw", "TAILAPPLY;OP_RAW");
#ifdef USE_NFN_NSTRANS
allocAndAdd(env, "translate",
"CLOSURE(OP_NSTRANS);CLOSURE(OP_FIND);"
"RESOLVENAME(@of(@o1(@x(@y x y o1 of))));TAILAPPLY");
#endif
}
// consumes the result stack, exports its content to a buffer
struct ccnl_buf_s*
Krivine_exportResultStack(struct ccnl_relay_s *ccnl,
struct configuration_s *config)
{
char res[64000]; //TODO longer???
int pos = 0;
struct stack_s *stack;
struct ccnl_content_s *cont;
while ((stack = pop_or_resolve_from_result_stack(ccnl, config))) {
if (stack->type == STACK_TYPE_PREFIX) {
cont = ccnl_nfn_local_content_search(ccnl, config, stack->content);
if (cont) {
memcpy(res+pos, (char*)cont->pkt->content, cont->pkt->contlen);
pos += cont->pkt->contlen;
}
} else if (stack->type == STACK_TYPE_PREFIXRAW) {
cont = ccnl_nfn_local_content_search(ccnl, config, stack->content);
if (cont) {
/*
DEBUGMSG(DEBUG, " PREFIXRAW packet: %p %d\n", (void*) cont->buf,
cont->buf ? cont->buf->datalen : -1);
*/
memcpy(res+pos, (char*)cont->pkt->buf->data,
cont->pkt->buf->datalen);
pos += cont->pkt->buf->datalen;
}
} else if (stack->type == STACK_TYPE_INT) {
//h = ccnl_buf_new(NULL, 10);
//sprintf((char*)h->data, "%d", *(int*)stack->content);
//h->datalen = strlen((char*)h->data);
pos += sprintf(res + pos, "%d", *(int*)stack->content);
}
ccnl_free(stack->content);
ccnl_free(stack);
}
return ccnl_buf_new(res, pos);
}
// executes (loops over) a Lambda expression: tries to run to termination,
// or returns after having emitted further remote lookup/reduction requests
// the return val is a buffer with the result stack's (concatenated) content
struct ccnl_buf_s*
Krivine_reduction(struct ccnl_relay_s *ccnl, char *expression,
int start_locally,
struct configuration_s **config,
struct ccnl_prefix_s *prefix, int suite)
{
int steps = 0, halt = 0, restart = 1;
int len = strlen("CLOSURE(HALT);RESOLVENAME()") + strlen(expression) + 1;
char *dummybuf;
DEBUGMSG(TRACE, "Krivine_reduction()\n");
if (!*config && strlen(expression) == 0)
return 0;
dummybuf = ccnl_malloc(2000);
if (!*config) {
char *prog;
struct environment_s *global_dict = NULL;
prog = ccnl_malloc(len*sizeof(char));
sprintf(prog, "CLOSURE(HALT);RESOLVENAME(%s)", expression);
setup_global_environment(&global_dict);
DEBUGMSG(DEBUG, "PREFIX %s\n", ccnl_prefix_to_path(prefix));
*config = new_config(ccnl, prog, global_dict,
start_locally,
prefix, ccnl->km->configid, suite);
DBL_LINKED_LIST_ADD(ccnl->km->configuration_list, (*config));
restart = 0;
--ccnl->km->configid;
}
DEBUGMSG(INFO, "Prog: %s\n", (*config)->prog);
while ((*config)->prog && !halt) {
char *oldprog = (*config)->prog;
steps++;
DEBUGMSG(DEBUG, "Step %d (%d/%d): %s\n", steps,
stack_len((*config)->argument_stack),
stack_len((*config)->result_stack), (*config)->prog);
(*config)->prog = ZAM_term(ccnl, *config, &halt, dummybuf, &restart);
ccnl_free(oldprog);
}
ccnl_free(dummybuf);
if (halt < 0) { //HALT < 0 means pause computation
DEBUGMSG(INFO,"Pause computation: %d\n", -(*config)->configid);
return NULL;
}
//HALT > 0 means computation finished
DEBUGMSG(INFO, "end-of-computation (%d/%d)\n",
stack_len((*config)->argument_stack),
stack_len((*config)->result_stack));
/*
print_argument_stack((*config)->argument_stack);
print_result_stack((*config)->result_stack);
*/
return Krivine_exportResultStack(ccnl, *config);
}
#endif // !CCNL_LINUXKERNEL
#endif // USE_NFN
// eof
|
the_stack_data/248581140.c | #include <string.h>
// Work around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51205
void * memset(void * b, int c, size_t len) __attribute__((externally_visible));
void * __attribute__((noinline)) memset(void * b, int c, size_t len) {
char * destination = (char *)b;
while (len--) {
*destination++ = (unsigned char)c;
}
return b;
}
|
the_stack_data/178266792.c | /*
* FUJITSU Extended Socket Network Device driver
* Copyright (c) 2015-2016 FUJITSU LIMITED
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
*/
/* debugfs support for fjes driver */
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/platform_device.h>
#include "fjes.h"
static struct dentry *fjes_debug_root;
static const char * const ep_status_string[] = {
"unshared",
"shared",
"waiting",
"complete",
};
static int fjes_dbg_status_show(struct seq_file *m, void *v)
{
struct fjes_adapter *adapter = m->private;
struct fjes_hw *hw = &adapter->hw;
int max_epid = hw->max_epid;
int my_epid = hw->my_epid;
int epidx;
seq_puts(m, "EPID\tSTATUS SAME_ZONE CONNECTED\n");
for (epidx = 0; epidx < max_epid; epidx++) {
if (epidx == my_epid) {
seq_printf(m, "ep%d\t%-16c %-16c %-16c\n",
epidx, '-', '-', '-');
} else {
seq_printf(m, "ep%d\t%-16s %-16c %-16c\n",
epidx,
ep_status_string[fjes_hw_get_partner_ep_status(hw, epidx)],
fjes_hw_epid_is_same_zone(hw, epidx) ? 'Y' : 'N',
fjes_hw_epid_is_shared(hw->hw_info.share, epidx) ? 'Y' : 'N');
}
}
return 0;
}
static int fjes_dbg_status_open(struct inode *inode, struct file *file)
{
return single_open(file, fjes_dbg_status_show, inode->i_private);
}
static const struct file_operations fjes_dbg_status_fops = {
.owner = THIS_MODULE,
.open = fjes_dbg_status_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
void fjes_dbg_adapter_init(struct fjes_adapter *adapter)
{
const char *name = dev_name(&adapter->plat_dev->dev);
struct dentry *pfile;
adapter->dbg_adapter = debugfs_create_dir(name, fjes_debug_root);
if (!adapter->dbg_adapter) {
dev_err(&adapter->plat_dev->dev,
"debugfs entry for %s failed\n", name);
return;
}
pfile = debugfs_create_file("status", 0444, adapter->dbg_adapter,
adapter, &fjes_dbg_status_fops);
if (!pfile)
dev_err(&adapter->plat_dev->dev,
"debugfs status for %s failed\n", name);
}
void fjes_dbg_adapter_exit(struct fjes_adapter *adapter)
{
debugfs_remove_recursive(adapter->dbg_adapter);
adapter->dbg_adapter = NULL;
}
void fjes_dbg_init(void)
{
fjes_debug_root = debugfs_create_dir(fjes_driver_name, NULL);
if (!fjes_debug_root)
pr_info("init of debugfs failed\n");
}
void fjes_dbg_exit(void)
{
debugfs_remove_recursive(fjes_debug_root);
fjes_debug_root = NULL;
}
#endif /* CONFIG_DEBUG_FS */
|
the_stack_data/26700701.c | #include <stdio.h>
//用于学习变量
int main()
{
//也是C99的写法,magic number
const int AMOUNT = 100; //常量只能赋值一次
int price = 0;
printf("请输入金额(元)\n");
//读入函数,如果没有成功读入数字,将会取默认值。
//int类型的默认值是0
scanf("%d", &price); //注意&符号
//C99允许在程序的任何位置定义变量
//传统的ANSI C只能在代码开头定义变量
int change = AMOUNT - price;
printf("找您%d元\n", change);
return 0;
} |
the_stack_data/178265949.c | /*
(C) CERN, Ulrich Schwickerath <[email protected]>
File: $Id: epoch2date.c,v 1.1 2011/03/24 14:49:16 uschwick Exp $
ChangeLog:
$Log: epoch2date.c,v $
Revision 1.1 2011/03/24 14:49:16 uschwick
add btools toolsuite
Revision 1.4 2008/07/28 12:05:14 uschwick
added quiet option + implemented security improvements in epoch tools
Revision 1.3 2006/11/22 13:00:07 uschwick
added documentation
Revision 1.2 2006/11/18 11:24:44 uschwick
added bjobsinfo man page to CVS
Revision 1.1 2006/11/17 22:10:26 uschwick
version 0.0.3 snapshot
Purpose: read a date from stdin and return the epoch
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <getopt.h>
struct tm Time;
int quiet = 0;
time_t epoch;
void usage(){
printf("Usage epoch2date --epoch <epoch> [--help] [--quiet] \n");
exit(0);
}
void readOptions(int argc, char* argv[]){
int c;
unsigned int input;
while (1) {
int option_index = 0;
static struct option long_options[] = {
{"help", no_argument, 0, 0},
{"quiet", no_argument, 0, 0},
{"epoch", required_argument, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "e:hq",
long_options, &option_index);
if (c == -1)
break;
switch(c) {
case '?':
usage();
break;
case 0:
if (optarg){
if (0 == strncmp(long_options[option_index].name,"epoch",5)){
if (0==sscanf(optarg,"%d",&input)){
usage();
}
epoch = (time_t) input;
break;
}
} else {
if (0 == strncmp(long_options[option_index].name,"quiet",5)){
quiet = 1;
break;
}
if (0 == strncmp(long_options[option_index].name,"help",5)){
usage();
break;
}
}
default:
fprintf(stderr,"[ERROR] Unknown option %c\n",c);
usage();
}
}
return;
}
int main(int argc, char *argv[]){
epoch = 0;
readOptions(argc,argv);
if (0 == epoch){
fprintf(stderr,"[ERROR] missing required argument epoch \n");
usage();
}
if (quiet){
printf("%s\n",ctime(&epoch));
} else {
printf("%s %d\n",ctime(&epoch),(unsigned int) epoch);
}
return(0);
}
|
the_stack_data/117329272.c | // ----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorized under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C)COPYRIGHT 2017 - 2018 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
// ----------------------------------------------------------------------------
#if defined(MBED_HEAP_STATS_ENABLED) || defined(MBED_STACK_STATS_ENABLED)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "mbed_stats.h"
#include "mbed_stats_helper.h"
#include "pal.h"
#include <string.h>
#if MBED_CONF_RTOS_PRESENT
#include "cmsis_os2.h"
#endif
#define MBED_STATS_FILE_NAME "/mbedos_stats.txt"
/**
Print mbedos stack and heap usage to stdout and to text file named mbedos_stats.txt.
Note: Make sure MBED_HEAP_STATS_ENABLED or MBED_STACK_STATS_ENABLED flags are set to 1
*/
void print_mbed_stats()
{
palStatus_t pal_result = PAL_SUCCESS;
// Max size of directory acquired by pal_fsGetMountPoint + file name (including '/') + '\0'
char file_name[PAL_MAX_FOLDER_DEPTH_CHAR + sizeof(MBED_STATS_FILE_NAME)] = { 0 };
pal_result = pal_fsGetMountPoint(PAL_FS_PARTITION_PRIMARY, PAL_MAX_FOLDER_DEPTH_CHAR + 1, file_name);
if (pal_result != PAL_SUCCESS) {
return;
}
strcat(file_name, MBED_STATS_FILE_NAME);
FILE *f = fopen(file_name, "wt");
if (f) {
// Heap
#if defined(MBED_HEAP_STATS_ENABLED)
mbed_stats_heap_t heap_stats;
mbed_stats_heap_get(&heap_stats);
fprintf(f, "Current heap usage size: %" PRIu32 "\n", heap_stats.current_size);
printf("Current heap usage size: %" PRIu32 "\n", heap_stats.current_size);
fprintf(f, "Max heap usage size: %" PRIu32 "\n", heap_stats.max_size);
printf("Max heap usage size: %" PRIu32 "\n", heap_stats.max_size);
#endif
// Stacks
#if defined(MBED_STACK_STATS_ENABLED) && defined(MBED_CONF_RTOS_PRESENT)
int cnt = osThreadGetCount();
mbed_stats_stack_t *stack_stats = (mbed_stats_stack_t*)malloc(cnt * sizeof(mbed_stats_stack_t));
if (stack_stats) {
fprintf(f, "Thread's stack usage:\n");
printf("Thread's stack usage:\n");
cnt = mbed_stats_stack_get_each(stack_stats, cnt);
for (int i = 0; i < cnt; i++) {
fprintf(f, "Thread: 0x%" PRIx32 ", Stack size: %" PRIu32 ", Max stack: %" PRIu32 "\r\n", stack_stats[i].thread_id, stack_stats[i].reserved_size, stack_stats[i].max_size);
printf("Thread: 0x%" PRIx32 ", Stack size: %" PRIu32 ", Max stack: %" PRIu32 "\r\n", stack_stats[i].thread_id, stack_stats[i].reserved_size, stack_stats[i].max_size);
}
free(stack_stats);
}
#endif
fclose(f);
printf("*****************************\n\n");
}
}
#endif
|
the_stack_data/61076368.c | #include<stdio.h>
int main()
{
int n,i;
scanf("%d",&n);
if(n<=2 || n%2!=0)printf("NO\n");
else printf("YES\n");
return 0;
}
|
the_stack_data/145717.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,r=0;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
while(n!=0)
{
r=r+n%10;
n=n/10;
}
printf("%d",r);
return 0;
}
|
the_stack_data/26701489.c | /* $XFree86: xc/programs/Xserver/hw/xfree86/vbe/vbe_module.c,v 1.4 2006/03/16 16:50:35 dawes Exp $ */
#ifdef XFree86LOADER
#include "vbe.h"
extern const char *vbe_ddcSymbols[];
extern const char *vbe_int10Symbols[];
/*
* Vbe.*InfoBlock structures were reworked starting with video driver ABI
* version number 0.9.
*/
static XF86ModReqInfo ParentModuleRequirements =
{
MAJOR_UNSPEC, /* majorversion */
MINOR_UNSPEC, /* minorversion */
PATCH_UNSPEC, /* patchlevel */
ABI_CLASS_VIDEODRV, /* abiclass */
SET_ABI_VERSION(0, 9), /* abiversion */
MOD_CLASS_NONE /* moduleclass */
};
static pointer
vbeSetup(ModuleDescPtr module, pointer opts, int *errmaj, int *errmin)
{
/*
* Tell the loader about symbols from other modules that this module
* might refer to.
*/
LoaderModRefSymLists(module, vbe_ddcSymbols, vbe_int10Symbols, NULL);
/* Cause parent module version to be checked */
xf86SetParentModuleRequirements(module, &ParentModuleRequirements);
/*
* The return value must be non-NULL on success even though there
* is no TearDownProc.
*/
return (pointer)1;
}
static XF86ModuleVersionInfo vbeVersRec =
{
"vbe", /* modname */
MODULEVENDORSTRING, /* vendor */
MODINFOSTRING1, /* _modinfo1_ */
MODINFOSTRING2, /* _modinfo2_ */
XF86_VERSION_CURRENT, /* xf86version */
2, 0, 0, /* majorversion, minorversion, patchlevel */
ABI_CLASS_VIDEODRV, /* needs the video driver ABI */
ABI_VIDEODRV_VERSION, /* abiversion (current) */
MOD_CLASS_NONE, /* moduleclass */
{0,0,0,0} /* checksum */
};
XF86ModuleData vbeModuleData =
{
&vbeVersRec, /* vers */
vbeSetup, /* setup */
NULL /* teardown */
};
#endif /* XFree86LOADER */
|
the_stack_data/225144021.c | #include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "demo.txt" // 文件名称
int main()
{
char* szAppendStr = "Text";
// 以附加方式打开可读/写的文件, 如果没有此文件则会进行创建,然后以附加方式打开可读/写的文件
printf("创建本地文件 %s\n", FILE_NAME);
FILE *fp = fopen(FILE_NAME, "a+");
if (fp == NULL){
fprintf(stderr, "打开文件失败\n");
return 1;
}
fputs(szAppendStr, fp);
szAppendStr = "file";
fputs(szAppendStr, fp);
fclose(fp);
return 0;
} |
the_stack_data/74724.c | #include <stdio.h>
#include <math.h>
int main()
{
int n, a, b;
double m;
for (a = 1; a < 10; a++)
{
for (b = 0; b < 10; b++)
{
n = a * 1100 + b * 11;
m = sqrt(n);
if (floor(m + 0.5) == m)
printf("%d\n", n);
}
}
return 0;
} |
the_stack_data/179830661.c | /*
* Date: 2014-06-08
* Author: [email protected]
*
*
* This is Example 1.3 from the test suit used in
*
* Termination Proofs for Linear Simple Loops.
* Hong Yi Chen, Shaked Flur, and Supratik Mukhopadhyay.
* SAS 2012.
*
* The test suite is available at the following URL.
* https://tigerbytes2.lsu.edu/users/hchen11/lsl/LSL_benchmark.txt
*
* Comment: terminating, linear
*/
extern int __VERIFIER_nondet_int();
int main() {
int x = __VERIFIER_nondet_int();
while (x > 1) {
int old_x = x;
x = __VERIFIER_nondet_int();
if (-2*x != old_x) {
break;
}
}
return 0;
}
|
the_stack_data/53062.c | #include <stdio.h>
#include <string.h>
#define ANSWER "Grant"
#define SIZE 40
char * s_gets(char * st, int n);
int main(void) {
char try[SIZE];
puts("Who is buried in Grant's tomb?");
s_gets(try, SIZE);
while (strcmp(try, ANSWER) != 0) {
puts("No that's wrong. Try again.");
s_gets(try, SIZE);
}
puts("That's right!");
return 0;
}
char * s_gets(char * st, int n) {
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) {
while (st[i] != '\n' && st[i] != '\0') {
i++;
}
if (st[i] == '\n') st[i] = '\0';
else {
while (getchar() != '\n') {
continue;
}
}
}
return ret_val;
}
|
the_stack_data/94262.c | //Transpose Program
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
|
the_stack_data/220454443.c | #include <stdio.h>
#include <stdbool.h>
int main(void)
{
unsigned long num;
unsigned long div;
bool isPrime;
printf("Please enter an integer for analysis; Enter q to quit.\n");
while(scanf("%lu", &num) == 1)
{
for(div = 2, isPrime = true;(div * div) <= num;div++)
{
if(num % div == 0)
{
if((div * div) != num)
printf("%lu is divisible by %lu and %lu.\n", num, div, num / div);
else
printf("%lu is divisible by %lu.\n", num, div);
isPrime = false;
}
}
if(isPrime)
printf("%lu is prime.\n", num);
printf("Please enter an integer for analysis; Enter q to quit.\n");
}
printf("Bye.\n");
return 0;
} |
the_stack_data/161081620.c | // Make sure that internal loops are properly processed when they are
// strictly nested
// FI: No problem if for loops are used, although I do not understand
// why when looking at PIPS source code for... while loops.
// FI: tortured while loops like these end up with a wrong semantic analysis
#include <assert.h>
#include <stdio.h>
main()
{
int i=0, j, m, n, k =0;
assert(m>=1 && n>=1);
while(i++, j=0, i<m)
while(j++, j<n)
k++;
// Check the loop nest postcondition
i = i;
//i = (1, 2, 3);
printf("%d\n", i);
}
|
the_stack_data/156393068.c | #include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define YES 'S'
#define FDT '\0'
#define NO_MATCH (-1)
#define AUTOMATON_STATES_ROWS 9
#define CHARACTER_MATCHERS_COLUMNS 8
#define CHARACTER_MATCHERS (CHARACTER_MATCHERS_COLUMNS - 1)
#define CENTINEL_CHARACTER '%'
struct _Buffer;
struct _Automaton;
struct _AutomatonTable;
struct _CharacterStateMatcher;
struct _PrettyPrinter;
struct _State;
char dot[] = ".";
char zeroAndOne[] = "01";
char fromTwoToNine[] = "23456789";
char b[] = "B";
char centinel[] = {CENTINEL_CHARACTER, FDT};
char othersShouldNotMatchThese[] = ".0123456789B%";
char fdt[] = {FDT};
//Utils functions defined at bottom
bool stateIsNotFinalNorFDT(struct _Automaton automaton);
bool actualStateIsFinal(struct _Automaton automaton);
bool askForAnotherLexicalCheck();
char *requestStringInputToCheck();
void stringRejectionObserver(struct _State, struct _PrettyPrinter *prettyPrinter, char textCharacter);
//State
typedef enum {
INITIAL, FINAL, CENTINEL_EXPECTANT, END_OF_TEXT, REJECTION, NULL_STATE, NONE
} StateProperty;
typedef struct _State {
int id;
StateProperty stateProperty;
} State;
//CharacterStateMatcher
typedef int (*Match)(struct _CharacterStateMatcher *self, char characterToMatch);
typedef struct _CharacterStateMatcher {
int column;
const char *charactersToMatch;
Match match;
} CharacterStateMatcher;
int CharacterStateMatcher__match(CharacterStateMatcher *self, char characterToMatch) {
const char *charactersToMatch = self->charactersToMatch;
size_t lengthOfMatchableCharacters = strlen(charactersToMatch);
if (lengthOfMatchableCharacters == 0 && characterToMatch == FDT) {
return self->column;
}
for (int i = 0; i < lengthOfMatchableCharacters; i++) {
if (charactersToMatch[i] == characterToMatch) {
return self->column;
}
}
return NO_MATCH;
}
int CharacterStateMatcher__otherMatch(CharacterStateMatcher *self, char characterToMatch) {
const char *characterNotToMatch = self->charactersToMatch;
size_t lengthOfMatchableCharacters = strlen(characterNotToMatch);
if (characterToMatch == FDT) {
return NO_MATCH;
}
for (int i = 0; i < lengthOfMatchableCharacters; i++) {
if (characterNotToMatch[i] == characterToMatch) {
return NO_MATCH;
}
}
return self->column;
}
CharacterStateMatcher CharacterStateMatcher__init(int column, const char *charactersToMatch) {
CharacterStateMatcher characterStateMatcher = {
.match = CharacterStateMatcher__match,
.charactersToMatch = charactersToMatch,
.column = column};
return characterStateMatcher;
};
//AutomatonTableService
typedef State **(*GetTable)();
typedef struct _AutomatonTableService {
GetTable getTable;
} AutomatonTableService;
State **AutomatonTableService__getTable() {
State **automatonTable;
automatonTable = calloc(AUTOMATON_STATES_ROWS, sizeof(State *));
for (int i = 0; i < AUTOMATON_STATES_ROWS; i++) {
automatonTable[i] = calloc(CHARACTER_MATCHERS_COLUMNS, sizeof(State));
}
/*
* Rows: 9 - Columns: 8
*
* 0 1 2 3 4 5 6 7
* +------------+-----------+-----+-----+---+---+-------+-----+
* | AFD | . (punto) | 0-1 | 2-9 | B | % | Otros | FDT |
* +------------+-----------+-----+-----+---+---+-------+-----+
* | 0- | 7 | 1 | 7 | 5 | 0 | 7 | 8 | 0
* | 1 | 2 | 4 | 7 | 5 | 0 | 7 | 8 | 1
* | 2 | 7 | 3 | 3 | 7 | 0 | 7 | 8 | 2
* | 3 | 7 | 5 | 5 | 7 | 0 | 7 | 8 | 3
* | 4 | 7 | 4 | 7 | 5 | 0 | 7 | 8 | 4
* | 5 | 7 | 7 | 7 | 7 | 6 | 7 | 6 | 5
* | 6+ | 7 | 1 | 7 | 5 | 0 | 7 | 8 | 6
* | 7(Rechazo) | 7 | 7 | 7 | 7 | 0 | 7 | 8 | 7
* | 8(fdt) | | | | | | | | 8
* +------------+-----------+-----+-----+---+---+-------+-----+
*/
State nullState = {.stateProperty = NULL_STATE};
State state0 = {.id = 0, .stateProperty = INITIAL};
State state1 = {.id = 1, .stateProperty = NONE};
State state2 = {.id = 2, .stateProperty = NONE};
State state3 = {.id = 3, .stateProperty = NONE};
State state4 = {.id = 4, .stateProperty = NONE};
State state5 = {.id = 5, .stateProperty = CENTINEL_EXPECTANT};
State state6 = {.id = 6, .stateProperty = FINAL};
State state7 = {.id = 7, .stateProperty = REJECTION};
State state8 = {.id = 8, .stateProperty = END_OF_TEXT};
//Hardcoded table with first column as all possible states for informative purposes
//ROW 0 ['7', '1', '7', '5', '0', '7', '8']
automatonTable[0][1] = state7;
automatonTable[0][2] = state1;
automatonTable[0][3] = state7;
automatonTable[0][4] = state5;
automatonTable[0][5] = state0;
automatonTable[0][6] = state7;
automatonTable[0][7] = state8;
//ROW 1 ['2', '4', '7', '5', '0', '7', '8']
automatonTable[1][1] = state2;
automatonTable[1][2] = state4;
automatonTable[1][3] = state7;
automatonTable[1][4] = state5;
automatonTable[1][5] = state0;
automatonTable[1][6] = state7;
automatonTable[1][7] = state8;
//ROW 2 ['7', '3', '3', '7', '0', '7', '8']
automatonTable[2][1] = state7;
automatonTable[2][2] = state3;
automatonTable[2][3] = state3;
automatonTable[2][4] = state7;
automatonTable[2][5] = state0;
automatonTable[2][6] = state7;
automatonTable[2][7] = state8;
//ROW 3 ['7', '5', '5', '7', '0', '7', '8']
automatonTable[3][1] = state7;
automatonTable[3][2] = state5;
automatonTable[3][3] = state5;
automatonTable[3][4] = state7;
automatonTable[3][5] = state0;
automatonTable[3][6] = state7;
automatonTable[3][7] = state8;
//ROW 4 ['7', '4', '7', '5', '0', '7', '8']
automatonTable[4][1] = state7;
automatonTable[4][2] = state4;
automatonTable[4][3] = state7;
automatonTable[4][4] = state5;
automatonTable[4][5] = state0;
automatonTable[4][6] = state7;
automatonTable[4][7] = state8;
//ROW 5 ['7', '7', '7', '7', '6', '7', '6']
automatonTable[5][1] = state7;
automatonTable[5][2] = state7;
automatonTable[5][3] = state7;
automatonTable[5][4] = state7;
automatonTable[5][5] = state6;
automatonTable[5][6] = state7;
automatonTable[5][7] = state6;
//ROW 6 ['7', '1', '7', '5', '0', '7', '8']
automatonTable[6][1] = state7;
automatonTable[6][2] = state1;
automatonTable[6][3] = state7;
automatonTable[6][4] = state5;
automatonTable[6][5] = state0;
automatonTable[6][6] = state7;
automatonTable[6][7] = state8;
//ROW 7 ['7', '7', '7', '7', '0', '7', '8']
automatonTable[7][1] = state7;
automatonTable[7][2] = state7;
automatonTable[7][3] = state7;
automatonTable[7][4] = state7;
automatonTable[7][5] = state0;
automatonTable[7][6] = state7;
automatonTable[7][7] = state8;
//ROW 8 ['', '', '', '', '', '', '']
automatonTable[8][1] = nullState;
automatonTable[8][2] = nullState;
automatonTable[8][3] = nullState;
automatonTable[8][4] = nullState;
automatonTable[8][5] = nullState;
automatonTable[8][6] = nullState;
automatonTable[8][7] = nullState;
return automatonTable;
}
// AutomatonTable
typedef State (*MakeTransitionFromState)(struct _AutomatonTable *self, State state, char character);
typedef State (*GetInitialState)(struct _AutomatonTable *self);
typedef void (*FreeAutomatonTable)(struct _AutomatonTable *self);
typedef struct _AutomatonTable {
State **table;
CharacterStateMatcher *characterStateMatchers;
GetInitialState getInitialState;
MakeTransitionFromState makeTransitionFromState;
FreeAutomatonTable freeAutomatonTable;
} AutomatonTable;
State AutomatonTable__getInitialState(AutomatonTable *self) {
State **table = self->table;
for (int i = 0; i < AUTOMATON_STATES_ROWS; i++) {
State currentState = table[i][0];
if (currentState.stateProperty == INITIAL) {
return currentState;
}
}
return table[0][0];
}
State AutomatonTable__makeTransitionFromState(AutomatonTable *self, State state, char character) {
State arrivalState = {};
for (int i = 0; i < CHARACTER_MATCHERS; i++) {
CharacterStateMatcher matcher = self->characterStateMatchers[i];
if (matcher.match(&matcher, character) != NO_MATCH) {
return self->table[state.id][matcher.column];
}
}
return arrivalState;
};
void AutomatonTable__free(AutomatonTable *self) {
free(self->characterStateMatchers);
for (int i = 0; i < AUTOMATON_STATES_ROWS; i++) {
free(self->table[i]);
}
free(self->table);
}
//CharacterStateMatcherService
typedef void *(*GetCharacterStateMatchers)(struct _AutomatonTable *automatonTable);
typedef struct _CharacterStateMatcherService {
GetCharacterStateMatchers getCharacterStateMatchers;
} CharacterStateMatcherService;
void *CharacterStateMatcherService__getCharacterStateMatchers(struct _AutomatonTable *automatonTable) {
CharacterStateMatcher *characterStateMatchers = calloc(CHARACTER_MATCHERS, sizeof(CharacterStateMatcher));
CharacterStateMatcher otherMatcher = CharacterStateMatcher__init(6, othersShouldNotMatchThese);
otherMatcher.match = CharacterStateMatcher__otherMatch;
characterStateMatchers[0] = CharacterStateMatcher__init(1, dot);
characterStateMatchers[1] = CharacterStateMatcher__init(2, zeroAndOne);
characterStateMatchers[2] = CharacterStateMatcher__init(3, fromTwoToNine);
characterStateMatchers[3] = CharacterStateMatcher__init(4, b);
characterStateMatchers[4] = CharacterStateMatcher__init(5, centinel);
characterStateMatchers[5] = otherMatcher;
characterStateMatchers[6] = CharacterStateMatcher__init(7, fdt);
automatonTable->characterStateMatchers = characterStateMatchers;
}
// Automaton
typedef void (*SetActualStateToInitialState)(struct _Automaton *self);
typedef void (*DetermineCurrentState)(struct _Automaton *self, char character);
typedef struct _Automaton {
State actualState;
AutomatonTable automatonTable;
SetActualStateToInitialState setActualStateToInitialState;
DetermineCurrentState determineCurrentState;
} Automaton;
void Automaton__setActualStateToInitialState(Automaton *self) {
AutomatonTable automatonTable = self->automatonTable;
self->actualState = automatonTable.getInitialState(&automatonTable);
}
void Automaton__determineCurrentState(Automaton *self, char character) {
AutomatonTable automatonTable = self->automatonTable;
State resultState = automatonTable.makeTransitionFromState(&automatonTable, self->actualState, character);
self->actualState = resultState;
}
//Buffer
typedef void (*BufferFree)(struct _Buffer *self);
typedef char (*FetchNextCharacter)(struct _Buffer *self);
typedef struct _Buffer {
char *input;
FetchNextCharacter fetchNextCharacter;
BufferFree bufferFree;
} Buffer;
char Buffer__fetchNextCharacter(Buffer *self) {
char *wholeBufferInput = self->input;
char nextCharacter = wholeBufferInput[0];
size_t sizeOfInput = strlen(wholeBufferInput);
if (sizeOfInput != 0) {
char *inputWithoutFirstCharacter = calloc(sizeOfInput, sizeof(char));
memcpy(inputWithoutFirstCharacter, wholeBufferInput + 1, sizeOfInput);
self->bufferFree(self);
self->input = inputWithoutFirstCharacter;
}
return nextCharacter;
}
void Buffer__free(Buffer *self) {
free(self->input);
}
//PrettyPrinter
typedef void (*Append)(struct _PrettyPrinter *self, char characterToAppend);
typedef void (*PersistString)(struct _PrettyPrinter *self);
typedef void (*PrettyPrinterFree)(struct _PrettyPrinter *self);
typedef void (*PrintResults)(struct _PrettyPrinter *self);
typedef void (*Flush)(struct _PrettyPrinter *self);
typedef void (*FlushPersistence)(struct _PrettyPrinter *self);
typedef struct _PrettyPrinter {
char *stringBuilder;
char **persistedStrings;
int persistedStringsQty;
Append append;
PersistString persistString;
PrintResults printResults;
PrettyPrinterFree prettyPrinterFree;
Flush flush;
FlushPersistence flushPersistence;
} PrettyPrinter;
void PrettyPrinter__append(PrettyPrinter *self, char characterToAppend) {
if (characterToAppend != FDT && characterToAppend != CENTINEL_CHARACTER) {
size_t positionToInsert = strlen(self->stringBuilder);
self->stringBuilder = realloc(self->stringBuilder, (positionToInsert + 2) * sizeof(char));
self->stringBuilder[positionToInsert] = characterToAppend;
self->stringBuilder[positionToInsert + 1] = FDT;
}
}
void PrettyPrinter__persistString(PrettyPrinter *self) {
char *stringToPersist = self->stringBuilder;
int persistedStringsQty = self->persistedStringsQty;
char **persistedStrings = self->persistedStrings;
size_t sizeOfString = strlen(stringToPersist);
char *persistedString = calloc(sizeOfString + 1, sizeof(char));
strcpy(persistedString, stringToPersist);
persistedStrings[persistedStringsQty] = persistedString;
persistedStringsQty++;
char **biggerPersistedStrings = realloc(persistedStrings, (persistedStringsQty + 1) * sizeof(char *));
biggerPersistedStrings[persistedStringsQty] = "";
self->persistedStringsQty = persistedStringsQty;
self->persistedStrings = biggerPersistedStrings;
self->flush(self);
}
void PrettyPrinter__printResults(PrettyPrinter *self) {
int persistedStringsQty = self->persistedStringsQty;
printf("-------Palabras encontradas-------\n");
if (persistedStringsQty == 0) {
printf("----No se encontraron palabras----\n");
} else {
for (int i = 0; i < persistedStringsQty; i++) {
printf("%d. %s\n", i + 1, self->persistedStrings[i]);
}
}
printf("----------------------------------\n");
}
void PrettyPrinter__flush(PrettyPrinter *self) {
self->stringBuilder = realloc(self->stringBuilder, 1 * sizeof(char));
self->stringBuilder[0] = FDT;
}
void PrettyPrinter__flushPersistence(PrettyPrinter *self) {
self->flush(self);
for (int i = 0; i < self->persistedStringsQty; i++) {
free(self->persistedStrings[i]);
}
self->persistedStringsQty = 0;
}
void PrettyPrinter__free(PrettyPrinter *self) {
free(self->stringBuilder);
free(self->persistedStrings);
}
/*
* Algoritmo 3
*
* - Intenta leer primer carácter del texto (porque el texto puede estar vacío)
* - Mientras no sea fdt, repetir:
* (1) Estado actual del autómata: estado inicial
* (2) Mientras no sea un estado final y no sea el estado FDT, repetir:
* (2.1) Determinar el nuevo estado actual
* (2.2) Actualizar el carácter a analizar
* (3) Si el estado es final, la cadena procesada es una constante entera;
* caso contrario, la cadena no pertenece al lenguaje.
*
* ER: [01]\.[0-9]{2}|[01]*B Centinela: %
*
* +-----+-----------+-----+-----+---+
* | AFD | . (punto) | 0-1 | 2-9 | B |
* +-----+-----------+-----+-----+---+
* | 0- | | 1 | | 5 |
* | 1 | 2 | 4 | | 5 |
* | 2 | | 3 | 3 | |
* | 3 | | 5 | 5 | |
* | 4 | | 4 | | 5 |
* | 5+ | | | | |
* +-----+-----------+-----+-----+---+
*
*/
int main() {
bool lexicalCheckRequired;
AutomatonTableService automatonTableService = {
.getTable = AutomatonTableService__getTable};
CharacterStateMatcherService characterStateMatcherService = {
.getCharacterStateMatchers = CharacterStateMatcherService__getCharacterStateMatchers};
AutomatonTable automatonTable = {
.table = automatonTableService.getTable(), //Use of stack memory after return?
.getInitialState = AutomatonTable__getInitialState,
.makeTransitionFromState = AutomatonTable__makeTransitionFromState,
.freeAutomatonTable = AutomatonTable__free};
characterStateMatcherService.getCharacterStateMatchers(&automatonTable);
Buffer buffer = {
.fetchNextCharacter = Buffer__fetchNextCharacter,
.bufferFree = Buffer__free};
Automaton automaton = {
.setActualStateToInitialState = Automaton__setActualStateToInitialState,
.determineCurrentState = Automaton__determineCurrentState,
.automatonTable = automatonTable};
PrettyPrinter prettyPrinter = {
.append = PrettyPrinter__append,
.persistString = PrettyPrinter__persistString,
.prettyPrinterFree = PrettyPrinter__free,
.printResults = PrettyPrinter__printResults,
.flush = PrettyPrinter__flush,
.flushPersistence = PrettyPrinter__flushPersistence,
.persistedStringsQty = 0,
.persistedStrings = calloc(1, sizeof(char *)),
.stringBuilder = calloc(1, sizeof(char))};
do {
buffer.input = requestStringInputToCheck();
char textCharacter = buffer.fetchNextCharacter(&buffer);
while (textCharacter != FDT) { //- Mientras no sea fdt, repetir:
automaton.setActualStateToInitialState(&automaton); // (1) Estado actual del autómata: estado inicial
// (2) Mientras no sea un estado final y no sea el estado FDT, repetir
while (stateIsNotFinalNorFDT(automaton)) {
automaton.determineCurrentState(&automaton, textCharacter); // (2.1) Determinar el nuevo estado actual
prettyPrinter.append(&prettyPrinter, textCharacter);
textCharacter = buffer.fetchNextCharacter(&buffer); // (2.2) Actualizar el carácter a analizar
stringRejectionObserver(automaton.actualState, &prettyPrinter, textCharacter);
}
// (3) Si el estado es final, la cadena procesada es una constante entera.
if (actualStateIsFinal(automaton)) {
prettyPrinter.persistString(&prettyPrinter);
} else {
prettyPrinter.flush(&prettyPrinter); // Caso contrario, la cadena no pertenece al lenguaje.
}
}
buffer.bufferFree(&buffer);
prettyPrinter.printResults(&prettyPrinter);
prettyPrinter.flushPersistence(&prettyPrinter);
lexicalCheckRequired = askForAnotherLexicalCheck();
} while (lexicalCheckRequired);
automatonTable.freeAutomatonTable(&automatonTable);
prettyPrinter.prettyPrinterFree(&prettyPrinter);
return 0;
}
//Utils functions
void stringRejectionObserver(State state, PrettyPrinter *prettyPrinter, char textCharacter) {
if (state.stateProperty != CENTINEL_EXPECTANT && textCharacter == CENTINEL_CHARACTER) {
prettyPrinter->flush(prettyPrinter);
}
}
bool stateIsNotFinalNorFDT(Automaton automaton) {
StateProperty stateProperty = automaton.actualState.stateProperty;
return stateProperty != FINAL && stateProperty != END_OF_TEXT;
}
bool actualStateIsFinal(Automaton automaton) {
return automaton.actualState.stateProperty == FINAL;
}
bool askForAnotherLexicalCheck() {
char answer;
printf("¿Desea ingresar otra cadena? S/N: ");
answer = (char) getc(stdin);
while ((getchar()) != '\n');
return toupper(answer) == YES ? true : false;
}
char *requestStringInputToCheck() {
int c;
char *string;
string = calloc(1, sizeof(char));
string[0] = '\0';
printf("Ingrese la cadena a analizar: ");
for (int i = 0; (c = getchar()) != '\n' && c != EOF; i++) {
string = realloc(string, (i + 2) * sizeof(char));
string[i] = (char) c;
string[i + 1] = FDT;
}
return string;
} |
the_stack_data/59513841.c | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2010, Ralink Technology, Inc.
*
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************/
#ifdef RT28xx
#include "rt_config.h"
extern RTMP_RF_REGS RF2850RegTable[];
extern UCHAR NUM_OF_2850_CHNL;
/*
==========================================================================
Description:
AsicSwitchChannel() dedicated for RT28xx ATE.
==========================================================================
*/
VOID RT28xxATEAsicSwitchChannel(
IN PRTMP_ADAPTER pAd)
{
PATE_INFO pATEInfo = &(pAd->ate);
UINT32 Value = 0;
CHAR TxPwer = 0, TxPwer2 = 0;
UCHAR index = 0, BbpValue = 0, Channel = 0;
UINT32 R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0;
RTMP_RF_REGS *RFRegTable = NULL;
SYNC_CHANNEL_WITH_QA(pATEInfo, &Channel);
/* fill Tx power value */
TxPwer = pATEInfo->TxPower0;
TxPwer2 = pATEInfo->TxPower1;
RFRegTable = RF2850RegTable;
switch (pAd->RfIcType)
{
/* But only 2850 and 2750 support 5.5GHz band... */
case RFIC_2820:
case RFIC_2850:
case RFIC_2720:
case RFIC_2750:
for (index = 0; index < NUM_OF_2850_CHNL; index++)
{
if (Channel == RFRegTable[index].Channel)
{
R2 = RFRegTable[index].R2;
/* If TX path is 1, bit 14 = 1. */
if (pAd->Antenna.field.TxPath == 1)
{
R2 |= 0x4000;
}
if (pAd->Antenna.field.TxPath == 2)
{
if (pATEInfo->TxAntennaSel == 1)
{
/* If TX Antenna select is 1 , bit 14 = 1; Disable Ant 2 */
R2 |= 0x4000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7; /* 11100111B */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
else if (pATEInfo->TxAntennaSel == 2)
{
/* If TX Antenna select is 2 , bit 15 = 1; Disable Ant 1 */
R2 |= 0x8000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7;
BbpValue |= 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
else
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7;
BbpValue |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
}
if (pAd->Antenna.field.RxPath == 2)
{
switch (pATEInfo->RxAntennaSel)
{
case 1:
R2 |= 0x20040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x00;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 2:
R2 |= 0x10040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x01;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
default:
R2 |= 0x40;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
/* Only enable two Antenna to receive. */
BbpValue |= 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
}
}
else if (pAd->Antenna.field.RxPath == 1)
{
/* write 1 to off RxPath */
R2 |= 0x20040;
}
if (pAd->Antenna.field.RxPath == 3)
{
switch (pATEInfo->RxAntennaSel)
{
case 1:
R2 |= 0x20040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x00;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 2:
R2 |= 0x10040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x01;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 3:
R2 |= 0x30000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x02;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
default:
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
}
}
if (Channel > 14)
{
/* initialize R3, R4 */
R3 = (RFRegTable[index].R3 & 0xffffc1ff);
R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pATEInfo->RFFreqOffset << 15);
/*
According the Rory's suggestion to solve the middle range issue.
5.5G band power range : 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0"
means the TX power reduce 7dB.
*/
/* R3 */
if ((TxPwer >= -7) && (TxPwer < 0))
{
TxPwer = (7+TxPwer);
R3 |= (TxPwer << 10);
DBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer=%d \n", TxPwer));
}
else
{
TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
R3 |= (TxPwer << 10) | (1 << 9);
}
/* R4 */
if ((TxPwer2 >= -7) && (TxPwer2 < 0))
{
TxPwer2 = (7+TxPwer2);
R4 |= (TxPwer2 << 7);
DBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
}
else
{
TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
R4 |= (TxPwer2 << 7) | (1 << 6);
}
}
else
{
/* Set TX power0. */
R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9);
/* Set frequency offset and TX power1. */
R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pATEInfo->RFFreqOffset << 15) | (TxPwer2 <<6);
}
/* based on BBP current mode before changing RF channel */
if (pATEInfo->TxWI.BW == BW_40)
{
R4 |=0x200000;
}
/* Update variables. */
pAd->LatchRfRegs.Channel = Channel;
pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
pAd->LatchRfRegs.R2 = R2;
pAd->LatchRfRegs.R3 = R3;
pAd->LatchRfRegs.R4 = R4;
RtmpRfIoWrite(pAd);
break;
}
}
break;
default:
break;
}
/* Change BBP setting during switch from a->g, g->a */
if (Channel <= 14)
{
UINT32 TxPinCfg = 0x00050F0A;/* 2007.10.09 by Brian : 0x0005050A ==> 0x00050F0A */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
/* According the Rory's suggestion to solve the middle range issue. */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);
/* Rx High power VGA offset for LNA select */
if (pAd->NicConfig2.field.ExternalLNAForG)
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
}
else
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
}
/* 2.4 G band selection PIN */
rtmp_mac_set_band(pAd, BAND_24G);
/* Turn off unused PA or LNA when only 1T or 1R. */
if (pAd->Antenna.field.TxPath == 1)
{
TxPinCfg &= 0xFFFFFFF3;
}
if (pAd->Antenna.field.RxPath == 1)
{
TxPinCfg &= 0xFFFFF3FF;
}
/* calibration power unbalance issues */
if (pAd->Antenna.field.TxPath == 2)
{
if (pATEInfo->TxAntennaSel == 1)
{
TxPinCfg &= 0xFFFFFFF7;
}
else if (pATEInfo->TxAntennaSel == 2)
{
TxPinCfg &= 0xFFFFFFFD;
}
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
}
/* channel > 14 */
else
{
UINT32 TxPinCfg = 0x00050F05;/* 2007.10.09 by Brian : 0x00050505 ==> 0x00050F05 */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
/* According the Rory's suggestion to solve the middle range issue. */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
/* Rx High power VGA offset for LNA select */
if (pAd->NicConfig2.field.ExternalLNAForA)
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
}
else
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
}
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R91, &BbpValue);
ASSERT((BbpValue == 0x04));
/* 5 G band selection PIN, bit1 and bit2 are complement */
rtmp_mac_set_band(pAd, BAND_5G);
/* Turn off unused PA or LNA when only 1T or 1R. */
if (pAd->Antenna.field.TxPath == 1)
{
TxPinCfg &= 0xFFFFFFF3;
}
if (pAd->Antenna.field.RxPath == 1)
{
TxPinCfg &= 0xFFFFF3FF;
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
}
ATE_CHIP_RX_VGA_GAIN_INIT(pAd);
RtmpOsMsDelay(1);
if (Channel > 14)
{
/* When 5.5GHz band the LSB of TxPwr will be used to reduced 7dB or not. */
DBGPRINT(RT_DEBUG_TRACE, ("RT28xx:SwitchChannel#%d(RF=%d, %dT) to , R1=0x%08x, R2=0x%08x, R3=0x%08x, R4=0x%08x\n",
Channel,
pAd->RfIcType,
pAd->Antenna.field.TxPath,
pAd->LatchRfRegs.R1,
pAd->LatchRfRegs.R2,
pAd->LatchRfRegs.R3,
pAd->LatchRfRegs.R4));
}
else
{
DBGPRINT(RT_DEBUG_TRACE, ("RT28xx:SwitchChannel#%d(RF=%d, Pwr0=%u, Pwr1=%u, %dT) to , R1=0x%08x, R2=0x%08x, R3=0x%08x, R4=0x%08x\n",
Channel,
pAd->RfIcType,
(R3 & 0x00003e00) >> 9,
(R4 & 0x000007c0) >> 6,
pAd->Antenna.field.TxPath,
pAd->LatchRfRegs.R1,
pAd->LatchRfRegs.R2,
pAd->LatchRfRegs.R3,
pAd->LatchRfRegs.R4));
}
}
INT RT28xxATETxPwrHandler(
IN PRTMP_ADAPTER pAd,
IN char index)
{
PATE_INFO pATEInfo = &(pAd->ate);
ULONG R;
CHAR TxPower = 0;
UCHAR Bbp94 = 0;
BOOLEAN bPowerReduce = FALSE;
#ifdef RALINK_QA
if ((pATEInfo->bQATxStart == TRUE) || (pATEInfo->bQARxStart == TRUE))
{
return 0;
}
else
#endif /* RALINK_QA */
if (index == 0)
{
TxPower = pATEInfo->TxPower0;
}
else if (index == 1)
{
TxPower = pATEInfo->TxPower1;
}
else
{
DBGPRINT_ERR(("%s : Only TxPower0 and TxPower1 are adjustable !\n", __FUNCTION__));
DBGPRINT_ERR(("%s : TxPower%d is out of range !\n", __FUNCTION__, index));
return -1;
}
if (pATEInfo->Channel <= 14)
{
if (TxPower > 31)
{
/* R3, R4 can't large than 31 (0x24), 31 ~ 36 used by BBP 94 */
R = 31;
if (TxPower <= 36)
Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
}
else if (TxPower < 0)
{
/* R3, R4 can't less than 0, -1 ~ -6 used by BBP 94 */
R = 0;
if (TxPower >= -6)
Bbp94 = BBPR94_DEFAULT + TxPower;
}
else
{
/* 0 ~ 31 */
R = (ULONG) TxPower;
Bbp94 = BBPR94_DEFAULT;
}
DBGPRINT(RT_DEBUG_TRACE, ("%s : (TxPower=%d, R=%ld, BBP_R94=%d)\n", __FUNCTION__, TxPower, R, Bbp94));
}
else /* 5.5 GHz */
{
if (TxPower > 15)
{
/* R3, R4 can't large than 15 (0x0F) */
R = 15;
}
else if (TxPower < 0)
{
/* R3, R4 can't less than 0 */
/* -1 ~ -7 */
ASSERT((TxPower >= -7));
R = (ULONG)(TxPower + 7);
bPowerReduce = TRUE;
}
else
{
/* 0 ~ 15 */
R = (ULONG) TxPower;
}
DBGPRINT(RT_DEBUG_TRACE, ("%s : (TxPower=%d, R=%lu)\n", __FUNCTION__, TxPower, R));
}
if (pATEInfo->Channel <= 14)
{
if (index == 0)
{
/* shift TX power control to correct RF(R3) register bit position */
R = R << 9;
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
pAd->LatchRfRegs.R3 = R;
}
else
{
/* shift TX power control to correct RF(R4) register bit position */
R = R << 6;
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
pAd->LatchRfRegs.R4 = R;
}
}
else /* 5.5GHz */
{
if (bPowerReduce == FALSE)
{
if (index == 0)
{
/* shift TX power control to correct RF(R3) register bit position */
R = (R << 10) | (1 << 9);
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
pAd->LatchRfRegs.R3 = R;
}
else
{
/* shift TX power control to correct RF(R4) register bit position */
R = (R << 7) | (1 << 6);
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
pAd->LatchRfRegs.R4 = R;
}
}
else
{
if (index == 0)
{
/* shift TX power control to correct RF(R3) register bit position */
R = (R << 10);
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
/* Clear bit 9 of R3 to reduce 7dB. */
pAd->LatchRfRegs.R3 = (R & (~(1 << 9)));
}
else
{
/* shift TX power control to correct RF(R4) register bit position */
R = (R << 7);
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
/* Clear bit 6 of R4 to reduce 7dB. */
pAd->LatchRfRegs.R4 = (R & (~(1 << 6)));
}
}
}
RtmpRfIoWrite(pAd);
return 0;
}
VOID RT28xxATERxVGAInit(
IN PRTMP_ADAPTER pAd)
{
PATE_INFO pATEInfo = &(pAd->ate);
UCHAR R66;
CHAR LNAGain = GET_LNA_GAIN(pAd);
if (pATEInfo->Channel <= 14)
{
/* BG band */
R66 = (UCHAR)(0x2E + LNAGain);
}
else
{
/* A band */
if (pATEInfo->TxWI.BW == BW_20)
{
/* A band, BW == 20 */
R66 = (UCHAR)(0x32 + (LNAGain*5)/3);
}
else
{
/* A band, BW == 40 */
R66 = (UCHAR)(0x3A + (LNAGain*5)/3);
}
}
ATEBBPWriteWithRxChain(pAd, BBP_R66, R66, RX_CHAIN_ALL);
return;
}
/*
==========================================================================
Description:
Set RT28xx/RT2880 ATE RF BW
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT RT28xx_Set_ATE_TX_BW_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PATE_INFO pATEInfo = &(pAd->ate);
INT powerIndex;
UCHAR value = 0;
UCHAR BBPCurrentBW;
BBPCurrentBW = simple_strtol(arg, 0, 10);
if (BBPCurrentBW == 0)
{
pATEInfo->TxWI.BW = BW_20;
}
else
{
pATEInfo->TxWI.BW = BW_40;
}
if ((pATEInfo->TxWI.TxWIPHYMODE == MODE_CCK) && (pATEInfo->TxWI.TxWIBW == BW_40))
{
DBGPRINT_ERR(("Set_ATE_TX_BW_Proc!! Warning!! CCK only supports 20MHZ!!\n"));
DBGPRINT_ERR(("Bandwidth switch to 20!!\n"));
pATEInfo->TxWI.BW = BW_20;
}
if (pATEInfo->TxWI.BW == BW_20)
{
if (pATEInfo->Channel <= 14)
{
/* BW=20;G band */
for (powerIndex=0; powerIndex<MAX_TXPOWER_ARRAY_SIZE; powerIndex++)
{
if (pAd->Tx20MPwrCfgGBand[powerIndex] == 0xffffffff)
continue;
/* TX_PWR_CFG_0 ~ TX_PWR_CFG_4 */
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + powerIndex*4, pAd->Tx20MPwrCfgGBand[powerIndex]);
RtmpOsMsDelay(5);
}
}
else
{
/* BW=20;A band */
for (powerIndex=0; powerIndex<MAX_TXPOWER_ARRAY_SIZE; powerIndex++)
{
if (pAd->Tx20MPwrCfgABand[powerIndex] == 0xffffffff)
continue;
/* TX_PWR_CFG_0 ~ TX_PWR_CFG_4 */
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + powerIndex*4, pAd->Tx20MPwrCfgABand[powerIndex]);
RtmpOsMsDelay(5);
}
}
/* set BW = 20 MHz */
/* Set BBP R4 bit[4:3]=0:0 */
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value &= (~0x18);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
/* Set BBP R66=0x3C */
value = 0x3C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
/* set BW = 20 MHz */
pAd->LatchRfRegs.R4 &= ~0x00200000;
RtmpRfIoWrite(pAd);
/* BW = 20 MHz */
/* Set BBP R68=0x0B to improve Rx sensitivity. */
value = 0x0B;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
/* Set BBP R69=0x16 */
value = 0x16;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
/* Set BBP R70=0x08 */
value = 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
/* Set BBP R73=0x11 */
value = 0x11;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
if (pATEInfo->Channel == 14)
{
INT TxMode = pATEInfo->TxWI.TxWIPHYMODE;
if (TxMode == MODE_CCK)
{
/* when Channel==14 && Mode==CCK && BandWidth==20M, BBP R4 bit5=1 */
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value |= 0x20; /* set bit5=1 */
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
}
}
}
/* If bandwidth = 40M, set RF Reg4 bit 21 = 0. */
else if (pATEInfo->TxWI.TxWIBW == BW_40)
{
if (pATEInfo->Channel <= 14)
{
/* BW=40;G band */
for (powerIndex=0; powerIndex<MAX_TXPOWER_ARRAY_SIZE; powerIndex++)
{
if (pAd->Tx40MPwrCfgGBand[powerIndex] == 0xffffffff)
continue;
/* TX_PWR_CFG_0 ~ TX_PWR_CFG_4 */
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + powerIndex*4, pAd->Tx40MPwrCfgGBand[powerIndex]);
RtmpOsMsDelay(5);
}
}
else
{
/* BW=40;A band */
for (powerIndex=0; powerIndex<MAX_TXPOWER_ARRAY_SIZE; powerIndex++)
{
if (pAd->Tx40MPwrCfgABand[powerIndex] == 0xffffffff)
continue;
/* TX_PWR_CFG_0 ~ TX_PWR_CFG_4 */
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + powerIndex*4, pAd->Tx40MPwrCfgABand[powerIndex]);
RtmpOsMsDelay(5);
}
if ((pATEInfo->TxWI.TxWIPHYMODE >= 2) && (pATEInfo->TxWI.TxWIMCS == 7))
{
value = 0x28;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R67, value);
}
}
/* Set BBP R4 bit[4:3]=1:0 */
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value &= (~0x18);
value |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
/* Set BBP R66=0x3C */
value = 0x3C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
/* set BW = 40 MHz */
pAd->LatchRfRegs.R4 |= 0x00200000;
RtmpRfIoWrite(pAd);
/* BW = 40 MHz */
/* Set BBP R68=0x0C to improve Rx sensitivity. */
value = 0x0C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
/* Set BBP R69=0x1A */
value = 0x1A;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
/* Set BBP R70=0x0A */
value = 0x0A;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
/* Set BBP R73=0x16 */
value = 0x16;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
}
return TRUE;
}
INT RT28xx_Set_ATE_TX_FREQ_OFFSET_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PATE_INFO pATEInfo = &(pAd->ate);
ULONG R4 = 0;
UCHAR RFFreqOffset = 0;
RFFreqOffset = simple_strtol(arg, 0, 10);
if (RFFreqOffset >= 64)
{
DBGPRINT_ERR(("Set_ATE_TX_FREQ_OFFSET_Proc::Out of range(0 ~ 63).\n"));
return FALSE;
}
pATEInfo->RFFreqOffset = RFFreqOffset;
/* shift TX power control to correct RF register bit position */
R4 = pATEInfo->RFFreqOffset << 15;
R4 |= (pAd->LatchRfRegs.R4 & ((~0x001f8000)));
pAd->LatchRfRegs.R4 = R4;
RtmpRfIoWrite(pAd);
return TRUE;
}
#endif /*RT28xx */
|
the_stack_data/170453817.c | /* Convert wide-character string to maximal integer.
Copyright (C) 1997-2019 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <inttypes.h>
#include <wchar.h>
intmax_t wcstoimax(const wchar_t* __restrict nptr, wchar_t** __restrict endptr,
int base)
{
return __wcstoll_internal(nptr, endptr, base, 0);
}
|
the_stack_data/62637889.c | /******************************************************************************
* Intel Management Engine Interface (Intel MEI) Linux driver
* Intel MEI Interface Header
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* Contact Information:
* Intel Corporation.
* [email protected]
* http://www.intel.com
*
* BSD LICENSE
*
* Copyright(c) 2003 - 2012 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>
#include <bits/wordsize.h>
#include <linux/mei.h>
/*****************************************************************************
* Intel Management Engine Interface
*****************************************************************************/
#define mei_msg(_me, fmt, ARGS...) do { \
if (_me->verbose) \
fprintf(stderr, fmt, ##ARGS); \
} while (0)
#define mei_err(_me, fmt, ARGS...) do { \
fprintf(stderr, "Error: " fmt, ##ARGS); \
} while (0)
struct mei {
uuid_le guid;
bool initialized;
bool verbose;
unsigned int buf_size;
unsigned char prot_ver;
int fd;
};
static void mei_deinit(struct mei *cl)
{
if (cl->fd != -1)
close(cl->fd);
cl->fd = -1;
cl->buf_size = 0;
cl->prot_ver = 0;
cl->initialized = false;
}
static bool mei_init(struct mei *me, const uuid_le *guid,
unsigned char req_protocol_version, bool verbose)
{
int result;
struct mei_client *cl;
struct mei_connect_client_data data;
me->verbose = verbose;
me->fd = open("/dev/mei0", O_RDWR);
if (me->fd == -1) {
mei_err(me, "Cannot establish a handle to the Intel MEI driver\n");
goto err;
}
memcpy(&me->guid, guid, sizeof(*guid));
memset(&data, 0, sizeof(data));
me->initialized = true;
memcpy(&data.in_client_uuid, &me->guid, sizeof(me->guid));
result = ioctl(me->fd, IOCTL_MEI_CONNECT_CLIENT, &data);
if (result) {
mei_err(me, "IOCTL_MEI_CONNECT_CLIENT receive message. err=%d\n", result);
goto err;
}
cl = &data.out_client_properties;
mei_msg(me, "max_message_length %d\n", cl->max_msg_length);
mei_msg(me, "protocol_version %d\n", cl->protocol_version);
if ((req_protocol_version > 0) &&
(cl->protocol_version != req_protocol_version)) {
mei_err(me, "Intel MEI protocol version not supported\n");
goto err;
}
me->buf_size = cl->max_msg_length;
me->prot_ver = cl->protocol_version;
return true;
err:
mei_deinit(me);
return false;
}
static ssize_t mei_recv_msg(struct mei *me, unsigned char *buffer,
ssize_t len, unsigned long timeout)
{
ssize_t rc;
mei_msg(me, "call read length = %zd\n", len);
rc = read(me->fd, buffer, len);
if (rc < 0) {
mei_err(me, "read failed with status %zd %s\n",
rc, strerror(errno));
mei_deinit(me);
} else {
mei_msg(me, "read succeeded with result %zd\n", rc);
}
return rc;
}
static ssize_t mei_send_msg(struct mei *me, const unsigned char *buffer,
ssize_t len, unsigned long timeout)
{
struct timeval tv;
ssize_t written;
ssize_t rc;
fd_set set;
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000000;
mei_msg(me, "call write length = %zd\n", len);
written = write(me->fd, buffer, len);
if (written < 0) {
rc = -errno;
mei_err(me, "write failed with status %zd %s\n",
written, strerror(errno));
goto out;
}
FD_ZERO(&set);
FD_SET(me->fd, &set);
rc = select(me->fd + 1 , &set, NULL, NULL, &tv);
if (rc > 0 && FD_ISSET(me->fd, &set)) {
mei_msg(me, "write success\n");
} else if (rc == 0) {
mei_err(me, "write failed on timeout with status\n");
goto out;
} else { /* rc < 0 */
mei_err(me, "write failed on select with status %zd\n", rc);
goto out;
}
rc = written;
out:
if (rc < 0)
mei_deinit(me);
return rc;
}
/***************************************************************************
* Intel Advanced Management Technology ME Client
***************************************************************************/
#define AMT_MAJOR_VERSION 1
#define AMT_MINOR_VERSION 1
#define AMT_STATUS_SUCCESS 0x0
#define AMT_STATUS_INTERNAL_ERROR 0x1
#define AMT_STATUS_NOT_READY 0x2
#define AMT_STATUS_INVALID_AMT_MODE 0x3
#define AMT_STATUS_INVALID_MESSAGE_LENGTH 0x4
#define AMT_STATUS_HOST_IF_EMPTY_RESPONSE 0x4000
#define AMT_STATUS_SDK_RESOURCES 0x1004
#define AMT_BIOS_VERSION_LEN 65
#define AMT_VERSIONS_NUMBER 50
#define AMT_UNICODE_STRING_LEN 20
struct amt_unicode_string {
uint16_t length;
char string[AMT_UNICODE_STRING_LEN];
} __attribute__((packed));
struct amt_version_type {
struct amt_unicode_string description;
struct amt_unicode_string version;
} __attribute__((packed));
struct amt_version {
uint8_t major;
uint8_t minor;
} __attribute__((packed));
struct amt_code_versions {
uint8_t bios[AMT_BIOS_VERSION_LEN];
uint32_t count;
struct amt_version_type versions[AMT_VERSIONS_NUMBER];
} __attribute__((packed));
/***************************************************************************
* Intel Advanced Management Technology Host Interface
***************************************************************************/
struct amt_host_if_msg_header {
struct amt_version version;
uint16_t _reserved;
uint32_t command;
uint32_t length;
} __attribute__((packed));
struct amt_host_if_resp_header {
struct amt_host_if_msg_header header;
uint32_t status;
unsigned char data[0];
} __attribute__((packed));
const uuid_le MEI_IAMTHIF = UUID_LE(0x12f80028, 0xb4b7, 0x4b2d, \
0xac, 0xa8, 0x46, 0xe0, 0xff, 0x65, 0x81, 0x4c);
#define AMT_HOST_IF_CODE_VERSIONS_REQUEST 0x0400001A
#define AMT_HOST_IF_CODE_VERSIONS_RESPONSE 0x0480001A
const struct amt_host_if_msg_header CODE_VERSION_REQ = {
.version = {AMT_MAJOR_VERSION, AMT_MINOR_VERSION},
._reserved = 0,
.command = AMT_HOST_IF_CODE_VERSIONS_REQUEST,
.length = 0
};
struct amt_host_if {
struct mei mei_cl;
unsigned long send_timeout;
bool initialized;
};
static bool amt_host_if_init(struct amt_host_if *acmd,
unsigned long send_timeout, bool verbose)
{
acmd->send_timeout = (send_timeout) ? send_timeout : 20000;
acmd->initialized = mei_init(&acmd->mei_cl, &MEI_IAMTHIF, 0, verbose);
return acmd->initialized;
}
static void amt_host_if_deinit(struct amt_host_if *acmd)
{
mei_deinit(&acmd->mei_cl);
acmd->initialized = false;
}
static uint32_t amt_verify_code_versions(const struct amt_host_if_resp_header *resp)
{
uint32_t status = AMT_STATUS_SUCCESS;
struct amt_code_versions *code_ver;
size_t code_ver_len;
uint32_t ver_type_cnt;
uint32_t len;
uint32_t i;
code_ver = (struct amt_code_versions *)resp->data;
/* length - sizeof(status) */
code_ver_len = resp->header.length - sizeof(uint32_t);
ver_type_cnt = code_ver_len -
sizeof(code_ver->bios) -
sizeof(code_ver->count);
if (code_ver->count != ver_type_cnt / sizeof(struct amt_version_type)) {
status = AMT_STATUS_INTERNAL_ERROR;
goto out;
}
for (i = 0; i < code_ver->count; i++) {
len = code_ver->versions[i].description.length;
if (len > AMT_UNICODE_STRING_LEN) {
status = AMT_STATUS_INTERNAL_ERROR;
goto out;
}
len = code_ver->versions[i].version.length;
if (code_ver->versions[i].version.string[len] != '\0' ||
len != strlen(code_ver->versions[i].version.string)) {
status = AMT_STATUS_INTERNAL_ERROR;
goto out;
}
}
out:
return status;
}
static uint32_t amt_verify_response_header(uint32_t command,
const struct amt_host_if_msg_header *resp_hdr,
uint32_t response_size)
{
if (response_size < sizeof(struct amt_host_if_resp_header)) {
return AMT_STATUS_INTERNAL_ERROR;
} else if (response_size != (resp_hdr->length +
sizeof(struct amt_host_if_msg_header))) {
return AMT_STATUS_INTERNAL_ERROR;
} else if (resp_hdr->command != command) {
return AMT_STATUS_INTERNAL_ERROR;
} else if (resp_hdr->_reserved != 0) {
return AMT_STATUS_INTERNAL_ERROR;
} else if (resp_hdr->version.major != AMT_MAJOR_VERSION ||
resp_hdr->version.minor < AMT_MINOR_VERSION) {
return AMT_STATUS_INTERNAL_ERROR;
}
return AMT_STATUS_SUCCESS;
}
static uint32_t amt_host_if_call(struct amt_host_if *acmd,
const unsigned char *command, ssize_t command_sz,
uint8_t **read_buf, uint32_t rcmd,
unsigned int expected_sz)
{
uint32_t in_buf_sz;
ssize_t out_buf_sz;
ssize_t written;
uint32_t status;
struct amt_host_if_resp_header *msg_hdr;
in_buf_sz = acmd->mei_cl.buf_size;
*read_buf = (uint8_t *)malloc(sizeof(uint8_t) * in_buf_sz);
if (*read_buf == NULL)
return AMT_STATUS_SDK_RESOURCES;
memset(*read_buf, 0, in_buf_sz);
msg_hdr = (struct amt_host_if_resp_header *)*read_buf;
written = mei_send_msg(&acmd->mei_cl,
command, command_sz, acmd->send_timeout);
if (written != command_sz)
return AMT_STATUS_INTERNAL_ERROR;
out_buf_sz = mei_recv_msg(&acmd->mei_cl, *read_buf, in_buf_sz, 2000);
if (out_buf_sz <= 0)
return AMT_STATUS_HOST_IF_EMPTY_RESPONSE;
status = msg_hdr->status;
if (status != AMT_STATUS_SUCCESS)
return status;
status = amt_verify_response_header(rcmd,
&msg_hdr->header, out_buf_sz);
if (status != AMT_STATUS_SUCCESS)
return status;
if (expected_sz && expected_sz != out_buf_sz)
return AMT_STATUS_INTERNAL_ERROR;
return AMT_STATUS_SUCCESS;
}
static uint32_t amt_get_code_versions(struct amt_host_if *cmd,
struct amt_code_versions *versions)
{
struct amt_host_if_resp_header *response = NULL;
uint32_t status;
status = amt_host_if_call(cmd,
(const unsigned char *)&CODE_VERSION_REQ,
sizeof(CODE_VERSION_REQ),
(uint8_t **)&response,
AMT_HOST_IF_CODE_VERSIONS_RESPONSE, 0);
if (status != AMT_STATUS_SUCCESS)
goto out;
status = amt_verify_code_versions(response);
if (status != AMT_STATUS_SUCCESS)
goto out;
memcpy(versions, response->data, sizeof(struct amt_code_versions));
out:
if (response != NULL)
free(response);
return status;
}
/************************** end of amt_host_if_command ***********************/
int main(int argc, char **argv)
{
struct amt_code_versions ver;
struct amt_host_if acmd;
unsigned int i;
uint32_t status;
int ret;
bool verbose;
verbose = (argc > 1 && strcmp(argv[1], "-v") == 0);
if (!amt_host_if_init(&acmd, 5000, verbose)) {
ret = 1;
goto out;
}
status = amt_get_code_versions(&acmd, &ver);
amt_host_if_deinit(&acmd);
switch (status) {
case AMT_STATUS_HOST_IF_EMPTY_RESPONSE:
printf("Intel AMT: DISABLED\n");
ret = 0;
break;
case AMT_STATUS_SUCCESS:
printf("Intel AMT: ENABLED\n");
for (i = 0; i < ver.count; i++) {
printf("%s:\t%s\n", ver.versions[i].description.string,
ver.versions[i].version.string);
}
ret = 0;
break;
default:
printf("An error has occurred\n");
ret = 1;
break;
}
out:
return ret;
}
|
the_stack_data/131389.c | #include<stdio.h>
int main () {
// Declare and initiliaze variables
int x = 2138;
float y = -52.358925;
char z = 'G';
double u = 61.295339687;
printf("x=%9d\n", x); // Output x over 9 positions
printf("y=%11.5f\n", y); // Output y over 11 positions with precision up to 5 digits
printf("z=%c\n", z); // Output c as a character
printf("u=%.7lf\n", u); // Output u with precision up to 7 digits
return 0;
} |
the_stack_data/39638.c | /*
* test sequence generator for xorshift64star.c
* Written by Kenji Rikitake
* License: CC0 / public domain
* NOTE: use C99 or later
*/
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
uint64_t next(void);
extern uint64_t s[16];
extern int p;
void print_s(void)
{
printf("p = %d ", p);
for(int j = 0; j < 16; j++) {
printf("s[%d] = %" PRIu64 " ", j, s[j]);
}
printf("\n");
}
int main(void)
{
int i;
p = 0;
s[0] = 0x0123456789abcdefULL;
s[1] = 0x123456789abcdef0ULL;
s[2] = 0x23456789abcdef01ULL;
s[3] = 0x3456789abcdef012ULL;
s[4] = 0x456789abcdef0123ULL;
s[5] = 0x56789abcdef01234ULL;
s[6] = 0x6789abcdef012345ULL;
s[7] = 0x789abcdef0123456ULL;
s[8] = 0x89abcdef01234567ULL;
s[9] = 0x9abcdef012345678ULL;
s[10] = 0xabcdef0123456789ULL;
s[11] = 0xbcdef0123456789aULL;
s[12] = 0xcdef0123456789abULL;
s[13] = 0xdef0123456789abcULL;
s[14] = 0xef0123456789abcdULL;
s[15] = 0xf0123456789abcdeULL;
print_s();
for (i = 0; i < 1000; i ++) {
printf("next = %" PRIu64 " ", next());
print_s();
}
}
|
the_stack_data/59511459.c | #include<stdio.h>
int main()
{
printf("hello_world");
if(1)
{
printf("hi");
}
else
{
printf("hello");
}
}
|
the_stack_data/23575232.c | // 2015-05-21 03:20:13
#include <stdio.h>
#define MAX 101
int main()
{
int ma[MAX][MAX], N, i, j, maior=0, cont=0, resul[1000], cont_r=0;
scanf(" %d" , &N);
cont++;
do{
maior=0;
for(i=0;i<N;i++){
for(j=0;j<N;j++){
scanf(" %d" , &ma[i][j]);
}
}
for(j=0;j<N;j++){
for(i=0;i<N;i++){
cont += ma[i][j];
}
if(cont>maior) maior = cont;
cont=0;
}
resul[cont_r] = maior;
cont_r++;
scanf(" %d" , &N);
} while(N!=0);
i=0;
while(i<cont_r){
printf("\n%d" , resul[i]);
i++;
}
return 0;
} |
the_stack_data/117747.c | /**
@file win32.c
@brief ENet Win32 system specific functions
*/
#ifdef WIN32
#include <time.h>
#define ENET_BUILDING_LIB 1
#include "enet.h"
static enet_uint32 timeBase = 0;
int
enet_initialize(void)
{
WORD versionRequested = MAKEWORD(1, 1);
WSADATA wsaData;
if (WSAStartup(versionRequested, &wsaData))
return -1;
if (LOBYTE(wsaData.wVersion) != 1 ||
HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return -1;
}
timeBeginPeriod(1);
return 0;
}
void
enet_deinitialize(void)
{
timeEndPeriod(1);
WSACleanup();
}
enet_uint32
enet_time_get(void)
{
return (enet_uint32)timeGetTime() - timeBase;
}
void
enet_time_set(enet_uint32 newTimeBase)
{
timeBase = (enet_uint32)timeGetTime() - newTimeBase;
}
int
enet_address_set_host(ENetAddress * address, const char * name)
{
struct hostent * hostEntry;
hostEntry = gethostbyname(name);
if (hostEntry == NULL ||
hostEntry->h_addrtype != AF_INET)
{
unsigned long host = inet_addr(name);
if (host == INADDR_NONE)
return -1;
address->host = host;
return 0;
}
address->host = *(enet_uint32 *)hostEntry->h_addr_list[0];
return 0;
}
int
enet_address_get_host_ip(const ENetAddress * address, char * name, size_t nameLength)
{
char * addr = inet_ntoa(*(struct in_addr *) & address->host);
if (addr == NULL)
return -1;
strncpy(name, addr, nameLength);
return 0;
}
int
enet_address_get_host(const ENetAddress * address, char * name, size_t nameLength)
{
struct in_addr in;
struct hostent * hostEntry;
in.s_addr = address->host;
hostEntry = gethostbyaddr((char *)& in, sizeof(struct in_addr), AF_INET);
if (hostEntry == NULL)
return enet_address_get_host_ip(address, name, nameLength);
strncpy(name, hostEntry->h_name, nameLength);
return 0;
}
int
enet_socket_bind(ENetSocket socket, const ENetAddress * address)
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
if (address != NULL)
{
sin.sin_port = ENET_HOST_TO_NET_16(address->port);
sin.sin_addr.s_addr = address->host;
}
else
{
sin.sin_port = 0;
sin.sin_addr.s_addr = INADDR_ANY;
}
return bind(socket,
(struct sockaddr *) & sin,
sizeof(struct sockaddr_in)) == SOCKET_ERROR ? -1 : 0;
}
int
enet_socket_listen(ENetSocket socket, int backlog)
{
return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
}
ENetSocket
enet_socket_create(ENetSocketType type)
{
return socket(PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
}
int
enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value)
{
int result = SOCKET_ERROR;
switch (option)
{
case ENET_SOCKOPT_NONBLOCK:
{
u_long nonBlocking = (u_long)value;
result = ioctlsocket(socket, FIONBIO, &nonBlocking);
break;
}
case ENET_SOCKOPT_BROADCAST:
result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)& value, sizeof(int));
break;
case ENET_SOCKOPT_REUSEADDR:
result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char *)& value, sizeof(int));
break;
case ENET_SOCKOPT_RCVBUF:
result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)& value, sizeof(int));
break;
case ENET_SOCKOPT_SNDBUF:
result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)& value, sizeof(int));
break;
default:
break;
}
return result == SOCKET_ERROR ? -1 : 0;
}
int
enet_socket_connect(ENetSocket socket, const ENetAddress * address)
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = ENET_HOST_TO_NET_16(address->port);
sin.sin_addr.s_addr = address->host;
return connect(socket, (struct sockaddr *) & sin, sizeof(struct sockaddr_in)) == SOCKET_ERROR ? -1 : 0;
}
ENetSocket
enet_socket_accept(ENetSocket socket, ENetAddress * address)
{
SOCKET result;
struct sockaddr_in sin;
int sinLength = sizeof(struct sockaddr_in);
result = accept(socket,
address != NULL ? (struct sockaddr *) & sin : NULL,
address != NULL ? &sinLength : NULL);
if (result == INVALID_SOCKET)
return ENET_SOCKET_NULL;
if (address != NULL)
{
address->host = (enet_uint32)sin.sin_addr.s_addr;
address->port = ENET_NET_TO_HOST_16(sin.sin_port);
}
return result;
}
void
enet_socket_destroy(ENetSocket socket)
{
closesocket(socket);
}
int
enet_socket_send(ENetSocket socket,
const ENetAddress * address,
const ENetBuffer * buffers,
size_t bufferCount)
{
struct sockaddr_in sin;
DWORD sentLength;
if (address != NULL)
{
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = ENET_HOST_TO_NET_16(address->port);
sin.sin_addr.s_addr = address->host;
}
if (WSASendTo(socket,
(LPWSABUF)buffers,
(DWORD)bufferCount,
&sentLength,
0,
address != NULL ? (struct sockaddr *) & sin : 0,
address != NULL ? sizeof(struct sockaddr_in) : 0,
NULL,
NULL) == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
return 0;
return -1;
}
return (int)sentLength;
}
int
enet_socket_receive(ENetSocket socket,
ENetAddress * address,
ENetBuffer * buffers,
size_t bufferCount)
{
INT sinLength = sizeof(struct sockaddr_in);
DWORD flags = 0,
recvLength;
struct sockaddr_in sin;
if (WSARecvFrom(socket,
(LPWSABUF)buffers,
(DWORD)bufferCount,
&recvLength,
&flags,
address != NULL ? (struct sockaddr *) & sin : NULL,
address != NULL ? &sinLength : NULL,
NULL,
NULL) == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSAEWOULDBLOCK:
case WSAECONNRESET:
return 0;
}
return -1;
}
if (flags & MSG_PARTIAL)
return -1;
if (address != NULL)
{
address->host = (enet_uint32)sin.sin_addr.s_addr;
address->port = ENET_NET_TO_HOST_16(sin.sin_port);
}
return (int)recvLength;
}
int
enet_socketset_select(ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout)
{
struct timeval timeVal;
timeVal.tv_sec = timeout / 1000;
timeVal.tv_usec = (timeout % 1000) * 1000;
return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
}
int
enet_socket_wait(ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout)
{
fd_set readSet, writeSet;
struct timeval timeVal;
int selectCount;
timeVal.tv_sec = timeout / 1000;
timeVal.tv_usec = (timeout % 1000) * 1000;
FD_ZERO(&readSet);
FD_ZERO(&writeSet);
if (*condition & ENET_SOCKET_WAIT_SEND)
FD_SET(socket, &writeSet);
if (*condition & ENET_SOCKET_WAIT_RECEIVE)
FD_SET(socket, &readSet);
selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
if (selectCount < 0)
return -1;
*condition = ENET_SOCKET_WAIT_NONE;
if (selectCount == 0)
return 0;
if (FD_ISSET(socket, &writeSet))
* condition |= ENET_SOCKET_WAIT_SEND;
if (FD_ISSET(socket, &readSet))
* condition |= ENET_SOCKET_WAIT_RECEIVE;
return 0;
}
#endif |
the_stack_data/130001.c | int x;
void *malloc(int i)
{
if (i == sizeof(int))
return &x;
else
return ((char *) 0);
}
int main(void)
{
int *p = malloc(sizeof(int));
if (!p)
return 1;
*p = 3;
test_assert(x == 3);
return 0;
}
/*
int main(void) {
unsigned n = 0;
scanf("%d", &n);
int i = 0;
int sum = 0;
while (++i < n - 3) {}
sum += i;
write_sum(sum);
}
*/
|
the_stack_data/370253.c | #include <stdio.h>
#include <locale.h>
int main()
{
// Learning about string
setlocale(LC_ALL, "Portuguese");
printf("\nHello, world.\n");
printf("\nLearners List");
printf("\n-----------------------------");
printf("\n%-17s %10s", "Name", "Note");
printf("\n%-17s %10.2f", "Ana Beatriz", 8.5);
printf("\n%-17s %10.2f", "Bianca Martins", 9.0);
printf("\n%-17s %10.2f", "Claudio Sa", 5.5);
printf("\n%-17s %10.2f\n\n", "Giovana Silva", 7.5);
return 0;
}
|
the_stack_data/357515.c | #define LOG2(X) ((unsigned) \
(8 * sizeof (unsigned long long) -\
__builtin_clzll((X)) - 1))
int main()
{
printf("%u %u\n", LOG2(0x10), LOG2(0.5));
}
|
the_stack_data/212642315.c | /* { dg-do compile } */
/* { dg-options "-O2 -floop-nest-optimize" } */
typedef struct { float x1; } bx;
typedef struct {
int w;
short o;
} T2P;
T2P a;
int b;
void fn2();
void fn3(bx*,short);
void fn1() {
unsigned i = 0;
int c;
bx *d;
bx **h;
if (b == 0) {
fn2();
return;
}
for (; c; c++)
for (; i < 100; i++) {
d = h[i];
d->x1 = a.w;
}
for (; i < 100; i++) {
d = h[i];
d->x1 = a.w;
}
if (a.o)
for (; b;)
fn3(d, a.o);
}
|
the_stack_data/40762578.c | #include <stdio.h>
int main()
{
int a, b, c;
scanf("%d %d", &a, &b);
c=a+b;
printf("%d\n",c);
return 0;
}
|
the_stack_data/150142312.c | /* strtod.c
*/
/* copyright 1991, 1993, 1995, 1999 John B. Roll jr.
This source is distributed without warranty under the terms of
the GNU General Public License, version 2, 1991.
*/
#include <stdio.h>
#include <ctype.h>
double strtod();
double pow();
int SAOdtype;
double SAOstrtod(str, ptr)
char *str;
char **ptr;
{
double d = 0.0, dx;
double m = 0.0;
double s = 0.0;
char *p, *px;
char c;
SAOdtype = 0;
if ( ptr == NULL ) ptr = &p;
while ( *str == ' ' ) str++;
/* No base implied (yet).
*/
d = strtod(str, ptr);
px = *ptr;
if ( ( c = **ptr )
&& ( c == 'h' || c == 'd' || c == ':' || c == ' ' || c == 'm' )
&& ( (*ptr - str) <= 4 )
&& ( ( isdigit(*((*ptr)+1)) )
|| ( (*((*ptr)+1)) == ' ' && isdigit(*((*ptr)+2)) ) ) ) {
double sign = 1.0;
SAOdtype = c;
(*ptr)++;
if ( *str == '-' ) {
sign = -1.0;
d = -d;
}
m = strtod(*ptr, ptr);
if ( c == 'm' ) {
s = m;
m = d;
d = 0.0;
} else
if ( ( c = **ptr )
&& ( c == ':' || c == ' ' || c == 'm' )
&& ( (*ptr - px) <= 3 )
&& ( ( isdigit(*((*ptr)+1)) )
|| ( (*((*ptr)+1)) == ' ' && isdigit(*((*ptr)+2)) ) ) ) {
(*ptr)++;
s = strtod(*ptr, ptr);
}
return sign * (d + m / 60 + s / 3600);
}
/* I guess that there wern't really any units.
*/
return d;
}
int SAOparsefmt(buff, type, width, prec, flag)
char *buff;
int *type;
int *width;
int *prec;
int *flag;
{
char *q = buff+1;
int t_flag = 0;
if ( *buff != '%' ) return 0;
*type = 0;
*width = 0;
*prec = 0;
*flag = 0;
/* eat the flags */
while (*q == '-' || *q == '+' || *q == ' ' ||
*q == '#' || *q == '0') {
switch ( *q ) {
case '-': *flag |= 2; break;
case '+': *flag |= 4; break;
case ' ': *flag |= 8; break;
case '#': *flag |= 16; break;
case '0': *flag |= 32; break;
}
q++ ;
}
if ( isdigit(*q) ) { *width = strtol( q, &q, 10); }
if ( *q == '.' ) { *prec = strtol(++q, &q, 10); }
if ( *q == 'h' || *q == 'l' ) {
t_flag = *q++;
}
switch ( *q ) {
case 'd': *type = 0; break;
case 'b':
case 'o':
case 'x':
case 'f':
case 'g':
case '@': *type = *q; break;
default: return 0;
}
if ( *type == '@' ) {
*type = ':';
if ( t_flag == 'h' ) *type = 'h';
if ( *flag & 8 ) *type = ' ';
}
return 1;
}
char *SAOconvert(buff, val, type, width, prec, flags)
char *buff;
double val;
int type;
int width;
int prec;
int flags; /* minus, plus, space, pound, zero */
{
char fmt[32];
char *sign = "";
char *zero = "";
char dfmt[64];
float degrees = val;
float minutes;
float seconds;
char ch1, ch2;
if ( flags & 2 ) sign = "-";
if ( flags & 4 ) sign = "+";
if ( flags & 8 ) sign = " ";
if ( flags & 16 ) type = ' ';
if ( flags & 32 ) zero = "0";
switch ( type ) {
case 'b': {
int v = val;
unsigned int i;
int c = 2;
buff[0] = '0';
buff[1] = 'b';
for ( i = 0x8000; i; i /= 2 ) {
if ( v & i || c > 2 ) {
buff[c] = v & i ? '1' : '0';
c++;
}
}
buff[c] = '\0';
return buff;
}
case 'o':
sprintf(buff, "0o%o", (int) val);
return buff;
case 'x':
sprintf(buff, "0x%x", (int) val);
return buff;
case ':': ch1 = ':'; ch2 = ':'; break;
case ' ': ch1 = ' '; ch2 = ' '; break;
case 'h': ch1 = 'h'; ch2 = 'm'; break;
case 'd': ch1 = 'd'; ch2 = 'm'; break;
case 'm': ch1 = 'm'; ch2 = 'm'; break;
default: return 0;
}
if ( degrees < 0.0 ) {
sign = "-";
degrees = - degrees;
}
minutes = (degrees - ((int) degrees)) * 60;
if ( minutes < 0 ) minutes = 0.0;
seconds = (minutes - ((int) minutes)) * 60;
if ( seconds < 0 ) seconds = 0.0;
if ( prec == -1 )
if ( type == 'h' ) prec = 4;
else prec = 3;
if ( prec == -2 ) {
if ( type == 'm' )
if ( seconds < 10.0 )
sprintf(buff, "%s%d%c0%g"
, sign, (int) minutes + degrees * 60, ch2, seconds);
else
sprintf(buff, "%s%d%c%g"
, sign, (int) minutes + degrees * 60, ch2, seconds);
else if ( seconds < 10.0 )
sprintf(buff, "%s%d%c0%2d%c0%g"
, sign, (int) (degrees)
, ch1 , (int) (minutes)
, ch2, seconds);
else
sprintf(buff, "%s%d%c%2d%c%g"
, sign, (int) (degrees)
, ch1 , (int) (minutes)
, ch2, seconds);
} else {
double p = pow(10.0, (double) prec);
int m = minutes;
int d = degrees;
if ( (((int)(seconds * p + .5))/ p) >= 60 ) {
seconds = 0.0;
m++;
if ( m >= 60 ) {
m = 0;
d++;
}
}
if ( width ) {
sprintf(dfmt, "%%%s%dd", zero, width);
} else
strcpy(dfmt, "%d");
if ( (((int)(seconds * p + .5))/ p) < 10.0 )
sprintf(fmt, "%%s%s%c%%2.2d%c0%%.%df", dfmt, ch1, ch2, prec);
else
sprintf(fmt, "%%s%s%c%%2.2d%c%%.%df" , dfmt, ch1, ch2, prec);
sprintf(buff, fmt, sign, d, m, seconds);
}
return buff;
}
|
the_stack_data/1221539.c | /* Empty; not needed. */
|
the_stack_data/154826860.c | // Example for testing part of CS333 P2.
// This is by NO MEANS a complete test.
#ifdef CS333_P2
#include "types.h"
#include "user.h"
static void
uidTest(uint nval)
{
uint uid = getuid();
printf(1, "Current UID is: %d\n", uid);
printf(1, "Setting UID to %d\n", nval);
if (setuid(nval) < 0)
printf(2, "Error. Invalid UID: %d\n", nval);
uid = getuid();
printf(1, "Current UID is: %d\n", uid);
sleep(5 * TPS); // now type control-p
}
static void
gidTest(uint nval)
{
uint gid = getgid();
printf(1, "Current GID is: %d\n", gid);
printf(1, "Setting GID to %d\n", nval);
if (setgid(nval) < 0)
printf(2, "Error. Invalid GID: %d\n", nval);
setgid(nval);
gid = getgid();
printf(1, "Current GID is: %d\n", gid);
sleep(5 * TPS); // now type control-p
}
static void
forkTest(uint nval)
{
uint uid, gid;
int pid;
printf(1, "Setting UID to %d and GID to %d before fork(). Value"
" should be inherited\n", nval, nval);
if (setuid(nval) < 0)
printf(2, "Error. Invalid UID: %d\n", nval);
if (setgid(nval) < 0)
printf(2, "Error. Invalid UID: %d\n", nval);
printf(1, "Before fork(), UID = %d, GID = %d\n", getuid(), getgid());
pid = fork();
if (pid == 0) { // child
uid = getuid();
gid = getgid();
printf(1, "Child: UID is: %d, GID is: %d\n", uid, gid);
sleep(5 * TPS); // now type control-p
exit();
}
else
//sleep(10 * TPS); // wait for child to exit before proceeding
pid = wait();
}
static void
invalidTest(uint nval)
{
printf(1, "Setting UID to %d. This test should FAIL\n", nval);
if (setuid(nval) < 0)
printf(1, "SUCCESS! The setuid sytem call indicated failure\n");
else
printf(2, "FAILURE! The setuid system call indicates success\n");
printf(1, "Setting GID to %d. This test should FAIL\n", nval);
if (setgid(nval) < 0)
printf(1, "SUCCESS! The setgid sytem call indicated failure\n");
else
printf(2, "FAILURE! The setgid system call indicates success\n");
printf(1, "Setting UID to %d. This test should FAIL\n", -1);
if (setuid(-1) < 0)
printf(1, "SUCCESS! The setuid sytem call indicated failure\n");
else
printf(2, "FAILURE! The setgid system call indicates success\n");
}
static int
testuidgid(void)
{
uint nval, ppid;
// get/set uid test
nval = 100;
uidTest(nval);
// get/set gid test
nval = 200;
gidTest(nval);
// getppid test
ppid = getppid();
printf(1, "My parent process is: %d\n", ppid);
// fork tests to demonstrate UID/GID inheritance
nval = 111;
forkTest(nval);
// tests for invalid values for uid and gid
nval = 32800; // 32767 is max value
invalidTest(nval);
printf(1, "Done!\n");
return 0;
}
int
main() {
testuidgid();
exit();
}
#endif
|
the_stack_data/26774.c | /*
* 修改温度转换程序,要求以逆序(即按照从300度到0度的顺序)打印温度转换表。
*/
#include <stdio.h>
int main()
{
int fahr;
printf("华氏温度-摄氏温度对照表\n");
for (fahr = 300; fahr >= 0; fahr = fahr - 20)
{
printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
}
}
|
the_stack_data/109583.c | #include <stdio.h>
/* echo command-line arguments; 2nd version */
int main(int argc, char *argv[])
{
while (--argc > 0)
printf("%s%s", *++argv, (argc > 1) ? " " : "");
printf("\n");
return 0;
}
|
the_stack_data/31386606.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORTNO 4000
void connect_to_socket (void (*handle) (int))
{
int sockfd, newsockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
fprintf (stderr, "ERROR opening socket.\n");
exit (1);
}
memset (&serv_addr, 0, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons (PORTNO);
if (bind (sockfd, (struct sockaddr*) &serv_addr, sizeof (serv_addr)) < 0) {
fprintf (stderr, "ERROR binding socket.\n");
exit (1);
}
listen (sockfd, 5);
while (1) {
clilen = sizeof (cli_addr);
newsockfd = accept (sockfd, (struct sockaddr*) &cli_addr, &clilen);
if (newsockfd < 0) {
fprintf (stderr, "ERROR on accept.\n");
} else {
handle (newsockfd);
}
}
}
|
the_stack_data/25137466.c | #include <stdio.h>
int main() {
double x_plus_y, x_minus_y, x, y;
scanf("%lf %lf", &x_plus_y, &x_minus_y);
x = (x_plus_y + x_minus_y ) / 2;
y = (x_plus_y - x_minus_y) / 2;
printf("x = %.2lf\ny = %.2lf\n", x, y);
} |
the_stack_data/1177652.c | int main(void) {
return 5;
}
|
the_stack_data/146887.c | #include <stdio.h>
typedef long long ll;
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
freopen("1.err", "w", stderr);
#endif
int n, t;
while (~scanf("%d", &n)) {
t = 3;
for (;n > 0;n--)
t = (t - 1) * 2;
printf("%d\n", t);
}
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
fclose(stderr);
#endif
return 0;
}
|
the_stack_data/248580383.c | /*
* Ve stáji jsou lidé a koně.
* Celkem je ve stáji 22 hlav a 72 nohou.
* Kolik koní a kolik lidí je celkem ve stáji?
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const int POCET_HLAV = 22;
const int POCET_NOHOU = 72;
int main()
{
int lidi, kone;
/* solution 1 */
/*
* 1: lidi + kone = 22
* 2: 2*lidi + 4*kone = 72
* -----------------------
* lidi = 22 - kone
* 2*(22 - kone) + 4*kone = 72
* 44 - 2*kone + 4*kone = 72
* 4*kone - 2*kone = 72 - 44
* 2*kone = 28
* kone = 28/2 = 14
* lidi = 22 - kone = 22 - 14 = 8
*/
kone = (POCET_NOHOU - 2 * POCET_HLAV) / (4 - 2);
lidi = POCET_HLAV - kone;
printf("lidi = %d\tkone = %d\n", lidi, kone);
/* solution 2 */
for (int lidi = 1; lidi < POCET_HLAV; lidi++)
{
kone = POCET_HLAV - lidi;
if (2 * lidi + 4 * kone == POCET_NOHOU)
{
printf("lidi = %d\tkone = %d\n", lidi, kone);
break;
}
}
/* solution 3 */
lidi = 0;
kone = POCET_HLAV;
do
{
lidi++;
kone--;
} while (2 * lidi + 4 * kone != POCET_NOHOU);
printf("lidi = %d\tkone = %d\n", lidi, kone);
return 0;
} |
the_stack_data/165768586.c | #include <stdio.h>
int LinearSearch(int arr[], int arrLength, int key) {
int i;
for(i = 0; i < arrLength; i++) {
if(arr[i] == key) {
return i;
}
}
return -1;
}
int main(int argc, char const *argv[]) {
int arr[] = {20, 12, 5, 14, 9, 31, 8, 2, 10, 0, 3};
int arrLength = sizeof(arr) / sizeof(int);
int searchKey = 31;
int foundAt = LinearSearch(arr, arrLength, searchKey);
if(foundAt == -1) {
printf("%d not found \n", searchKey);
} else {
printf("%d found Index :: %d \n", searchKey, foundAt);
}
searchKey = 55;
foundAt = LinearSearch(arr, arrLength, searchKey);
if(foundAt == -1) {
printf("%d not found \n", searchKey);
} else {
printf("%d found Index :: %d \n", searchKey, foundAt);
}
return 0;
}
|
the_stack_data/1033670.c | //
// Created by Vashon on 2020/7/15.
//
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/*
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
*/
// 方法一:每个字符逐个对比
int firstUniqChar(char *s);
// 方法二:散列表思想,将时间复杂度从n^2变成n
int firstUniqChar_(char *s);
// 字符串中的第一个唯一字符,LeetCode第387题
void homework_031_387(void) {
char *s1 = "leetcode";
char *s2 = "loveleetcode";
printf("first index : %d\n", firstUniqChar_(s1));
printf("first index : %d\n", firstUniqChar_(s2));
}
int firstUniqChar(char *s) {
if (!s)
return -1;
unsigned long long len = strlen(s);
if (len == 0)
return -1;
char *pre = s;
int index = 0;
for (int i = 0; i < len; ++i) { // 两次循环进行比较
bool exited = false;
index = i;
for (int j = 0; j < len; ++j) {
if (i == j)
continue;
if (pre[i] == pre[j]) {
exited = true;
index = -1;
break;
}
}
if (!exited)
break;
}
return index;
}
int firstUniqChar_(char *s) {
if (!s)
return -1;
unsigned long long len = strlen(s);
if (len == 0)
return -1;
int words[26] = {0};
for (int i = 0; i < len; ++i) // 将每个字符出现的次数累计在一个数组内
words[s[i] - 'a']++;
for (int j = 0; j < len; ++j) {
if (words[s[j] - 'a'] == 1) // 当字符累计数为 1,则满足条件
return j;
}
return -1;
}
|
the_stack_data/503370.c | // %%cpp strange_example.c
// %run gcc strange_example.c -o strange_example.exe
// %run echo "Hello world!" > a.txt
// %run ./strange_example.exe 5< a.txt > strange_example.out
// %run cat strange_example.out
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char buffer[4096];
int bytes_read = read(5, buffer, sizeof(buffer)); // not standart opened fd
if (bytes_read < 0) {
perror("Error reading file");
return -1;
}
int written_bytes = write(1, buffer, bytes_read);
if (written_bytes < 0) {
perror("Error writing file");
return -1;
}
return 0;
}
|
the_stack_data/61076223.c | /*
Copyright (c) 2014-2021, Alexey Frunze
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE 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.
*/
/*****************************************************************************/
/* */
/* Smaller C linker */
/* */
/* A simple linker for Smaller C compiler and NASM */
/* */
/* Consumes ELF32 x86 object files produced with NASM */
/* */
/* Produces: */
/* - 16/32-bit DOS executables */
/* (tiny model/.COM, small model/.EXE, */
/* huge model/.EXE, unreal model/.EXE, */
/* 32-bit DPMI/.EXE) */
/* - 32-bit PE/Windows executables */
/* - 32-bit ELF/Linux executables */
/* - 32-bit Mach-O/Mac OS X executables */
/* - 32-bit OMAGIC a.out executables */
/* - 16/32-bit flat executables */
/* */
/* Main file */
/* */
/*****************************************************************************/
#ifndef __SMALLER_C__
#include <limits.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#else
#ifndef __SMALLER_C_32__
#error must be compiled for 32-bit or huge mode(l)
#endif
#define NULL 0
typedef void FILE;
#define EOF (-1)
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#define CHAR_BIT 8
#define INT_MAX 0x7FFFFFFF
#define LONG_MAX 0x7FFFFFFF
typedef unsigned size_t;
char* strtok(char*, char*);
unsigned long strtoul(char*, char**, int);
void qsort(void*, size_t, size_t, int (*)(void*, void*));
#define EXIT_FAILURE 1
void exit(int);
size_t strlen(char*);
int strcmp(char*, char*);
int strncmp(char*, char*, size_t);
char* strncpy(char*, char*, size_t);
void* memmove(void*, void*, size_t);
void* memcpy(void*, void*, size_t);
void* memset(void*, int, size_t);
int memcmp(void*, void*, size_t);
FILE* fopen(char*, char*);
int fclose(FILE*);
int fgetc(FILE*);
int puts(char*);
int sprintf(char*, char*, ...);
//int vsprintf(char*, char*, va_list);
int vsprintf(char*, char*, void*);
int printf(char*, ...);
int fprintf(FILE*, char*, ...);
//int vprintf(char*, va_list);
int vprintf(char*, void*);
size_t fread(void*, size_t, size_t, FILE*);
size_t fwrite(void*, size_t, size_t, FILE*);
int fseek(FILE*, long, int);
long ftell(FILE*);
int remove(char*);
void* malloc(size_t);
void* realloc(void*, size_t);
void free(void*);
#endif
// By default don't support relocations with local symbols
// other than section symbols in DOS huge memory model.
// This is to conserve memory.
#ifndef SUPPORT_LOCAL_RELS
#ifdef __SMALLER_C__
#ifdef __HUGE__
#define SHOULDNT_SUPPORT_LOCAL_RELS
#endif
#endif
#ifndef SHOULDNT_SUPPORT_LOCAL_RELS
#define SUPPORT_LOCAL_RELS
#endif
#endif // SUPPORT_LOCAL_RELS
typedef unsigned char uchar, uint8;
typedef signed char schar, int8;
typedef unsigned short ushort, uint16;
typedef short int16;
#ifndef __SMALLER_C__
#if UINT_MAX >= 0xFFFFFFFF
typedef unsigned uint32;
typedef int int32;
#else
typedef unsigned long uint32;
typedef long int32;
#endif
#else
typedef unsigned uint32;
typedef int int32;
#endif
typedef unsigned uint;
typedef unsigned long ulong;
#ifndef __SMALLER_C_32__
#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
C_ASSERT(CHAR_BIT == 8);
C_ASSERT(sizeof(uint16) == 2);
C_ASSERT(sizeof(uint32) == 4);
C_ASSERT(sizeof(size_t) >= 4); // need a 32-bit compiler
#endif
typedef struct
{
uint8 e_ident[16];
#define ELFCLASS32 1
#define ELFDATA2LSB 1
uint16 e_type;
#define ET_REL 1
#define ET_EXEC 2
uint16 e_machine;
#define EM_386 3
uint32 e_version;
#define EV_CURRENT 1
uint32 e_entry;
uint32 e_phoff;
uint32 e_shoff;
uint32 e_flags;
uint16 e_ehsize;
uint16 e_phentsize;
uint16 e_phnum;
uint16 e_shentsize;
uint16 e_shnum;
uint16 e_shstrndx;
#define SHN_UNDEF 0
#define SHN_LORESERVE 0xFF00
#define SHN_COMMON 0xFFF2
} Elf32_Ehdr;
typedef struct
{
uint32 sh_name;
uint32 sh_type;
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
uint32 sh_flags;
#define SHF_WRITE 1
#define SHF_ALLOC 2
#define SHF_EXECINSTR 4
uint32 sh_addr;
uint32 sh_offset;
uint32 sh_size;
uint32 sh_link;
uint32 sh_info;
uint32 sh_addralign;
uint32 sh_entsize;
} Elf32_Shd;
typedef struct
{
uint32 st_name;
#define STN_UNDEF 0
uint32 st_value;
uint32 st_size;
uint8 st_info;
#define STB_LOCAL 0
#define STB_GLOBAL 1
#define STB_WEAK 2
#define STT_NOTYPE 0
#define STT_OBJECT 1
#define STT_FUNC 2
#define STT_SECTION 3
#define STT_FILE 4
uint8 st_other;
uint16 st_shndx;
} Elf32_Sym;
typedef struct
{
uint32 r_offset;
uint32 r_info; // bits 0...7: relocation type, bits 8...31: index into the symbol table
// relocation section's sh_link is the section index of the symbol section to use
// relocation section's sh_info is the section index of the code/data section to make relocations in
// symbol section's sh_link is the section index of the string table section containing symbol names
// symbol section's sh_info is the number of all local symblols, others (global, weak, etc) follow local ones
// it's a pity that symbols referring to whole sections can be local and thus I can't simply ignore all
// local symbols
#define R_386_32 1
#define R_386_PC32 2
#define R_386_16 20
#define R_386_PC16 21
} Elf32_Rel;
typedef struct
{
uint32 r_offset;
uint32 r_info;
uint32 r_addend;
} Elf32_Rela;
typedef struct
{
uint32 p_type;
#define PT_NULL 0
#define PT_LOAD 1
#define PT_NOTE 4
#define PT_PHDR 6
uint32 p_offset;
uint32 p_vaddr;
uint32 p_paddr;
uint32 p_filesz;
uint32 p_memsz;
uint32 p_flags;
uint32 p_align;
} Elf32_Phdr;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(Elf32_Ehdr) == 52);
C_ASSERT(sizeof(Elf32_Shd) == 40);
C_ASSERT(sizeof(Elf32_Sym) == 16);
C_ASSERT(sizeof(Elf32_Rel) == 8);
C_ASSERT(sizeof(Elf32_Rela) == 12);
C_ASSERT(sizeof(Elf32_Phdr) == 32);
#endif
typedef struct
{
#define MACH_MAGIC_32 0xfeedface
uint32 magic;
#define MACH_CPU_ARCH_ABI32 0x00000000
#define MACH_CPU_TYPE_I386 0x00000007
#define MACH_CPU_TYPE_X86 (MACH_CPU_ARCH_ABI32 | MACH_CPU_TYPE_I386)
uint32 cputype;
#define MACH_CPU_SUBTYPE_I386_ALL 0x00000003
uint32 cpusubtype;
#define MACH_EXECUTE 0x2
uint32 filetype;
uint32 ncmds;
uint32 sizeofcmds;
#define MACH_NOUNDEFS 0x1
uint32 flags;
} Mach32_Header;
typedef struct
{
#define MACH_LC_SEGMENT 0x1
#define MACH_LC_SYMTAB 0x2
#define MACH_LC_THREAD 0x4
#define MACH_LC_UNIXTHREAD 0x5
uint32 cmd;
uint32 cmdsize;
} Mach32_LoadCmd;
typedef struct
{
uint32 cmd;
uint32 cmdsize;
char segname[16];
uint32 vmaddr;
uint32 vmsize;
uint32 fileoff;
uint32 filesize;
#define MACH_VM_PROT_READ 0x1
#define MACH_VM_PROT_WRITE 0x2
#define MACH_VM_PROT_EXECUTE 0x4
uint32 maxprot;
uint32 initprot;
uint32 nsects;
uint32 flags;
} Mach32_SegmentCmd;
typedef struct
{
char sectname[16];
char segname[16];
uint32 addr;
uint32 size;
uint32 offset;
uint32 align;
uint32 reloff;
uint32 nreloc;
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000
#define S_ATTR_SOME_INSTRUCTIONS 0x400
uint32 flags;
uint32 reserved1;
uint32 reserved2;
} Mach32_Section;
typedef struct
{
uint32 eax;
uint32 ebx;
uint32 ecx;
uint32 edx;
uint32 edi;
uint32 esi;
uint32 ebp;
uint32 esp;
uint32 ss;
uint32 eflags;
uint32 eip;
uint32 cs;
uint32 ds;
uint32 es;
uint32 fs;
uint32 gs;
} Mach32_ThreadState;
typedef struct
{
uint32 cmd; /* MACH_LC_THREAD or MACH_LC_UNIXTHREAD */
uint32 cmdsize; /* total size of this command */
#define MACH_X86_THREAD_STATE 0x1
uint32 flavor; /* flavor of thread state */
uint32 count; /* count of longs in thread state */
Mach32_ThreadState state;
} Mach32_ThreadCmd;
typedef struct
{
uint32 cmd;
uint32 cmdsize;
uint32 symoff;
uint32 nsyms;
uint32 stroff;
uint32 strsize;
} Mach32_SymtabCmd;
typedef struct
{
uint32 n_strx;
#define MACH_N_EXT 0x1
#define MACH_N_ABS 0x2
#define MACH_N_SECT 0xe
uint8 n_type;
uint8 n_sect;
#define MACH_REFERENCE_FLAG_UNDEFINED_NON_LAZY 0x00
#define MACH_REFERENCED_DYNAMICALLY 0x10
int16 n_desc;
uint32 n_value;
} Mach32_Nlist;
typedef struct
{
uint8 Signature[2];
uint16 PartPage;
uint16 PageCnt;
uint16 ReloCnt;
uint16 HdrSize;
uint16 MinAlloc;
uint16 MaxAlloc;
uint16 InitSs;
uint16 InitSp;
uint16 ChkSum;
uint16 InitIp;
uint16 InitCs;
uint16 ReloOff;
uint16 OverlayNo;
uint16 FirstRelo[2];
} tDosExeHeader;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tDosExeHeader) == 32);
#endif
typedef struct
{
uint16 Machine;
uint16 NumberOfSections;
uint32 TimeDateStamp;
uint32 PointerToSymbolTable;
uint32 NumberOfSymbols;
uint16 SizeOfOptionalHeader;
uint16 Characteristics;
} tPeImageFileHeader;
typedef struct
{
uint32 VirtualAddress;
uint32 Size;
} tPeImageDataDirectory;
typedef struct
{
uint16 Magic;
uint8 MajorLinkerVersion;
uint8 MinorLinkerVersion;
uint32 SizeOfCode;
uint32 SizeOfInitializedData;
uint32 SizeOfUninitializedData;
uint32 AddressOfEntryPoint;
uint32 BaseOfCode;
uint32 BaseOfData;
uint32 ImageBase;
uint32 SectionAlignment;
uint32 FileAlignment;
uint16 MajorOperatingSystemVersion;
uint16 MinorOperatingSystemVersion;
uint16 MajorImageVersion;
uint16 MinorImageVersion;
uint16 MajorSubsystemVersion;
uint16 MinorSubsystemVersion;
uint32 Win32VersionValue;
uint32 SizeOfImage;
uint32 SizeOfHeaders;
uint32 CheckSum;
uint16 Subsystem;
uint16 DllCharacteristics;
uint32 SizeOfStackReserve;
uint32 SizeOfStackCommit;
uint32 SizeOfHeapReserve;
uint32 SizeOfHeapCommit;
uint32 LoaderFlags;
uint32 NumberOfRvaAndSizes;
tPeImageDataDirectory DataDirectory[16];
} tPeImageOptionalHeader;
typedef struct
{
uint8 Name[8];
union
{
uint32 PhysicalAddress;
uint32 VirtualSize;
} Misc;
uint32 VirtualAddress;
uint32 SizeOfRawData;
uint32 PointerToRawData;
uint32 PointerToRelocations;
uint32 PointerToLinenumbers;
uint16 NumberOfRelocations;
uint16 NumberOfLinenumbers;
uint32 Characteristics;
} tPeImageSectionHeader;
typedef struct
{
union
{
uint32 Characteristics;
uint32 OrdinalFirstThunk;
} u;
uint32 TimeDateStamp;
uint32 ForwarderChain;
uint32 Name;
uint32 FirstThunk;
} tPeImageImportDescriptor;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tPeImageFileHeader) == 20);
C_ASSERT(sizeof(tPeImageDataDirectory) == 8);
C_ASSERT(sizeof(tPeImageOptionalHeader) == 224);
C_ASSERT(sizeof(tPeImageSectionHeader) == 40);
C_ASSERT(sizeof(tPeImageImportDescriptor) == 20);
#endif
typedef struct
{
uint32 magic; // machine ID and magic
#define OMAGIC 0x107
//#define NMAGIC 0x108
//#define ZMAGIC 0x10B
//#define QMAGIC 0x0CC
uint32 text;
uint32 data;
uint32 bss;
uint32 syms;
uint32 entry;
uint32 trsize;
uint32 drsize;
} tAout;
typedef struct
{
uint32 address;
uint32 info; // bit field:
// 0-23 symbolnum
#define N_UNDF 0
#define N_ABS 2
#define N_TEXT 4
#define N_DATA 6
#define N_BSS 8
// 24-24 pcrel
// 25-26 length: 0 for 8-bit relocations, 1 for 16-bit rel's, 2 for 32-bit rel's
// 27-27 extern
// 28-31 nothing
} tAoutRel;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tAout) == 32);
C_ASSERT(sizeof(tAoutRel) == 8);
#endif
typedef struct
{
char name[16];
char date[12];
char uid[6];
char gid[6];
char mode[8];
char size[10];
char fmag[2];
} tArchiveFileHeader;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tArchiveFileHeader) == 60);
#endif
typedef struct
{
void** Buf;
size_t Reserved;
size_t Used;
} tDynArr;
typedef struct
{
Elf32_Shd h;
union
{
void* pData;
char* pStr; // SHT_STRTAB
Elf32_Sym* pSym; // SHT_SYMTAB
Elf32_Rel* pRel; // SHT_REL
Elf32_Rela* pRela; // SHT_RELA
} d;
uint32 OutOffset;
uint32 OutFileOffset;
} tElfSection;
typedef struct
{
const char* ElfName;
uint32 ObjOffset;
char* pSectNames;
tElfSection* pSections;
uint32 SectionCnt;
int Needed;
} tElfMeta;
typedef struct
{
const char* pName;
int32 Attrs;
uint32 Start;
uint32 Stop;
} tSectDescr;
typedef struct
{
const char* pName;
uint32 SectIdx;
int IsStop;
} tDeferredSym;
#define FBUF_SIZE 1024
const char* OutName = "a.out";
const char* MapName;
const char* EntryPoint = "__start";
const char* StubName;
#define FormatDosComTiny 1
#define FormatDosExeSmall 2
#define FormatDosExeHuge 3
#define FormatDosExeUnreal 4
#define FormatFlat16 5
#define FormatFlat32 6
#define FormatWinPe32 7
#define FormatElf32 8
#define FormatAout 9
#define FormatMach32 10
int OutputFormat = 0;
int UseBss = 1;
int NoRelocations = 0;
int verbose = 0;
uint32 Origin = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 StackSize = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 MinHeap = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 MaxHeap = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
tDynArr OpenFiles;
uint32 ObjFileCnt;
tElfMeta* pMetas;
tSectDescr* pSectDescrs;
uint32 SectCnt;
tDeferredSym* pDeferredSyms;
uint32 DeferredSymCnt;
// Size of the .relod section generated by the linker for FormatDosExeUnreal
uint32 UnrealRelodSize;
#ifdef __SMALLER_C__
#ifdef DETERMINE_VA_LIST
// 2 if va_list is a one-element array containing a pointer
// (typical for x86 Open Watcom C/C++)
// 1 if va_list is a pointer
// (typical for Turbo C++, x86 gcc)
// 0 if va_list is something else, and
// the code may have long crashed by now
int VaListType = 0;
// Attempts to determine the type of va_list as
// expected by the standard library
void DetermineVaListType(void)
{
void* testptr[2];
// hopefully enough space to sprintf() 3 pointers using "%p"
char testbuf[3][CHAR_BIT * sizeof(void*) + 1];
// TBD!!! This is not good. Really need the va_something macros.
// Test whether va_list is a pointer to the first optional parameter or
// an array of one element containing said pointer
testptr[0] = &testptr[1];
testptr[1] = &testptr[0];
memset(testbuf, '\0', sizeof(testbuf));
sprintf(testbuf[0], "%p", testptr[0]);
sprintf(testbuf[1], "%p", testptr[1]);
vsprintf(testbuf[2], "%p", &testptr[0]);
if (!strcmp(testbuf[2], testbuf[0]))
{
// va_list is a pointer
VaListType = 1;
}
else if (!strcmp(testbuf[2], testbuf[1]))
{
// va_list is a one-element array containing a pointer
VaListType = 2;
}
else
{
// va_list is something else, and
// the code may have long crashed by now
printf("Internal error: Indeterminate underlying type of va_list\n");
exit(EXIT_FAILURE);
}
}
#endif // DETERMINE_VA_LIST
#endif // __SMALLER_C__
size_t StrAnyOf(const char* s, const char* ss)
{
size_t idx = 1, slen;
if (!s || !*s || !ss)
return 0;
slen = strlen(s);
for (;;)
{
size_t sslen = strlen(ss);
if (sslen == 0)
return 0;
if (slen == sslen && !memcmp(s, ss, slen))
return idx;
ss += sslen + 1;
idx++;
}
}
void error(char* format, ...)
{
size_t i;
#ifndef __SMALLER_C__
va_list vl;
va_start(vl, format);
#else
void* vl = &format + 1;
#endif
// Make sure all files get closed if linking fails (DOS doesn't like leaked file handles)
for (i = 0; i < OpenFiles.Reserved; i++)
if (OpenFiles.Buf[i])
fclose(OpenFiles.Buf[i]);
remove(OutName);
puts("");
#ifndef __SMALLER_C__
vprintf(format, vl);
#else
// TBD!!! This is not good. Really need the va_something macros.
#ifdef DETERMINE_VA_LIST
if (VaListType == 2)
{
// va_list is a one-element array containing a pointer
vprintf(format, &vl);
}
else // if (VaListType == 1)
// fallthrough
#endif // DETERMINE_VA_LIST
{
// va_list is a pointer
vprintf(format, vl);
}
#endif // __SMALLER_C__
#ifndef __SMALLER_C__
va_end(vl);
#endif
exit(EXIT_FAILURE);
}
void errInternal(int n)
{
error("%d (internal)\n", n);
}
void errMem(void)
{
error("Out of memory\n");
}
void errSectTooBig(void)
{
error("Too much code (or data) or too big origin\n");
}
void errStackTooSmall(void)
{
error("Too small stack\n");
}
void errStackTooBig(void)
{
error("Too big stack or too much data (or code)\n");
}
void errArchive(void)
{
error("Corrupted archive\n");
}
void* Malloc(size_t size)
{
void* p = malloc(size);
if (!p)
errMem();
return p;
}
void* Realloc(void* ptr, size_t size)
{
void* p = realloc(ptr, size);
if (!p)
errMem();
return p;
}
void** DynArrFindSpot(tDynArr* pArr)
{
size_t i, oldcnt, oldsz, newcnt, newsz;
void* p = NULL;
if (pArr->Used < pArr->Reserved)
for (i = 0; i < pArr->Reserved; i++)
if (!pArr->Buf[i])
return pArr->Buf + i;
oldcnt = pArr->Reserved;
oldsz = oldcnt * sizeof pArr->Buf[0];
newcnt = oldcnt ? oldcnt * 2 : 1;
newsz = newcnt * sizeof pArr->Buf[0];
if (newcnt < oldcnt ||
newsz / sizeof pArr->Buf[0] != newcnt ||
!(p = realloc(pArr->Buf, newsz)))
errMem();
pArr->Buf = p;
pArr->Reserved = newcnt;
memset(pArr->Buf + oldcnt, 0, newsz - oldsz);
return pArr->Buf + oldcnt;
}
void DynArrFillSpot(tDynArr* pArr, void** spot, void* p)
{
*spot = p;
pArr->Used++;
}
void DynArrVacateSpot(tDynArr* pArr, void* p)
{
size_t i;
for (i = 0; i < pArr->Reserved; i++)
if (pArr->Buf[i] == p)
{
pArr->Buf[i] = NULL;
pArr->Used--;
break;
}
}
FILE* Fopen(const char* filename, const char* mode)
{
void** spot = DynArrFindSpot(&OpenFiles);
FILE* stream = fopen(filename, mode);
if (!stream)
error("Can't open/create file '%s'\n", filename);
DynArrFillSpot(&OpenFiles, spot, stream);
return stream;
}
void Fclose(FILE* stream)
{
DynArrVacateSpot(&OpenFiles, stream);
if (fclose(stream))
error("Can't close a file\n");
}
void Fseek(FILE* stream, long offset, int whence)
{
int r = fseek(stream, offset, whence);
if (r)
error("Can't seek a file\n");
}
void Fread(void* ptr, size_t size, FILE* stream)
{
size_t r = fread(ptr, 1, size, stream);
if (r != size)
error("Can't read a file\n");
}
void Fwrite(const void* ptr, size_t size, FILE* stream)
{
size_t r = fwrite(ptr, 1, size, stream);
if (r != size)
error("Can't write a file\n");
}
void FillWithByte(unsigned char byte, size_t size, FILE* stream)
{
static unsigned char buf[FBUF_SIZE];
memset(buf, byte, FBUF_SIZE);
while (size)
{
size_t csz = size;
if (csz > FBUF_SIZE)
csz = FBUF_SIZE;
Fwrite(buf, csz, stream);
size -= csz;
}
}
uint32 AlignTo(uint32 ofs, uint32 align)
{
return (ofs + align - 1) / align * align;
}
int RelCmp(const void* p1_, const void* p2_)
{
const Elf32_Rel *p1 = (const Elf32_Rel*)p1_, *p2 = (const Elf32_Rel*)p2_;
if (p1->r_offset < p2->r_offset)
return -1;
if (p1->r_offset > p2->r_offset)
return +1;
return 0;
}
// TBD??? Thoroughly validate ELF object files, specifically sections
void loadElfObj(tElfMeta* pMeta, const char* ElfName, FILE* file, uint32 objOfs)
{
Elf32_Ehdr elfHdr;
Elf32_Shd sectHdr;
uint32 sectIdx;
int unsupported = 0;
memset(pMeta, 0, sizeof *pMeta);
pMeta->ElfName = ElfName;
pMeta->ObjOffset = objOfs;
if (verbose)
printf("File %s:\n\n", ElfName);
Fseek(file, objOfs, SEEK_SET);
Fread(&elfHdr, sizeof elfHdr, file);
if (memcmp(elfHdr.e_ident, "\x7F""ELF", 4))
error("Not an ELF file\n");
if (elfHdr.e_ident[6] != EV_CURRENT)
error("Not a v1 ELF file\n");
if (elfHdr.e_ehsize != sizeof elfHdr)
error("Unexpected ELF header size\n");
if (elfHdr.e_shentsize != sizeof sectHdr)
error("Unexpected ELF section size\n");
if (elfHdr.e_ident[4] != ELFCLASS32)
error("Not a 32-bit file\n");
if (elfHdr.e_ident[5] != ELFDATA2LSB)
error("Not a little-endian file\n");
if (elfHdr.e_type != ET_REL)
error("Not a relocatable file\n");
if (elfHdr.e_machine != EM_386)
error("Not an x86 file\n");
if (elfHdr.e_shoff == 0 || elfHdr.e_shstrndx == 0)
error("Invalid file\n");
Fseek(file, objOfs + elfHdr.e_shoff + elfHdr.e_shstrndx * sizeof sectHdr, SEEK_SET);
Fread(§Hdr, sizeof sectHdr, file);
pMeta->pSectNames = Malloc(sectHdr.sh_size);
Fseek(file, objOfs + sectHdr.sh_offset, SEEK_SET);
Fread(pMeta->pSectNames, sectHdr.sh_size, file);
pMeta->pSections = Malloc((elfHdr.e_shnum + 1) * sizeof(tElfSection));
if (verbose)
printf(" # Type XAW FileOffs Align Size Link Info EnSz Name\n");
for (sectIdx = 0; sectIdx < elfHdr.e_shnum; sectIdx++)
{
const char* typeName = "????????";
static const char* const typeNames[] =
{
"NULL",
"PROGBITS",
"SYMTAB",
"STRTAB",
"RELA",
"HASH",
"DYNAMIC",
"NOTE",
"NOBITS",
"REL",
"SHLIB",
"DYNSYM",
};
const char* name = "";
Fseek(file, objOfs + elfHdr.e_shoff + sectIdx * sizeof sectHdr, SEEK_SET);
Fread(§Hdr, sizeof sectHdr, file);
if (sectHdr.sh_type == SHT_NULL)
memset(§Hdr, 0, sizeof sectHdr);
if (sectHdr.sh_name)
name = pMeta->pSectNames + sectHdr.sh_name;
unsupported |=
sectHdr.sh_type != SHT_NULL &&
sectHdr.sh_type != SHT_PROGBITS &&
sectHdr.sh_type != SHT_SYMTAB &&
sectHdr.sh_type != SHT_STRTAB &&
// sectHdr.sh_type != SHT_RELA &&
// sectHdr.sh_type != SHT_NOTE &&
sectHdr.sh_type != SHT_NOBITS &&
sectHdr.sh_type != SHT_REL;
if (sectHdr.sh_type < sizeof typeNames / sizeof typeNames[0])
typeName = typeNames[sectHdr.sh_type];
if (verbose)
printf("%2u %-8s %c%c%c 0x%08lX %5lu %10lu %4lu %4lu %4lu %s\n",
sectIdx,
typeName,
"-X"[(sectHdr.sh_flags / SHF_EXECINSTR) & 1],
"-A"[(sectHdr.sh_flags / SHF_ALLOC) & 1],
"-W"[(sectHdr.sh_flags / SHF_WRITE) & 1],
(ulong)sectHdr.sh_offset,
(ulong)sectHdr.sh_addralign,
(ulong)sectHdr.sh_size,
(ulong)sectHdr.sh_link,
(ulong)sectHdr.sh_info,
(ulong)sectHdr.sh_entsize,
name);
memset(&pMeta->pSections[pMeta->SectionCnt], 0, sizeof pMeta->pSections[pMeta->SectionCnt]);
pMeta->pSections[pMeta->SectionCnt++].h = sectHdr;
}
if (unsupported)
error("Unsupported section\n");
for (sectIdx = 1; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
switch (pSect->h.sh_type)
{
case SHT_SYMTAB:
{
uint32 cnt, sz, ofs;
#ifndef SUPPORT_LOCAL_RELS
uint32 i;
#endif
cnt = pSect->h.sh_size / sizeof(Elf32_Sym);
if (!cnt ||
cnt < pSect->h.sh_info ||
pSect->h.sh_entsize != sizeof(Elf32_Sym))
error("Incorrect number of symbols\n");
pSect->h.sh_entsize = cnt; // repurpose sh_entsize for number of symbols
// NOTE: can't skip all local symbols (they are the first sh_info symbols)
// as there can be section symbols :(
// pMeta->LocalSymsCnt = pSect->h.sh_info;
sz = cnt * sizeof(Elf32_Sym); // TBD!!! overflow checks
pSect->d.pSym = Malloc(sz);
ofs = pSect->h.sh_offset;
Fseek(file, objOfs + ofs, SEEK_SET);
Fread(pSect->d.pSym, sz, file);
#ifndef SUPPORT_LOCAL_RELS
// Collect all local section symbols and throw away other local symbols
for (cnt = i = 0; i < pSect->h.sh_info; i++)
{
Elf32_Sym* pSym = &pSect->d.pSym[i];
if ((pSym->st_info & 0xF) == STT_SECTION && pSym->st_shndx)
{
if (i > cnt)
pSect->d.pSym[cnt] = *pSym;
pSect->d.pSym[cnt++].st_value = i; // repurpose st_value for the original index of the section symbol, so it can still be found
}
}
memmove(pSect->d.pSym + cnt, pSect->d.pSym + pSect->h.sh_info, (pSect->h.sh_entsize - pSect->h.sh_info) * sizeof(Elf32_Sym));
pSect->h.sh_addralign = cnt; // repurpose sh_addralign for the number of the remaining local section symbols
pSect->h.sh_entsize -= pSect->h.sh_info - cnt; // adjust total symbol count
if (pSect->h.sh_entsize)
{
void* p;
if ((p = realloc(pSect->d.pSym, pSect->h.sh_entsize * sizeof(Elf32_Sym))) != NULL) // shrink the buffer
pSect->d.pSym = p;
}
else
{
free(pSect->d.pSym);
pSect->d.pSym = NULL;
}
#endif
}
break;
case SHT_STRTAB:
pSect->d.pStr = Malloc(pSect->h.sh_size);
Fseek(file, objOfs + pSect->h.sh_offset, SEEK_SET);
Fread(pSect->d.pStr, pSect->h.sh_size, file);
break;
case SHT_REL:
if (!pSect->h.sh_size ||
pSect->h.sh_entsize != sizeof(Elf32_Rel))
error("Incorrect number of relocations\n");
pSect->h.sh_entsize = pSect->h.sh_size / sizeof(Elf32_Rel); // repurpose sh_entsize for number of relocations
pSect->d.pRel = Malloc(pSect->h.sh_size);
Fseek(file, objOfs + pSect->h.sh_offset, SEEK_SET);
Fread(pSect->d.pRel, pSect->h.sh_size, file);
// Sort the relocations by offset, so relocation can be done while copying sections
qsort(pSect->d.pRel, pSect->h.sh_entsize, sizeof(Elf32_Rel), &RelCmp);
break;
}
} // endof for
if (verbose)
{
puts("");
puts("Symbols of sections and globals:");
for (sectIdx = 1; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type == SHT_SYMTAB)
{
uint32 symIdx;
for (symIdx = 0; symIdx < pSect->h.sh_entsize; symIdx++)
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
const char* name = NULL;
if (pSym->st_name)
name = pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name;
else if ((pSym->st_info & 0xF) == STT_SECTION && pSym->st_shndx)
name = pMeta->pSectNames + pMeta->pSections[pSym->st_shndx].h.sh_name;
if ((pSym->st_info & 0xF) == STT_SECTION)
{
printf(" section %s\n",
name);
}
else if ((pSym->st_info >> 4) == STB_GLOBAL && name)
{
printf("%s global %s\n",
pSym->st_shndx ? " " : "undef",
name);
}
}
}
}
puts("");
}
}
// TBD??? Thoroughly validate archive files
void loadMeta(const char* FileName)
{
FILE* f = Fopen(FileName, "rb");
char magic[8];
uint32 ofs = sizeof magic;
Fread(magic, sizeof magic, f);
if (!memcmp(magic, "!<arch>\n", sizeof magic))
{
for (;;)
{
tArchiveFileHeader fh;
uint32 nlen = 0, fsz = 0, fofs;
uint i;
Fseek(f, ofs, SEEK_SET);
if (fread(&fh, 1, sizeof fh, f) != sizeof fh)
break;
if (fh.fmag[0] != 0x60 || fh.fmag[1] != 0x0A)
errArchive();
// Special names:
//
// - "// " entry is a string table, containing long file names (GNU)
// - "/ " entry is a symbol lookup table (GNU)
// - "/nnn ", where n's are decimal digits, entry is a file entry with a long name (GNU style)
// nnn is an index into the string table
//
// - "__.SYMDEF " entry is a symbol lookup table (BSD)
// - "#1/nnn ", where n's are decimal digits, entry is a file entry with a long name (BSD style)
// nnn is the length of the long name (prepended to file data; file size includes this length)
//
// - otherwise it's a regular file with a short name
if (!memcmp(fh.name, "#1/", 3))
{
for (i = 3; i < sizeof fh.name; i++)
{
if (fh.name[i] >= '0' && fh.name[i] <= '9')
nlen = nlen * 10 + fh.name[i] - '0';
else
break;
}
}
for (i = 0; i < sizeof fh.size; i++)
{
if (fh.size[i] >= '0' && fh.size[i] <= '9')
fsz = fsz * 10 + fh.size[i] - '0';
else
break;
}
if (nlen > fsz)
errArchive();
fofs = ofs + sizeof fh + nlen;
fsz -= nlen;
// TBD??? load and use symbol lookup tables
if (memcmp(fh.name, "// ", sizeof fh.name) &&
memcmp(fh.name, "/ ", sizeof fh.name) &&
memcmp(fh.name, "__.SYMDEF ", sizeof fh.name))
{
if (fsz < sizeof(Elf32_Ehdr))
errArchive();
pMetas = Realloc(pMetas, (sizeof *pMetas) * (ObjFileCnt + 1));
// TBD!!! extract object file name and pass it instead of the library file name
loadElfObj(pMetas + ObjFileCnt, FileName, f, fofs);
ObjFileCnt++;
}
ofs = fofs + fsz;
ofs += ofs & 1;
}
}
else
{
pMetas = Realloc(pMetas, (sizeof *pMetas) * (ObjFileCnt + 1));
loadElfObj(pMetas + ObjFileCnt, FileName, f, 0);
ObjFileCnt++;
}
Fclose(f);
}
void DeferSymbol(const char* SymName)
{
uint32 i;
for (i = 0; i < DeferredSymCnt; i++)
if (!strcmp(pDeferredSyms[i].pName, SymName))
return;
pDeferredSyms = Realloc(pDeferredSyms, (sizeof *pDeferredSyms) * (DeferredSymCnt + 1));
pDeferredSyms[DeferredSymCnt].pName = SymName;
pDeferredSyms[DeferredSymCnt++].SectIdx = 0xFFFFFFFF;
}
int FindSymbolByName(const char* SymName)
{
uint32 cnt = 0, fIdx, sectIdx, symIdx;
int includedObj = 0;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx = pSect->h.sh_info; symIdx < pSect->h.sh_entsize; symIdx++)
#else
for (symIdx = pSect->h.sh_addralign; symIdx < pSect->h.sh_entsize; symIdx++)
#endif
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
// Check exported symbols
if ((pSym->st_info >> 4) == STB_GLOBAL &&
pSym->st_shndx &&
pSym->st_name &&
!strcmp(pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name, SymName))
{
cnt++;
if (!pMeta->Needed)
{
includedObj = 1;
pMeta->Needed = 1;
}
break;
}
}
if (cnt)
break;
}
if (cnt)
break;
}
if (!cnt)
{
// Don't error out on symbols of:
// - section start, e.g. __start__text (for .text)
// - section end, e.g. __stop__text (for .text)
// - stack start, e.g. __start_stack__
// which aren't defined yet
if (StrAnyOf(SymName, "__start_allcode__\0"
"__stop_allcode__\0"
"__start_alldata__\0"
"__stop_alldata__\0") ||
(!strncmp(SymName, "__start_", sizeof "__start_" - 1) && SymName[sizeof "__start_" - 1] != '\0') ||
(!strncmp(SymName, "__stop_", sizeof "__stop_" - 1) && SymName[sizeof "__stop_" - 1] != '\0'))
DeferSymbol(SymName);
else
error("Symbol '%s' not found\n", SymName);
}
return includedObj;
}
void CheckDuplicates(void)
{
uint32 fIdx, sectIdx, symIdx;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx = pSect->h.sh_info; symIdx < pSect->h.sh_entsize; symIdx++)
#else
for (symIdx = pSect->h.sh_addralign; symIdx < pSect->h.sh_entsize; symIdx++)
#endif
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
// Check exported symbols
if ((pSym->st_info >> 4) == STB_GLOBAL &&
pSym->st_shndx &&
pSym->st_name)
{
uint32 fIdx2, sectIdx2, symIdx2;
for (fIdx2 = fIdx + 1; fIdx2 < ObjFileCnt; fIdx2++)
{
tElfMeta* pMeta2 = &pMetas[fIdx2];
if (!pMeta2->Needed)
continue;
for (sectIdx2 = 0; sectIdx2 < pMeta2->SectionCnt; sectIdx2++)
{
tElfSection* pSect2 = &pMeta2->pSections[sectIdx2];
if (pSect2->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx2 = pSect2->h.sh_info; symIdx2 < pSect2->h.sh_entsize; symIdx2++)
#else
for (symIdx2 = pSect2->h.sh_addralign; symIdx2 < pSect2->h.sh_entsize; symIdx2++)
#endif
{
Elf32_Sym* pSym2 = &pSect2->d.pSym[symIdx2];
// Check exported symbols
if ((pSym2->st_info >> 4) == STB_GLOBAL &&
pSym2->st_shndx &&
pSym2->st_name)
{
if (!strcmp(pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name,
pMeta2->pSections[pSect2->h.sh_link].d.pStr + pSym2->st_name))
error("Symbol '%s' defined multiple times\n",
pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name);
}
}
}
}
}
}
}
}
}
void FindAllSymbols(void)
{
uint32 fIdx, sectIdx, symIdx;
int includedObj;
do
{
includedObj = 0;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx = pSect->h.sh_info; symIdx < pSect->h.sh_entsize; symIdx++)
#else
for (symIdx = pSect->h.sh_addralign; symIdx < pSect->h.sh_entsize; symIdx++)
#endif
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
// Check imported symbols
if ((pSym->st_info >> 4) == STB_GLOBAL &&
!pSym->st_shndx &&
pSym->st_name)
{
includedObj |= FindSymbolByName(pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name);
}
}
}
}
} while (includedObj);
}
int SectDescCmp(const void* p1_, const void* p2_)
{
const tSectDescr *p1 = (const tSectDescr*)p1_, *p2 = (const tSectDescr*)p2_;
int i;
// SHT_NOBITS (e.g. .bss) goes after SHT_PROGBITS (e.g. .text, .rodata, .data)
if ((p1->Attrs ^ p2->Attrs) & SHT_NOBITS)
return +((p1->Attrs & SHT_NOBITS) - (p2->Attrs & SHT_NOBITS));
// code (e.g. .text) goes before data (e.g. .rodata, .data)
if ((p1->Attrs ^ p2->Attrs) & SHF_EXECINSTR)
return -((p1->Attrs & SHF_EXECINSTR) - (p2->Attrs & SHF_EXECINSTR));
// writable data (e.g. .data) goes after read-only data (e.g. .rodata)
if ((p1->Attrs ^ p2->Attrs) & SHF_WRITE)
return +((p1->Attrs & SHF_WRITE) - (p2->Attrs & SHF_WRITE));
// If attributes are equal, order sections by name,
// but make .text appear before all other code sections (if any)
i = strcmp(p1->pName, p2->pName);
if (i && (p1->Attrs & SHF_EXECINSTR))
{
if (!strcmp(p1->pName, ".text"))
return -1;
if (!strcmp(p2->pName, ".text"))
return +1;
}
// but make .dll_* appear before all other writable data sections (if any)
if (i && (p1->Attrs & SHF_WRITE))
{
int i1 = !strncmp(p1->pName, ".dll_", sizeof ".dll_" - 1);
int i2 = !strncmp(p2->pName, ".dll_", sizeof ".dll_" - 1);
if (i1 != i2)
return i2 - i1;
}
return i;
}
void FindAllSections(void)
{
uint32 fIdx, sectIdx, i;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
{
// TBD??? free the memory used by the unused files.
continue;
}
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
char* sname = pMeta->pSectNames + pSect->h.sh_name;
int found = 0;
if (!(pSect->h.sh_flags & SHF_ALLOC))
{
if (OutputFormat == FormatDosExeUnreal &&
pSect->h.sh_type == SHT_REL)
{
// Calculate the size of the new .relod section (count only 32-bit non-PC-relative relocations).
uint32 relIdx;
for (relIdx = 0; relIdx < pSect->h.sh_entsize; relIdx++)
{
Elf32_Rel* pRel = &pSect->d.pRel[relIdx];
uint32 symIdx = pRel->r_info >> 8;
uint32 absSym = symIdx == 0;
uint32 relType = pRel->r_info & 0xFFu;
// TBD??? additional error checks
if (!absSym && relType == R_386_32)
UnrealRelodSize += 4;
}
}
continue;
}
for (i = 0; i < SectCnt; i++)
{
if (!strcmp(pSectDescrs[i].pName, sname))
{
uint32 oldAttrs = pSectDescrs[i].Attrs;
uint32 newAttrs = (pSect->h.sh_flags & (SHF_WRITE | SHF_EXECINSTR)) | (pSect->h.sh_type & SHT_NOBITS);
if ((oldAttrs ^ newAttrs) & (SHF_WRITE | SHF_EXECINSTR | SHT_NOBITS))
error("Inconsistent section type/flags\n");
found = 1;
break;
}
}
if (!found)
{
if (OutputFormat == FormatDosExeUnreal && !strcmp(sname, ".relod"))
error("Unexpected section .relod for unreal format\n");
pSectDescrs = Realloc(pSectDescrs, (sizeof *pSectDescrs) * (SectCnt + 1));
memset(&pSectDescrs[SectCnt], 0, sizeof pSectDescrs[SectCnt]);
pSectDescrs[SectCnt].Attrs = (pSect->h.sh_flags & (SHF_WRITE | SHF_EXECINSTR)) | (pSect->h.sh_type & SHT_NOBITS);
pSectDescrs[SectCnt++].pName = sname;
}
}
}
if (UnrealRelodSize)
{
pSectDescrs = Realloc(pSectDescrs, (sizeof *pSectDescrs) * (SectCnt + 1));
memset(&pSectDescrs[SectCnt], 0, sizeof pSectDescrs[SectCnt]);
pSectDescrs[SectCnt].Attrs = 0;
pSectDescrs[SectCnt++].pName = ".relod";
}
// Sort sections by attributes/names
qsort(pSectDescrs, SectCnt, sizeof *pSectDescrs, &SectDescCmp);
if (verbose)
{
printf("Sections used:\n");
for (i = 0; i < SectCnt; i++)
printf(" %s\n", pSectDescrs[i].pName);
puts("");
}
if (!(pSectDescrs[0].Attrs & SHF_EXECINSTR))
error("Executable section not found\n");
for (i = 0; i < SectCnt; i++)
if ((pSectDescrs[i].Attrs & SHF_EXECINSTR) &&
(pSectDescrs[i].Attrs & (SHT_NOBITS | SHF_WRITE)))
error("Inconsistent section type/flags\n");
// Add 3 hidden pseudo sections:
// - one for all code sections combined
// - one for all data sections combined
// - one for the stack start symbol (only for tiny/.COM and small/.EXE)
pSectDescrs = Realloc(pSectDescrs, (sizeof *pSectDescrs) * (SectCnt + 3));
memset(&pSectDescrs[SectCnt], 0, 3 * sizeof pSectDescrs[SectCnt]);
pSectDescrs[SectCnt + 0].pName = "allcode__";
pSectDescrs[SectCnt + 1].pName = (pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR) ? "" : "alldata__";
pSectDescrs[SectCnt + 2].pName = (OutputFormat == FormatDosComTiny || OutputFormat == FormatDosExeSmall) ? "stack__" : "";
// Link deferred symbols to sections
for (i = 0; i < DeferredSymCnt; i++)
{
const char* p1 = pDeferredSyms[i].pName;
int isStop = strncmp(p1, "__start_", sizeof "__start_" - 1) != 0;
size_t pfxLen = isStop ? sizeof "__stop_" - 1 : sizeof "__start_" - 1;
size_t len = strlen(p1 + pfxLen);
int found = 0;
p1 += pfxLen;
for (sectIdx = 0; sectIdx < SectCnt + 3; sectIdx++)
{
const char* p2 = pSectDescrs[sectIdx].pName;
if (len == strlen(p2))
{
size_t i;
found = 1;
for (i = 0; i < len; i++)
if (p1[i] != p2[i] && !(p1[i] == '_' && p2[i] == '.')) // e.g. "__start__text" and "__stop__text" match ".text" section
{
found = 0;
break;
}
if (found)
break;
}
}
if (found)
{
pDeferredSyms[i].SectIdx = sectIdx;
pDeferredSyms[i].IsStop = isStop;
}
else
error("Symbol '%s' not found\n", pDeferredSyms[i].pName);
}
}
uint32 FindSymbolAddress(const char* SymName)
{
uint32 fIdx, sectIdx, symIdx;
uint32 addr = 0;
// First, check for section start/stop symbols
for (symIdx = 0; symIdx < DeferredSymCnt; symIdx++)
{
if (!strcmp(pDeferredSyms[symIdx].pName, SymName))
return pDeferredSyms[symIdx].IsStop ?
pSectDescrs[pDeferredSyms[symIdx].SectIdx].Stop :
pSectDescrs[pDeferredSyms[symIdx].SectIdx].Start;
}
// Do all other symbols
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx = pSect->h.sh_info; symIdx < pSect->h.sh_entsize; symIdx++)
#else
for (symIdx = pSect->h.sh_addralign; symIdx < pSect->h.sh_entsize; symIdx++)
#endif
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
// Check exported symbols
if ((pSym->st_info >> 4) == STB_GLOBAL &&
pSym->st_shndx &&
pSym->st_name &&
!strcmp(pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name, SymName))
{
tElfSection* pSect;
if (pSym->st_shndx == SHN_COMMON)
error("Common symbols unsupported\n");
pSect = &pMeta->pSections[pSym->st_shndx];
addr = pSect->OutOffset + pSym->st_value;
return addr;
}
}
}
}
// TBD??? error???
return addr;
}
void Relocate(tElfMeta* pMeta, tElfSection* pRelSect, Elf32_Rel* pRel, unsigned char* buf, uint32 off, uint32 fileOff)
{
uint32 symIdx = pRel->r_info >> 8;
uint32 relType = pRel->r_info & 0xFFu;
tElfSection* pSymSect = &pMeta->pSections[pRelSect->h.sh_link];
Elf32_Sym* pSym = NULL;
const char* name = NULL;
uint32 symAddr = 0;
if (symIdx == 0)
{
// it's an absolute symbol
}
else
{
#ifdef SUPPORT_LOCAL_RELS
pSym = &pSymSect->d.pSym[symIdx];
#else
if (symIdx >= pSymSect->h.sh_info)
{
// it's a global symbol
pSym = &pSymSect->d.pSym[symIdx - pSymSect->h.sh_info + pSymSect->h.sh_addralign];
}
else
{
// it must be a local symbol for a section
uint32 i;
for (i = 0; i < pSymSect->h.sh_addralign; i++)
if (pSymSect->d.pSym[i].st_value == symIdx)
{
pSym = &pSymSect->d.pSym[i];
break;
}
if (!pSym)
goto err;
}
#endif
if (pSym->st_name)
name = pMeta->pSections[pSymSect->h.sh_link].d.pStr + pSym->st_name;
else if ((pSym->st_info & 0xF) == STT_SECTION && pSym->st_shndx)
name = pMeta->pSectNames + pMeta->pSections[pSym->st_shndx].h.sh_name;
if ((pSym->st_info & 0xF) == STT_SECTION)
{
symAddr = pMeta->pSections[pSym->st_shndx].OutOffset;
}
else if ((pSym->st_info >> 4) == STB_GLOBAL && name)
{
symAddr = FindSymbolAddress(name);
}
#ifdef SUPPORT_LOCAL_RELS
else if ((pSym->st_info >> 4) == STB_LOCAL)
{
symAddr = pMeta->pSections[pSym->st_shndx].OutOffset + pSym->st_value;
}
#endif
else
#ifndef SUPPORT_LOCAL_RELS
err:
#endif
error("Unsupported relocation symbol type\n");
}
if (verbose)
printf("%08lX %3lu %08lX %s\n", (ulong)fileOff, (ulong)relType, (ulong)symAddr, name ? name : "*ABS*");
if (relType == R_386_32 || relType == R_386_PC32)
{
uint32 dd = buf[0] + ((uint32)buf[1] << 8) + ((uint32)buf[2] << 16) + ((uint32)buf[3] << 24);
dd += symAddr;
if (relType == R_386_PC32)
dd -= off;
buf[0] = dd; buf[1] = (dd >>= 8); buf[2] = (dd >>= 8); buf[3] = (dd >>= 8);
}
else if (relType == R_386_16 || relType == R_386_PC16)
{
uint32 dd = buf[0] + ((uint)buf[1] << 8);
dd += symAddr;
if (relType == R_386_PC16)
dd -= off;
buf[0] = dd; buf[1] = (dd >>= 8);
}
else
error("Unsupported relocation type\n");
}
void RelocateAndWriteSection(FILE* outStream, FILE* inStream, size_t size, tElfMeta* pMeta, tElfSection* pRelSect)
{
static unsigned char buf[FBUF_SIZE + sizeof(uint32) - 1];
size_t sz = 0; // how many bytes are in buf[]
uint32 ofs = 0; // offset within the section corresponding to &buf[0]
uint32 relIdx = 0;
int first = 1;
if (size)
{
size_t csz = sizeof(uint32) - 1;
if (csz > size)
csz = size;
Fread(buf, csz, inStream);
size -= csz;
sz = csz;
}
while (sz)
{
size_t csz = size;
if (csz > FBUF_SIZE)
csz = FBUF_SIZE;
if (csz)
{
Fread(buf + sz, csz, inStream);
size -= csz;
sz += csz;
}
if (pRelSect)
{
while (relIdx < pRelSect->h.sh_entsize &&
pRelSect->d.pRel[relIdx].r_offset < ofs + FBUF_SIZE)
{
Elf32_Rel* pRel = &pRelSect->d.pRel[relIdx];
if (verbose && first)
{
printf("File Ofs Type Sym Addr Sym\n");
first = 0;
}
Relocate(pMeta,
pRelSect,
pRel,
buf + pRel->r_offset - ofs,
pRel->r_offset + pMeta->pSections[pRelSect->h.sh_info].OutOffset,
pRel->r_offset + pMeta->pSections[pRelSect->h.sh_info].OutFileOffset);
relIdx++;
}
}
csz = sz;
if (csz > FBUF_SIZE)
csz = FBUF_SIZE;
Fwrite(buf, csz, outStream);
sz -= csz;
memcpy(buf, buf + FBUF_SIZE, sz);
ofs += FBUF_SIZE;
}
}
tDosExeHeader DosExeHeader =
{
{ "MZ" }, // Signature
0, // PartPage
0, // PageCnt
0, // ReloCnt
2, // HdrSize
0, // MinAlloc
0, // MaxAlloc
0, // InitSs
0xFFFC, // InitSp
0, // ChkSum
0, // InitIp
0, // InitCs
28, // ReloOff
0, // OverlayNo
{ 0, 0 } // FirstRelo
};
uint8 DosMzExeStub[128] =
{
0x4D, 0x5A, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x10, 0x00, 0x10, 0x04, 0x00,
0xFC, 0xFF, 0x00, 0x00, 0x40, 0x00, 0xFC, 0xFF, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0E, 0x1F, 0xBA, 0x4E, 0x00, 0xB4, 0x09, 0xCD, 0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72, 0x61, 0x6D, 0x20, 0x63, 0x61, 0x6E, 0x6E, 0x6F,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E, 0x20, 0x69, 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20,
0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
tPeImageFileHeader PeFileHeader =
{
0x014C, // Machine (Intel 80386)
1, // NumberOfSections
0x52C3CB00, // TimeDateStamp
0, // PointerToSymbolTable
0, // NumberOfSymbols
sizeof(tPeImageOptionalHeader), // SizeOfOptionalHeader
0x30F // Characteristics (no symbol/debug info, no relocations, executable, 32-bit)
};
tPeImageOptionalHeader PeOptionalHeader =
{
0x10B, // Magic (PE32)
8, // MajorLinkerVersion
0, // MinorLinkerVersion
0, // SizeOfCode
0, // SizeOfInitializedData
0, // SizeOfUninitializedData
0, // AddressOfEntryPoint
0, // BaseOfCode
0, // BaseOfData
0, // ImageBase
4096, // SectionAlignment
512, // FileAlignment
4, // MajorOperatingSystemVersion
0, // MinorOperatingSystemVersion
0, // MajorImageVersion
0, // MinorImageVersion
4, // MajorSubsystemVersion
0, // MinorSubsystemVersion
0, // Win32VersionValue
0, // SizeOfImage
4096, // SizeOfHeaders
0, // CheckSum
3, // Subsystem (Windows CUI)
0, // DllCharacteristics
0x100000, // SizeOfStackReserve
0x10000, // SizeOfStackCommit
0x4000000,// SizeOfHeapReserve
0, // SizeOfHeapCommit
0, // LoaderFlags
16, // NumberOfRvaAndSizes
// Data directories
{
{ 0, 0 }, // Export Table
{ 0, 0 }, // Import Table
{ 0, 0 }, // Resource Table
{ 0, 0 }, // Exception Table
{ 0, 0 }, // Security Table
{ 0, 0 }, // Relocation Table
{ 0, 0 }, // Debug Info
{ 0, 0 }, // Description
{ 0, 0 }, // Machine-specific
{ 0, 0 }, // TLS
{ 0, 0 }, // Load Configuration
{ 0, 0 }, // Bound Import Table
{ 0, 0 }, // Import Address Table
{ 0, 0 }, // Delay Import Table
{ 0, 0 }, // COM+
{ 0, 0 } // Reserved
}
};
tPeImageSectionHeader PeSectionHeaderZero;
tPeImageSectionHeader PeSectionHeaderText =
{
{ ".text" }, // Name
{ 0 }, // VirtualSize
0, // VirtualAddress
0, // SizeOfRawData
0, // PointerToRawData
0, // PointerToRelocations
0, // PointerToLinenumbers
0, // NumberOfRelocations
0, // NumberOfLinenumbers
0x60000020 // Characteristics (code, executable, readable)
};
tPeImageSectionHeader PeSectionHeaderRoData =
{
{ ".rdata" }, // Name
{ 0 }, // VirtualSize
0, // VirtualAddress
0, // SizeOfRawData
0, // PointerToRawData
0, // PointerToRelocations
0, // PointerToLinenumbers
0, // NumberOfRelocations
0, // NumberOfLinenumbers
0x40000040 // Characteristics (data, readable)
};
tPeImageSectionHeader PeSectionHeaderImpData =
{
{ ".idata" }, // Name
{ 0 }, // VirtualSize
0, // VirtualAddress
0, // SizeOfRawData
0, // PointerToRawData
0, // PointerToRelocations
0, // PointerToLinenumbers
0, // NumberOfRelocations
0, // NumberOfLinenumbers
0xc0000040 // Characteristics (data, readable, writable)
};
tPeImageSectionHeader PeSectionHeaderData =
{
{ ".data" }, // Name
{ 0 }, // VirtualSize
0, // VirtualAddress
0, // SizeOfRawData
0, // PointerToRawData
0, // PointerToRelocations
0, // PointerToLinenumbers
0, // NumberOfRelocations
0, // NumberOfLinenumbers
0xc0000040 // Characteristics (data, readable, writable)
};
tPeImageSectionHeader PeSectionHeaderReloc =
{
{ ".reloc" }, // Name
{ 0 }, // VirtualSize
0, // VirtualAddress
0, // SizeOfRawData
0, // PointerToRawData
0, // PointerToRelocations
0, // PointerToLinenumbers
0, // NumberOfRelocations
0, // NumberOfLinenumbers
0x42000040 // Characteristics (data, readable, discardable)
};
Elf32_Ehdr ElfHeader =
{
{ "\177ELF\1\1\1" }, // e_ident (32-bit objects, little-endian, current version)
ET_EXEC, // e_type (executable)
EM_386, // e_machine (Intel 80386)
1, // e_version (current version)
0, // e_entry
sizeof(Elf32_Ehdr), // e_phoff
0, // e_shoff
0, // e_flags
sizeof(Elf32_Ehdr), // e_ehsize
sizeof(Elf32_Phdr), // e_phentsize
1, // e_phnum
0, // e_shentsize
0, // e_shnum
0 // e_shstrndx
};
Elf32_Phdr ElfProgramHeaders[2] =
{
// .text
{
1, // p_type (load)
0, // p_offset
0, // p_vaddr
0, // p_paddr
0, // p_filesz
0, // p_memsz
5, // p_flags (readable, executable)
4096 // p_align
},
// .data
{
1, // p_type (load)
0, // p_offset
0, // p_vaddr
0, // p_paddr
0, // p_filesz
0, // p_memsz
6, // p_flags (readable, writable)
4096 // p_align
}
};
Mach32_Header MachHeader =
{
MACH_MAGIC_32, // magic
MACH_CPU_TYPE_X86, // cputype
MACH_CPU_SUBTYPE_I386_ALL, // cpusubtype
MACH_EXECUTE, // filetype
0, // ncmds
0, // sizeofcmds
MACH_NOUNDEFS, // flags
};
tAout AoutHeader =
{
OMAGIC | 0x640000/*80386*/, // magic
0, // text
0, // data
0, // bss
0, // syms
0, // entry
0, // trsize
0 // drsize
};
void Pass(int pass, FILE* fout, uint32 hdrsz)
{
uint32 startOfs = Origin;
uint32 ofs = Origin;
uint32 written = 0;
uint32 j, fIdx, sectIdx, relSectIdx;
// Two passes:
// pass 0 (may be repeated for flat binaries) is used to find out section and symbol locations
// pass 1 is used to perform actual relocation and write the executable file
if (!pass)
{
// Will use these to find the minimum and maximum offsets/addresses within combined sections/segments
pSectDescrs[SectCnt].Start = 0xFFFFFFFF;
pSectDescrs[SectCnt].Stop = 0;
pSectDescrs[SectCnt + 1].Start = 0xFFFFFFFF;
pSectDescrs[SectCnt + 1].Stop = 0;
}
// Handle individual sections
for (j = 0; j < SectCnt; j++)
{
int isDataSection = !(pSectDescrs[j].Attrs & SHF_EXECINSTR);
if (!pass)
{
// Will use these to find the minimum and maximum offsets/addresses within individual sections/segments
pSectDescrs[j].Start = 0xFFFFFFFF;
pSectDescrs[j].Stop = 0;
}
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
tElfSection* pRelSect = NULL;
if (strcmp(pSectDescrs[j].pName, pMeta->pSectNames + pSect->h.sh_name))
continue;
// Find relocations for this section, if any
for (relSectIdx = 0; relSectIdx < pMeta->SectionCnt; relSectIdx++)
{
if (pMeta->pSections[relSectIdx].h.sh_type == SHT_REL &&
pMeta->pSections[relSectIdx].h.sh_info == sectIdx)
{
pRelSect = &pMeta->pSections[relSectIdx];
break;
}
}
// Align the section and check for segment overflow
{
uint32 newOfs, align = pSect->h.sh_addralign;
if (align & (align - 1))
error("Section alignment not a power of 2\n");
switch (OutputFormat)
{
case FormatDosComTiny:
case FormatFlat16:
case FormatDosExeSmall:
// Don't use unreasonably large alignments (greater than 4) in 16-bit code segments
// (in ELF32 object files produced by NASM, .text sections are 16-byte aligned)
if (!isDataSection && align > 4)
align = 4;
break;
case FormatDosExeHuge:
// Force 4-byte alignment of the .relot and .relod relocation sections in the huge mode(l)
if (StrAnyOf(pMeta->pSectNames + pSect->h.sh_name, ".relot\0"
".relod\0"))
align = 4;
if (align > 16)
error("Section alignment larger than paragraph size (16)\n");
break;
case FormatWinPe32:
case FormatElf32:
case FormatMach32:
if (align > 4096)
error("Section alignment larger than page size (4KB)\n");
break;
}
if (align > 1)
{
newOfs = AlignTo(ofs, align);
if (newOfs < ofs)
errSectTooBig();
if (pass)
{
if (pSect->h.sh_type == SHT_PROGBITS ||
!UseBss)
{
unsigned char fillByte = 0xCC * !isDataSection; // int3
FillWithByte(fillByte, newOfs - ofs, fout);
}
}
ofs = newOfs;
}
newOfs = ofs + pSect->h.sh_size;
if (newOfs < ofs)
errSectTooBig();
switch (OutputFormat)
{
case FormatDosComTiny:
case FormatFlat16:
case FormatDosExeSmall:
if (newOfs > 0x10000)
errSectTooBig();
break;
}
}
pSect->OutOffset = ofs;
pSect->OutFileOffset = hdrsz + written + (ofs - startOfs);
if (!pass)
{
// Calculate start addresses of combined sections
if (pSectDescrs[j].Start > pSect->OutOffset)
pSectDescrs[j].Start = pSect->OutOffset;
if (pSectDescrs[SectCnt + isDataSection].Start > pSectDescrs[j].Start)
pSectDescrs[SectCnt + isDataSection].Start = pSectDescrs[j].Start;
}
if (pass)
{
// Relocate (if needed) and write the section
if (pSect->h.sh_type == SHT_PROGBITS)
{
FILE* fin = Fopen(pMeta->ElfName, "rb");
if (verbose)
printf("Relocating %s in %s:\n", pMeta->pSectNames + pSect->h.sh_name, pMeta->ElfName);
Fseek(fin, pMeta->ObjOffset + pSect->h.sh_offset, SEEK_SET);
RelocateAndWriteSection(fout, fin, pSect->h.sh_size, pMeta, pRelSect);
Fclose(fin);
if (verbose)
puts("");
}
else if (!UseBss) // if (pSect->h.sh_type == SHT_NOBITS)
{
FillWithByte(0, pSect->h.sh_size, fout);
}
}
ofs += pSect->h.sh_size;
if (!pass)
{
// Calculate stop addresses of combined sections (actually, the addresses right after the end)
if (pSectDescrs[j].Stop < pSect->OutOffset + pSect->h.sh_size)
pSectDescrs[j].Stop = pSect->OutOffset + pSect->h.sh_size;
if (pSectDescrs[SectCnt + isDataSection].Stop < pSectDescrs[j].Stop)
pSectDescrs[SectCnt + isDataSection].Stop = pSectDescrs[j].Stop;
}
} // endof: for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
} // endof: for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
if (UnrealRelodSize && !strcmp(pSectDescrs[j].pName, ".relod"))
{
uint32 newOfs = (ofs + 3) / 4 * 4;
if (newOfs < ofs)
errSectTooBig();
if (pass && newOfs != ofs)
FillWithByte(0, newOfs - ofs, fout);
ofs = newOfs;
newOfs = ofs + UnrealRelodSize;
if (newOfs < ofs)
errSectTooBig();
if (!pass)
{
// Calculate start addresses of combined sections
if (pSectDescrs[j].Start > ofs)
pSectDescrs[j].Start = ofs;
if (pSectDescrs[SectCnt + isDataSection].Start > pSectDescrs[j].Start)
pSectDescrs[SectCnt + isDataSection].Start = pSectDescrs[j].Start;
// Calculate stop addresses of combined sections (actually, the addresses right after the end)
if (pSectDescrs[j].Stop < newOfs)
pSectDescrs[j].Stop = newOfs;
if (pSectDescrs[SectCnt + isDataSection].Stop < pSectDescrs[j].Stop)
pSectDescrs[SectCnt + isDataSection].Stop = pSectDescrs[j].Stop;
}
else
{
uint32 sz = 0;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pRelSect = &pMeta->pSections[sectIdx];
if (pRelSect->h.sh_type == SHT_REL)
{
// Handle only 32-bit non-PC-relative relocations.
uint32 relIdx;
for (relIdx = 0; relIdx < pRelSect->h.sh_entsize; relIdx++)
{
Elf32_Rel* pRel = &pRelSect->d.pRel[relIdx];
uint32 symIdx = pRel->r_info >> 8;
uint32 absSym = symIdx == 0;
uint32 relType = pRel->r_info & 0xFFu;
if (!absSym && relType == R_386_32)
{
uint32 addr = pRel->r_offset + pMeta->pSections[pRelSect->h.sh_info].OutOffset;
if (sz >= UnrealRelodSize)
errInternal(1);
Fwrite(&addr, sizeof addr, fout);
sz += 4;
}
}
}
}
}
if (sz != UnrealRelodSize)
errInternal(2);
}
ofs = newOfs;
} // endof: if (UnrealRelodSize && !strcmp(pSectDescrs[j].pName, ".relod"))
// Trailing section/segment/executable padding
switch (OutputFormat)
{
case FormatDosExeSmall:
if (!isDataSection &&
(j + 1 == SectCnt ||
!(pSectDescrs[j + 1].Attrs & SHF_EXECINSTR))) // last code section or last code section before first data section
{
// The code segment has been written, prepare for writing the data segment.
// Pad the code segment to an integral number of 16-byte paragraphs
uint32 newOfs = AlignTo(ofs, 16);
if (pass)
{
FillWithByte(0xCC, newOfs - ofs, fout); // int3
}
ofs = newOfs;
// Reset the offset for the data segment
written += ofs - startOfs;
ofs = startOfs = 0;
// Reserve several bytes so that variables don't appear at address/offset 0 (NULL)
if (j + 1 != SectCnt)
{
if (pass)
{
Fwrite("NULL", 4, fout);
}
ofs += 4;
}
}
break;
case FormatWinPe32:
case FormatElf32:
case FormatAout:
case FormatMach32:
if (!isDataSection &&
(j + 1 == SectCnt ||
!(pSectDescrs[j + 1].Attrs & SHF_EXECINSTR))) // last code section or last code section before first data section
{
// The code section has been written, prepare for writing the data section.
// Pad the code section to an integral number of 4KB pages
uint32 newOfs = AlignTo(ofs, 4096);
if (newOfs < ofs)
errSectTooBig();
if (pass)
{
FillWithByte(0xCC, newOfs - ofs, fout); // int3
}
ofs = newOfs;
}
else
{
int lastData =
(!UseBss && j + 1 == SectCnt) ||
(UseBss &&
!(pSectDescrs[j].Attrs & SHT_NOBITS) &&
(j + 1 == SectCnt ||
(pSectDescrs[j + 1].Attrs & SHT_NOBITS))); // last written data section
int lastImpData =
OutputFormat == FormatWinPe32 &&
!strncmp(pSectDescrs[j].pName, ".dll_", sizeof ".dll_" - 1) &&
((pSectDescrs[j].Attrs & (SHT_NOBITS | SHF_WRITE | SHF_EXECINSTR)) == SHF_WRITE) &&
(j + 1 == SectCnt ||
strncmp(pSectDescrs[j + 1].pName, ".dll_", sizeof ".dll_" - 1)); // last import data section in PE
int lastRoData =
OutputFormat == FormatWinPe32 &&
!(pSectDescrs[j].Attrs & (SHT_NOBITS | SHF_WRITE | SHF_EXECINSTR)) &&
(j + 1 == SectCnt ||
(pSectDescrs[j + 1].Attrs & SHF_WRITE)); // last read-only data section in PE
if (lastRoData || lastImpData || lastData)
{
// The data section has been written.
// Pad the data section to an integral number of 4KB pages
uint32 newOfs = AlignTo(ofs, 4096);
if (newOfs < ofs)
errSectTooBig();
if (pass)
{
FillWithByte(0, newOfs - ofs, fout);
}
ofs = newOfs;
}
}
break;
}
} // endof: for (j = 0; j < SectCnt; j++)
}
void RwFlat(void)
{
int hasData = !(pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR); // non-executable/data sections, if any, are last
FILE* fout = Fopen(OutName, "wb+");
uint32 hdrsz = 0;
uint32 ip;
// Based on the file format, figure out:
// - header sizes
// - start offsets/base addresses
// - stack size and location
switch (OutputFormat)
{
case FormatDosComTiny:
Origin = 0x100;
if (StackSize == 0xFFFFFFFF)
StackSize = 8192; // default stack size if unspecified
if (StackSize < 4096)
errStackTooSmall();
if (StackSize > 0xFFFC)
errStackTooBig();
pSectDescrs[SectCnt + 2].Start = 0xFFFC - StackSize; // __start_stack__
pSectDescrs[SectCnt + 2].Stop = 0xFFFC; // __stop_stack__ should be unused
break;
case FormatFlat16:
case FormatFlat32:
if (Origin == 0xFFFFFFFF)
Origin = 0; // default origin if unspecified
if (OutputFormat == FormatFlat16 && Origin > 0xFFFF)
errSectTooBig();
break;
}
Pass(0, NULL, 0);
// Ensure the entry point in flat binaries is at the very first byte
ip = FindSymbolAddress(EntryPoint);
if (ip != Origin)
{
uint32 newOrigin;
uint32 imm;
// The entry point is not at the very first byte of the flat binary,
// start the binary with a jump to the entry point
hdrsz = (OutputFormat == FormatFlat32) ? 1+4 : 1+2; // size of the jump instruction
newOrigin = Origin + hdrsz; // adjust origin w.r.t. the jump instruction size
if (newOrigin < Origin)
errSectTooBig();
if (OutputFormat == FormatFlat16 && newOrigin > 0xFFFF)
errSectTooBig();
Origin = newOrigin;
Pass(0, NULL, hdrsz); // repeat pass 0, now with a fake header containing a jump instruction to the entry point
// It was determined in pass 0 that the entry point was not
// at the very first byte of the flat binary,
// a fake header containing a jump instruction to the entry point is needed
ip = FindSymbolAddress(EntryPoint);
imm = ip - Origin;
Fwrite("\xE9", 1, fout); // jmp rel16/32 to entry point
Fwrite(&imm, hdrsz - 1, fout);
}
// Check for code/data colliding with the stack
if (OutputFormat == FormatDosComTiny &&
pSectDescrs[SectCnt + hasData].Stop > pSectDescrs[SectCnt + 2].Start)
errStackTooBig();
Pass(1, fout, hdrsz);
Fclose(fout);
}
void RwAout(void)
{
int hasData = !(pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR); // non-executable/data sections, if any, are last
FILE* fout = Fopen(OutName, "wb+");
uint32 start, stop;
uint32 hdrsz = sizeof AoutHeader;
uint32 j, fIdx, sectIdx, relSectIdx, relIdx;
Origin = 0;
// Copy the DPMI stub
if (StubName)
{
static unsigned char buf[FBUF_SIZE]; // must be larger than tDosExeHeader
tDosExeHeader h;
static uint32 stubInfo[16];
FILE* fin = Fopen(StubName, "rb");
uint32 sz;
uint32 header = 0, i = 0;
memset(&h, 0, sizeof h); // shut gcc up
while ((sz = fread(buf, 1, sizeof buf, fin)) != 0)
{
Fwrite(buf, sz, fout);
hdrsz += sz;
if (i == 0 && sz >= sizeof h)
{
// Preserve the EXE header for simple validation
memcpy(&h, buf, sizeof h);
header = 1;
}
i++;
}
Fclose(fin);
if (header)
{
// The header must contain the correct size of the stub file.
// The stub will use the size from the header to locate the extra info and the a.out portion.
uint32 sz = ((uint32)h.PageCnt - (h.PartPage != 0)) * 512 + h.PartPage;
if (h.Signature[0] != 'M' || h.Signature[1] != 'Z' ||
sizeof AoutHeader + sz != hdrsz)
header = 0;
}
if (!header)
error("Invalid stub\n");
// Add extra info for the stub to use
stubInfo[0] = 0x21245044; // magic number ("DP$!")
if (StackSize == 0xFFFFFFFF || StackSize == 0)
StackSize = 65536; // default stack size if unspecified
StackSize = (StackSize + 0xFFF) & 0xFFFFF000;
stubInfo[1] = StackSize;
if (MinHeap == 0xFFFFFFFF || MinHeap == 0)
MinHeap = 0x80000; // default minimum heap size if unspecified
MinHeap = (MinHeap + 0xFFF) & 0xFFFFF000;
if (MaxHeap == 0xFFFFFFFF)
MaxHeap = 0x1000000; // default maximum heap size if unspecified
MaxHeap = (MaxHeap + 0xFFF) & 0xFFFFF000;
if (MaxHeap < MinHeap)
MaxHeap = MinHeap;
stubInfo[2] = MinHeap;
stubInfo[3] = MaxHeap;
Fwrite(stubInfo, sizeof stubInfo, fout);
hdrsz += sizeof stubInfo;
}
// TBD??? insert something (NOPs?) at the beginning to ensure no function is at address/offset 0(NULL)
Pass(0, NULL, hdrsz);
AoutHeader.entry = FindSymbolAddress(EntryPoint);
start = pSectDescrs[SectCnt].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt].Stop + 0xFFF) & 0xFFFFF000;
AoutHeader.text = stop - start;
if (hasData)
{
start = pSectDescrs[SectCnt + 1].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt + 1].Stop + 0xFFF) & 0xFFFFF000;
AoutHeader.data = stop - start;
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
uint32 datasz = 0;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
if ((pSectDescrs[i].Attrs & SHF_EXECINSTR) == 0)
datasz = ((pSectDescrs[i].Stop + 0xFFF) & 0xFFFFF000) - start;
AoutHeader.bss = AoutHeader.data - datasz;
AoutHeader.data = datasz;
}
}
Fwrite(&AoutHeader, sizeof AoutHeader, fout);
Pass(1, fout, hdrsz);
// Write relocation table
// Handle individual sections
for (j = 0; j < SectCnt; j++)
{
int isDataSection = !(pSectDescrs[j].Attrs & SHF_EXECINSTR);
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
tElfSection* pRelSect = NULL;
if (pSect->h.sh_type != SHT_PROGBITS)
continue;
if (strcmp(pSectDescrs[j].pName, pMeta->pSectNames + pSect->h.sh_name))
continue;
// Find relocations for this section, if any
for (relSectIdx = 0; relSectIdx < pMeta->SectionCnt; relSectIdx++)
{
if (pMeta->pSections[relSectIdx].h.sh_type == SHT_REL &&
pMeta->pSections[relSectIdx].h.sh_info == sectIdx)
{
pRelSect = &pMeta->pSections[relSectIdx];
break;
}
}
if (!pRelSect)
continue;
// Write relocation records
for (relIdx = 0; relIdx < pRelSect->h.sh_entsize; relIdx++)
{
Elf32_Rel* pRel = &pRelSect->d.pRel[relIdx];
uint32 symIdx = pRel->r_info >> 8;
uint32 absSym = symIdx == 0;
uint32 relType = pRel->r_info & 0xFFu;
uint32 relative = relType == R_386_PC16 || relType == R_386_PC32;
uint32 length = (relType == R_386_32 || relType == R_386_PC32) * 2 +
(relType == R_386_16 || relType == R_386_PC16);
tAoutRel aoutRel;
if (absSym != relative)
continue;
aoutRel.address = pRel->r_offset + pMeta->pSections[pRelSect->h.sh_info].OutOffset -
pSectDescrs[SectCnt + isDataSection].Start;
aoutRel.info = (relative << 24) | (length << 25);
// TBD??? use N_TEXT, N_DATA and N_BSS instead of N_UNDF
aoutRel.info |= absSym ? N_ABS : N_UNDF;
Fwrite(&aoutRel, sizeof aoutRel, fout);
AoutHeader.trsize += !isDataSection;
AoutHeader.drsize += isDataSection;
}
} // endof: for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
} // endof: for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
} // endof: for (j = 0; j < SectCnt; j++)
// update AoutHeader
AoutHeader.trsize *= sizeof(tAoutRel);
AoutHeader.drsize *= sizeof(tAoutRel);
Fseek(fout, hdrsz - sizeof AoutHeader, SEEK_SET);
Fwrite(&AoutHeader, sizeof AoutHeader, fout);
Fclose(fout);
}
void CheckFxnSizes(void)
{
// In the huge mode(l) individual functions must each fit into a 64KB segment.
// A special non-allocated section, ".fxnsz", holds function sizes. Check them.
uint32 fIdx, sectIdx;
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
uint32 sz = pSect->h.sh_size;
if (!(pSect->h.sh_flags & SHF_ALLOC) &&
sz &&
!strcmp(pMeta->pSectNames + pSect->h.sh_name, ".fxnsz"))
{
FILE* fin = Fopen(pMeta->ElfName, "rb");
uint32 o, fsz;
Fseek(fin, pMeta->ObjOffset + pSect->h.sh_offset, SEEK_SET);
for (o = 0; o < sz; o += sizeof fsz)
{
Fread(&fsz, sizeof fsz, fin);
if (fsz >= 0xFFF0) // allow for imperfect alignment with segment boundary
error("Function larger than 64KB found in '%s'\n", pMeta->ElfName);
}
Fclose(fin);
continue;
}
}
}
}
void RwDosExe(void)
{
int hasData = !(pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR); // non-executable/data sections, if any, are last
FILE* fout = Fopen(OutName, "wb+");
uint32 hdrsz = 0;
// Based on the file format, figure out:
// - header sizes
// - start offsets/base addresses
// - stack size and location
switch (OutputFormat)
{
case FormatDosExeSmall:
Origin = sizeof(tDosExeHeader);
hdrsz = sizeof(tDosExeHeader);
if (StackSize == 0xFFFFFFFF)
StackSize = 8192; // default stack size if unspecified
if (StackSize < 4096)
errStackTooSmall();
if (StackSize > 0xFFFC)
errStackTooBig();
pSectDescrs[SectCnt + 2].Start = 0xFFFC - StackSize; // __start_stack__
pSectDescrs[SectCnt + 2].Stop = 0xFFFC; // __stop_stack__ should be unused
break;
case FormatDosExeHuge:
case FormatDosExeUnreal:
Origin = sizeof(tDosExeHeader);
hdrsz = sizeof(tDosExeHeader);
if (StackSize == 0xFFFFFFFF)
StackSize = 32768; // default stack size if unspecified
if (StackSize < 8192)
errStackTooSmall();
if (StackSize > 0xFFFC)
errStackTooBig();
break;
}
Pass(0, NULL, hdrsz);
// Check for code/data colliding with the stack
if (OutputFormat == FormatDosExeSmall &&
pSectDescrs[SectCnt + hasData].Stop > pSectDescrs[SectCnt + 2].Start)
errStackTooBig();
switch (OutputFormat)
{
case FormatDosExeSmall:
{
uint32 dsz = 0, fsz;
if (hasData)
dsz = pSectDescrs[SectCnt + 1].Stop; // data size
fsz = (pSectDescrs[SectCnt].Stop + 15) / 16 * 16; // code size + padding
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
if (!(pSectDescrs[i].Attrs & SHF_EXECINSTR))
{
fsz += pSectDescrs[i].Stop; // + non-bss data size (includes "NULL")
dsz = pSectDescrs[i].Stop;
}
else
{
fsz += 4; // account for "NULL" at the beginning of the data/stack segment
dsz = 4;
}
}
else
{
fsz += dsz; // + non-bss data size
}
DosExeHeader.PartPage = fsz % 512;
DosExeHeader.PageCnt = (fsz + 511) / 512;
DosExeHeader.InitIp = FindSymbolAddress(EntryPoint);
DosExeHeader.InitCs = 0xFFFE;
DosExeHeader.InitSs = (pSectDescrs[SectCnt].Stop + 15) / 16 - 2; // data/stack segment starts right after code segment's padding
DosExeHeader.MaxAlloc = DosExeHeader.MinAlloc = 4096 - dsz / 16; // maximum stack size = data segment size - data size
Fwrite(&DosExeHeader, sizeof DosExeHeader, fout);
}
break;
case FormatDosExeHuge:
case FormatDosExeUnreal:
{
uint32 ip = FindSymbolAddress(EntryPoint);
uint32 sz = pSectDescrs[SectCnt].Stop; // code size
uint32 fsz;
if (hasData)
sz = pSectDescrs[SectCnt + 1].Stop; // code size + data size
if (sz > 524288)
error("Executable too big (bigger than 512KB)\n");
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
fsz = pSectDescrs[i].Stop;
}
else
{
fsz = sz;
}
DosExeHeader.PartPage = fsz % 512;
DosExeHeader.PageCnt = (fsz + 511) / 512;
DosExeHeader.InitIp = ip & 0xF;
DosExeHeader.InitCs = (ip >> 4) - 2;
DosExeHeader.InitSs = (sz + 15) / 16 - 2; // stack segment starts right after data segment's padding
DosExeHeader.InitSp = StackSize;
DosExeHeader.MaxAlloc = DosExeHeader.MinAlloc = (sz - fsz + 15) / 16 + (StackSize + 15) / 16 + 1; // maximum stack size = 64KB
Fwrite(&DosExeHeader, sizeof DosExeHeader, fout);
}
break;
}
Pass(1, fout, hdrsz);
Fclose(fout);
}
void RwMach(void)
{
int hasData = !(pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR); // non-executable/data sections, if any, are last
FILE* fout = Fopen(OutName, "wb+");
uint32 sectionIdx;
uint32 hdrsz;
uint32 imageBase;
int hasPageZero;
uint32 start, stop;
uint32 sections_stop, vmaddr_stop;
uint32 predefinedLinkeditSize = 52;
Mach32_SegmentCmd linkeditSegmentCmd;
static const uint32 num_syms = 2;
static const uint32 strsize = 28;
Mach32_SymtabCmd symtabCmd;
Mach32_ThreadCmd unixThreadCmd =
{
MACH_LC_UNIXTHREAD, // cmd
sizeof(Mach32_ThreadCmd), // cmdsize
MACH_X86_THREAD_STATE, // flavor
16, // count
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // state
};
Mach32_Nlist mhExecuteHeaderSym =
{
2, // n_strx
MACH_N_EXT | MACH_N_ABS, // n_type
0x01, // n_sect
MACH_REFERENCED_DYNAMICALLY, // n_desc
0x0, // n_value
};
Mach32_Nlist startSym =
{
22, // n_strx
MACH_N_EXT | MACH_N_SECT, // n_type
0x01, // n_sect
MACH_REFERENCE_FLAG_UNDEFINED_NON_LAZY, // n_desc
0, // n_value
};
char predefinedStringTable[] = "\x20\x0__mh_execute_header\x0start";
Mach32_SegmentCmd segz = // unmapped memory to catch NULL pointer dereferences
{
MACH_LC_SEGMENT, // cmd
sizeof(Mach32_SegmentCmd), // cmdsize
{ "__PAGEZERO" }, // segname
0, // vmaddr
0, // vmsize
0, // fileoff
0, // filesize
0, // maxprot
0, // initprot
0, // nsects
0, // flags
};
// TBD!!! Check if this is still true: using proper segment/section names drives otool crazy.
Mach32_SegmentCmd seg[2] =
{
{
MACH_LC_SEGMENT, // cmd
sizeof(Mach32_SegmentCmd) + sizeof(Mach32_Section), // cmdsize
{ "__TEXT" }, // segname
0, // vmaddr
0, // vmsize
0, // fileoff
0, // filesize
MACH_VM_PROT_READ | MACH_VM_PROT_EXECUTE | MACH_VM_PROT_WRITE, // maxprot
MACH_VM_PROT_READ | MACH_VM_PROT_EXECUTE, // initprot
1, // nsects
0, // flags
},
{
MACH_LC_SEGMENT, // cmd
sizeof(Mach32_SegmentCmd) + sizeof(Mach32_Section), // cmdsize
{ "__DATA" }, // segname
0, // vmaddr
0, // vmsize
0, // fileoff
0, // filesize
MACH_VM_PROT_READ | MACH_VM_PROT_EXECUTE | MACH_VM_PROT_WRITE, // maxprot
MACH_VM_PROT_READ | MACH_VM_PROT_WRITE, // initprot
1, // nsects
0, // flags
},
};
Mach32_Section sect[2] =
{
{
{ "__text" }, // sectname
{ "__TEXT" }, // segname
0, // addr
0, // size
0, // offset
0, // align
0, // reloff
0, // nreloc
S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS, // flags
0, // reserved1
0, // reserved2
},
{
{ "__data" }, // sectname
{ "__DATA" }, // segname
0, // addr
0, // size
0, // offset
0, // align
0, // reloff
0, // nreloc
0, // flags
0, // reserved1
0, // reserved2
},
};
// Note that we create sections (in addition to segments) and
// a couple of symbols to make the OS and tools happy (there
// seem to be tighter checks in newer MacOS).
// They shouldn't be needed otherwise.
if (Origin == 0xFFFFFFFF)
imageBase = 0x1000; // default image base if origin is unspecified
else
imageBase = Origin & 0xFFFFF000;
if (imageBase >= 0xFFFFF000)
errSectTooBig();
hasPageZero = imageBase != 0;
MachHeader.ncmds = hasPageZero + 4 + hasData;
MachHeader.sizeofcmds =
hasPageZero * sizeof(Mach32_SegmentCmd) +
(1 + hasData) * (sizeof(Mach32_SegmentCmd) + sizeof(Mach32_Section)) +
sizeof(Mach32_SegmentCmd) + sizeof(Mach32_SymtabCmd) +
sizeof(Mach32_ThreadCmd);
hdrsz = sizeof MachHeader + MachHeader.sizeofcmds;
Origin = imageBase + hdrsz;
Pass(0, NULL, hdrsz);
Fwrite(&MachHeader, sizeof MachHeader, fout);
// Note that the header is part of the code segment.
start = imageBase;
stop = (pSectDescrs[SectCnt].Stop + 0xFFF) & 0xFFFFF000;
seg[0].filesize = seg[0].vmsize = stop - start;
seg[0].vmaddr = start;
sect[0].addr = Origin;
sect[0].offset = hdrsz;
sect[0].size = stop - Origin;
if (hasData)
{
start = pSectDescrs[SectCnt + 1].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt + 1].Stop + 0xFFF) & 0xFFFFF000;
seg[1].vmsize = stop - start;
sect[1].addr = seg[1].vmaddr = start;
sect[1].offset = seg[1].fileoff = start - imageBase;
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
seg[1].filesize = ((pSectDescrs[i].Stop + 0xFFF) & 0xFFFFF000) - start;
}
else
{
seg[1].filesize = stop - start;
}
sect[1].size = seg[1].filesize;
}
if (hasPageZero)
{
segz.vmsize = imageBase;
Fwrite(&segz, sizeof segz, fout);
}
for (sectionIdx = 0; sectionIdx <= hasData; ++sectionIdx)
{
Fwrite(&seg[sectionIdx], sizeof seg[sectionIdx], fout);
Fwrite(§[sectionIdx], sizeof sect[sectionIdx], fout);
}
sections_stop = seg[hasData].fileoff + seg[hasData].filesize;
vmaddr_stop = seg[hasData].vmaddr + seg[hasData].vmsize;
linkeditSegmentCmd.cmd = MACH_LC_SEGMENT;
linkeditSegmentCmd.cmdsize = sizeof(Mach32_SegmentCmd);
strncpy(linkeditSegmentCmd.segname, "__LINKEDIT", 16);
linkeditSegmentCmd.vmaddr = vmaddr_stop;
// TBD???(tilarids): Should we change the vmsize here?
linkeditSegmentCmd.vmsize = 0x1000;
linkeditSegmentCmd.fileoff = sections_stop;
linkeditSegmentCmd.filesize = predefinedLinkeditSize;
linkeditSegmentCmd.maxprot = MACH_VM_PROT_READ | MACH_VM_PROT_EXECUTE | MACH_VM_PROT_WRITE;
linkeditSegmentCmd.initprot = MACH_VM_PROT_READ;
linkeditSegmentCmd.nsects = 0x0;
linkeditSegmentCmd.flags = 0x0;
// TBD??? Consider writing a proper symbol table.
symtabCmd.cmd = MACH_LC_SYMTAB;
symtabCmd.cmdsize = sizeof(Mach32_SymtabCmd);
symtabCmd.symoff = sections_stop;
symtabCmd.nsyms = num_syms;
symtabCmd.stroff = sections_stop + num_syms * sizeof(Mach32_Nlist);
symtabCmd.strsize = strsize;
unixThreadCmd.state.eip = FindSymbolAddress(EntryPoint);
Fwrite(&linkeditSegmentCmd, sizeof linkeditSegmentCmd, fout);
Fwrite(&symtabCmd, sizeof symtabCmd, fout);
Fwrite(&unixThreadCmd, sizeof unixThreadCmd, fout);
Pass(1, fout, hdrsz);
// Write the symbol table.
// TBD??? Write a proper table instead of the predefined one.
mhExecuteHeaderSym.n_value = imageBase;
startSym.n_value = FindSymbolAddress(EntryPoint);
Fwrite(&mhExecuteHeaderSym, sizeof mhExecuteHeaderSym, fout);
Fwrite(&startSym, sizeof startSym, fout);
// Write the string table.
// TBD??? Write a proper string table instead of the predefined one.
Fwrite(predefinedStringTable, sizeof predefinedStringTable, fout);
Fclose(fout);
}
void RwPe(void)
{
FILE* fout = Fopen(OutName, "wb+");
uint32 hdrsz = 0;
uint32 imageBase = 0;
uint32 peImportsStart = 0;
int j = 0;
int tmpCnt = SectCnt;
int textSectCnt = 0;
int roDataSectCnt = 0;
int impDataSectCnt = 0;
int dataSectCnt = 0;
int bssSectCnt = 0;
int hasData = 0;
while (tmpCnt &&
!(pSectDescrs[j].Attrs & SHT_NOBITS) &&
(pSectDescrs[j].Attrs & SHF_EXECINSTR) &&
!(pSectDescrs[j].Attrs & SHF_WRITE))
tmpCnt--, j++, textSectCnt++;
while (tmpCnt &&
!(pSectDescrs[j].Attrs & SHT_NOBITS) &&
!(pSectDescrs[j].Attrs & SHF_EXECINSTR) &&
!(pSectDescrs[j].Attrs & SHF_WRITE))
tmpCnt--, j++, roDataSectCnt++;
while (tmpCnt &&
!(pSectDescrs[j].Attrs & SHT_NOBITS) &&
!(pSectDescrs[j].Attrs & SHF_EXECINSTR) &&
(pSectDescrs[j].Attrs & SHF_WRITE) &&
!strncmp(pSectDescrs[j].pName, ".dll_", sizeof ".dll_" - 1))
tmpCnt--, j++, impDataSectCnt++;
while (tmpCnt &&
!(pSectDescrs[j].Attrs & SHT_NOBITS) &&
!(pSectDescrs[j].Attrs & SHF_EXECINSTR) &&
(pSectDescrs[j].Attrs & SHF_WRITE))
tmpCnt--, j++, dataSectCnt++;
while (tmpCnt &&
(pSectDescrs[j].Attrs & SHT_NOBITS) &&
!(pSectDescrs[j].Attrs & SHF_EXECINSTR) &&
(pSectDescrs[j].Attrs & SHF_WRITE))
tmpCnt--, j++, bssSectCnt++;
if (!textSectCnt || tmpCnt)
errInternal(3);
hasData = roDataSectCnt || impDataSectCnt || dataSectCnt || bssSectCnt;
// Figure out:
// - header sizes
// - start offsets/base addresses
// - stack size and location
if (Origin == 0xFFFFFFFF)
imageBase = 0x00400000; // default image base if origin is unspecified
else
imageBase = Origin & 0xFFFFF000;
if (imageBase >= 0xFFFFF000)
errSectTooBig();
// hdrsz = 4096; // make the first section page-aligned in the file
hdrsz = 1024; // traditional 1KB size of headers, 1st section isn't page-aligned in file
Origin = imageBase + 4096;
PeOptionalHeader.SizeOfHeaders = hdrsz;
Pass(0, NULL, hdrsz);
{
uint32 hsz = sizeof DosMzExeStub +
sizeof "PE\0" +
sizeof PeFileHeader +
sizeof PeOptionalHeader +
sizeof(tPeImageSectionHeader) * 5/*.text,.rdata,.idata,.data,.reloc*/;
uint32 start, stop;
PeFileHeader.NumberOfSections =
1 + !!roDataSectCnt + !!impDataSectCnt + (dataSectCnt || bssSectCnt);
PeOptionalHeader.ImageBase = imageBase;
PeOptionalHeader.AddressOfEntryPoint = FindSymbolAddress(EntryPoint) - imageBase;
start = pSectDescrs[SectCnt].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt].Stop + 0xFFF) & 0xFFFFF000;
PeOptionalHeader.BaseOfCode =
PeSectionHeaderText.VirtualAddress =
start - imageBase;
PeSectionHeaderText.PointerToRawData =
hdrsz;
PeSectionHeaderText.Misc.VirtualSize = PeSectionHeaderText.SizeOfRawData =
PeOptionalHeader.SizeOfCode = stop - start;
if (hasData)
{
start = pSectDescrs[SectCnt + 1].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt + 1].Stop + 0xFFF) & 0xFFFFF000;
PeOptionalHeader.BaseOfData =
PeSectionHeaderData.VirtualAddress =
start - imageBase;
PeSectionHeaderData.PointerToRawData =
PeSectionHeaderText.PointerToRawData + PeSectionHeaderText.SizeOfRawData;
PeSectionHeaderData.Misc.VirtualSize =
PeOptionalHeader.SizeOfInitializedData = stop - start;
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
PeSectionHeaderData.SizeOfRawData = ((pSectDescrs[i].Stop + 0xFFF) & 0xFFFFF000) - start;
}
else
{
PeSectionHeaderData.SizeOfRawData = stop - start;
}
// Carve out .rodata into its own section
if (roDataSectCnt)
{
PeSectionHeaderRoData.Misc.VirtualSize =
((pSectDescrs[textSectCnt + roDataSectCnt - 1].Stop + 0xFFF) & 0xFFFFF000) - start;
PeSectionHeaderData.Misc.VirtualSize -=
PeSectionHeaderRoData.Misc.VirtualSize;
PeSectionHeaderRoData.VirtualAddress =
PeSectionHeaderData.VirtualAddress;
PeSectionHeaderData.VirtualAddress +=
PeSectionHeaderRoData.Misc.VirtualSize;
PeSectionHeaderRoData.SizeOfRawData =
PeSectionHeaderRoData.Misc.VirtualSize;
PeSectionHeaderData.SizeOfRawData -=
PeSectionHeaderRoData.SizeOfRawData;
PeSectionHeaderRoData.PointerToRawData =
PeSectionHeaderData.PointerToRawData;
PeSectionHeaderData.PointerToRawData +=
PeSectionHeaderRoData.SizeOfRawData;
}
// Carve out .dll_* into the .idata section
if (impDataSectCnt)
{
PeSectionHeaderImpData.Misc.VirtualSize =
((pSectDescrs[textSectCnt + roDataSectCnt + impDataSectCnt - 1].Stop + 0xFFF) & 0xFFFFF000) -
pSectDescrs[textSectCnt + roDataSectCnt].Start & 0xFFFFF000;
PeSectionHeaderData.Misc.VirtualSize -=
PeSectionHeaderImpData.Misc.VirtualSize;
PeSectionHeaderImpData.VirtualAddress =
PeSectionHeaderData.VirtualAddress;
PeSectionHeaderData.VirtualAddress +=
PeSectionHeaderImpData.Misc.VirtualSize;
PeSectionHeaderImpData.SizeOfRawData =
PeSectionHeaderImpData.Misc.VirtualSize;
PeSectionHeaderData.SizeOfRawData -=
PeSectionHeaderImpData.SizeOfRawData;
PeSectionHeaderImpData.PointerToRawData =
PeSectionHeaderData.PointerToRawData;
PeSectionHeaderData.PointerToRawData +=
PeSectionHeaderImpData.SizeOfRawData;
}
}
PeOptionalHeader.SizeOfImage = stop - imageBase;
peImportsStart = FindSymbolAddress("__dll_imports");
if (peImportsStart)
{
uint32 peImportsStop = FindSymbolAddress("__dll_imports_end");
uint32 peIatsStart = FindSymbolAddress("__dll_iats");
PeOptionalHeader.DataDirectory[1].VirtualAddress = peImportsStart - imageBase;
if (peImportsStop)
PeOptionalHeader.DataDirectory[1].Size = peImportsStop - peImportsStart;
if (peIatsStart)
{
uint32 peIatsStop = FindSymbolAddress("__dll_iats_end");
PeOptionalHeader.DataDirectory[12].VirtualAddress = peIatsStart - imageBase;
if (peIatsStop)
PeOptionalHeader.DataDirectory[12].Size = peIatsStop - peIatsStart;
}
}
Fwrite(DosMzExeStub, sizeof DosMzExeStub, fout);
Fwrite("PE\0", sizeof "PE\0", fout);
Fwrite(&PeFileHeader, sizeof PeFileHeader, fout);
Fwrite(&PeOptionalHeader, sizeof PeOptionalHeader, fout);
Fwrite(&PeSectionHeaderText, sizeof PeSectionHeaderText, fout);
if (roDataSectCnt)
Fwrite(&PeSectionHeaderRoData, sizeof PeSectionHeaderRoData, fout);
if (impDataSectCnt)
Fwrite(&PeSectionHeaderImpData, sizeof PeSectionHeaderImpData, fout);
if (dataSectCnt || bssSectCnt)
Fwrite(&PeSectionHeaderData, sizeof PeSectionHeaderData, fout);
if (!roDataSectCnt)
Fwrite(&PeSectionHeaderZero, sizeof PeSectionHeaderZero, fout);
if (!impDataSectCnt)
Fwrite(&PeSectionHeaderZero, sizeof PeSectionHeaderZero, fout);
if (!(dataSectCnt || bssSectCnt))
Fwrite(&PeSectionHeaderZero, sizeof PeSectionHeaderZero, fout);
Fwrite(&PeSectionHeaderZero, sizeof PeSectionHeaderZero, fout);
FillWithByte(0, hdrsz - hsz, fout);
}
Pass(1, fout, hdrsz);
{
uint32 pos = ftell(fout); // TBD!!! clean up
// In PE, some importing-related addresses must be relative to the image base, so make them relative
if (peImportsStart)
{
uint32 iofs;
for (iofs = peImportsStart; ; iofs += sizeof(tPeImageImportDescriptor))
{
tPeImageImportDescriptor id;
uint32 ofs, v;
Fseek(fout, iofs - Origin + hdrsz, SEEK_SET);
Fread(&id, sizeof id, fout);
if (!id.u.OrdinalFirstThunk || !id.Name || !id.FirstThunk)
break;
id.u.OrdinalFirstThunk -= imageBase;
id.Name -= imageBase;
id.FirstThunk -= imageBase;
Fseek(fout, iofs - Origin + hdrsz, SEEK_SET);
Fwrite(&id, sizeof id, fout);
for (ofs = id.u.OrdinalFirstThunk; ; ofs += sizeof v)
{
Fseek(fout, ofs - 4096 + hdrsz, SEEK_SET);
Fread(&v, sizeof v, fout);
if (!v)
break;
v -= imageBase;
Fseek(fout, ofs - 4096 + hdrsz, SEEK_SET);
Fwrite(&v, sizeof v, fout);
}
for (ofs = id.FirstThunk; ; ofs += sizeof v)
{
Fseek(fout, ofs - 4096 + hdrsz, SEEK_SET);
Fread(&v, sizeof v, fout);
if (!v)
break;
v -= imageBase;
Fseek(fout, ofs - 4096 + hdrsz, SEEK_SET);
Fwrite(&v, sizeof v, fout);
}
}
}
// Write relocation table
if (!NoRelocations)
{
uint32 j, fIdx, sectIdx, relSectIdx, relIdx;
uint32 lastPage = 0xFFFFFFFF, page = 0xFFFFFFFF, blockSize = 0;
uint32 totalFixupsSize = 0, blockPos = pos;
Fseek(fout, pos, SEEK_SET);
// Handle individual sections
for (j = 0; j < SectCnt; j++)
{
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
tElfSection* pRelSect = NULL;
const char* sectName;
size_t sectNameLen;
if (pSect->h.sh_type != SHT_PROGBITS)
continue;
if (strcmp(pSectDescrs[j].pName, pMeta->pSectNames + pSect->h.sh_name))
continue;
// Find relocations for this section, if any
for (relSectIdx = 0; relSectIdx < pMeta->SectionCnt; relSectIdx++)
{
if (pMeta->pSections[relSectIdx].h.sh_type == SHT_REL &&
pMeta->pSections[relSectIdx].h.sh_info == sectIdx)
{
pRelSect = &pMeta->pSections[relSectIdx];
break;
}
}
if (!pRelSect)
continue;
// Don't create relocations for anything in sections whose names
// start with ".dll_import" or ".dll_iat".
sectName = pSectDescrs[j].pName;
sectNameLen = strlen(sectName);
if (!strncmp(sectName, ".dll_import", sizeof ".dll_import" - 1) ||
!strncmp(sectName, ".dll_iat", sizeof ".dll_iat" - 1))
continue;
// Write relocation records
for (relIdx = 0; relIdx < pRelSect->h.sh_entsize; relIdx++)
{
Elf32_Rel* pRel = &pRelSect->d.pRel[relIdx];
uint32 symIdx = pRel->r_info >> 8;
uint32 absSym = symIdx == 0;
uint32 relType = pRel->r_info & 0xFFu;
uint32 relative = relType == R_386_PC16 || relType == R_386_PC32;
uint32 length = (relType == R_386_32 || relType == R_386_PC32) * 2 +
(relType == R_386_16 || relType == R_386_PC16);
uint32 addr;
uint16 typeOffs;
if (absSym)
error("Unsupported relocation type in PE\n");
if (relative)
continue;
if (length != 2)
error("Unsupported relocation size in PE\n");
addr = pRel->r_offset + pMeta->pSections[pRelSect->h.sh_info].OutOffset -
imageBase;
page = addr >> 12;
if (page != lastPage)
{
// finish off fixups for the last page, if any
if (blockSize)
{
if (blockSize & 2)
{
// pad to 4 bytes
typeOffs = 0;
Fwrite(&typeOffs, sizeof typeOffs, fout);
blockSize += sizeof(typeOffs);
}
// update block header
blockSize += sizeof lastPage + sizeof blockSize;
totalFixupsSize += blockSize;
// update the filler
Fseek(fout, blockPos, SEEK_SET);
blockPos += blockSize;
lastPage <<= 12;
Fwrite(&lastPage, sizeof lastPage, fout);
Fwrite(&blockSize, sizeof blockSize, fout);
Fseek(fout, blockPos, SEEK_SET);
}
// fixups for a new (or first) page
lastPage = page;
blockSize = 0;
// filler for page's RVA and block size
Fwrite(&lastPage, sizeof lastPage, fout);
Fwrite(&blockSize, sizeof blockSize, fout);
}
typeOffs = (addr & 0xFFF) | (3 << 12);
Fwrite(&typeOffs, sizeof typeOffs, fout);
blockSize += sizeof(typeOffs);
}
} // endof: for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
} // endof: for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
} // endof: for (j = 0; j < SectCnt; j++)
// finish off fixups for the last page, if any
if (blockSize)
{
if (blockSize & 2)
{
// pad to 4 bytes
uint16 typeOffs = 0;
Fwrite(&typeOffs, sizeof typeOffs, fout);
blockSize += sizeof(typeOffs);
}
// update block header
blockSize += sizeof lastPage + sizeof blockSize;
totalFixupsSize += blockSize;
// update the filler
Fseek(fout, blockPos, SEEK_SET);
blockPos += blockSize;
lastPage <<= 12;
Fwrite(&lastPage, sizeof lastPage, fout);
Fwrite(&blockSize, sizeof blockSize, fout);
Fseek(fout, blockPos, SEEK_SET);
}
// if there's nothing to relocate, write a dummy fixup block
if (!totalFixupsSize)
{
static uint32 tmp[3];
tmp[1] = sizeof tmp;
Fwrite(tmp, sizeof tmp, fout);
totalFixupsSize = sizeof tmp;
blockPos += totalFixupsSize;
}
// pad fixup blocks to PeOptionalHeader.FileAlignment (512)
FillWithByte(0, (512 - totalFixupsSize) & 511, fout);
// update headers
{
uint32 pos = sizeof DosMzExeStub + sizeof "PE\0";
uint32 idx = PeFileHeader.NumberOfSections++;
tPeImageSectionHeader* lastHdr =
(dataSectCnt || bssSectCnt) ? &PeSectionHeaderData :
(impDataSectCnt ? &PeSectionHeaderImpData :
(roDataSectCnt ? &PeSectionHeaderRoData : &PeSectionHeaderText));
PeFileHeader.Characteristics &= ~1; // reset no relocations
// TBD??? PeFileHeader.Characteristics |= 0x20; // large address aware
PeOptionalHeader.DllCharacteristics |= 0x40; // ASLR / dynamic base
// ".reloc"
PeOptionalHeader.DataDirectory[5].VirtualAddress =
PeSectionHeaderReloc.VirtualAddress =
lastHdr->VirtualAddress +
lastHdr->Misc.VirtualSize;
PeSectionHeaderReloc.PointerToRawData = blockPos - totalFixupsSize;
PeOptionalHeader.DataDirectory[5].Size = totalFixupsSize;
PeSectionHeaderReloc.Misc.VirtualSize =
PeSectionHeaderReloc.SizeOfRawData =
(totalFixupsSize + 0x1FF) & 0xFFFFFE00;
PeOptionalHeader.SizeOfImage += PeSectionHeaderReloc.Misc.VirtualSize;
PeOptionalHeader.SizeOfImage = (PeOptionalHeader.SizeOfImage + 0xFFF) & 0xFFFFF000;
PeOptionalHeader.SizeOfInitializedData += PeSectionHeaderReloc.Misc.VirtualSize;
Fseek(fout, pos, SEEK_SET);
Fwrite(&PeFileHeader, sizeof PeFileHeader, fout);
pos += sizeof PeFileHeader;
Fseek(fout, pos, SEEK_SET);
Fwrite(&PeOptionalHeader, sizeof PeOptionalHeader, fout);
pos += sizeof PeOptionalHeader + idx * sizeof(tPeImageSectionHeader);
Fseek(fout, pos, SEEK_SET);
Fwrite(&PeSectionHeaderReloc, sizeof PeSectionHeaderReloc, fout);
}
}
}
Fclose(fout);
}
void RwElf(void)
{
int hasData = !(pSectDescrs[SectCnt - 1].Attrs & SHF_EXECINSTR); // non-executable/data sections, if any, are last
FILE* fout = Fopen(OutName, "wb+");
uint32 hdrsz = 0;
uint32 imageBase = 0;
// Figure out:
// - header sizes
// - start offsets/base addresses
// - stack size and location
if (Origin == 0xFFFFFFFF)
imageBase = 0x08048000; // default image base if origin is unspecified
else
imageBase = Origin & 0xFFFFF000;
if (imageBase >= 0xFFFFF000)
errSectTooBig();
hdrsz = 4096; // make the first section page-aligned
Origin = imageBase + hdrsz;
Pass(0, NULL, hdrsz);
{
uint32 hsz = sizeof ElfHeader +
sizeof ElfProgramHeaders;
uint32 start, stop;
ElfHeader.e_phnum = 1 + hasData;
ElfHeader.e_entry = FindSymbolAddress(EntryPoint);
start = pSectDescrs[SectCnt].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt].Stop + 0xFFF) & 0xFFFFF000;
ElfProgramHeaders[0].p_offset = start - imageBase;
ElfProgramHeaders[0].p_vaddr = ElfProgramHeaders[0].p_paddr = start;
ElfProgramHeaders[0].p_filesz = ElfProgramHeaders[0].p_memsz = stop - start;
if (hasData)
{
start = pSectDescrs[SectCnt + 1].Start & 0xFFFFF000;
stop = (pSectDescrs[SectCnt + 1].Stop + 0xFFF) & 0xFFFFF000;
ElfProgramHeaders[1].p_offset = start - imageBase;
ElfProgramHeaders[1].p_vaddr = ElfProgramHeaders[1].p_paddr = start;
ElfProgramHeaders[1].p_memsz = stop - start;
if ((pSectDescrs[SectCnt - 1].Attrs & SHT_NOBITS) && UseBss)
{
uint32 i = SectCnt - 1;
while (pSectDescrs[i].Attrs & SHT_NOBITS)
i--;
ElfProgramHeaders[1].p_filesz = ((pSectDescrs[i].Stop + 0xFFF) & 0xFFFFF000) - start;
}
else
{
ElfProgramHeaders[1].p_filesz = stop - start;
}
}
else
{
memset(&ElfProgramHeaders[1], 0, sizeof ElfProgramHeaders[1]);
}
Fwrite(&ElfHeader, sizeof ElfHeader, fout);
Fwrite(ElfProgramHeaders, sizeof ElfProgramHeaders, fout);
FillWithByte(0, 4096 - hsz, fout);
}
Pass(1, fout, hdrsz);
Fclose(fout);
}
void RelocateAndWriteAllSections(void)
{
switch (OutputFormat)
{
case FormatDosComTiny:
case FormatFlat16:
case FormatFlat32:
RwFlat();
break;
case FormatAout:
RwAout();
break;
case FormatDosExeHuge:
case FormatDosExeUnreal:
CheckFxnSizes();
// fallthrough
case FormatDosExeSmall:
RwDosExe();
break;
case FormatWinPe32:
RwPe();
break;
case FormatElf32:
RwElf();
break;
case FormatMach32:
RwMach();
break;
}
}
void GenerateMap(void)
{
uint32 j, fIdx, sectIdx, symIdx;
FILE* f;
if (!MapName)
return;
f = Fopen(MapName, "w");
fprintf(f, "File Ofs Sym Addr Sym\n\n");
for (j = 0; j < SectCnt; j++)
{
fprintf(f, " %08lX section %s:\n", (ulong)pSectDescrs[j].Start, pSectDescrs[j].pName);
for (symIdx = 0; symIdx < DeferredSymCnt; symIdx++)
if (pDeferredSyms[symIdx].SectIdx == j && !pDeferredSyms[symIdx].IsStop)
{
fprintf(f, " %08lX %s\n", (ulong)pSectDescrs[j].Start, pDeferredSyms[symIdx].pName);
break;
}
for (fIdx = 0; fIdx < ObjFileCnt; fIdx++)
{
tElfMeta* pMeta = &pMetas[fIdx];
if (!pMeta->Needed)
continue;
for (sectIdx = 0; sectIdx < pMeta->SectionCnt; sectIdx++)
{
tElfSection* pSect = &pMeta->pSections[sectIdx];
if (pSect->h.sh_type != SHT_SYMTAB)
continue;
#ifdef SUPPORT_LOCAL_RELS
for (symIdx = pSect->h.sh_info; symIdx < pSect->h.sh_entsize; symIdx++)
#else
for (symIdx = pSect->h.sh_addralign; symIdx < pSect->h.sh_entsize; symIdx++)
#endif
{
Elf32_Sym* pSym = &pSect->d.pSym[symIdx];
// Check exported symbols
if ((pSym->st_info >> 4) == STB_GLOBAL &&
pSym->st_shndx &&
pSym->st_name)
{
tElfSection* pSymSect = &pMeta->pSections[pSym->st_shndx];
uint32 fofs, addr;
if (strcmp(pSectDescrs[j].pName, pMeta->pSectNames + pSymSect->h.sh_name))
continue;
fofs = pSymSect->OutFileOffset + pSym->st_value;
addr = pSymSect->OutOffset + pSym->st_value;
fprintf(f, "%08lX %08lX %s\n", (ulong)fofs, (ulong)addr, pMeta->pSections[pSect->h.sh_link].d.pStr + pSym->st_name);
}
}
}
}
for (symIdx = 0; symIdx < DeferredSymCnt; symIdx++)
if (pDeferredSyms[symIdx].SectIdx == j && pDeferredSyms[symIdx].IsStop)
{
fprintf(f, " %08lX %s\n", (ulong)pSectDescrs[j].Stop, pDeferredSyms[symIdx].pName);
break;
}
fprintf(f, " %08lX\n\n", (ulong)pSectDescrs[j].Stop);
}
Fclose(f);
}
// Determines binary file size portably (when stat()/fstat() aren't available)
long fsize(FILE* binaryStream)
{
long ofs, ofs2;
int result;
if (fseek(binaryStream, 0, SEEK_SET) != 0 ||
fgetc(binaryStream) == EOF)
return 0;
ofs = 1;
while ((result = fseek(binaryStream, ofs, SEEK_SET)) == 0 &&
(result = (fgetc(binaryStream) == EOF)) == 0 &&
ofs <= LONG_MAX / 4 + 1)
ofs *= 2;
// If the last seek failed, back up to the last successfully seekable offset
if (result != 0)
ofs /= 2;
for (ofs2 = ofs / 2; ofs2 != 0; ofs2 /= 2)
if (fseek(binaryStream, ofs + ofs2, SEEK_SET) == 0 &&
fgetc(binaryStream) != EOF)
ofs += ofs2;
// Return -1 for files longer than LONG_MAX
if (ofs == LONG_MAX)
return -1;
return ofs + 1;
}
// Expands "@filename" in program arguments into arguments contained within file "filename".
// This is a workaround for short DOS command lines limited to 126 characters.
// Note, the expansion is NOT recursive.
// TBD!!! parse the file the same way as the command line.
void fatargs(int* pargc, char*** pargv)
{
int i, j = 0;
char** pp;
int pcnt = *pargc;
if (pcnt < 2)
return;
for (i = 1; i < pcnt; i++)
if ((*pargv)[i][0] == '@')
break;
if (i >= pcnt)
return;
if ((pp = malloc(++pcnt * sizeof(char*))) == NULL) // there's supposed to be one more NULL pointer argument
{
errMem();
}
pp[j++] = (*pargv)[0]; // skip program name
for (i = 1; i < *pargc; i++)
if ((*pargv)[i][0] != '@')
{
pp[j++] = (*pargv)[i]; // it's not an name of a file with arguments, treat it as an argument
}
else
{
FILE* f;
long fsz;
if (!(f = fopen((*pargv)[i] + 1, "rb")))
{
pp[j++] = (*pargv)[i]; // there's no file by this name, treat it as an argument
continue;
}
if ((fsz = fsize(f)) < 0)
{
fclose(f);
errMem();
}
if (fsz > 0)
{
size_t sz;
char* buf;
if ((sz = fsz) == (ulong)fsz &&
sz + 1 > sz &&
(buf = malloc(sz + 1)) != NULL)
{
static const char* const sep = "\f\n\r\t\v ";
char* p;
memset(buf, '\0', sz + 1);
fseek(f, 0, SEEK_SET);
buf[fread(buf, 1, sz, f)] = '\0';
p = strtok(buf, sep);
pcnt--; // don't count the file name as an argument, count only what's inside
while (p)
{
size_t s;
if (++pcnt == INT_MAX ||
(s = (unsigned)pcnt * sizeof(char*)) / sizeof(char*) != (unsigned)pcnt ||
(pp = realloc(pp, s)) == NULL)
{
fclose(f);
errMem();
}
pp[j++] = p;
p = strtok(NULL, sep);
}
}
else
{
fclose(f);
errMem();
}
}
fclose(f);
}
pp[j] = NULL; // there's supposed to be one more NULL pointer argument
*pargc = j;
*pargv = pp;
}
#ifdef SHOW_MEM_USAGE
#ifdef _DOS
void freemem(char* s)
{
void* ap[160+1];
unsigned i;
for (i = 0; i < 160; i++)
if ((ap[i] = malloc(4096)) == NULL)
{
printf("smlrl: free mem (%s): %u\n", s, i * 4096);
ap[i + 1] = NULL;
break;
}
for (i = 0; i < 160; i++)
if (ap[i])
free(ap[i]);
else
break;
}
#endif
#endif
int main(int argc, char* argv[])
{
uint32 ui32 = 0x44434241;
uint16 ui16 = 0x3231;
#ifdef __SMALLER_C__
#ifdef DETERMINE_VA_LIST
DetermineVaListType();
#endif
#endif
if (memcmp(&ui32, "ABCD", sizeof ui32) || memcmp(&ui16, "12", sizeof ui16))
error("Little-endian platform required\n");
#ifdef SHOW_MEM_USAGE
#ifdef _DOS
freemem("start");
#endif
#endif
fatargs(&argc, &argv);
if (argc > 1)
{
int i;
// Check for -verbose before processing other options
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-verbose"))
{
verbose = 1;
break;
}
}
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-verbose"))
{
continue;
}
else if (!strcmp(argv[i], "-o"))
{
if (i + 1 < argc)
{
OutName = argv[++i];
continue;
}
}
else if (!strcmp(argv[i], "-map"))
{
if (i + 1 < argc)
{
MapName = argv[++i];
continue;
}
}
else if (!strcmp(argv[i], "-entry"))
{
if (i + 1 < argc)
{
EntryPoint = argv[++i];
continue;
}
}
else if (!strcmp(argv[i], "-origin"))
{
if (i + 1 < argc)
{
++i;
Origin = strtoul(argv[i], NULL, 0);
continue;
}
}
else if (!strcmp(argv[i], "-stack"))
{
if (i + 1 < argc)
{
++i;
StackSize = strtoul(argv[i], NULL, 0);
continue;
}
}
else if (!strcmp(argv[i], "-minheap"))
{
if (i + 1 < argc)
{
++i;
MinHeap = strtoul(argv[i], NULL, 0);
continue;
}
}
else if (!strcmp(argv[i], "-maxheap"))
{
if (i + 1 < argc)
{
++i;
MaxHeap = strtoul(argv[i], NULL, 0);
continue;
}
}
else if (!strcmp(argv[i], "-nobss"))
{
UseBss = 0;
continue;
}
else if (!strcmp(argv[i], "-tiny"))
{
OutputFormat = FormatDosComTiny;
continue;
}
else if (!strcmp(argv[i], "-small"))
{
OutputFormat = FormatDosExeSmall;
continue;
}
else if (!strcmp(argv[i], "-huge"))
{
OutputFormat = FormatDosExeHuge;
continue;
}
else if (!strcmp(argv[i], "-unreal"))
{
OutputFormat = FormatDosExeUnreal;
continue;
}
else if (StrAnyOf(argv[i], "-pe\0"
"-win\0"))
{
OutputFormat = FormatWinPe32;
continue;
}
else if (!strcmp(argv[i], "-pesubsys")) // primarily for UEFI subsystems
{
if (i + 1 < argc)
{
++i;
PeOptionalHeader.Subsystem = strtoul(argv[i], NULL, 0);
continue;
}
}
else if (!strcmp(argv[i], "-gui"))
{
PeOptionalHeader.Subsystem = 2; // change the default CUI to GUI
continue;
}
else if (!strcmp(argv[i], "-elf"))
{
OutputFormat = FormatElf32;
continue;
}
else if (!strcmp(argv[i], "-mach"))
{
OutputFormat = FormatMach32;
continue;
}
else if (!strcmp(argv[i], "-norel"))
{
NoRelocations = 1;
continue;
}
else if (!strcmp(argv[i], "-flat16"))
{
OutputFormat = FormatFlat16;
continue;
}
else if (!strcmp(argv[i], "-flat32"))
{
OutputFormat = FormatFlat32;
continue;
}
else if (!strcmp(argv[i], "-aout"))
{
OutputFormat = FormatAout;
continue;
}
else if (!strcmp(argv[i], "-stub"))
{
if (i + 1 < argc)
{
StubName = argv[++i];
continue;
}
}
else if (argv[i][0] == '-')
{
// Unknown option
}
else
{
loadMeta(argv[i]);
continue;
}
error("Invalid or unsupported command line option\n");
}
if (!OutputFormat)
error("Output format not specified\n"); // TBD??? switch to a default format when done
FindSymbolByName(EntryPoint);
FindAllSymbols();
CheckDuplicates();
FindAllSections();
RelocateAndWriteAllSections();
GenerateMap();
}
else
error("No inputs\n");
#ifdef SHOW_MEM_USAGE
#ifdef _DOS
freemem("end");
#endif
#endif
return 0;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.