file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/206394435.c | #include <stdio.h>
int mdays[][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} };
int isleap(int year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
int dayofyear(int y, int m, int d) {
int i;
int days = d;
for (i = 1; i < m; i++)
days += mdays[isleap(y)][i - 1];
return days;
}
int main(void) {
int year, month, day;
int retry;
do {
printf("Y: "); scanf_s("%d", &year);
printf("M: "); scanf_s("%d", &month);
printf("D: "); scanf_s("%d", &day);
printf("%d Year %dth days.\n", year, dayofyear(year, month, day));
printf("Retry?(1:Yes, 2:No)>> "); scanf_s("%d", &retry);
} while (retry == 1);
return 0;
} |
the_stack_data/212643894.c | /*-
* Copyright (c) 2008-2011 David Schultz <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/tools/regression/lib/msun/test-ctrig.c,v 1.1 2011/10/21 06:34:38 das Exp $
*/
/*
* Tests for csin[h](), ccos[h](), and ctan[h]().
*/
#include <assert.h>
#include <complex.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#define ALL_STD_EXCEPT (FE_DIVBYZERO | FE_INEXACT | FE_INVALID | \
FE_OVERFLOW | FE_UNDERFLOW)
#define OPT_INVALID (ALL_STD_EXCEPT & ~FE_INVALID)
#define OPT_INEXACT (ALL_STD_EXCEPT & ~FE_INEXACT)
#define FLT_ULP() ldexpl(1.0, 1 - FLT_MANT_DIG)
#define DBL_ULP() ldexpl(1.0, 1 - DBL_MANT_DIG)
#define LDBL_ULP() ldexpl(1.0, 1 - LDBL_MANT_DIG)
#pragma STDC FENV_ACCESS ON
#pragma STDC CX_LIMITED_RANGE OFF
/*
* XXX gcc implements complex multiplication incorrectly. In
* particular, it implements it as if the CX_LIMITED_RANGE pragma
* were ON. Consequently, we need this function to form numbers
* such as x + INFINITY * I, since gcc evalutes INFINITY * I as
* NaN + INFINITY * I.
*/
static inline long double complex
cpackl(long double x, long double y)
{
long double complex z;
__real__ z = x;
__imag__ z = y;
return (z);
}
/* Flags that determine whether to check the signs of the result. */
#define CS_REAL 1
#define CS_IMAG 2
#define CS_BOTH (CS_REAL | CS_IMAG)
#ifdef DEBUG
#define debug(...) printf(__VA_ARGS__)
#else
#define debug(...) (void)0
#endif
/*
* Test that a function returns the correct value and sets the
* exception flags correctly. The exceptmask specifies which
* exceptions we should check. We need to be lenient for several
* reasons, but mainly because on some architectures it's impossible
* to raise FE_OVERFLOW without raising FE_INEXACT.
*
* These are macros instead of functions so that assert provides more
* meaningful error messages.
*
* XXX The volatile here is to avoid gcc's bogus constant folding and work
* around the lack of support for the FENV_ACCESS pragma.
*/
#define test_p(func, z, result, exceptmask, excepts, checksign) do { \
volatile long double complex _d = z; \
debug(" testing %s(%Lg + %Lg I) == %Lg + %Lg I\n", #func, \
creall(_d), cimagl(_d), creall(result), cimagl(result)); \
assert(feclearexcept(FE_ALL_EXCEPT) == 0); \
assert(cfpequal((func)(_d), (result), (checksign))); \
assert(((func), fetestexcept(exceptmask) == (excepts))); \
} while (0)
/*
* Test within a given tolerance. The tolerance indicates relative error
* in ulps. If result is 0, however, it measures absolute error in units
* of <format>_EPSILON.
*/
#define test_p_tol(func, z, result, tol) do { \
volatile long double complex _d = z; \
debug(" testing %s(%Lg + %Lg I) ~= %Lg + %Lg I\n", #func, \
creall(_d), cimagl(_d), creall(result), cimagl(result)); \
assert(cfpequal_tol((func)(_d), (result), (tol))); \
} while (0)
/* These wrappers apply the identities f(conj(z)) = conj(f(z)). */
#define test(func, z, result, exceptmask, excepts, checksign) do { \
test_p(func, z, result, exceptmask, excepts, checksign); \
test_p(func, conjl(z), conjl(result), exceptmask, excepts, checksign); \
} while (0)
#define test_tol(func, z, result, tol) do { \
test_p_tol(func, z, result, tol); \
test_p_tol(func, conjl(z), conjl(result), tol); \
} while (0)
/* Test the given function in all precisions. */
#define testall(func, x, result, exceptmask, excepts, checksign) do { \
test(func, x, result, exceptmask, excepts, checksign); \
test(func##f, x, result, exceptmask, excepts, checksign); \
} while (0)
#define testall_odd(func, x, result, exceptmask, excepts, checksign) do { \
testall(func, x, result, exceptmask, excepts, checksign); \
testall(func, -x, -result, exceptmask, excepts, checksign); \
} while (0)
#define testall_even(func, x, result, exceptmask, excepts, checksign) do { \
testall(func, x, result, exceptmask, excepts, checksign); \
testall(func, -x, result, exceptmask, excepts, checksign); \
} while (0)
/*
* Test the given function in all precisions, within a given tolerance.
* The tolerance is specified in ulps.
*/
#define testall_tol(func, x, result, tol) do { \
test_tol(func, x, result, tol * DBL_ULP()); \
test_tol(func##f, x, result, tol * FLT_ULP()); \
} while (0)
#define testall_odd_tol(func, x, result, tol) do { \
test_tol(func, x, result, tol * DBL_ULP()); \
test_tol(func, -x, -result, tol * DBL_ULP()); \
} while (0)
#define testall_even_tol(func, x, result, tol) do { \
test_tol(func, x, result, tol * DBL_ULP()); \
test_tol(func, -x, result, tol * DBL_ULP()); \
} while (0)
/*
* Determine whether x and y are equal, with two special rules:
* +0.0 != -0.0
* NaN == NaN
* If checksign is 0, we compare the absolute values instead.
*/
static int
fpequal(long double x, long double y, int checksign)
{
if (isnan(x) && isnan(y))
return (1);
if (checksign)
return (x == y && !signbit(x) == !signbit(y));
else
return (fabsl(x) == fabsl(y));
}
static int
fpequal_tol(long double x, long double y, long double tol)
{
fenv_t env;
int ret;
if (isnan(x) && isnan(y))
return (1);
if (!signbit(x) != !signbit(y) && tol == 0)
return (0);
if (x == y)
return (1);
if (tol == 0)
return (0);
/* Hard case: need to check the tolerance. */
feholdexcept(&env);
/*
* For our purposes here, if y=0, we interpret tol as an absolute
* tolerance. This is to account for roundoff in the input, e.g.,
* cos(Pi/2) ~= 0.
*/
if (y == 0.0)
ret = fabsl(x - y) <= fabsl(tol);
else
ret = fabsl(x - y) <= fabsl(y * tol);
fesetenv(&env);
return (ret);
}
static int
cfpequal(long double complex x, long double complex y, int checksign)
{
return (fpequal(creal(x), creal(y), checksign & CS_REAL)
&& fpequal(cimag(x), cimag(y), checksign & CS_IMAG));
}
static int
cfpequal_tol(long double complex x, long double complex y, long double tol)
{
return (fpequal_tol(creal(x), creal(y), tol)
&& fpequal_tol(cimag(x), cimag(y), tol));
}
/* Tests for 0 */
void
test_zero(void)
{
long double complex zero = cpackl(0.0, 0.0);
/* csinh(0) = ctanh(0) = 0; ccosh(0) = 1 (no exceptions raised) */
testall_odd(csinh, zero, zero, ALL_STD_EXCEPT, 0, CS_BOTH);
testall_odd(csin, zero, zero, ALL_STD_EXCEPT, 0, CS_BOTH);
testall_even(ccosh, zero, 1.0, ALL_STD_EXCEPT, 0, CS_BOTH);
testall_even(ccos, zero, cpackl(1.0, -0.0), ALL_STD_EXCEPT, 0, CS_BOTH);
testall_odd(ctanh, zero, zero, ALL_STD_EXCEPT, 0, CS_BOTH);
testall_odd(ctan, zero, zero, ALL_STD_EXCEPT, 0, CS_BOTH);
}
/*
* Tests for NaN inputs.
*/
void
test_nan()
{
long double complex nan_nan = cpackl(NAN, NAN);
long double complex z;
/*
* IN CSINH CCOSH CTANH
* NaN,NaN NaN,NaN NaN,NaN NaN,NaN
* finite,NaN NaN,NaN [inval] NaN,NaN [inval] NaN,NaN [inval]
* NaN,finite NaN,NaN [inval] NaN,NaN [inval] NaN,NaN [inval]
* NaN,Inf NaN,NaN [inval] NaN,NaN [inval] NaN,NaN [inval]
* Inf,NaN +-Inf,NaN Inf,NaN 1,+-0
* 0,NaN +-0,NaN NaN,+-0 NaN,NaN [inval]
* NaN,0 NaN,0 NaN,+-0 NaN,0
*/
z = nan_nan;
testall_odd(csinh, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
testall_even(ccosh, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
testall_odd(ctanh, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
testall_odd(csin, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
testall_even(ccos, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
testall_odd(ctan, z, nan_nan, ALL_STD_EXCEPT, 0, 0);
z = cpackl(42, NAN);
testall_odd(csinh, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccosh, z, nan_nan, OPT_INVALID, 0, 0);
/* XXX We allow a spurious inexact exception here. */
testall_odd(ctanh, z, nan_nan, OPT_INVALID & ~FE_INEXACT, 0, 0);
testall_odd(csin, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccos, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(ctan, z, nan_nan, OPT_INVALID, 0, 0);
z = cpackl(NAN, 42);
testall_odd(csinh, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccosh, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(ctanh, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(csin, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccos, z, nan_nan, OPT_INVALID, 0, 0);
/* XXX We allow a spurious inexact exception here. */
testall_odd(ctan, z, nan_nan, OPT_INVALID & ~FE_INEXACT, 0, 0);
z = cpackl(NAN, INFINITY);
testall_odd(csinh, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccosh, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(ctanh, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(csin, z, cpackl(NAN, INFINITY), ALL_STD_EXCEPT, 0, 0);
testall_even(ccos, z, cpackl(INFINITY, NAN), ALL_STD_EXCEPT, 0,
CS_IMAG);
testall_odd(ctan, z, cpackl(0, 1), ALL_STD_EXCEPT, 0, CS_IMAG);
z = cpackl(INFINITY, NAN);
testall_odd(csinh, z, cpackl(INFINITY, NAN), ALL_STD_EXCEPT, 0, 0);
testall_even(ccosh, z, cpackl(INFINITY, NAN), ALL_STD_EXCEPT, 0,
CS_REAL);
testall_odd(ctanh, z, cpackl(1, 0), ALL_STD_EXCEPT, 0, CS_REAL);
testall_odd(csin, z, nan_nan, OPT_INVALID, 0, 0);
testall_even(ccos, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(ctan, z, nan_nan, OPT_INVALID, 0, 0);
z = cpackl(0, NAN);
testall_odd(csinh, z, cpackl(0, NAN), ALL_STD_EXCEPT, 0, 0);
testall_even(ccosh, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, 0);
testall_odd(ctanh, z, nan_nan, OPT_INVALID, 0, 0);
testall_odd(csin, z, cpackl(0, NAN), ALL_STD_EXCEPT, 0, CS_REAL);
testall_even(ccos, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, 0);
testall_odd(ctan, z, cpackl(0, NAN), ALL_STD_EXCEPT, 0, CS_REAL);
z = cpackl(NAN, 0);
testall_odd(csinh, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, CS_IMAG);
testall_even(ccosh, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, 0);
testall_odd(ctanh, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, CS_IMAG);
testall_odd(csin, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, 0);
testall_even(ccos, z, cpackl(NAN, 0), ALL_STD_EXCEPT, 0, 0);
testall_odd(ctan, z, nan_nan, OPT_INVALID, 0, 0);
}
void
test_inf(void)
{
static const long double finites[] = {
0, M_PI / 4, 3 * M_PI / 4, 5 * M_PI / 4,
};
long double complex z, c, s;
int i;
/*
* IN CSINH CCOSH CTANH
* Inf,Inf +-Inf,NaN inval +-Inf,NaN inval 1,+-0
* Inf,finite Inf cis(finite) Inf cis(finite) 1,0 sin(2 finite)
* 0,Inf +-0,NaN inval NaN,+-0 inval NaN,NaN inval
* finite,Inf NaN,NaN inval NaN,NaN inval NaN,NaN inval
*/
z = cpackl(INFINITY, INFINITY);
testall_odd(csinh, z, cpackl(INFINITY, NAN),
ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccosh, z, cpackl(INFINITY, NAN),
ALL_STD_EXCEPT, FE_INVALID, 0);
testall_odd(ctanh, z, cpackl(1, 0), ALL_STD_EXCEPT, 0, CS_REAL);
testall_odd(csin, z, cpackl(NAN, INFINITY),
ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccos, z, cpackl(INFINITY, NAN),
ALL_STD_EXCEPT, FE_INVALID, 0);
testall_odd(ctan, z, cpackl(0, 1), ALL_STD_EXCEPT, 0, CS_REAL);
/* XXX We allow spurious inexact exceptions here (hard to avoid). */
for (i = 0; i < sizeof(finites) / sizeof(finites[0]); i++) {
z = cpackl(INFINITY, finites[i]);
c = INFINITY * cosl(finites[i]);
s = finites[i] == 0 ? finites[i] : INFINITY * sinl(finites[i]);
testall_odd(csinh, z, cpackl(c, s), OPT_INEXACT, 0, CS_BOTH);
testall_even(ccosh, z, cpackl(c, s), OPT_INEXACT, 0, CS_BOTH);
testall_odd(ctanh, z, cpackl(1, 0 * sin(finites[i] * 2)),
OPT_INEXACT, 0, CS_BOTH);
z = cpackl(finites[i], INFINITY);
testall_odd(csin, z, cpackl(s, c), OPT_INEXACT, 0, CS_BOTH);
testall_even(ccos, z, cpackl(c, -s), OPT_INEXACT, 0, CS_BOTH);
testall_odd(ctan, z, cpackl(0 * sin(finites[i] * 2), 1),
OPT_INEXACT, 0, CS_BOTH);
}
z = cpackl(0, INFINITY);
testall_odd(csinh, z, cpackl(0, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccosh, z, cpackl(NAN, 0), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_odd(ctanh, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
z = cpackl(INFINITY, 0);
testall_odd(csin, z, cpackl(NAN, 0), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccos, z, cpackl(NAN, 0), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_odd(ctan, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
z = cpackl(42, INFINITY);
testall_odd(csinh, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccosh, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
/* XXX We allow a spurious inexact exception here. */
testall_odd(ctanh, z, cpackl(NAN, NAN), OPT_INEXACT, FE_INVALID, 0);
z = cpackl(INFINITY, 42);
testall_odd(csin, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
testall_even(ccos, z, cpackl(NAN, NAN), ALL_STD_EXCEPT, FE_INVALID, 0);
/* XXX We allow a spurious inexact exception here. */
testall_odd(ctan, z, cpackl(NAN, NAN), OPT_INEXACT, FE_INVALID, 0);
}
/* Tests along the real and imaginary axes. */
void
test_axes(void)
{
static const long double nums[] = {
M_PI / 4, M_PI / 2, 3 * M_PI / 4,
5 * M_PI / 4, 3 * M_PI / 2, 7 * M_PI / 4,
};
long double complex z;
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
/* Real axis */
z = cpackl(nums[i], 0.0);
testall_odd_tol(csinh, z, cpackl(sinh(nums[i]), 0), 0);
testall_even_tol(ccosh, z, cpackl(cosh(nums[i]), 0), 0);
testall_odd_tol(ctanh, z, cpackl(tanh(nums[i]), 0), 1);
testall_odd_tol(csin, z, cpackl(sin(nums[i]),
copysign(0, cos(nums[i]))), 0);
testall_even_tol(ccos, z, cpackl(cos(nums[i]),
-copysign(0, sin(nums[i]))), 0);
testall_odd_tol(ctan, z, cpackl(tan(nums[i]), 0), 1);
/* Imaginary axis */
z = cpackl(0.0, nums[i]);
testall_odd_tol(csinh, z, cpackl(copysign(0, cos(nums[i])),
sin(nums[i])), 0);
testall_even_tol(ccosh, z, cpackl(cos(nums[i]),
copysign(0, sin(nums[i]))), 0);
testall_odd_tol(ctanh, z, cpackl(0, tan(nums[i])), 1);
testall_odd_tol(csin, z, cpackl(0, sinh(nums[i])), 0);
testall_even_tol(ccos, z, cpackl(cosh(nums[i]), -0.0), 0);
testall_odd_tol(ctan, z, cpackl(0, tanh(nums[i])), 1);
}
}
void
test_small(void)
{
/*
* z = 0.5 + i Pi/4
* sinh(z) = (sinh(0.5) + i cosh(0.5)) * sqrt(2)/2
* cosh(z) = (cosh(0.5) + i sinh(0.5)) * sqrt(2)/2
* tanh(z) = (2cosh(0.5)sinh(0.5) + i) / (2 cosh(0.5)**2 - 1)
* z = -0.5 + i Pi/2
* sinh(z) = cosh(0.5)
* cosh(z) = -i sinh(0.5)
* tanh(z) = -coth(0.5)
* z = 1.0 + i 3Pi/4
* sinh(z) = (-sinh(1) + i cosh(1)) * sqrt(2)/2
* cosh(z) = (-cosh(1) + i sinh(1)) * sqrt(2)/2
* tanh(z) = (2cosh(1)sinh(1) - i) / (2cosh(1)**2 - 1)
*/
static const struct {
long double a, b;
long double sinh_a, sinh_b;
long double cosh_a, cosh_b;
long double tanh_a, tanh_b;
} tests[] = {
{ 0.5L,
0.78539816339744830961566084581987572L,
0.36847002415910435172083660522240710L,
0.79735196663945774996093142586179334L,
0.79735196663945774996093142586179334L,
0.36847002415910435172083660522240710L,
0.76159415595576488811945828260479359L,
0.64805427366388539957497735322615032L },
{ -0.5L,
1.57079632679489661923132169163975144L,
0.0L,
1.12762596520638078522622516140267201L,
0.0L,
-0.52109530549374736162242562641149156L,
-2.16395341373865284877000401021802312L,
0.0L },
{ 1.0L,
2.35619449019234492884698253745962716L,
-0.83099273328405698212637979852748608L,
1.09112278079550143030545602018565236L,
-1.09112278079550143030545602018565236L,
0.83099273328405698212637979852748609L,
0.96402758007581688394641372410092315L,
-0.26580222883407969212086273981988897L }
};
long double complex z;
int i;
for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
z = cpackl(tests[i].a, tests[i].b);
testall_odd_tol(csinh, z,
cpackl(tests[i].sinh_a, tests[i].sinh_b), 1.1);
testall_even_tol(ccosh, z,
cpackl(tests[i].cosh_a, tests[i].cosh_b), 1.1);
testall_odd_tol(ctanh, z,
cpackl(tests[i].tanh_a, tests[i].tanh_b), 1.1);
}
}
/* Test inputs that might cause overflow in a sloppy implementation. */
void
test_large(void)
{
long double complex z;
/* tanh() uses a threshold around x=22, so check both sides. */
z = cpackl(21, 0.78539816339744830961566084581987572L);
testall_odd_tol(ctanh, z,
cpackl(1.0, 1.14990445285871196133287617611468468e-18L), 1);
z++;
testall_odd_tol(ctanh, z,
cpackl(1.0, 1.55622644822675930314266334585597964e-19L), 1);
z = cpackl(355, 0.78539816339744830961566084581987572L);
testall_odd_tol(ctanh, z,
cpackl(1.0, 8.95257245135025991216632140458264468e-309L), 1);
z = cpackl(30, 0x1p1023L);
testall_odd_tol(ctanh, z,
cpackl(1.0, -1.62994325413993477997492170229268382e-26L), 1);
z = cpackl(1, 0x1p1023L);
testall_odd_tol(ctanh, z,
cpackl(0.878606311888306869546254022621986509L,
-0.225462792499754505792678258169527424L), 1);
z = cpackl(710.6, 0.78539816339744830961566084581987572L);
testall_odd_tol(csinh, z,
cpackl(1.43917579766621073533185387499658944e308L,
1.43917579766621073533185387499658944e308L), 1);
testall_even_tol(ccosh, z,
cpackl(1.43917579766621073533185387499658944e308L,
1.43917579766621073533185387499658944e308L), 1);
z = cpackl(1500, 0.78539816339744830961566084581987572L);
testall_odd(csinh, z, cpackl(INFINITY, INFINITY), OPT_INEXACT,
FE_OVERFLOW, CS_BOTH);
testall_even(ccosh, z, cpackl(INFINITY, INFINITY), OPT_INEXACT,
FE_OVERFLOW, CS_BOTH);
}
int
main(int argc, char *argv[])
{
printf("1..6\n");
test_zero();
printf("ok 1 - ctrig zero\n");
test_nan();
printf("ok 2 - ctrig nan\n");
test_inf();
printf("ok 3 - ctrig inf\n");
test_axes();
printf("ok 4 - ctrig axes\n");
test_small();
printf("ok 5 - ctrig small\n");
test_large();
printf("ok 6 - ctrig large\n");
return (0);
}
|
the_stack_data/1249772.c | // Fig. 4.5: fig04_05.c
// Summation with for
#include <stdio.h>
int main(void)
{
unsigned int sum = 0; // initialize sum
for (unsigned int number = 2; number <= 100; number += 2) {
sum += number; // add number to sum
}
printf("Sum is %u\n", sum);
}
/**************************************************************************
* (C) Copyright 1992-2015 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/ |
the_stack_data/167331764.c | #include <stdio.h>
int list[] = {5,2,4,6,1,3};
int size = 6;
void insertion_sort(int * list, int size){
for(int j = 1; j < size; j++){
int item = list[j];
int i = j - 1;
while(i >= 0 && list[i] > item){
list[i + 1] = list[i];
i = i - 1;
}
list[i+1] = item;
}
return;
}
int main(){
insertion_sort(list,size);
for(int i = 0; i < size; i++){
printf("%d ",list[i]);
}
return 0;
} |
the_stack_data/9574.c | #include<stdio.h>
#include<malloc.h>
#define IGNORE while((getchar() != '\n') && !feof(stdin))
int sort(int* array,int len);
void display_all(int* array, int len);
void insert(int **array, int len, int shit);
int main()
{
int * array = NULL;
char reply= '\0';
int number = 0;
int count = 0;
do{
printf("Enter number: ");
scanf("%d", &number);
IGNORE;
insert(&array, count, number);
++count;
printf("Do you want to add another number? y/n: ");
scanf("%c",&reply);
IGNORE;
printf("\n");
}while(reply == 'y');
display_all(array,count);
sort(array,count);
display_all(array, count);
return 0;
}
void insert(int **array, int len, int shit)
{
int * temp = (int*) malloc(sizeof(int)*(len+1));
int i = 0;
for(i = 0; i < len; ++i)
temp[i] = (*array)[i];
temp[len] = shit;
free(*array);
*array = temp;
}
void display_all(int* array, int len)
{
int i = 0;
for(i = 0; i < len; ++i)
printf("Index %d: %d\n",i,array[i]);
printf("\n");
}
|
the_stack_data/130808.c | #ifdef STM32F2xx
#include "stm32f2xx_hal_cryp.c"
#endif
#ifdef STM32F4xx
#include "stm32f4xx_hal_cryp.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_cryp.c"
#endif
#ifdef STM32G0xx
#include "stm32g0xx_hal_cryp.c"
#endif
#ifdef STM32G4xx
#include "stm32g4xx_hal_cryp.c"
#endif
#ifdef STM32H7xx
#include "stm32h7xx_hal_cryp.c"
#endif
#ifdef STM32L0xx
#include "stm32l0xx_hal_cryp.c"
#endif
#ifdef STM32L1xx
#include "stm32l1xx_hal_cryp.c"
#endif
#ifdef STM32L4xx
#include "stm32l4xx_hal_cryp.c"
#endif
#ifdef STM32MP1xx
#include "stm32mp1xx_hal_cryp.c"
#endif
#ifdef STM32WBxx
#include "stm32wbxx_hal_cryp.c"
#endif
|
the_stack_data/51473.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char *value; // must use dynamic allocation
struct node *next;
} node_t;
node_t *construct_3_strs()
{
node_t *x;
node_t *y;
node_t *z;
x = malloc(sizeof(node_t));
y = malloc(sizeof(node_t));
z = malloc(sizeof(node_t));
x->value = malloc(sizeof(node_t));
y->value = malloc(sizeof(node_t));
z->value = malloc(sizeof(node_t));
x->value = "CS232";
y->value = "is";
z->value = "awesome";
x->next = y;
y->next = z;
z->next = x;
return x; // just to pass compiler, please edit as needed.
}
// You can ignore the following code for testing
int dump_all(node_t *);
int main(int argc, char **argv)
{
node_t *x = construct_3_strs();
return dump_all(x);
}
int dump_all(node_t *x)
{
printf("x -> %s", x->value);
node_t *y = x->next;
printf(" %s", y->value);
node_t *z = y->next;
printf(" %s\n", z->value);
if (z->next != x)
{
printf("failed");
return -1;
}
else
{
return 0;
}
}
|
the_stack_data/7949944.c | #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main()
{
int shmid = shmget(IPC_PRIVATE, 100 * 4096,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
assert(shmid != -1);
void *addr = shmat(shmid, NULL, 0);
assert(addr != (void *)-1);
addr = mremap(addr, 100 * 4096, 400 * 4096, MREMAP_MAYMOVE);
assert(addr != (void *)-1);
return 0;
}
|
the_stack_data/76335.c | /* { dg-additional-options "-fipa-pta" } */
#include <stdlib.h>
#define N 2
int
main (void)
{
unsigned int *a = (unsigned int *)malloc (N * sizeof (unsigned int));
unsigned int *b = (unsigned int *)malloc (N * sizeof (unsigned int));
unsigned int *c = (unsigned int *)malloc (N * sizeof (unsigned int));
#pragma acc kernels pcopyout (a[0:N], b[0:N], c[0:N])
{
a[0] = 0;
b[0] = 1;
c[0] = a[0];
}
if (a[0] != 0 || b[0] != 1 || c[0] != 0)
abort ();
free (a);
free (b);
free (c);
}
|
the_stack_data/170452396.c | // Ogg Vorbis audio decoder - v1.22 - public domain
// http://nothings.org/stb_vorbis/
//
// Original version written by Sean Barrett in 2007.
//
// Originally sponsored by RAD Game Tools. Seeking implementation
// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
// Elias Software, Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
// See end of file for license information.
//
// Limitations:
//
// - floor 0 not supported (used in old ogg vorbis files pre-2004)
// - lossless sample-truncation at beginning ignored
// - cannot concatenate multiple vorbis streams
// - sample positions are 32-bit, limiting seekable 192Khz
// files to around 6 hours (Ogg supports 64-bit)
//
// Feature contributors:
// Dougall Johnson (sample-exact seeking)
//
// Bugfix/warning contributors:
// Terje Mathisen Niklas Frykholm Andy Hill
// Casey Muratori John Bolton Gargaj
// Laurent Gomila Marc LeBlanc Ronny Chevalier
// Bernhard Wodo Evan Balster github:alxprd
// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
// Phillip Bennefall Rohit Thiago Goulart
// github:manxorist Saga Musix github:infatum
// Timur Gagiev Maxwell Koo Peter Waller
// github:audinowho Dougall Johnson David Reid
// github:Clownacy Pedro J. Estebanez Remi Verschelde
// AnthoFoxo github:morlat Gabriel Ravier
//
// Partial history:
// 1.22 - 2021-07-11 - various small fixes
// 1.21 - 2021-07-02 - fix bug for files with no comments
// 1.20 - 2020-07-11 - several small fixes
// 1.19 - 2020-02-05 - warnings
// 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc.
// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)
// 1.16 - 2019-03-04 - fix warnings
// 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
// 1.14 - 2018-02-11 - delete bogus dealloca usage
// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
// 1.11 - 2017-07-23 - fix MinGW compilation
// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version
// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame
// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const
// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
// some crash fixes when out of memory or with corrupt files
// fix some inappropriately signed shifts
// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
// 1.04 - 2014-08-27 - fix missing const-correct case in API
// 1.03 - 2014-08-07 - warning fixes
// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows
// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)
// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
// (API change) report sample rate for decode-full-file funcs
//
// See end of file for full version history.
//////////////////////////////////////////////////////////////////////////////
//
// HEADER BEGINS HERE
//
#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define STB_VORBIS_INCLUDE_STB_VORBIS_H
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/////////// THREAD SAFETY
// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
// them from multiple threads at the same time. However, you can have multiple
// stb_vorbis* handles and decode from them independently in multiple thrads.
/////////// MEMORY ALLOCATION
// normally stb_vorbis uses malloc() to allocate memory at startup,
// and alloca() to allocate temporary memory during a frame on the
// stack. (Memory consumption will depend on the amount of setup
// data in the file and how you set the compile flags for speed
// vs. size. In my test files the maximal-size usage is ~150KB.)
//
// You can modify the wrapper functions in the source (setup_malloc,
// setup_temp_malloc, temp_malloc) to change this behavior, or you
// can use a simpler allocation model: you pass in a buffer from
// which stb_vorbis will allocate _all_ its memory (including the
// temp memory). "open" may fail with a VORBIS_outofmem if you
// do not pass in enough data; there is no way to determine how
// much you do need except to succeed (at which point you can
// query get_info to find the exact amount required. yes I know
// this is lame).
//
// If you pass in a non-NULL buffer of the type below, allocation
// will occur from it as described above. Otherwise just pass NULL
// to use malloc()/alloca()
typedef struct
{
char *alloc_buffer;
int alloc_buffer_length_in_bytes;
} stb_vorbis_alloc;
/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
typedef struct stb_vorbis stb_vorbis;
typedef struct
{
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int setup_temp_memory_required;
unsigned int temp_memory_required;
int max_frame_size;
} stb_vorbis_info;
typedef struct
{
char *vendor;
int comment_list_length;
char **comment_list;
} stb_vorbis_comment;
// get general information about the file
extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
// get ogg comments
extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);
// get the last error detected (clears it, too)
extern int stb_vorbis_get_error(stb_vorbis *f);
// close an ogg vorbis file and free all memory in use
extern void stb_vorbis_close(stb_vorbis *f);
// this function returns the offset (in samples) from the beginning of the
// file that will be returned by the next decode, if it is known, or -1
// otherwise. after a flush_pushdata() call, this may take a while before
// it becomes valid again.
// NOT WORKING YET after a seek with PULLDATA API
extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
// returns the current seek point within the file, or offset from the beginning
// of the memory buffer. In pushdata mode it returns 0.
extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
/////////// PUSHDATA API
#ifndef STB_VORBIS_NO_PUSHDATA_API
// this API allows you to get blocks of data from any source and hand
// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
// you how much it used, and you have to give it the rest next time;
// and stb_vorbis may not have enough data to work with and you will
// need to give it the same data again PLUS more. Note that the Vorbis
// specification does not bound the size of an individual frame.
extern stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char * datablock, int datablock_length_in_bytes,
int *datablock_memory_consumed_in_bytes,
int *error,
const stb_vorbis_alloc *alloc_buffer);
// create a vorbis decoder by passing in the initial data block containing
// the ogg&vorbis headers (you don't need to do parse them, just provide
// the first N bytes of the file--you're told if it's not enough, see below)
// on success, returns an stb_vorbis *, does not set error, returns the amount of
// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
// if returns NULL and *error is VORBIS_need_more_data, then the input block was
// incomplete and you need to pass in a larger block from the start of the file
extern int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f,
const unsigned char *datablock, int datablock_length_in_bytes,
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
);
// decode a frame of audio sample data if possible from the passed-in data block
//
// return value: number of bytes we used from datablock
//
// possible cases:
// 0 bytes used, 0 samples output (need more data)
// N bytes used, 0 samples output (resynching the stream, keep going)
// N bytes used, M samples output (one frame of data)
// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
// frame, because Vorbis always "discards" the first frame.
//
// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
// instead only datablock_length_in_bytes-3 or less. This is because it wants
// to avoid missing parts of a page header if they cross a datablock boundary,
// without writing state-machiney code to record a partial detection.
//
// The number of channels returned are stored in *channels (which can be
// NULL--it is always the same as the number of channels reported by
// get_info). *output will contain an array of float* buffers, one per
// channel. In other words, (*output)[0][0] contains the first sample from
// the first channel, and (*output)[1][0] contains the first sample from
// the second channel.
//
// *output points into stb_vorbis's internal output buffer storage; these
// buffers are owned by stb_vorbis and application code should not free
// them or modify their contents. They are transient and will be overwritten
// once you ask for more data to get decoded, so be sure to grab any data
// you need before then.
extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
// inform stb_vorbis that your next datablock will not be contiguous with
// previous ones (e.g. you've seeked in the data); future attempts to decode
// frames will cause stb_vorbis to resynchronize (as noted above), and
// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
// will begin decoding the _next_ frame.
//
// if you want to seek using pushdata, you need to seek in your file, then
// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
// decoding is returning you data, call stb_vorbis_get_sample_offset, and
// if you don't like the result, seek your file again and repeat.
#endif
////////// PULLING INPUT API
#ifndef STB_VORBIS_NO_PULLDATA_API
// This API assumes stb_vorbis is allowed to pull data from a source--
// either a block of memory containing the _entire_ vorbis stream, or a
// FILE * that you or it create, or possibly some other reading mechanism
// if you go modify the source to replace the FILE * case with some kind
// of callback to your code. (But if you don't support seeking, you may
// just want to go ahead and use pushdata.)
#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
#endif
#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
#endif
// decode an entire file and output the data interleaved into a malloc()ed
// buffer stored in *output. The return value is the number of samples
// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
// When you're done with it, just free() the pointer returned in *output.
extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
// this must be the entire stream!). on failure, returns NULL and sets *error
#ifndef STB_VORBIS_NO_STDIO
extern stb_vorbis * stb_vorbis_open_filename(const char *filename,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from a filename via fopen(). on failure,
// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
// note that stb_vorbis must "own" this stream; if you seek it in between
// calls to stb_vorbis, it will become confused. Moreover, if you attempt to
// perform stb_vorbis_seek_*() operations on this file, it will assume it
// owns the _entire_ rest of the file after the start point. Use the next
// function, stb_vorbis_open_file_section(), to limit it.
extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
// this stream; if you seek it in between calls to stb_vorbis, it will become
// confused.
#endif
extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
// these functions seek in the Vorbis file to (approximately) 'sample_number'.
// after calling seek_frame(), the next call to get_frame_*() will include
// the specified sample. after calling stb_vorbis_seek(), the next call to
// stb_vorbis_get_samples_* will start with the specified sample. If you
// do not need to seek to EXACTLY the target sample when using get_samples_*,
// you can also use seek_frame().
extern int stb_vorbis_seek_start(stb_vorbis *f);
// this function is equivalent to stb_vorbis_seek(f,0)
extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
// these functions return the total length of the vorbis stream
extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
// decode the next frame and return the number of samples. the number of
// channels returned are stored in *channels (which can be NULL--it is always
// the same as the number of channels reported by get_info). *output will
// contain an array of float* buffers, one per channel. These outputs will
// be overwritten on the next call to stb_vorbis_get_frame_*.
//
// You generally should not intermix calls to stb_vorbis_get_frame_*()
// and stb_vorbis_get_samples_*(), since the latter calls the former.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
#endif
// decode the next frame and return the number of *samples* per channel.
// Note that for interleaved data, you pass in the number of shorts (the
// size of your array), but the return value is the number of samples per
// channel, not the total number of samples.
//
// The data is coerced to the number of channels you request according to the
// channel coercion rules (see below). You must pass in the size of your
// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
// The maximum buffer size needed can be gotten from get_info(); however,
// the Vorbis I specification implies an absolute maximum of 4096 samples
// per channel.
// Channel coercion rules:
// Let M be the number of channels requested, and N the number of channels present,
// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
// and stereo R be the sum of all R and center channels (channel assignment from the
// vorbis spec).
// M N output
// 1 k sum(Ck) for all k
// 2 * stereo L, stereo R
// k l k > l, the first l channels, then 0s
// k l k <= l, the first k channels
// Note that this is not _good_ surround etc. mixing at all! It's just so
// you get something useful.
extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
// Returns the number of samples stored per channel; it may be less than requested
// at the end of the file. If there are no more samples in the file, returns 0.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
#endif
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. Applies the coercion rules above
// to produce 'channels' channels. Returns the number of samples stored per channel;
// it may be less than requested at the end of the file. If there are no more
// samples in the file, returns 0.
#endif
//////// ERROR CODES
enum STBVorbisError
{
VORBIS__no_error,
VORBIS_need_more_data=1, // not a real error
VORBIS_invalid_api_mixing, // can't mix API modes
VORBIS_outofmem, // not enough memory
VORBIS_feature_not_supported, // uses floor 0
VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
VORBIS_file_open_failure, // fopen() failed
VORBIS_seek_without_length, // can't seek in unknown-length file
VORBIS_unexpected_eof=10, // file is truncated?
VORBIS_seek_invalid, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
VORBIS_invalid_setup=20,
VORBIS_invalid_stream,
// ogg errors:
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version,
VORBIS_continued_packet_flag_invalid,
VORBIS_incorrect_stream_serial_number,
VORBIS_invalid_first_page,
VORBIS_bad_packet_type,
VORBIS_cant_find_last_page,
VORBIS_seek_failed,
VORBIS_ogg_skeleton_not_supported
};
#ifdef __cplusplus
}
#endif
#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
//
// HEADER ENDS HERE
//
//////////////////////////////////////////////////////////////////////////////
#ifndef STB_VORBIS_HEADER_ONLY
// global configuration settings (e.g. set these in the project/makefile),
// or just set them in this file at the top (although ideally the first few
// should be visible when the header file is compiled too, although it's not
// crucial)
// STB_VORBIS_NO_PUSHDATA_API
// does not compile the code for the various stb_vorbis_*_pushdata()
// functions
// #define STB_VORBIS_NO_PUSHDATA_API
// STB_VORBIS_NO_PULLDATA_API
// does not compile the code for the non-pushdata APIs
// #define STB_VORBIS_NO_PULLDATA_API
// STB_VORBIS_NO_STDIO
// does not compile the code for the APIs that use FILE *s internally
// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_STDIO
// STB_VORBIS_NO_INTEGER_CONVERSION
// does not compile the code for converting audio sample data from
// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_INTEGER_CONVERSION
// STB_VORBIS_NO_FAST_SCALED_FLOAT
// does not use a fast float-to-int trick to accelerate float-to-int on
// most platforms which requires endianness be defined correctly.
//#define STB_VORBIS_NO_FAST_SCALED_FLOAT
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
#ifndef STB_VORBIS_MAX_CHANNELS
#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
#endif
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
#endif
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
#endif
// STB_VORBIS_FAST_BINARY_LENGTH [number]
// sets the log size of the binary-search acceleration table. this
// is used in similar fashion to the fast-huffman size to set initial
// parameters for the binary search
// STB_VORBIS_FAST_HUFFMAN_INT
// The fast huffman tables are much more efficient if they can be
// stored as 16-bit results instead of 32-bit results. This restricts
// the codebooks to having only 65535 possible outcomes, though.
// (At least, accelerated by the huffman table.)
#ifndef STB_VORBIS_FAST_HUFFMAN_INT
#define STB_VORBIS_FAST_HUFFMAN_SHORT
#endif
// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
// back on binary searching for the correct one. This requires storing
// extra tables with the huffman codes in sorted order. Defining this
// symbol trades off space for speed by forcing a linear search in the
// non-fast case, except for "sparse" codebooks.
// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// STB_VORBIS_DIVIDES_IN_RESIDUE
// stb_vorbis precomputes the result of the scalar residue decoding
// that would otherwise require a divide per chunk. you can trade off
// space for time by defining this symbol.
// #define STB_VORBIS_DIVIDES_IN_RESIDUE
// STB_VORBIS_DIVIDES_IN_CODEBOOK
// vorbis VQ codebooks can be encoded two ways: with every case explicitly
// stored, or with all elements being chosen from a small range of values,
// and all values possible in all elements. By default, stb_vorbis expands
// this latter kind out to look like the former kind for ease of decoding,
// because otherwise an integer divide-per-vector-element is required to
// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
// trade off storage for speed.
//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
#ifdef STB_VORBIS_CODEBOOK_SHORTS
#error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
#endif
// STB_VORBIS_DIVIDE_TABLE
// this replaces small integer divides in the floor decode loop with
// table lookups. made less than 1% difference, so disabled by default.
// STB_VORBIS_NO_INLINE_DECODE
// disables the inlining of the scalar codebook fast-huffman decode.
// might save a little codespace; useful for debugging
// #define STB_VORBIS_NO_INLINE_DECODE
// STB_VORBIS_NO_DEFER_FLOOR
// Normally we only decode the floor without synthesizing the actual
// full curve. We can instead synthesize the curve immediately. This
// requires more memory and is very likely slower, so I don't think
// you'd ever want to do it except for debugging.
// #define STB_VORBIS_NO_DEFER_FLOOR
//////////////////////////////////////////////////////////////////////////////
#ifdef STB_VORBIS_NO_PULLDATA_API
#define STB_VORBIS_NO_INTEGER_CONVERSION
#define STB_VORBIS_NO_STDIO
#endif
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
// only need endianness for fast-float-to-int, which we don't
// use for pushdata
#ifndef STB_VORBIS_BIG_ENDIAN
#define STB_VORBIS_ENDIAN 0
#else
#define STB_VORBIS_ENDIAN 1
#endif
#endif
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifndef STB_VORBIS_NO_CRT
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
// find definition of alloca if it's not in stdlib.h:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if defined(__linux__) || defined(__linux) || defined(__sun__) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)
#include <alloca.h>
#endif
#else // STB_VORBIS_NO_CRT
#define NULL 0
#define malloc(s) 0
#define free(s) ((void) 0)
#define realloc(s) 0
#endif // STB_VORBIS_NO_CRT
#include <limits.h>
#ifdef __MINGW32__
// eff you mingw:
// "fixed":
// http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
// "no that broke the build, reverted, who cares about C":
// http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
#ifdef __forceinline
#undef __forceinline
#endif
#define __forceinline
#ifndef alloca
#define alloca __builtin_alloca
#endif
#elif !defined(_MSC_VER)
#if __GNUC__
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
#if STB_VORBIS_MAX_CHANNELS > 256
#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
#endif
#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
#endif
#if 0
#include <crtdbg.h>
#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
#else
#define CHECK(f) ((void) 0)
#endif
#define MAX_BLOCKSIZE_LOG 13 // from specification
#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
typedef float codetype;
#ifdef _MSC_VER
#define STBV_NOTUSED(v) (void)(v)
#else
#define STBV_NOTUSED(v) (void)sizeof(v)
#endif
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
typedef struct
{
int dimensions, entries;
uint8 *codeword_lengths;
float minimum_value;
float delta_value;
uint8 value_bits;
uint8 lookup_type;
uint8 sequence_p;
uint8 sparse;
uint32 lookup_values;
codetype *multiplicands;
uint32 *codewords;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#else
int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#endif
uint32 *sorted_codewords;
int *sorted_values;
int sorted_entries;
} Codebook;
typedef struct
{
uint8 order;
uint16 rate;
uint16 bark_map_size;
uint8 amplitude_bits;
uint8 amplitude_offset;
uint8 number_of_books;
uint8 book_list[16]; // varies
} Floor0;
typedef struct
{
uint8 partitions;
uint8 partition_class_list[32]; // varies
uint8 class_dimensions[16]; // varies
uint8 class_subclasses[16]; // varies
uint8 class_masterbooks[16]; // varies
int16 subclass_books[16][8]; // varies
uint16 Xlist[31*8+2]; // varies
uint8 sorted_order[31*8+2];
uint8 neighbors[31*8+2][2];
uint8 floor1_multiplier;
uint8 rangebits;
int values;
} Floor1;
typedef union
{
Floor0 floor0;
Floor1 floor1;
} Floor;
typedef struct
{
uint32 begin, end;
uint32 part_size;
uint8 classifications;
uint8 classbook;
uint8 **classdata;
int16 (*residue_books)[8];
} Residue;
typedef struct
{
uint8 magnitude;
uint8 angle;
uint8 mux;
} MappingChannel;
typedef struct
{
uint16 coupling_steps;
MappingChannel *chan;
uint8 submaps;
uint8 submap_floor[15]; // varies
uint8 submap_residue[15]; // varies
} Mapping;
typedef struct
{
uint8 blockflag;
uint8 mapping;
uint16 windowtype;
uint16 transformtype;
} Mode;
typedef struct
{
uint32 goal_crc; // expected crc if match
int bytes_left; // bytes left in packet
uint32 crc_so_far; // running crc
int bytes_done; // bytes processed in _current_ chunk
uint32 sample_loc; // granule pos encoded in page
} CRCscan;
typedef struct
{
uint32 page_start, page_end;
uint32 last_decoded_sample;
} ProbedPage;
struct stb_vorbis
{
// user-accessible info
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int temp_memory_required;
unsigned int setup_temp_memory_required;
char *vendor;
int comment_list_length;
char **comment_list;
// input config
#ifndef STB_VORBIS_NO_STDIO
FILE *f;
uint32 f_start;
int close_on_free;
#endif
uint8 *stream;
uint8 *stream_start;
uint8 *stream_end;
uint32 stream_len;
uint8 push_mode;
// the page to seek to when seeking to start, may be zero
uint32 first_audio_page_offset;
// p_first is the page on which the first audio packet ends
// (but not necessarily the page on which it starts)
ProbedPage p_first, p_last;
// memory management
stb_vorbis_alloc alloc;
int setup_offset;
int temp_offset;
// run-time results
int eof;
enum STBVorbisError error;
// user-useful data
// header info
int blocksize[2];
int blocksize_0, blocksize_1;
int codebook_count;
Codebook *codebooks;
int floor_count;
uint16 floor_types[64]; // varies
Floor *floor_config;
int residue_count;
uint16 residue_types[64]; // varies
Residue *residue_config;
int mapping_count;
Mapping *mapping;
int mode_count;
Mode mode_config[64]; // varies
uint32 total_samples;
// decode buffer
float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
float *outputs [STB_VORBIS_MAX_CHANNELS];
float *previous_window[STB_VORBIS_MAX_CHANNELS];
int previous_length;
#ifndef STB_VORBIS_NO_DEFER_FLOOR
int16 *finalY[STB_VORBIS_MAX_CHANNELS];
#else
float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
#endif
uint32 current_loc; // sample location of next frame to decode
int current_loc_valid;
// per-blocksize precomputed data
// twiddle factors
float *A[2],*B[2],*C[2];
float *window[2];
uint16 *bit_reverse[2];
// current page/packet/segment streaming info
uint32 serial; // stream serial number for verification
int last_page;
int segment_count;
uint8 segments[255];
uint8 page_flag;
uint8 bytes_in_seg;
uint8 first_decode;
int next_seg;
int last_seg; // flag that we're on the last segment
int last_seg_which; // what was the segment number of the last seg?
uint32 acc;
int valid_bits;
int packet_bytes;
int end_seg_with_known_loc;
uint32 known_loc_for_packet;
int discard_samples_deferred;
uint32 samples_output;
// push mode scanning
int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
#ifndef STB_VORBIS_NO_PUSHDATA_API
CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
#endif
// sample-access
int channel_buffer_start;
int channel_buffer_end;
};
#if defined(STB_VORBIS_NO_PUSHDATA_API)
#define IS_PUSH_MODE(f) FALSE
#elif defined(STB_VORBIS_NO_PULLDATA_API)
#define IS_PUSH_MODE(f) TRUE
#else
#define IS_PUSH_MODE(f) ((f)->push_mode)
#endif
typedef struct stb_vorbis vorb;
static int error(vorb *f, enum STBVorbisError e)
{
f->error = e;
if (!f->eof && e != VORBIS_need_more_data) {
f->error=e; // breakpoint for debugging
}
return 0;
}
// these functions are used for allocating temporary memory
// while decoding. if you can afford the stack space, use
// alloca(); otherwise, provide a temp buffer and it will
// allocate out of those.
#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
#define temp_free(f,p) (void)0
#define temp_alloc_save(f) ((f)->temp_offset)
#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
// given a sufficiently large block of memory, make an array of pointers to subblocks of it
static void *make_block_array(void *mem, int count, int size)
{
int i;
void ** p = (void **) mem;
char *q = (char *) (p + count);
for (i=0; i < count; ++i) {
p[i] = q;
q += size;
}
return p;
}
static void *setup_malloc(vorb *f, int sz)
{
sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
f->setup_memory_required += sz;
if (f->alloc.alloc_buffer) {
void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
if (f->setup_offset + sz > f->temp_offset) return NULL;
f->setup_offset += sz;
return p;
}
return sz ? malloc(sz) : NULL;
}
static void setup_free(vorb *f, void *p)
{
if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
free(p);
}
static void *setup_temp_malloc(vorb *f, int sz)
{
sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
if (f->alloc.alloc_buffer) {
if (f->temp_offset - sz < f->setup_offset) return NULL;
f->temp_offset -= sz;
return (char *) f->alloc.alloc_buffer + f->temp_offset;
}
return malloc(sz);
}
static void setup_temp_free(vorb *f, void *p, int sz)
{
if (f->alloc.alloc_buffer) {
f->temp_offset += (sz+7)&~7;
return;
}
free(p);
}
#define CRC32_POLY 0x04c11db7 // from spec
static uint32 crc_table[256];
static void crc32_init(void)
{
int i,j;
uint32 s;
for(i=0; i < 256; i++) {
for (s=(uint32) i << 24, j=0; j < 8; ++j)
s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
crc_table[i] = s;
}
}
static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
{
return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
}
// used in setup, and for huffman that doesn't go fast path
static unsigned int bit_reverse(unsigned int n)
{
n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
return (n >> 16) | (n << 16);
}
static float square(float x)
{
return x*x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
// as required by the specification. fast(?) implementation from stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
static int ilog(int32 n)
{
static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
if (n < 0) return 0; // signed n returns 0
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1 << 14))
if (n < (1 << 4)) return 0 + log2_4[n ];
else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
else return 10 + log2_4[n >> 10];
else if (n < (1 << 24))
if (n < (1 << 19)) return 15 + log2_4[n >> 15];
else return 20 + log2_4[n >> 20];
else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
else return 30 + log2_4[n >> 30];
}
#ifndef M_PI
#define M_PI 3.14159265358979323846264f // from CRC
#endif
// code length assigned to a value with no huffman encoding
#define NO_CODE 255
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times
// per file
static float float32_unpack(uint32 x)
{
// from the specification
uint32 mantissa = x & 0x1fffff;
uint32 sign = x & 0x80000000;
uint32 exp = (x & 0x7fe00000) >> 21;
double res = sign ? -(double)mantissa : (double)mantissa;
return (float) ldexp((float)res, (int)exp-788);
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
{
if (!c->sparse) {
c->codewords [symbol] = huff_code;
} else {
c->codewords [count] = huff_code;
c->codeword_lengths[count] = len;
values [count] = symbol;
}
}
static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
{
int i,k,m=0;
uint32 available[32];
memset(available, 0, sizeof(available));
// find the first entry
for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
assert(len[k] < 32); // no error return required, code reading lens checks this
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i=1; i <= len[k]; ++i)
available[i] = 1U << (32-i);
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i=k+1; i < n; ++i) {
uint32 res;
int z = len[i], y;
if (z == NO_CODE) continue;
assert(z < 32); // no error return required, code reading lens checks this
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) { return FALSE; }
res = available[z];
available[z] = 0;
add_entry(c, bit_reverse(res), i, m++, len[i], values);
// propagate availability up the tree
if (z != len[i]) {
for (y=len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res + (1 << (32-y));
}
}
}
return TRUE;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
static void compute_accelerated_huffman(Codebook *c)
{
int i, len;
for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
c->fast_huffman[i] = -1;
len = c->sparse ? c->sorted_entries : c->entries;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; // largest possible value we can encode!
#endif
for (i=0; i < len; ++i) {
if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c->fast_huffman[z] = i;
z += 1 << c->codeword_lengths[i];
}
}
}
}
#ifdef _MSC_VER
#define STBV_CDECL __cdecl
#else
#define STBV_CDECL
#endif
static int STBV_CDECL uint32_compare(const void *p, const void *q)
{
uint32 x = * (uint32 *) p;
uint32 y = * (uint32 *) q;
return x < y ? -1 : x > y;
}
static int include_in_sort(Codebook *c, uint8 len)
{
if (c->sparse) { assert(len != NO_CODE); return TRUE; }
if (len == NO_CODE) return FALSE;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
return FALSE;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
{
int i, len;
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
// this is kind of a frivolous optimization--I don't see any performance improvement,
// but it's like 4 extra lines of code, so.
if (!c->sparse) {
int k = 0;
for (i=0; i < c->entries; ++i)
if (include_in_sort(c, lengths[i]))
c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i=0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
}
qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
c->sorted_codewords[c->sorted_entries] = 0xffffffff;
len = c->sparse ? c->sorted_entries : c->entries;
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who corresponds
// #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
for (i=0; i < len; ++i) {
int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
if (include_in_sort(c,huff_len)) {
uint32 code = bit_reverse(c->codewords[i]);
int x=0, n=c->sorted_entries;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
assert(c->sorted_codewords[x] == code);
if (c->sparse) {
c->sorted_values[x] = values[i];
c->codeword_lengths[x] = huff_len;
} else {
c->sorted_values[x] = i;
}
}
}
}
// only run while parsing the header (3 times)
static int vorbis_validate(uint8 *data)
{
static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
return memcmp(data, vorbis, 6) == 0;
}
// called from setup only, once per code book
// (formula implied by specification)
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
}
// called twice per file
static void compute_twiddle_factors(int n, float *A, float *B, float *C)
{
int n4 = n >> 2, n8 = n >> 3;
int k,k2;
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
}
static void compute_window(int n, float *window)
{
int n2 = n >> 1, i;
for (i=0; i < n2; ++i)
window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
}
static void compute_bitreverse(int n, uint16 *rev)
{
int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
int i, n8 = n >> 3;
for (i=0; i < n8; ++i)
rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
}
static int init_blocksize(vorb *f, int b, int n)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
if (!f->window[b]) return error(f, VORBIS_outofmem);
compute_window(n, f->window[b]);
f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f->bit_reverse[b]);
return TRUE;
}
static void neighbors(uint16 *x, int n, int *plow, int *phigh)
{
int low = -1;
int high = 65536;
int i;
for (i=0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
}
}
// this has been repurposed so y is now the original index instead of y
typedef struct
{
uint16 x,id;
} stbv__floor_ordering;
static int STBV_CDECL point_compare(const void *p, const void *q)
{
stbv__floor_ordering *a = (stbv__floor_ordering *) p;
stbv__floor_ordering *b = (stbv__floor_ordering *) q;
return a->x < b->x ? -1 : a->x > b->x;
}
//
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
#if defined(STB_VORBIS_NO_STDIO)
#define USE_MEMORY(z) TRUE
#else
#define USE_MEMORY(z) ((z)->stream)
#endif
static uint8 get8(vorb *z)
{
if (USE_MEMORY(z)) {
if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
return *z->stream++;
}
#ifndef STB_VORBIS_NO_STDIO
{
int c = fgetc(z->f);
if (c == EOF) { z->eof = TRUE; return 0; }
return c;
}
#endif
}
static uint32 get32(vorb *f)
{
uint32 x;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += (uint32) get8(f) << 24;
return x;
}
static int getn(vorb *z, uint8 *data, int n)
{
if (USE_MEMORY(z)) {
if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
memcpy(data, z->stream, n);
z->stream += n;
return 1;
}
#ifndef STB_VORBIS_NO_STDIO
if (fread(data, n, 1, z->f) == 1)
return 1;
else {
z->eof = 1;
return 0;
}
#endif
}
static void skip(vorb *z, int n)
{
if (USE_MEMORY(z)) {
z->stream += n;
if (z->stream >= z->stream_end) z->eof = 1;
return;
}
#ifndef STB_VORBIS_NO_STDIO
{
long x = ftell(z->f);
fseek(z->f, x+n, SEEK_SET);
}
#endif
}
static int set_file_offset(stb_vorbis *f, unsigned int loc)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
f->eof = 0;
if (USE_MEMORY(f)) {
if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
f->stream = f->stream_end;
f->eof = 1;
return 0;
} else {
f->stream = f->stream_start + loc;
return 1;
}
}
#ifndef STB_VORBIS_NO_STDIO
if (loc + f->f_start < loc || loc >= 0x80000000) {
loc = 0x7fffffff;
f->eof = 1;
} else {
loc += f->f_start;
}
if (!fseek(f->f, loc, SEEK_SET))
return 1;
f->eof = 1;
fseek(f->f, f->f_start, SEEK_END);
return 0;
#endif
}
static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
static int capture_pattern(vorb *f)
{
if (0x4f != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x53 != get8(f)) return FALSE;
return TRUE;
}
#define PAGEFLAG_continued_packet 1
#define PAGEFLAG_first_page 2
#define PAGEFLAG_last_page 4
static int start_page_no_capturepattern(vorb *f)
{
uint32 loc0,loc1,n;
if (f->first_decode && !IS_PUSH_MODE(f)) {
f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;
}
// stream structure version
if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
// header flag
f->page_flag = get8(f);
// absolute granule position
loc0 = get32(f);
loc1 = get32(f);
// @TODO: validate loc0,loc1 as valid positions?
// stream serial number -- vorbis doesn't interleave, so discard
get32(f);
//if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
// page sequence number
n = get32(f);
f->last_page = n;
// CRC32
get32(f);
// page_segments
f->segment_count = get8(f);
if (!getn(f, f->segments, f->segment_count))
return error(f, VORBIS_unexpected_eof);
// assume we _don't_ know any the sample position of any segments
f->end_seg_with_known_loc = -2;
if (loc0 != ~0U || loc1 != ~0U) {
int i;
// determine which packet is the last one that will complete
for (i=f->segment_count-1; i >= 0; --i)
if (f->segments[i] < 255)
break;
// 'i' is now the index of the _last_ segment of a packet that ends
if (i >= 0) {
f->end_seg_with_known_loc = i;
f->known_loc_for_packet = loc0;
}
}
if (f->first_decode) {
int i,len;
len = 0;
for (i=0; i < f->segment_count; ++i)
len += f->segments[i];
len += 27 + f->segment_count;
f->p_first.page_end = f->p_first.page_start + len;
f->p_first.last_decoded_sample = loc0;
}
f->next_seg = 0;
return TRUE;
}
static int start_page(vorb *f)
{
if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
return start_page_no_capturepattern(f);
}
static int start_packet(vorb *f)
{
while (f->next_seg == -1) {
if (!start_page(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet)
return error(f, VORBIS_continued_packet_flag_invalid);
}
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
// f->next_seg is now valid
return TRUE;
}
static int maybe_start_packet(vorb *f)
{
if (f->next_seg == -1) {
int x = get8(f);
if (f->eof) return FALSE; // EOF at page boundary is not an error!
if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (!start_page_no_capturepattern(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet) {
// set up enough state that we can read this packet if we want,
// e.g. during recovery
f->last_seg = FALSE;
f->bytes_in_seg = 0;
return error(f, VORBIS_continued_packet_flag_invalid);
}
}
return start_packet(f);
}
static int next_segment(vorb *f)
{
int len;
if (f->last_seg) return 0;
if (f->next_seg == -1) {
f->last_seg_which = f->segment_count-1; // in case start_page fails
if (!start_page(f)) { f->last_seg = 1; return 0; }
if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
}
len = f->segments[f->next_seg++];
if (len < 255) {
f->last_seg = TRUE;
f->last_seg_which = f->next_seg-1;
}
if (f->next_seg >= f->segment_count)
f->next_seg = -1;
assert(f->bytes_in_seg == 0);
f->bytes_in_seg = len;
return len;
}
#define EOP (-1)
#define INVALID_BITS (-1)
static int get8_packet_raw(vorb *f)
{
if (!f->bytes_in_seg) { // CLANG!
if (f->last_seg) return EOP;
else if (!next_segment(f)) return EOP;
}
assert(f->bytes_in_seg > 0);
--f->bytes_in_seg;
++f->packet_bytes;
return get8(f);
}
static int get8_packet(vorb *f)
{
int x = get8_packet_raw(f);
f->valid_bits = 0;
return x;
}
static int get32_packet(vorb *f)
{
uint32 x;
x = get8_packet(f);
x += get8_packet(f) << 8;
x += get8_packet(f) << 16;
x += (uint32) get8_packet(f) << 24;
return x;
}
static void flush_packet(vorb *f)
{
while (get8_packet_raw(f) != EOP);
}
// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
// as the huffman decoder?
static uint32 get_bits(vorb *f, int n)
{
uint32 z;
if (f->valid_bits < 0) return 0;
if (f->valid_bits < n) {
if (n > 24) {
// the accumulator technique below would not work correctly in this case
z = get_bits(f, 24);
z += get_bits(f, n-24) << 24;
return z;
}
if (f->valid_bits == 0) f->acc = 0;
while (f->valid_bits < n) {
int z = get8_packet_raw(f);
if (z == EOP) {
f->valid_bits = INVALID_BITS;
return 0;
}
f->acc += z << f->valid_bits;
f->valid_bits += 8;
}
}
assert(f->valid_bits >= n);
z = f->acc & ((1 << n)-1);
f->acc >>= n;
f->valid_bits -= n;
return z;
}
// @OPTIMIZE: primary accumulator for huffman
// expand the buffer to as many bits as possible without reading off end of packet
// it might be nice to allow f->valid_bits and f->acc to be stored in registers,
// e.g. cache them locally and decode locally
static __forceinline void prep_huffman(vorb *f)
{
if (f->valid_bits <= 24) {
if (f->valid_bits == 0) f->acc = 0;
do {
int z;
if (f->last_seg && !f->bytes_in_seg) return;
z = get8_packet_raw(f);
if (z == EOP) return;
f->acc += (unsigned) z << f->valid_bits;
f->valid_bits += 8;
} while (f->valid_bits <= 24);
}
}
enum
{
VORBIS_packet_id = 1,
VORBIS_packet_comment = 3,
VORBIS_packet_setup = 5
};
static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
{
int i;
prep_huffman(f);
if (c->codewords == NULL && c->sorted_codewords == NULL)
return -1;
// cases to use binary search: sorted_codewords && !c->codewords
// sorted_codewords && c->entries > 8
if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
// binary search
uint32 code = bit_reverse(f->acc);
int x=0, n=c->sorted_entries, len;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
// x is now the sorted index
if (!c->sparse) x = c->sorted_values[x];
// x is now sorted index if sparse, or symbol otherwise
len = c->codeword_lengths[x];
if (f->valid_bits >= len) {
f->acc >>= len;
f->valid_bits -= len;
return x;
}
f->valid_bits = 0;
return -1;
}
// if small, linear search
assert(!c->sparse);
for (i=0; i < c->entries; ++i) {
if (c->codeword_lengths[i] == NO_CODE) continue;
if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
if (f->valid_bits >= c->codeword_lengths[i]) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
return i;
}
f->valid_bits = 0;
return -1;
}
}
error(f, VORBIS_invalid_stream);
f->valid_bits = 0;
return -1;
}
#ifndef STB_VORBIS_NO_INLINE_DECODE
#define DECODE_RAW(var, f,c) \
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
prep_huffman(f); \
var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
var = c->fast_huffman[var]; \
if (var >= 0) { \
int n = c->codeword_lengths[var]; \
f->acc >>= n; \
f->valid_bits -= n; \
if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
} else { \
var = codebook_decode_scalar_raw(f,c); \
}
#else
static int codebook_decode_scalar(vorb *f, Codebook *c)
{
int i;
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
prep_huffman(f);
// fast huffman table lookup
i = f->acc & FAST_HUFFMAN_TABLE_MASK;
i = c->fast_huffman[i];
if (i >= 0) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
return i;
}
return codebook_decode_scalar_raw(f,c);
}
#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
#endif
#define DECODE(var,f,c) \
DECODE_RAW(var,f,c) \
if (c->sparse) var = c->sorted_values[var];
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
#define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
#else
#define DECODE_VQ(var,f,c) DECODE(var,f,c)
#endif
// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
// where we avoid one addition
#define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_BASE(c) (0)
static int codebook_decode_start(vorb *f, Codebook *c)
{
int z = -1;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0)
error(f, VORBIS_invalid_stream);
else {
DECODE_VQ(z,f,c);
if (c->sparse) assert(z < c->sorted_entries);
if (z < 0) { // check for EOP
if (!f->bytes_in_seg)
if (f->last_seg)
return z;
error(f, VORBIS_invalid_stream);
}
}
return z;
}
static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
{
int i,z = codebook_decode_start(f,c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
float last = CODEBOOK_ELEMENT_BASE(c);
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i] += val;
if (c->sequence_p) last = val + c->minimum_value;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
if (c->sequence_p) {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i] += val;
last = val + c->minimum_value;
}
} else {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
}
}
return TRUE;
}
static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
{
int i,z = codebook_decode_start(f,c);
float last = CODEBOOK_ELEMENT_BASE(c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
}
return TRUE;
}
static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
{
int c_inter = *c_inter_p;
int p_inter = *p_inter_p;
int i,z, effective = c->dimensions;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
while (total_decode > 0) {
float last = CODEBOOK_ELEMENT_BASE(c);
DECODE_VQ(z,f,c);
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
assert(!c->sparse || z < c->sorted_entries);
#endif
if (z < 0) {
if (!f->bytes_in_seg)
if (f->last_seg) return FALSE;
return error(f, VORBIS_invalid_stream);
}
// if this will take us off the end of the buffers, stop short!
// we check by computing the length of the virtual interleaved
// buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
// and the length we'll be using (effective)
if (c_inter + p_inter*ch + effective > len * ch) {
effective = len*ch - (p_inter*ch - c_inter);
}
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < effective; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
} else
#endif
{
z *= c->dimensions;
if (c->sequence_p) {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
last = val;
}
} else {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
}
}
}
total_decode -= effective;
}
*c_inter_p = c_inter;
*p_inter_p = p_inter;
return TRUE;
}
static int predict_point(int x, int x0, int x1, int y0, int y1)
{
int dy = y1 - y0;
int adx = x1 - x0;
// @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
int err = abs(dy) * (x - x0);
int off = err / adx;
return dy < 0 ? y0 - off : y0 + off;
}
// the following table is block-copied from the specification
static float inverse_db_table[256] =
{
1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
0.82788260f, 0.88168307f, 0.9389798f, 1.0f
};
// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
// note that you must produce bit-identical output to decode correctly;
// this specific sequence of operations is specified in the spec (it's
// drawing integer-quantized frequency-space lines that the encoder
// expects to be exactly the same)
// ... also, isn't the whole point of Bresenham's algorithm to NOT
// have to divide in the setup? sigh.
#ifndef STB_VORBIS_NO_DEFER_FLOOR
#define LINE_OP(a,b) a *= b
#else
#define LINE_OP(a,b) a = b
#endif
#ifdef STB_VORBIS_DIVIDE_TABLE
#define DIVTAB_NUMER 32
#define DIVTAB_DENOM 64
int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
#endif
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y&255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y&255]);
}
}
}
static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
{
int k;
if (rtype == 0) {
int step = n / book->dimensions;
for (k=0; k < step; ++k)
if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
return FALSE;
} else {
for (k=0; k < n; ) {
if (!codebook_decode(f, book, target+offset, n-k))
return FALSE;
k += book->dimensions;
offset += book->dimensions;
}
}
return TRUE;
}
// n is 1/2 of the blocksize --
// specification: "Correct per-vector decode length is [n]/2"
static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
unsigned int actual_size = rtype == 2 ? n*2 : n;
unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i=0; i < ch; ++i)
if (!do_not_decode[i])
memset(residue_buffers[i], 0, sizeof(float) * n);
if (rtype == 2 && ch != 1) {
for (j=0; j < ch; ++j)
if (!do_not_decode[j])
break;
if (j == ch)
goto done;
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = (z & 1), p_inter = z>>1;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#else
// saves 1%
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch > 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = z % ch, p_inter = z/ch;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set=0;
while (pcount < part_read) {
if (pass == 0) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks+r->classbook;
int temp;
DECODE(temp,f,c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[j][i+pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype))
goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f,part_classdata);
#else
temp_free(f,classifications);
#endif
temp_alloc_restore(f,temp_alloc_point);
}
#if 0
// slow way for debugging
void inverse_mdct_slow(float *buffer, int n)
{
int i,j;
int n2 = n >> 1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
// formula from paper:
//acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
// formula from wikipedia
//acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
// these are equivalent, except the formula from the paper inverts the multiplier!
// however, what actually works is NO MULTIPLIER!?!
//acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
buffer[i] = acc;
}
free(x);
}
#elif 0
// same as above, but just barely able to run in real time on modern machines
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
float mcos[16384];
int i,j;
int n2 = n >> 1, nmask = (n << 2) -1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < 4*n; ++i)
mcos[i] = (float) cos(M_PI / 2 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
buffer[i] = acc;
}
free(x);
}
#elif 0
// transform to use a slow dct-iv; this is STILL basically trivial,
// but only requires half as many ops
void dct_iv_slow(float *buffer, int n)
{
float mcos[16384];
float x[2048];
int i,j;
int n2 = n >> 1, nmask = (n << 3) - 1;
memcpy(x, buffer, sizeof(*x) * n);
for (i=0; i < 8*n; ++i)
mcos[i] = (float) cos(M_PI / 4 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n; ++j)
acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
buffer[i] = acc;
}
}
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
float temp[4096];
memcpy(temp, buffer, n2 * sizeof(float));
dct_iv_slow(temp, n2); // returns -c'-d, a-b'
for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
}
#endif
#ifndef LIBVORBIS_MDCT
#define LIBVORBIS_MDCT 0
#endif
#if LIBVORBIS_MDCT
// directly call the vorbis MDCT using an interface documented
// by Jeff Roberts... useful for performance comparison
typedef struct
{
int n;
int log2n;
float *trig;
int *bitrev;
float scale;
} mdct_lookup;
extern void mdct_init(mdct_lookup *lookup, int n);
extern void mdct_clear(mdct_lookup *l);
extern void mdct_backward(mdct_lookup *init, float *in, float *out);
mdct_lookup M1,M2;
void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
mdct_lookup *M;
if (M1.n == n) M = &M1;
else if (M2.n == n) M = &M2;
else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
else {
if (M2.n) __asm int 3;
mdct_init(&M2, n);
M = &M2;
}
mdct_backward(M, buffer, buffer);
}
#endif
// the following were split out into separate functions while optimizing;
// they could be pushed back up but eh. __forceinline showed no change;
// they're probably already being inlined.
static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
{
float *ee0 = e + i_off;
float *ee2 = ee0 + k_off;
int i;
assert((n & 3) == 0);
for (i=(n>>2); i > 0; --i) {
float k00_20, k01_21;
k00_20 = ee0[ 0] - ee2[ 0];
k01_21 = ee0[-1] - ee2[-1];
ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-2] - ee2[-2];
k01_21 = ee0[-3] - ee2[-3];
ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-4] - ee2[-4];
k01_21 = ee0[-5] - ee2[-5];
ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-6] - ee2[-6];
k01_21 = ee0[-7] - ee2[-7];
ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
ee0 -= 8;
ee2 -= 8;
}
}
static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
{
int i;
float k00_20, k01_21;
float *e0 = e + d0;
float *e2 = e0 + k_off;
for (i=lim >> 2; i > 0; --i) {
k00_20 = e0[-0] - e2[-0];
k01_21 = e0[-1] - e2[-1];
e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-2] - e2[-2];
k01_21 = e0[-3] - e2[-3];
e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-4] - e2[-4];
k01_21 = e0[-5] - e2[-5];
e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-6] - e2[-6];
k01_21 = e0[-7] - e2[-7];
e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
e0 -= 8;
e2 -= 8;
A += k1;
}
}
static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
{
int i;
float A0 = A[0];
float A1 = A[0+1];
float A2 = A[0+a_off];
float A3 = A[0+a_off+1];
float A4 = A[0+a_off*2+0];
float A5 = A[0+a_off*2+1];
float A6 = A[0+a_off*3+0];
float A7 = A[0+a_off*3+1];
float k00,k11;
float *ee0 = e +i_off;
float *ee2 = ee0+k_off;
for (i=n; i > 0; --i) {
k00 = ee0[ 0] - ee2[ 0];
k11 = ee0[-1] - ee2[-1];
ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = (k00) * A0 - (k11) * A1;
ee2[-1] = (k11) * A0 + (k00) * A1;
k00 = ee0[-2] - ee2[-2];
k11 = ee0[-3] - ee2[-3];
ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = (k00) * A2 - (k11) * A3;
ee2[-3] = (k11) * A2 + (k00) * A3;
k00 = ee0[-4] - ee2[-4];
k11 = ee0[-5] - ee2[-5];
ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = (k00) * A4 - (k11) * A5;
ee2[-5] = (k11) * A4 + (k00) * A5;
k00 = ee0[-6] - ee2[-6];
k11 = ee0[-7] - ee2[-7];
ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = (k00) * A6 - (k11) * A7;
ee2[-7] = (k11) * A6 + (k00) * A7;
ee0 -= k0;
ee2 -= k0;
}
}
static __forceinline void iter_54(float *z)
{
float k00,k11,k22,k33;
float y0,y1,y2,y3;
k00 = z[ 0] - z[-4];
y0 = z[ 0] + z[-4];
y2 = z[-2] + z[-6];
k22 = z[-2] - z[-6];
z[-0] = y0 + y2; // z0 + z4 + z2 + z6
z[-2] = y0 - y2; // z0 + z4 - z2 - z6
// done with y0,y2
k33 = z[-3] - z[-7];
z[-4] = k00 + k33; // z0 - z4 + z3 - z7
z[-6] = k00 - k33; // z0 - z4 - z3 + z7
// done with k33
k11 = z[-1] - z[-5];
y1 = z[-1] + z[-5];
y3 = z[-3] + z[-7];
z[-1] = y1 + y3; // z1 + z5 + z3 + z7
z[-3] = y1 - y3; // z1 + z5 - z3 - z7
z[-5] = k11 - k22; // z1 - z5 + z2 - z6
z[-7] = k11 + k22; // z1 - z5 - z2 + z6
}
static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
{
int a_off = base_n >> 3;
float A2 = A[0+a_off];
float *z = e + i_off;
float *base = z - 16 * n;
while (z > base) {
float k00,k11;
float l00,l11;
k00 = z[-0] - z[ -8];
k11 = z[-1] - z[ -9];
l00 = z[-2] - z[-10];
l11 = z[-3] - z[-11];
z[ -0] = z[-0] + z[ -8];
z[ -1] = z[-1] + z[ -9];
z[ -2] = z[-2] + z[-10];
z[ -3] = z[-3] + z[-11];
z[ -8] = k00;
z[ -9] = k11;
z[-10] = (l00+l11) * A2;
z[-11] = (l11-l00) * A2;
k00 = z[ -4] - z[-12];
k11 = z[ -5] - z[-13];
l00 = z[ -6] - z[-14];
l11 = z[ -7] - z[-15];
z[ -4] = z[ -4] + z[-12];
z[ -5] = z[ -5] + z[-13];
z[ -6] = z[ -6] + z[-14];
z[ -7] = z[ -7] + z[-15];
z[-12] = k11;
z[-13] = -k00;
z[-14] = (l11-l00) * A2;
z[-15] = (l00+l11) * -A2;
iter_54(z);
iter_54(z-8);
z -= 16;
}
}
static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int ld;
// @OPTIMIZE: reduce register pressure by using fewer variables?
int save_point = temp_alloc_save(f);
float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
float *u=NULL,*v=NULL;
// twiddle factors
float *A = f->A[blocktype];
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
// kernel from paper
// merged:
// copy and reflect spectral data
// step 0
// note that it turns out that the items added together during
// this step are, in fact, being added to themselves (as reflected
// by step 0). inexplicable inefficiency! this became obvious
// once I combined the passes.
// so there's a missing 'times 2' here (for adding X to itself).
// this propagates through linearly to the end, where the numbers
// are 1/2 too small, and need to be compensated for.
{
float *d,*e, *AA, *e_stop;
d = &buf2[n2-2];
AA = A;
e = &buffer[0];
e_stop = &buffer[n2];
while (e != e_stop) {
d[1] = (e[0] * AA[0] - e[2]*AA[1]);
d[0] = (e[0] * AA[1] + e[2]*AA[0]);
d -= 2;
AA += 2;
e += 4;
}
e = &buffer[n2-3];
while (d >= buf2) {
d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
d -= 2;
AA += 2;
e -= 4;
}
}
// now we use symbolic names for these, so that we can
// possibly swap their meaning as we change which operations
// are in place
u = buffer;
v = buf2;
// step 2 (paper output is w, now u)
// this could be in place, but the data ends up in the wrong
// place... _somebody_'s got to swap it, so this is nominated
{
float *AA = &A[n2-8];
float *d0,*d1, *e0, *e1;
e0 = &v[n4];
e1 = &v[0];
d0 = &u[n4];
d1 = &u[0];
while (AA >= A) {
float v40_20, v41_21;
v41_21 = e0[1] - e1[1];
v40_20 = e0[0] - e1[0];
d0[1] = e0[1] + e1[1];
d0[0] = e0[0] + e1[0];
d1[1] = v41_21*AA[4] - v40_20*AA[5];
d1[0] = v40_20*AA[4] + v41_21*AA[5];
v41_21 = e0[3] - e1[3];
v40_20 = e0[2] - e1[2];
d0[3] = e0[3] + e1[3];
d0[2] = e0[2] + e1[2];
d1[3] = v41_21*AA[0] - v40_20*AA[1];
d1[2] = v40_20*AA[0] + v41_21*AA[1];
AA -= 8;
d0 += 4;
d1 += 4;
e0 += 4;
e1 += 4;
}
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
// optimized step 3:
// the original step3 loop can be nested r inside s or s inside r;
// it's written originally as s inside r, but this is dumb when r
// iterates many times, and s few. So I have two copies of it and
// switch between them halfway.
// this is iteration 0 of step 3
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
// this is iteration 1 of step 3
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
l=2;
for (; l < (ld-3)>>1; ++l) {
int k0 = n >> (l+2), k0_2 = k0>>1;
int lim = 1 << (l+1);
int i;
for (i=0; i < lim; ++i)
imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
}
for (; l < ld-6; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
int rlim = n >> (l+6), r;
int lim = 1 << (l+1);
int i_off;
float *A0 = A;
i_off = n2-1;
for (r=rlim; r > 0; --r) {
imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
A0 += k1*4;
i_off -= 8;
}
}
// iterations with count:
// ld-6,-5,-4 all interleaved together
// the big win comes from getting rid of needless flops
// due to the constants on pass 5 & 4 being all 1 and 0;
// combining them to be simultaneous to improve cache made little difference
imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
// output is u
// step 4, 5, and 6
// cannot be in-place because of step 5
{
uint16 *bitrev = f->bit_reverse[blocktype];
// weirdly, I'd have thought reading sequentially and writing
// erratically would have been better than vice-versa, but in
// fact that's not what my testing showed. (That is, with
// j = bitreverse(i), do you read i and write j, or read j and write i.)
float *d0 = &v[n4-4];
float *d1 = &v[n2-4];
while (d0 >= v) {
int k4;
k4 = bitrev[0];
d1[3] = u[k4+0];
d1[2] = u[k4+1];
d0[3] = u[k4+2];
d0[2] = u[k4+3];
k4 = bitrev[1];
d1[1] = u[k4+0];
d1[0] = u[k4+1];
d0[1] = u[k4+2];
d0[0] = u[k4+3];
d0 -= 4;
d1 -= 4;
bitrev += 2;
}
}
// (paper output is u, now v)
// data must be in buf2
assert(v == buf2);
// step 7 (paper output is v, now v)
// this is now in place
{
float *C = f->C[blocktype];
float *d, *e;
d = v;
e = v + n2 - 4;
while (d < e) {
float a02,a11,b0,b1,b2,b3;
a02 = d[0] - e[2];
a11 = d[1] + e[3];
b0 = C[1]*a02 + C[0]*a11;
b1 = C[1]*a11 - C[0]*a02;
b2 = d[0] + e[ 2];
b3 = d[1] - e[ 3];
d[0] = b2 + b0;
d[1] = b3 + b1;
e[2] = b2 - b0;
e[3] = b1 - b3;
a02 = d[2] - e[0];
a11 = d[3] + e[1];
b0 = C[3]*a02 + C[2]*a11;
b1 = C[3]*a11 - C[2]*a02;
b2 = d[2] + e[ 0];
b3 = d[3] - e[ 1];
d[2] = b2 + b0;
d[3] = b3 + b1;
e[0] = b2 - b0;
e[1] = b1 - b3;
C += 4;
d += 4;
e -= 4;
}
}
// data must be in buf2
// step 8+decode (paper output is X, now buffer)
// this generates pairs of data a la 8 and pushes them directly through
// the decode kernel (pushing rather than pulling) to avoid having
// to make another pass later
// this cannot POSSIBLY be in place, so we refer to the buffers directly
{
float *d0,*d1,*d2,*d3;
float *B = f->B[blocktype] + n2 - 8;
float *e = buf2 + n2 - 8;
d0 = &buffer[0];
d1 = &buffer[n2-4];
d2 = &buffer[n2];
d3 = &buffer[n-4];
while (e >= v) {
float p0,p1,p2,p3;
p3 = e[6]*B[7] - e[7]*B[6];
p2 = -e[6]*B[6] - e[7]*B[7];
d0[0] = p3;
d1[3] = - p3;
d2[0] = p2;
d3[3] = p2;
p1 = e[4]*B[5] - e[5]*B[4];
p0 = -e[4]*B[4] - e[5]*B[5];
d0[1] = p1;
d1[2] = - p1;
d2[1] = p0;
d3[2] = p0;
p3 = e[2]*B[3] - e[3]*B[2];
p2 = -e[2]*B[2] - e[3]*B[3];
d0[2] = p3;
d1[1] = - p3;
d2[2] = p2;
d3[1] = p2;
p1 = e[0]*B[1] - e[1]*B[0];
p0 = -e[0]*B[0] - e[1]*B[1];
d0[3] = p1;
d1[0] = - p1;
d2[3] = p0;
d3[0] = p0;
B -= 8;
e -= 8;
d0 += 4;
d2 += 4;
d1 -= 4;
d3 -= 4;
}
}
temp_free(f,buf2);
temp_alloc_restore(f,save_point);
}
#if 0
// this is the original version of the above code, if you want to optimize it from scratch
void inverse_mdct_naive(float *buffer, int n)
{
float s;
float A[1 << 12], B[1 << 12], C[1 << 11];
int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int n3_4 = n - n4, ld;
// how can they claim this only uses N words?!
// oh, because they're only used sparsely, whoops
float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
// set up twiddle factors
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// Note there are bugs in that pseudocode, presumably due to them attempting
// to rename the arrays nicely rather than representing the way their actual
// implementation bounces buffers back and forth. As a result, even in the
// "some formulars corrected" version, a direct implementation fails. These
// are noted below as "paper bug".
// copy and reflect spectral data
for (k=0; k < n2; ++k) u[k] = buffer[k];
for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
// kernel from paper
// step 1
for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
}
// step 2
for (k=k4=0; k < n8; k+=1, k4+=4) {
w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
for (l=0; l < ld-3; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3);
int rlim = n >> (l+4), r4, r;
int s2lim = 1 << (l+2), s2;
for (r=r4=0; r < rlim; r4+=4,++r) {
for (s2=0; s2 < s2lim; s2+=2) {
u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
+ (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
}
}
if (l+1 < ld-3) {
// paper bug: ping-ponging of u&w here is omitted
memcpy(w, u, sizeof(u));
}
}
// step 4
for (i=0; i < n8; ++i) {
int j = bit_reverse(i) >> (32-ld+3);
assert(j < n8);
if (i == j) {
// paper bug: original code probably swapped in place; if copying,
// need to directly copy in this case
int i8 = i << 3;
v[i8+1] = u[i8+1];
v[i8+3] = u[i8+3];
v[i8+5] = u[i8+5];
v[i8+7] = u[i8+7];
} else if (i < j) {
int i8 = i << 3, j8 = j << 3;
v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
}
}
// step 5
for (k=0; k < n2; ++k) {
w[k] = v[k*2+1];
}
// step 6
for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
u[n-1-k2] = w[k4];
u[n-2-k2] = w[k4+1];
u[n3_4 - 1 - k2] = w[k4+2];
u[n3_4 - 2 - k2] = w[k4+3];
}
// step 7
for (k=k2=0; k < n8; ++k, k2 += 2) {
v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
}
// step 8
for (k=k2=0; k < n4; ++k,k2 += 2) {
X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
}
// decode kernel to output
// determined the following value experimentally
// (by first figuring out what made inverse_mdct_slow work); then matching that here
// (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
s = 0.5; // theoretically would be n4
// [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
// so it needs to use the "old" B values to behave correctly, or else
// set s to 1.0 ]]]
for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
}
#endif
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
#ifndef STB_VORBIS_NO_DEFER_FLOOR
typedef int16 YTYPE;
#else
typedef int YTYPE;
#endif
static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
{
int n2 = n >> 1;
int s = map->chan[i].mux, floor;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
int j,q;
int lx = 0, ly = finalY[0] * g->floor1_multiplier;
for (q=1; q < g->values; ++q) {
j = g->sorted_order[q];
#ifndef STB_VORBIS_NO_DEFER_FLOOR
STBV_NOTUSED(step2_flag);
if (finalY[j] >= 0)
#else
if (step2_flag[j])
#endif
{
int hy = finalY[j] * g->floor1_multiplier;
int hx = g->Xlist[j];
if (lx != hx)
draw_line(target, lx,ly, hx,hy, n2);
CHECK(f);
lx = hx, ly = hy;
}
}
if (lx < n2) {
// optimization of: draw_line(target, lx,ly, n,ly, n2);
for (j=lx; j < n2; ++j)
LINE_OP(target[j], inverse_db_table[ly]);
CHECK(f);
}
}
return TRUE;
}
// The meaning of "left" and "right"
//
// For a given frame:
// we compute samples from 0..n
// window_center is n/2
// we'll window and mix the samples from left_start to left_end with data from the previous frame
// all of the samples from left_end to right_start can be output without mixing; however,
// this interval is 0-length except when transitioning between short and long frames
// all of the samples from right_start to right_end need to be mixed with the next frame,
// which we don't have, so those get saved in a buffer
// frame N's right_end-right_start, the number of samples to mix with the next frame,
// has to be the same as frame N+1's left_end-left_start (which they are by
// construction)
static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
Mode *m;
int i, n, prev, next, window_center;
f->channel_buffer_start = f->channel_buffer_end = 0;
retry:
if (f->eof) return FALSE;
if (!maybe_start_packet(f))
return FALSE;
// check packet type
if (get_bits(f,1) != 0) {
if (IS_PUSH_MODE(f))
return error(f,VORBIS_bad_packet_type);
while (EOP != get8_packet(f));
goto retry;
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
i = get_bits(f, ilog(f->mode_count-1));
if (i == EOP) return FALSE;
if (i >= f->mode_count) return FALSE;
*mode = i;
m = f->mode_config + i;
if (m->blockflag) {
n = f->blocksize_1;
prev = get_bits(f,1);
next = get_bits(f,1);
} else {
prev = next = 0;
n = f->blocksize_0;
}
// WINDOWING
window_center = n >> 1;
if (m->blockflag && !prev) {
*p_left_start = (n - f->blocksize_0) >> 2;
*p_left_end = (n + f->blocksize_0) >> 2;
} else {
*p_left_start = 0;
*p_left_end = window_center;
}
if (m->blockflag && !next) {
*p_right_start = (n*3 - f->blocksize_0) >> 2;
*p_right_end = (n*3 + f->blocksize_0) >> 2;
} else {
*p_right_start = window_center;
*p_right_end = n;
}
return TRUE;
}
static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
{
Mapping *map;
int i,j,k,n,n2;
int zero_channel[256];
int really_zero_channel[256];
// WINDOWING
STBV_NOTUSED(left_end);
n = f->blocksize[m->blockflag];
map = &f->mapping[m->mapping];
// FLOORS
n2 = n >> 1;
CHECK(f);
for (i=0; i < f->channels; ++i) {
int s = map->chan[i].mux, floor;
zero_channel[i] = FALSE;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
if (get_bits(f, 1)) {
short *finalY;
uint8 step2_flag[256];
static int range_list[4] = { 256, 128, 86, 64 };
int range = range_list[g->floor1_multiplier-1];
int offset = 2;
finalY = f->finalY[i];
finalY[0] = get_bits(f, ilog(range)-1);
finalY[1] = get_bits(f, ilog(range)-1);
for (j=0; j < g->partitions; ++j) {
int pclass = g->partition_class_list[j];
int cdim = g->class_dimensions[pclass];
int cbits = g->class_subclasses[pclass];
int csub = (1 << cbits)-1;
int cval = 0;
if (cbits) {
Codebook *c = f->codebooks + g->class_masterbooks[pclass];
DECODE(cval,f,c);
}
for (k=0; k < cdim; ++k) {
int book = g->subclass_books[pclass][cval & csub];
cval = cval >> cbits;
if (book >= 0) {
int temp;
Codebook *c = f->codebooks + book;
DECODE(temp,f,c);
finalY[offset++] = temp;
} else
finalY[offset++] = 0;
}
}
if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
step2_flag[0] = step2_flag[1] = 1;
for (j=2; j < g->values; ++j) {
int low, high, pred, highroom, lowroom, room, val;
low = g->neighbors[j][0];
high = g->neighbors[j][1];
//neighbors(g->Xlist, j, &low, &high);
pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
val = finalY[j];
highroom = range - pred;
lowroom = pred;
if (highroom < lowroom)
room = highroom * 2;
else
room = lowroom * 2;
if (val) {
step2_flag[low] = step2_flag[high] = 1;
step2_flag[j] = 1;
if (val >= room)
if (highroom > lowroom)
finalY[j] = val - lowroom + pred;
else
finalY[j] = pred - val + highroom - 1;
else
if (val & 1)
finalY[j] = pred - ((val+1)>>1);
else
finalY[j] = pred + (val>>1);
} else {
step2_flag[j] = 0;
finalY[j] = pred;
}
}
#ifdef STB_VORBIS_NO_DEFER_FLOOR
do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
#else
// defer final floor computation until _after_ residue
for (j=0; j < g->values; ++j) {
if (!step2_flag[j])
finalY[j] = -1;
}
#endif
} else {
error:
zero_channel[i] = TRUE;
}
// So we just defer everything else to later
// at this point we've decoded the floor into buffer
}
}
CHECK(f);
// at this point we've decoded all floors
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
// re-enable coupled channels if necessary
memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
for (i=0; i < map->coupling_steps; ++i)
if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
}
CHECK(f);
// RESIDUE DECODE
for (i=0; i < map->submaps; ++i) {
float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
int r;
uint8 do_not_decode[256];
int ch = 0;
for (j=0; j < f->channels; ++j) {
if (map->chan[j].mux == i) {
if (zero_channel[j]) {
do_not_decode[ch] = TRUE;
residue_buffers[ch] = NULL;
} else {
do_not_decode[ch] = FALSE;
residue_buffers[ch] = f->channel_buffers[j];
}
++ch;
}
}
r = map->submap_residue[i];
decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
CHECK(f);
// INVERSE COUPLING
for (i = map->coupling_steps-1; i >= 0; --i) {
int n2 = n >> 1;
float *m = f->channel_buffers[map->chan[i].magnitude];
float *a = f->channel_buffers[map->chan[i].angle ];
for (j=0; j < n2; ++j) {
float a2,m2;
if (m[j] > 0)
if (a[j] > 0)
m2 = m[j], a2 = m[j] - a[j];
else
a2 = m[j], m2 = m[j] + a[j];
else
if (a[j] > 0)
m2 = m[j], a2 = m[j] + a[j];
else
a2 = m[j], m2 = m[j] - a[j];
m[j] = m2;
a[j] = a2;
}
}
CHECK(f);
// finish decoding the floors
#ifndef STB_VORBIS_NO_DEFER_FLOOR
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
}
}
#else
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
for (j=0; j < n2; ++j)
f->channel_buffers[i][j] *= f->floor_buffers[i][j];
}
}
#endif
// INVERSE MDCT
CHECK(f);
for (i=0; i < f->channels; ++i)
inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
CHECK(f);
// this shouldn't be necessary, unless we exited on an error
// and want to flush to get to the next packet
flush_packet(f);
if (f->first_decode) {
// assume we start so first non-discarded sample is sample 0
// this isn't to spec, but spec would require us to read ahead
// and decode the size of all current frames--could be done,
// but presumably it's not a commonly used feature
f->current_loc = 0u - n2; // start of first frame is positioned for discard (NB this is an intentional unsigned overflow/wrap-around)
// we might have to discard samples "from" the next frame too,
// if we're lapping a large block then a small at the start?
f->discard_samples_deferred = n - right_end;
f->current_loc_valid = TRUE;
f->first_decode = FALSE;
} else if (f->discard_samples_deferred) {
if (f->discard_samples_deferred >= right_start - left_start) {
f->discard_samples_deferred -= (right_start - left_start);
left_start = right_start;
*p_left = left_start;
} else {
left_start += f->discard_samples_deferred;
*p_left = left_start;
f->discard_samples_deferred = 0;
}
} else if (f->previous_length == 0 && f->current_loc_valid) {
// we're recovering from a seek... that means we're going to discard
// the samples from this packet even though we know our position from
// the last page header, so we need to update the position based on
// the discarded samples here
// but wait, the code below is going to add this in itself even
// on a discard, so we don't need to do it here...
}
// check if we have ogg information about the sample # for this packet
if (f->last_seg_which == f->end_seg_with_known_loc) {
// if we have a valid current loc, and this is final:
if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
uint32 current_end = f->known_loc_for_packet;
// then let's infer the size of the (probably) short final frame
if (current_end < f->current_loc + (right_end-left_start)) {
if (current_end < f->current_loc) {
// negative truncation, that's impossible!
*len = 0;
} else {
*len = current_end - f->current_loc;
}
*len += left_start; // this doesn't seem right, but has no ill effect on my test files
if (*len > right_end) *len = right_end; // this should never happen
f->current_loc += *len;
return TRUE;
}
}
// otherwise, just set our sample loc
// guess that the ogg granule pos refers to the _middle_ of the
// last frame?
// set f->current_loc to the position of left_start
f->current_loc = f->known_loc_for_packet - (n2-left_start);
f->current_loc_valid = TRUE;
}
if (f->current_loc_valid)
f->current_loc += (right_start - left_start);
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
*len = right_end; // ignore samples after the window goes to 0
CHECK(f);
return TRUE;
}
static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
{
int mode, left_end, right_end;
if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
}
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
}
static int vorbis_pump_first_frame(stb_vorbis *f)
{
int len, right, left, res;
res = vorbis_decode_packet(f, &len, &left, &right);
if (res)
vorbis_finish_frame(f, len, left, right);
return res;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
static int is_whole_packet_present(stb_vorbis *f)
{
// make sure that we have the packet available before continuing...
// this requires a full ogg parse, but we know we can fetch from f->stream
// instead of coding this out explicitly, we could save the current read state,
// read the next packet with get8() until end-of-packet, check f->eof, then
// reset the state? but that would be slower, esp. since we'd have over 256 bytes
// of state to restore (primarily the page segment table)
int s = f->next_seg, first = TRUE;
uint8 *p = f->stream;
if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
for (; s < f->segment_count; ++s) {
p += f->segments[s];
if (f->segments[s] < 255) // stop at first short segment
break;
}
// either this continues, or it ends it...
if (s == f->segment_count)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
for (; s == -1;) {
uint8 *q;
int n;
// check that we have the page header ready
if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
// validate the page
if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
if (p[4] != 0) return error(f, VORBIS_invalid_stream);
if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
if (f->previous_length)
if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
// if no previous length, we're resynching, so we can come in on a continued-packet,
// which we'll just drop
} else {
if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
}
n = p[26]; // segment counts
q = p+27; // q points to segment table
p = q + n; // advance past header
// make sure we've read the segment table
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
for (s=0; s < n; ++s) {
p += q[s];
if (q[s] < 255)
break;
}
if (s == n)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
return TRUE;
}
#endif // !STB_VORBIS_NO_PUSHDATA_API
static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
// first page, first packet
f->first_decode = TRUE;
if (!start_page(f)) return FALSE;
// validate page flag
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
// check for expected packet length
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) {
// check for the Ogg skeleton fishead identifying header to refine our error
if (f->segments[0] == 64 &&
getn(f, header, 6) &&
header[0] == 'f' &&
header[1] == 'i' &&
header[2] == 's' &&
header[3] == 'h' &&
header[4] == 'e' &&
header[5] == 'a' &&
get8(f) == 'd' &&
get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
else
return error(f, VORBIS_invalid_first_page);
}
// read packet
// check packet header
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
// vorbis_version
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
// framing_flag
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
// second packet!
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
if (!next_segment(f)) return FALSE;
if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
//file vendor
len = get32_packet(f);
f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1));
if (f->vendor == NULL) return error(f, VORBIS_outofmem);
for(i=0; i < len; ++i) {
f->vendor[i] = get8_packet(f);
}
f->vendor[len] = (char)'\0';
//user comments
f->comment_list_length = get32_packet(f);
f->comment_list = NULL;
if (f->comment_list_length > 0)
{
f->comment_list = (char**) setup_malloc(f, sizeof(char*) * (f->comment_list_length));
if (f->comment_list == NULL) return error(f, VORBIS_outofmem);
}
for(i=0; i < f->comment_list_length; ++i) {
len = get32_packet(f);
f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1));
if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem);
for(j=0; j < len; ++j) {
f->comment_list[i][j] = get8_packet(f);
}
f->comment_list[i][len] = (char)'\0';
}
// framing_flag
x = get8_packet(f);
if (!(x & 1)) return error(f, VORBIS_invalid_setup);
skip(f, f->bytes_in_seg);
f->bytes_in_seg = 0;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
// third packet!
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f)) {
// convert error in ogg header to write type
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
// codebooks
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_length >= 32) return error(f, VORBIS_invalid_setup);
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
// convert sparse items to non-sparse!
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
// compute the size of the sorted tables
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
// allocate an extra slot for sentinels
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
// allocate an extra slot at the front so that c->sorted_values[-1] is defined
// so that we can catch that case without an extra if
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
int values = lookup1_values(c->entries, c->dimensions);
if (values < 0) return error(f, VORBIS_invalid_setup);
c->lookup_values = (uint32) values;
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
// pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
// time domain transfers (notused)
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
// Floors
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = (int16)get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
// precompute the sorting
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values-1; ++j)
if (p[j].x == p[j+1].x)
return error(f, VORBIS_invalid_setup);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
// precompute the neighbors
for (j=2; j < g->values; ++j) {
int low = 0,hi = 0;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
// Residue
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
// precompute the classifications[] array to avoid inner-loop mod/divide
// call it 'classdata' since we already have r->classifications
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
// reserved field
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
// @SPECIFICATION: this case is missing from the spec
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
// Modes
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
// compute how much temporary memory is needed
// 1.
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
// maximum reasonable partition size is f->blocksize_1
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
// check if there's enough temp memory so we don't error later
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
// @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page
// without PAGEFLAG_continued_packet, so this either points to the first page, or
// the page after the end of the headers. It might be cleaner to point to a page
// in the middle of the headers, when that's the page where the first audio packet
// starts, but we'd have to also correctly skip the end of any continued packet in
// stb_vorbis_seek_start.
if (f->next_seg == -1) {
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
} else {
f->first_audio_page_offset = 0;
}
return TRUE;
}
static void vorbis_deinit(stb_vorbis *p)
{
int i,j;
setup_free(p, p->vendor);
for (i=0; i < p->comment_list_length; ++i) {
setup_free(p, p->comment_list[i]);
}
setup_free(p, p->comment_list);
if (p->residue_config) {
for (i=0; i < p->residue_count; ++i) {
Residue *r = p->residue_config+i;
if (r->classdata) {
for (j=0; j < p->codebooks[r->classbook].entries; ++j)
setup_free(p, r->classdata[j]);
setup_free(p, r->classdata);
}
setup_free(p, r->residue_books);
}
}
if (p->codebooks) {
CHECK(p);
for (i=0; i < p->codebook_count; ++i) {
Codebook *c = p->codebooks + i;
setup_free(p, c->codeword_lengths);
setup_free(p, c->multiplicands);
setup_free(p, c->codewords);
setup_free(p, c->sorted_codewords);
// c->sorted_values[-1] is the first entry in the array
setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
}
setup_free(p, p->codebooks);
}
setup_free(p, p->floor_config);
setup_free(p, p->residue_config);
if (p->mapping) {
for (i=0; i < p->mapping_count; ++i)
setup_free(p, p->mapping[i].chan);
setup_free(p, p->mapping);
}
CHECK(p);
for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
setup_free(p, p->channel_buffers[i]);
setup_free(p, p->previous_window[i]);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
setup_free(p, p->floor_buffers[i]);
#endif
setup_free(p, p->finalY[i]);
}
for (i=0; i < 2; ++i) {
setup_free(p, p->A[i]);
setup_free(p, p->B[i]);
setup_free(p, p->C[i]);
setup_free(p, p->window[i]);
setup_free(p, p->bit_reverse[i]);
}
#ifndef STB_VORBIS_NO_STDIO
if (p->close_on_free) fclose(p->f);
#endif
}
void stb_vorbis_close(stb_vorbis *p)
{
if (p == NULL) return;
vorbis_deinit(p);
setup_free(p,p);
}
static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
{
memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
if (z) {
p->alloc = *z;
p->alloc.alloc_buffer_length_in_bytes &= ~7;
p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
}
p->eof = 0;
p->error = VORBIS__no_error;
p->stream = NULL;
p->codebooks = NULL;
p->page_crc_tests = -1;
#ifndef STB_VORBIS_NO_STDIO
p->close_on_free = FALSE;
p->f = NULL;
#endif
}
int stb_vorbis_get_sample_offset(stb_vorbis *f)
{
if (f->current_loc_valid)
return f->current_loc;
else
return -1;
}
stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
{
stb_vorbis_info d;
d.channels = f->channels;
d.sample_rate = f->sample_rate;
d.setup_memory_required = f->setup_memory_required;
d.setup_temp_memory_required = f->setup_temp_memory_required;
d.temp_memory_required = f->temp_memory_required;
d.max_frame_size = f->blocksize_1 >> 1;
return d;
}
stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f)
{
stb_vorbis_comment d;
d.vendor = f->vendor;
d.comment_list_length = f->comment_list_length;
d.comment_list = f->comment_list;
return d;
}
int stb_vorbis_get_error(stb_vorbis *f)
{
int e = f->error;
f->error = VORBIS__no_error;
return e;
}
static stb_vorbis * vorbis_alloc(stb_vorbis *f)
{
stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
return p;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
void stb_vorbis_flush_pushdata(stb_vorbis *f)
{
f->previous_length = 0;
f->page_crc_tests = 0;
f->discard_samples_deferred = 0;
f->current_loc_valid = FALSE;
f->first_decode = FALSE;
f->samples_output = 0;
f->channel_buffer_start = 0;
f->channel_buffer_end = 0;
}
static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
{
int i,n;
for (i=0; i < f->page_crc_tests; ++i)
f->scan[i].bytes_done = 0;
// if we have room for more scans, search for them first, because
// they may cause us to stop early if their header is incomplete
if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
if (data_len < 4) return 0;
data_len -= 3; // need to look for 4-byte sequence, so don't miss
// one that straddles a boundary
for (i=0; i < data_len; ++i) {
if (data[i] == 0x4f) {
if (0==memcmp(data+i, ogg_page_header, 4)) {
int j,len;
uint32 crc;
// make sure we have the whole page header
if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
// only read up to this page start, so hopefully we'll
// have the whole page header start next time
data_len = i;
break;
}
// ok, we have it all; compute the length of the page
len = 27 + data[i+26];
for (j=0; j < data[i+26]; ++j)
len += data[i+27+j];
// scan everything up to the embedded crc (which we must 0)
crc = 0;
for (j=0; j < 22; ++j)
crc = crc32_update(crc, data[i+j]);
// now process 4 0-bytes
for ( ; j < 26; ++j)
crc = crc32_update(crc, 0);
// len is the total number of bytes we need to scan
n = f->page_crc_tests++;
f->scan[n].bytes_left = len-j;
f->scan[n].crc_so_far = crc;
f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
// if the last frame on a page is continued to the next, then
// we can't recover the sample_loc immediately
if (data[i+27+data[i+26]-1] == 255)
f->scan[n].sample_loc = ~0;
else
f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
f->scan[n].bytes_done = i+j;
if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
break;
// keep going if we still have room for more
}
}
}
}
for (i=0; i < f->page_crc_tests;) {
uint32 crc;
int j;
int n = f->scan[i].bytes_done;
int m = f->scan[i].bytes_left;
if (m > data_len - n) m = data_len - n;
// m is the bytes to scan in the current chunk
crc = f->scan[i].crc_so_far;
for (j=0; j < m; ++j)
crc = crc32_update(crc, data[n+j]);
f->scan[i].bytes_left -= m;
f->scan[i].crc_so_far = crc;
if (f->scan[i].bytes_left == 0) {
// does it match?
if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
// Houston, we have page
data_len = n+m; // consumption amount is wherever that scan ended
f->page_crc_tests = -1; // drop out of page scan mode
f->previous_length = 0; // decode-but-don't-output one frame
f->next_seg = -1; // start a new page
f->current_loc = f->scan[i].sample_loc; // set the current sample location
// to the amount we'd have decoded had we decoded this page
f->current_loc_valid = f->current_loc != ~0U;
return data_len;
}
// delete entry
f->scan[i] = f->scan[--f->page_crc_tests];
} else {
++i;
}
}
return data_len;
}
// return value: number of bytes we used
int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f, // the file we're decoding
const uint8 *data, int data_len, // the memory available for decoding
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
)
{
int i;
int len,right,left;
if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (f->page_crc_tests >= 0) {
*samples = 0;
return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);
}
f->stream = (uint8 *) data;
f->stream_end = (uint8 *) data + data_len;
f->error = VORBIS__no_error;
// check that we have the entire packet in memory
if (!is_whole_packet_present(f)) {
*samples = 0;
return 0;
}
if (!vorbis_decode_packet(f, &len, &left, &right)) {
// save the actual error we encountered
enum STBVorbisError error = f->error;
if (error == VORBIS_bad_packet_type) {
// flush and resynch
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
if (error == VORBIS_continued_packet_flag_invalid) {
if (f->previous_length == 0) {
// we may be resynching, in which case it's ok to hit one
// of these; just discard the packet
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
}
// if we get an error while parsing, what to do?
// well, it DEFINITELY won't work to continue from where we are!
stb_vorbis_flush_pushdata(f);
// restore the error that actually made us bail
f->error = error;
*samples = 0;
return 1;
}
// success!
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
if (channels) *channels = f->channels;
*samples = len;
*output = f->outputs;
return (int) (f->stream - data);
}
stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char *data, int data_len, // the memory available for decoding
int *data_used, // only defined if result is not NULL
int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + data_len;
p.push_mode = TRUE;
if (!start_decoder(&p)) {
if (p.eof)
*error = VORBIS_need_more_data;
else
*error = p.error;
vorbis_deinit(&p);
return NULL;
}
f = vorbis_alloc(&p);
if (f) {
*f = p;
*data_used = (int) (f->stream - data);
*error = 0;
return f;
} else {
vorbis_deinit(&p);
return NULL;
}
}
#endif // STB_VORBIS_NO_PUSHDATA_API
unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
#ifndef STB_VORBIS_NO_STDIO
return (unsigned int) (ftell(f->f) - f->f_start);
#endif
}
#ifndef STB_VORBIS_NO_PULLDATA_API
//
// DATA-PULLING API
//
static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
{
for(;;) {
int n;
if (f->eof) return 0;
n = get8(f);
if (n == 0x4f) { // page header candidate
unsigned int retry_loc = stb_vorbis_get_file_offset(f);
int i;
// check if we're off the end of a file_section stream
if (retry_loc - 25 > f->stream_len)
return 0;
// check the rest of the header
for (i=1; i < 4; ++i)
if (get8(f) != ogg_page_header[i])
break;
if (f->eof) return 0;
if (i == 4) {
uint8 header[27];
uint32 i, crc, goal, len;
for (i=0; i < 4; ++i)
header[i] = ogg_page_header[i];
for (; i < 27; ++i)
header[i] = get8(f);
if (f->eof) return 0;
if (header[4] != 0) goto invalid;
goal = header[22] + (header[23] << 8) + (header[24]<<16) + ((uint32)header[25]<<24);
for (i=22; i < 26; ++i)
header[i] = 0;
crc = 0;
for (i=0; i < 27; ++i)
crc = crc32_update(crc, header[i]);
len = 0;
for (i=0; i < header[26]; ++i) {
int s = get8(f);
crc = crc32_update(crc, s);
len += s;
}
if (len && f->eof) return 0;
for (i=0; i < len; ++i)
crc = crc32_update(crc, get8(f));
// finished parsing probable page
if (crc == goal) {
// we could now check that it's either got the last
// page flag set, OR it's followed by the capture
// pattern, but I guess TECHNICALLY you could have
// a file with garbage between each ogg page and recover
// from it automatically? So even though that paranoia
// might decrease the chance of an invalid decode by
// another 2^32, not worth it since it would hose those
// invalid-but-useful files?
if (end)
*end = stb_vorbis_get_file_offset(f);
if (last) {
if (header[5] & 0x04)
*last = 1;
else
*last = 0;
}
set_file_offset(f, retry_loc-1);
return 1;
}
}
invalid:
// not a valid page, so rewind and look for next one
set_file_offset(f, retry_loc);
}
}
}
#define SAMPLE_unknown 0xffffffff
// seeking is implemented with a binary search, which narrows down the range to
// 64K, before using a linear search (because finding the synchronization
// pattern can be expensive, and the chance we'd find the end page again is
// relatively high for small ranges)
//
// two initial interpolation-style probes are used at the start of the search
// to try to bound either side of the binary search sensibly, while still
// working in O(log n) time if they fail.
static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
{
uint8 header[27], lacing[255];
int i,len;
// record where the page starts
z->page_start = stb_vorbis_get_file_offset(f);
// parse the header
getn(f, header, 27);
if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
return 0;
getn(f, lacing, header[26]);
// determine the length of the payload
len = 0;
for (i=0; i < header[26]; ++i)
len += lacing[i];
// this implies where the page ends
z->page_end = z->page_start + 27 + header[26] + len;
// read the last-decoded sample out of the data
z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
// restore file state to where we were
set_file_offset(f, z->page_start);
return 1;
}
// rarely used function to seek back to the preceding page while finding the
// start of a packet
static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
{
unsigned int previous_safe, end;
// now we want to seek back 64K from the limit
if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
previous_safe = limit_offset - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
while (vorbis_find_page(f, &end, NULL)) {
if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
return 1;
set_file_offset(f, end);
}
return 0;
}
// implements the search logic for finding a page and starting decoding. if
// the function succeeds, current_loc_valid will be true and current_loc will
// be less than or equal to the provided sample number (the closer the
// better).
static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
{
ProbedPage left, right, mid;
int i, start_seg_with_known_loc, end_pos, page_start;
uint32 delta, stream_length, padding, last_sample_limit;
double offset = 0.0, bytes_per_sample = 0.0;
int probe = 0;
// find the last page and validate the target sample
stream_length = stb_vorbis_stream_length_in_samples(f);
if (stream_length == 0) return error(f, VORBIS_seek_without_length);
if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
// this is the maximum difference between the window-center (which is the
// actual granule position value), and the right-start (which the spec
// indicates should be the granule position (give or take one)).
padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
if (sample_number < padding)
last_sample_limit = 0;
else
last_sample_limit = sample_number - padding;
left = f->p_first;
while (left.last_decoded_sample == ~0U) {
// (untested) the first page does not have a 'last_decoded_sample'
set_file_offset(f, left.page_end);
if (!get_seek_page_info(f, &left)) goto error;
}
right = f->p_last;
assert(right.last_decoded_sample != ~0U);
// starting from the start is handled differently
if (last_sample_limit <= left.last_decoded_sample) {
if (stb_vorbis_seek_start(f)) {
if (f->current_loc > sample_number)
return error(f, VORBIS_seek_failed);
return 1;
}
return 0;
}
while (left.page_end != right.page_start) {
assert(left.page_end < right.page_start);
// search range in bytes
delta = right.page_start - left.page_end;
if (delta <= 65536) {
// there's only 64K left to search - handle it linearly
set_file_offset(f, left.page_end);
} else {
if (probe < 2) {
if (probe == 0) {
// first probe (interpolate)
double data_bytes = right.page_end - left.page_start;
bytes_per_sample = data_bytes / right.last_decoded_sample;
offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample);
} else {
// second probe (try to bound the other side)
double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample;
if (error >= 0 && error < 8000) error = 8000;
if (error < 0 && error > -8000) error = -8000;
offset += error * 2;
}
// ensure the offset is valid
if (offset < left.page_end)
offset = left.page_end;
if (offset > right.page_start - 65536)
offset = right.page_start - 65536;
set_file_offset(f, (unsigned int) offset);
} else {
// binary search for large ranges (offset by 32K to ensure
// we don't hit the right page)
set_file_offset(f, left.page_end + (delta / 2) - 32768);
}
if (!vorbis_find_page(f, NULL, NULL)) goto error;
}
for (;;) {
if (!get_seek_page_info(f, &mid)) goto error;
if (mid.last_decoded_sample != ~0U) break;
// (untested) no frames end on this page
set_file_offset(f, mid.page_end);
assert(mid.page_start < right.page_start);
}
// if we've just found the last page again then we're in a tricky file,
// and we're close enough (if it wasn't an interpolation probe).
if (mid.page_start == right.page_start) {
if (probe >= 2 || delta <= 65536)
break;
} else {
if (last_sample_limit < mid.last_decoded_sample)
right = mid;
else
left = mid;
}
++probe;
}
// seek back to start of the last packet
page_start = left.page_start;
set_file_offset(f, page_start);
if (!start_page(f)) return error(f, VORBIS_seek_failed);
end_pos = f->end_seg_with_known_loc;
assert(end_pos >= 0);
for (;;) {
for (i = end_pos; i > 0; --i)
if (f->segments[i-1] != 255)
break;
start_seg_with_known_loc = i;
if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
break;
// (untested) the final packet begins on an earlier page
if (!go_to_page_before(f, page_start))
goto error;
page_start = stb_vorbis_get_file_offset(f);
if (!start_page(f)) goto error;
end_pos = f->segment_count - 1;
}
// prepare to start decoding
f->current_loc_valid = FALSE;
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
f->previous_length = 0;
f->next_seg = start_seg_with_known_loc;
for (i = 0; i < start_seg_with_known_loc; i++)
skip(f, f->segments[i]);
// start decoding (optimizable - this frame is generally discarded)
if (!vorbis_pump_first_frame(f))
return 0;
if (f->current_loc > sample_number)
return error(f, VORBIS_seek_failed);
return 1;
error:
// try to restore the file to a valid state
stb_vorbis_seek_start(f);
return error(f, VORBIS_seek_failed);
}
// the same as vorbis_decode_initial, but without advancing
static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
int bits_read, bytes_read;
if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
return 0;
// either 1 or 2 bytes were read, figure out which so we can rewind
bits_read = 1 + ilog(f->mode_count-1);
if (f->mode_config[*mode].blockflag)
bits_read += 2;
bytes_read = (bits_read + 7) / 8;
f->bytes_in_seg += bytes_read;
f->packet_bytes -= bytes_read;
skip(f, -bytes_read);
if (f->next_seg == -1)
f->next_seg = f->segment_count - 1;
else
f->next_seg--;
f->valid_bits = 0;
return 1;
}
int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
{
uint32 max_frame_samples;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
// fast page-level search
if (!seek_to_sample_coarse(f, sample_number))
return 0;
assert(f->current_loc_valid);
assert(f->current_loc <= sample_number);
// linear search for the relevant packet
max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
while (f->current_loc < sample_number) {
int left_start, left_end, right_start, right_end, mode, frame_samples;
if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
return error(f, VORBIS_seek_failed);
// calculate the number of samples returned by the next frame
frame_samples = right_start - left_start;
if (f->current_loc + frame_samples > sample_number) {
return 1; // the next frame will contain the sample
} else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
// there's a chance the frame after this could contain the sample
vorbis_pump_first_frame(f);
} else {
// this frame is too early to be relevant
f->current_loc += frame_samples;
f->previous_length = 0;
maybe_start_packet(f);
flush_packet(f);
}
}
// the next frame should start with the sample
if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed);
return 1;
}
int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
{
if (!stb_vorbis_seek_frame(f, sample_number))
return 0;
if (sample_number != f->current_loc) {
int n;
uint32 frame_start = f->current_loc;
stb_vorbis_get_frame_float(f, &n, NULL);
assert(sample_number > frame_start);
assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
f->channel_buffer_start += (sample_number - frame_start);
}
return 1;
}
int stb_vorbis_seek_start(stb_vorbis *f)
{
if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }
set_file_offset(f, f->first_audio_page_offset);
f->previous_length = 0;
f->first_decode = TRUE;
f->next_seg = -1;
return vorbis_pump_first_frame(f);
}
unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
{
unsigned int restore_offset, previous_safe;
unsigned int end, last_page_loc;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!f->total_samples) {
unsigned int last;
uint32 lo,hi;
char header[6];
// first, store the current decode position so we can restore it
restore_offset = stb_vorbis_get_file_offset(f);
// now we want to seek back 64K from the end (the last page must
// be at most a little less than 64K, but let's allow a little slop)
if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
previous_safe = f->stream_len - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
// previous_safe is now our candidate 'earliest known place that seeking
// to will lead to the final page'
if (!vorbis_find_page(f, &end, &last)) {
// if we can't find a page, we're hosed!
f->error = VORBIS_cant_find_last_page;
f->total_samples = 0xffffffff;
goto done;
}
// check if there are more pages
last_page_loc = stb_vorbis_get_file_offset(f);
// stop when the last_page flag is set, not when we reach eof;
// this allows us to stop short of a 'file_section' end without
// explicitly checking the length of the section
while (!last) {
set_file_offset(f, end);
if (!vorbis_find_page(f, &end, &last)) {
// the last page we found didn't have the 'last page' flag
// set. whoops!
break;
}
//previous_safe = last_page_loc+1; // NOTE: not used after this point, but note for debugging
last_page_loc = stb_vorbis_get_file_offset(f);
}
set_file_offset(f, last_page_loc);
// parse the header
getn(f, (unsigned char *)header, 6);
// extract the absolute granule position
lo = get32(f);
hi = get32(f);
if (lo == 0xffffffff && hi == 0xffffffff) {
f->error = VORBIS_cant_find_last_page;
f->total_samples = SAMPLE_unknown;
goto done;
}
if (hi)
lo = 0xfffffffe; // saturate
f->total_samples = lo;
f->p_last.page_start = last_page_loc;
f->p_last.page_end = end;
f->p_last.last_decoded_sample = lo;
done:
set_file_offset(f, restore_offset);
}
return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
}
float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
{
return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
}
int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
{
int len, right,left,i;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!vorbis_decode_packet(f, &len, &left, &right)) {
f->channel_buffer_start = f->channel_buffer_end = 0;
return 0;
}
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
f->channel_buffer_start = left;
f->channel_buffer_end = left+len;
if (channels) *channels = f->channels;
if (output) *output = f->outputs;
return len;
}
#ifndef STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.f = file;
p.f_start = (uint32) ftell(file);
p.stream_len = length;
p.close_on_free = close_on_free;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
{
unsigned int len, start;
start = (unsigned int) ftell(file);
fseek(file, 0, SEEK_END);
len = (unsigned int) (ftell(file) - start);
fseek(file, start, SEEK_SET);
return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
}
stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
{
FILE *f;
#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
if (0 != fopen_s(&f, filename, "rb"))
f = NULL;
#else
f = fopen(filename, "rb");
#endif
if (f)
return stb_vorbis_open_file(f, TRUE, error, alloc);
if (error) *error = VORBIS_file_open_failure;
return NULL;
}
#endif // STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
if (!data) {
if (error) *error = VORBIS_unexpected_eof;
return NULL;
}
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + len;
p.stream_start = (uint8 *) p.stream;
p.stream_len = len;
p.push_mode = FALSE;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
if (error) *error = VORBIS__no_error;
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#define PLAYBACK_MONO 1
#define PLAYBACK_LEFT 2
#define PLAYBACK_RIGHT 4
#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
static int8 channel_position[7][6] =
{
{ 0 },
{ C },
{ L, R },
{ L, C, R },
{ L, R, L, R },
{ L, C, R, L, R },
{ L, C, R, L, R, C },
};
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
typedef union {
float f;
int i;
} float_conv;
typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
#define FASTDEF(x) float_conv x
// add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
#define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
#define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
#define check_endianness()
#else
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
#define check_endianness()
#define FASTDEF(x)
#endif
static void copy_samples(short *dest, float *src, int len)
{
int i;
check_endianness();
for (i=0; i < len; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
dest[i] = v;
}
}
static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
{
#define STB_BUFFER_SIZE 32
float buffer[STB_BUFFER_SIZE];
int i,j,o,n = STB_BUFFER_SIZE;
check_endianness();
for (o = 0; o < len; o += STB_BUFFER_SIZE) {
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
if (channel_position[num_c][j] & mask) {
for (i=0; i < n; ++i)
buffer[i] += data[j][d_offset+o+i];
}
}
for (i=0; i < n; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o+i] = v;
}
}
#undef STB_BUFFER_SIZE
}
static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
{
#define STB_BUFFER_SIZE 32
float buffer[STB_BUFFER_SIZE];
int i,j,o,n = STB_BUFFER_SIZE >> 1;
// o is the offset in the source data
check_endianness();
for (o = 0; o < len; o += STB_BUFFER_SIZE >> 1) {
// o2 is the offset in the output data
int o2 = o << 1;
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
buffer[i*2+1] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_LEFT) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_RIGHT) {
for (i=0; i < n; ++i) {
buffer[i*2+1] += data[j][d_offset+o+i];
}
}
}
for (i=0; i < (n<<1); ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o2+i] = v;
}
}
#undef STB_BUFFER_SIZE
}
static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
{
int i;
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
for (i=0; i < buf_c; ++i)
compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
for (i=0; i < limit; ++i)
copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
for ( ; i < buf_c; ++i)
memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
}
}
int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
{
float **output = NULL;
int len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len > num_samples) len = num_samples;
if (len)
convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
return len;
}
static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
{
int i;
check_endianness();
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
assert(buf_c == 2);
for (i=0; i < buf_c; ++i)
compute_stereo_samples(buffer, data_c, data, d_offset, len);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
int j;
for (j=0; j < len; ++j) {
for (i=0; i < limit; ++i) {
FASTDEF(temp);
float f = data[i][d_offset+j];
int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
*buffer++ = v;
}
for ( ; i < buf_c; ++i)
*buffer++ = 0;
}
}
}
int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
{
float **output;
int len;
if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len) {
if (len*num_c > num_shorts) len = num_shorts / num_c;
convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
}
return len;
}
int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
{
float **outputs;
int len = num_shorts / channels;
int n=0;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
buffer += k*channels;
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
{
float **outputs;
int n=0;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
#ifndef STB_VORBIS_NO_STDIO
int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // NO_STDIO
int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // STB_VORBIS_NO_INTEGER_CONVERSION
int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
{
float **outputs;
int len = num_floats / channels;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int i,j;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
for (j=0; j < k; ++j) {
for (i=0; i < z; ++i)
*buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
for ( ; i < channels; ++i)
*buffer++ = 0;
}
n += k;
f->channel_buffer_start += k;
if (n == len)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
{
float **outputs;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < num_samples) {
int i;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= num_samples) k = num_samples - n;
if (k) {
for (i=0; i < z; ++i)
memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
for ( ; i < channels; ++i)
memset(buffer[i]+n, 0, sizeof(float) * k);
}
n += k;
f->channel_buffer_start += k;
if (n == num_samples)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
#endif // STB_VORBIS_NO_PULLDATA_API
/* Version history
1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223
found with Mayhem by ForAllSecure
1.16 - 2019-03-04 - fix warnings
1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
1.14 - 2018-02-11 - delete bogus dealloca usage
1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
1.11 - 2017-07-23 - fix MinGW compilation
1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version
1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;
avoid discarding last frame of audio data
1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API
some more crash fixes when out of memory or with corrupt files
1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
some crash fixes when out of memory or with corrupt files
1.05 - 2015-04-19 - don't define __forceinline if it's redundant
1.04 - 2014-08-27 - fix missing const-correct case in API
1.03 - 2014-08-07 - Warning fixes
1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows
1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float
1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel
(API change) report sample rate for decode-full-file funcs
0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
0.99993 - remove assert that fired on legal files with empty tables
0.99992 - rewind-to-start
0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
0.9998 - add a full-decode function with a memory source
0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
0.9996 - query length of vorbis stream in samples/seconds
0.9995 - bugfix to another optimization that only happened in certain files
0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
0.9992 - performance improvement of IMDCT; now performs close to reference implementation
0.9991 - performance improvement of IMDCT
0.999 - (should have been 0.9990) performance improvement of IMDCT
0.998 - no-CRT support from Casey Muratori
0.997 - bugfixes for bugs found by Terje Mathisen
0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
0.992 - fixes for MinGW warning
0.991 - turn fast-float-conversion on by default
0.990 - fix push-mode seek recovery if you seek into the headers
0.98b - fix to bad release of 0.98
0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
0.97 - builds under c++ (typecasting, don't use 'class' keyword)
0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
0.95 - clamping code for 16-bit functions
0.94 - not publically released
0.93 - fixed all-zero-floor case (was decoding garbage)
0.92 - fixed a memory leak
0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
0.90 - first public release
*/
#endif // STB_VORBIS_HEADER_ONLY
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
|
the_stack_data/147306.c | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
void mutal_rec_d();
void
mutal_rec_a()
{
mutal_rec_d();
}
void
mutal_rec_d()
{
mutal_rec_a();
}
void
recurse()
{
recurse();
}
int
main()
{
recurse();
mutal_rec_a();
return 0;
}
|
the_stack_data/173576926.c | #include <stdio.h>
#include <stdlib.h>
struct ll_node {
int n;
struct ll_node * next;
};
struct ll_node * build_list(int n){
struct ll_node * head = malloc(sizeof(struct ll_node));
struct ll_node * current = head;
for (int i=1; i < n; i++){
current->n = i;
current->next = malloc(sizeof(struct ll_node));
current = current->next;
}
current->n = n;
current->next = head;
return head;
}
struct ll_node * run_through(struct ll_node * current){
struct ll_node * next_item = 0;
while(current->next != current){
next_item = current->next;
current->next = next_item->next;
current = current->next;
free(next_item);
}
return current;
}
int main(){
struct ll_node * head = build_list(3001330);
head = run_through(head);
printf("%d\n", head->n);
fflush(stdout);
free(head);
return 0;
} |
the_stack_data/61074779.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void przepisz(int n,int m,int tab1[n][m],int tab2[n][m]);
int main()
{
int n,m;
printf("Podaj liczbe wierszy tablicy: ");
scanf("%i",&n);
printf("Podaj liczbe kolumn tablicy: ");
scanf("%i",&m);
int tab1[n][m],tab2[n][m],i,j;
srand(time(NULL));
//---------------------------------------------------------------------
printf("tablice przed zadzialaniem funkji przepisz: \n\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
tab1[i][j]=rand()%11;
printf("%4i",tab1[i][j]);
}
printf("\n\n");
}
printf("\n\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
tab2[i][j]=rand()%11;
printf("%4i",tab2[i][j]);
}
printf("\n\n");
}
printf("\n\n");
//---------------------------------------------------------------------
printf("tablice po zadzialaniu funkji przepisz: \n\n");
przepisz(n,m,tab1,tab2);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%4i",tab1[i][j]);
}
printf("\n\n");
}
printf("\n\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%4i",tab2[i][j]);
}
printf("\n\n");
}
printf("\n\n");
//---------------------------------------------------------------------
return 0;
}
void przepisz(int n,int m,int tab1[n][m],int tab2[n][m])
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
tab2[i][j]=tab1[i][j];
}
}
}
|
the_stack_data/248581802.c | // RUN: %clang_cc1 -analyze -analyzer-checker=core,deadcode.DeadStores,experimental.deadcode.UnreachableCode -verify -analyzer-opt-analyze-nested-blocks -Wno-unused-value %s
extern void foo(int a);
// The first few tests are non-path specific - we should be able to find them
void test(unsigned a) {
switch (a) {
a += 5; // expected-warning{{never executed}}
case 2:
a *= 10;
case 3:
a %= 2;
}
foo(a);
}
void test2(unsigned a) {
help:
if (a > 0)
return;
if (a == 0)
return;
foo(a); // expected-warning{{never executed}}
goto help;
}
void test3(unsigned a) {
while(1);
if (a > 5) { // expected-warning{{never executed}}
return;
}
}
// These next tests are path-sensitive
void test4() {
int a = 5;
while (a > 1)
a -= 2;
if (a > 1) {
a = a + 56; // expected-warning{{never executed}}
}
foo(a);
}
extern void bar(char c);
void test5(const char *c) {
foo(c[0]);
if (!c) {
bar(1); // expected-warning{{never executed}}
}
}
// These next tests are false positives and should not generate warnings
void test6(const char *c) {
if (c) return;
if (!c) return;
__builtin_unreachable(); // no-warning
}
// Compile-time constant false positives
#define CONSTANT 0
enum test_enum { Off, On };
void test7() {
if (CONSTANT)
return; // no-warning
if (sizeof(int))
return; // no-warning
if (Off)
return; // no-warning
}
void test8() {
static unsigned a = 0;
if (a)
a = 123; // no-warning
a = 5;
}
// Check for bugs where multiple statements are reported
void test9(unsigned a) {
switch (a) {
if (a) // expected-warning{{never executed}}
foo(a + 5); // no-warning
else // no-warning
foo(a); // no-warning
case 1:
case 2:
break;
default:
break;
}
}
// Tests from flow-sensitive version
void test10() {
goto c;
d:
goto e; // expected-warning {{never executed}}
c: ;
int i;
return;
goto b; // expected-warning {{never executed}}
goto a; // expected-warning {{never executed}}
b:
i = 1; // no-warning
a:
i = 2; // no-warning
goto f;
e:
goto d;
f: ;
}
// test11: we can actually end up in the default case, even if it is not
// obvious: there might be something wrong with the given argument.
enum foobar { FOO, BAR };
extern void error();
void test11(enum foobar fb) {
switch (fb) {
case FOO:
break;
case BAR:
break;
default:
error(); // no-warning
return;
error(); // expected-warning {{never executed}}
}
}
|
the_stack_data/20450303.c | /*
* Copyright (c) 2013
* - Zachary Cutlip <[email protected]>
* - Tactical Network Solutions, LLC
*
* See LICENSE.txt for more details.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int accept_remote(const char *local_port);
int receive_data(int sockfd);
int use_stack_space(int sockfd);
int main(int argc, char **argv)
{
int sockfd;
char *local_port;
int bytes_received;
if(argc != 2)
{
printf("Please specify local port.\n");
exit(1);
}
local_port=argv[1];
sockfd=accept_remote(local_port);
if(sockfd < 0)
{
printf("Failed to accept connection.\n");
exit(1);
}
bytes_received=use_stack_space(sockfd);
printf("recieved %d bytes\n",bytes_received);
shutdown(sockfd,SHUT_RDWR);
close(sockfd);
return 0;
}
int use_stack_space(int sockfd)
{
/* allocate a bunch of space on the stack
* before calling the vulnerable function.
* so we can overflow with a larger buffer.
*/
char buf[2048];
memset(buf,1,sizeof(buf));
return receive_data(sockfd);
}
/*
* vulnerable function.
* reads up to 2048 off a socket onto a small buffer on the stack.
*/
int receive_data(int sockfd)
{
int read_bytes;
char buf[512];
if(sockfd < 0)
{
return -1;
}
read_bytes=recv(sockfd,buf,2048,0);
if(read_bytes < 0)
{
perror("recv");
}else
{
printf("read %d bytes.\n",read_bytes);
}
return read_bytes;
}
int accept_remote(const char *local_port)
{
int server_sockfd;
int connection_sockfd;
socklen_t sin_size;
struct addrinfo hints;
struct addrinfo *srvinfo;
struct addrinfo *p;
struct sockaddr_storage their_addr;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
if(NULL == local_port)
{
printf("Invalid parameter: local_port string was NULL.\n");
return -1;
}
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; //use my ip
if((rv = getaddrinfo(NULL,local_port,&hints,&srvinfo)) != 0)
{
printf("getaddrinfo: %s\n",gai_strerror(rv));
return -1;
}
for(p=srvinfo; p != NULL; p=p->ai_next)
{
if((server_sockfd = socket(p->ai_family,p->ai_socktype,
p->ai_protocol)) == -1)
{
printf("server: socket %s",strerror(errno));
continue;
}
if(setsockopt(server_sockfd, SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1)
{
printf("setsockopt: %s",strerror(errno));
return -1;
}
if(bind(server_sockfd,p->ai_addr, p->ai_addrlen) == -1)
{
printf("server: bind %s",strerror(errno));
close(server_sockfd);
continue;
}
break;
}
if(NULL == p)
{
printf("server: failed to bind.");
return -1;
}
freeaddrinfo(srvinfo);
if(listen(server_sockfd,1) == -1)
{
printf("listen=: %s",strerror(errno));
return -1;
}
while(1)
{
sin_size=sizeof(their_addr);
connection_sockfd = accept(server_sockfd,(struct sockaddr *)&their_addr,&sin_size);
if(connection_sockfd == -1)
{
printf("accept: %s",strerror(errno));
continue;
}
inet_ntop(their_addr.ss_family,
&(((struct sockaddr_in *)&their_addr)->sin_addr),
s,sizeof(s));
printf("Connection from %s",s);
close(server_sockfd); //done with listener
return connection_sockfd;
}
}
|
the_stack_data/741478.c | #include <stdio.h>
#define STACKSIZE 100
int stack_one[STACKSIZE];
int sp_one=-1;
void push_one(int item){
stack_one[++sp_one]=item;
}
int pop_one(void){
return stack_one[sp_one--];
}
int empty_one(void){
return sp_one==-1;
}
int full_one(void){
return sp_one==STACKSIZE-1;
}
int stack_two[STACKSIZE];
int sp_two=-1;
void push_two(int item){
stack_two[++sp_two]=item;
}
int pop_two(void){
return stack_two[sp_two--];
}
int empty_two(void){
return sp_two==-1;
}
int full_two(void){
return sp_two==STACKSIZE-1;
}
void enqueue(int item){
if(full_queue()){
printf("Full!\n");
return;
}
if(!full_one())
push_one(item);
else{
while(!full_two() && !empty_one())
push_two(pop_one());
push_one(item);
}
}
int dequeue(void){
int retval;
if(empty_two()){
while(!empty_one()){
retval=pop_one();
push_two(retval);
}
}
if(empty_two()){
printf("Queue empty.\n");
return -1;
}else
retval=pop_two();
return retval;
}
int empty_queue(){
return empty_one() && empty_two();
}
int full_queue(){
return full_one() && full_two();
}
int main(int argc, char const *argv[])
{
int data[]={1,2,3,4,5,6,7,8,9,10};
int size=sizeof(data)/sizeof(int);
int i=0;
while(i<6)
enqueue(data[i++]);
while(!empty_queue())
printf("%d\n",dequeue());
while(i<size)
enqueue(data[i++]);
while(!empty_queue())
printf("%d\n",dequeue());
return 0;
} |
the_stack_data/69279.c | #include <stdio.h>
#include <stdlib.h>
int main ()
{
int vet[8],i,rr,ri;
i=7;
rr=0;
scanf("%d",&ri);
if ((ri>=0) && (ri<256))
{
while (i>=0)
{
vet[i]=0;
i--;
}
i=7;
while (ri>=1)
{
rr=(ri%2);
ri=(ri/2);
vet[i]=rr;
i--;
}
i=0;
printf("\n\n");
while (i<8)
{
printf("%d",vet[i]);
i++;
}
printf("\n\n");
}
else
printf("\n\n");
printf("numero invalido\n");
printf("\n\n");
system ("pause");
return 0;
}
|
the_stack_data/178265140.c | /* { dg-do compile } */
/* { dg-options "-O2 -fdelete-null-pointer-checks -fdump-tree-vrp1" } */
struct B { int x; };
extern void g3(struct B *that) __attribute__((nonnull));
int f3(struct B *a)
{
g3(a);
return a != (void *)0;
}
/* { dg-final { scan-tree-dump "return 1;" "vrp1" } } */
|
the_stack_data/605511.c | /* $OpenBSD: enc_des.c,v 1.1 1998/03/12 04:48:48 art Exp $ */
/* $Id: enc_des.c,v 1.1 1998/03/12 04:48:48 art Exp $ */
/*-
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(AUTHENTICATION) && defined(ENCRYPTION) && defined(DES_ENCRYPTION)
#include <arpa/telnet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "encrypt.h"
#include "misc-proto.h"
#include <des.h>
extern int encrypt_debug_mode;
#define CFB 0
#define OFB 1
#define NO_SEND_IV 1
#define NO_RECV_IV 2
#define NO_KEYID 4
#define IN_PROGRESS (NO_SEND_IV|NO_RECV_IV|NO_KEYID)
#define SUCCESS 0
#define FAILED -1
struct stinfo {
des_cblock str_output;
des_cblock str_feed;
des_cblock str_iv;
des_cblock str_ikey;
des_key_schedule str_sched;
int str_index;
int str_flagshift;
};
struct fb {
des_cblock krbdes_key;
des_key_schedule krbdes_sched;
des_cblock temp_feed;
unsigned char fb_feed[64];
int need_start;
int state[2];
int keyid[2];
int once;
struct stinfo streams[2];
};
static struct fb fb[2];
struct keyidlist {
char *keyid;
int keyidlen;
char *key;
int keylen;
int flags;
} keyidlist [] = {
{ "\0", 1, 0, 0, 0 }, /* default key of zero */
{ 0, 0, 0, 0, 0 }
};
#define KEYFLAG_MASK 03
#define KEYFLAG_NOINIT 00
#define KEYFLAG_INIT 01
#define KEYFLAG_OK 02
#define KEYFLAG_BAD 03
#define KEYFLAG_SHIFT 2
#define SHIFT_VAL(a,b) (KEYFLAG_SHIFT*((a)+((b)*2)))
#define FB64_IV 1
#define FB64_IV_OK 2
#define FB64_IV_BAD 3
void fb64_stream_iv (des_cblock, struct stinfo *);
void fb64_init (struct fb *);
static int fb64_start (struct fb *, int, int);
int fb64_is (unsigned char *, int, struct fb *);
int fb64_reply (unsigned char *, int, struct fb *);
static void fb64_session (Session_Key *, int, struct fb *);
void fb64_stream_key (des_cblock, struct stinfo *);
int fb64_keyid (int, unsigned char *, int *, struct fb *);
void cfb64_init(int server)
{
fb64_init(&fb[CFB]);
fb[CFB].fb_feed[4] = ENCTYPE_DES_CFB64;
fb[CFB].streams[0].str_flagshift = SHIFT_VAL(0, CFB);
fb[CFB].streams[1].str_flagshift = SHIFT_VAL(1, CFB);
}
void ofb64_init(int server)
{
fb64_init(&fb[OFB]);
fb[OFB].fb_feed[4] = ENCTYPE_DES_OFB64;
fb[CFB].streams[0].str_flagshift = SHIFT_VAL(0, OFB);
fb[CFB].streams[1].str_flagshift = SHIFT_VAL(1, OFB);
}
void fb64_init(struct fb *fbp)
{
memset(fbp,0, sizeof(*fbp));
fbp->state[0] = fbp->state[1] = FAILED;
fbp->fb_feed[0] = IAC;
fbp->fb_feed[1] = SB;
fbp->fb_feed[2] = TELOPT_ENCRYPT;
fbp->fb_feed[3] = ENCRYPT_IS;
}
/*
* Returns:
* -1: some error. Negotiation is done, encryption not ready.
* 0: Successful, initial negotiation all done.
* 1: successful, negotiation not done yet.
* 2: Not yet. Other things (like getting the key from
* Kerberos) have to happen before we can continue.
*/
int cfb64_start(int dir, int server)
{
return(fb64_start(&fb[CFB], dir, server));
}
int ofb64_start(int dir, int server)
{
return(fb64_start(&fb[OFB], dir, server));
}
static int fb64_start(struct fb *fbp, int dir, int server)
{
int x;
unsigned char *p;
int state;
switch (dir) {
case DIR_DECRYPT:
/*
* This is simply a request to have the other side
* start output (our input). He will negotiate an
* IV so we need not look for it.
*/
state = fbp->state[dir-1];
if (state == FAILED)
state = IN_PROGRESS;
break;
case DIR_ENCRYPT:
state = fbp->state[dir-1];
if (state == FAILED)
state = IN_PROGRESS;
else if ((state & NO_SEND_IV) == 0) {
break;
}
if (!VALIDKEY(fbp->krbdes_key)) {
fbp->need_start = 1;
break;
}
state &= ~NO_SEND_IV;
state |= NO_RECV_IV;
if (encrypt_debug_mode)
printf("Creating new feed\r\n");
/*
* Create a random feed and send it over.
*/
#ifndef OLD_DES_RANDOM_KEY
des_new_random_key(&fbp->temp_feed);
#else
/*
* From des_cryp.man "If the des_check_key flag is non-zero,
* des_set_key will check that the key passed is
* of odd parity and is not a week or semi-weak key."
*/
do {
des_random_key(fbp->temp_feed);
des_set_odd_parity(fbp->temp_feed);
} while (des_is_weak_key(fbp->temp_feed));
#endif
des_ecb_encrypt(&fbp->temp_feed,
&fbp->temp_feed,
fbp->krbdes_sched, 1);
p = fbp->fb_feed + 3;
*p++ = ENCRYPT_IS;
p++;
*p++ = FB64_IV;
for (x = 0; x < sizeof(des_cblock); ++x) {
if ((*p++ = fbp->temp_feed[x]) == IAC)
*p++ = IAC;
}
*p++ = IAC;
*p++ = SE;
printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
net_write(fbp->fb_feed, p - fbp->fb_feed);
break;
default:
return(FAILED);
}
return(fbp->state[dir-1] = state);
}
/*
* Returns:
* -1: some error. Negotiation is done, encryption not ready.
* 0: Successful, initial negotiation all done.
* 1: successful, negotiation not done yet.
*/
int cfb64_is(unsigned char *data, int cnt)
{
return(fb64_is(data, cnt, &fb[CFB]));
}
int ofb64_is(unsigned char *data, int cnt)
{
return(fb64_is(data, cnt, &fb[OFB]));
}
int fb64_is(unsigned char *data, int cnt, struct fb *fbp)
{
unsigned char *p;
int state = fbp->state[DIR_DECRYPT-1];
if (cnt-- < 1)
goto failure;
switch (*data++) {
case FB64_IV:
if (cnt != sizeof(des_cblock)) {
if (encrypt_debug_mode)
printf("CFB64: initial vector failed on size\r\n");
state = FAILED;
goto failure;
}
if (encrypt_debug_mode)
printf("CFB64: initial vector received\r\n");
if (encrypt_debug_mode)
printf("Initializing Decrypt stream\r\n");
fb64_stream_iv(data, &fbp->streams[DIR_DECRYPT-1]);
p = fbp->fb_feed + 3;
*p++ = ENCRYPT_REPLY;
p++;
*p++ = FB64_IV_OK;
*p++ = IAC;
*p++ = SE;
printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
net_write(fbp->fb_feed, p - fbp->fb_feed);
state = fbp->state[DIR_DECRYPT-1] = IN_PROGRESS;
break;
default:
if (encrypt_debug_mode) {
printf("Unknown option type: %d\r\n", *(data-1));
printd(data, cnt);
printf("\r\n");
}
/* FALL THROUGH */
failure:
/*
* We failed. Send an FB64_IV_BAD option
* to the other side so it will know that
* things failed.
*/
p = fbp->fb_feed + 3;
*p++ = ENCRYPT_REPLY;
p++;
*p++ = FB64_IV_BAD;
*p++ = IAC;
*p++ = SE;
printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
net_write(fbp->fb_feed, p - fbp->fb_feed);
break;
}
return(fbp->state[DIR_DECRYPT-1] = state);
}
/*
* Returns:
* -1: some error. Negotiation is done, encryption not ready.
* 0: Successful, initial negotiation all done.
* 1: successful, negotiation not done yet.
*/
int cfb64_reply(unsigned char *data, int cnt)
{
return(fb64_reply(data, cnt, &fb[CFB]));
}
int ofb64_reply(unsigned char *data, int cnt)
{
return(fb64_reply(data, cnt, &fb[OFB]));
}
int fb64_reply(unsigned char *data, int cnt, struct fb *fbp)
{
int state = fbp->state[DIR_ENCRYPT-1];
if (cnt-- < 1)
goto failure;
switch (*data++) {
case FB64_IV_OK:
fb64_stream_iv(fbp->temp_feed, &fbp->streams[DIR_ENCRYPT-1]);
if (state == FAILED)
state = IN_PROGRESS;
state &= ~NO_RECV_IV;
encrypt_send_keyid(DIR_ENCRYPT, (unsigned char *)"\0", 1, 1);
break;
case FB64_IV_BAD:
memset(fbp->temp_feed, 0, sizeof(des_cblock));
fb64_stream_iv(fbp->temp_feed, &fbp->streams[DIR_ENCRYPT-1]);
state = FAILED;
break;
default:
if (encrypt_debug_mode) {
printf("Unknown option type: %d\r\n", data[-1]);
printd(data, cnt);
printf("\r\n");
}
/* FALL THROUGH */
failure:
state = FAILED;
break;
}
return(fbp->state[DIR_ENCRYPT-1] = state);
}
void cfb64_session(Session_Key *key, int server)
{
fb64_session(key, server, &fb[CFB]);
}
void ofb64_session(Session_Key *key, int server)
{
fb64_session(key, server, &fb[OFB]);
}
static void fb64_session(Session_Key *key, int server, struct fb *fbp)
{
if (!key || key->type != SK_DES) {
if (encrypt_debug_mode)
printf("Can't set krbdes's session key (%d != %d)\r\n",
key ? key->type : -1, SK_DES);
return;
}
memcpy(fbp->krbdes_key, key->data, sizeof(des_cblock));
fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_ENCRYPT-1]);
fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_DECRYPT-1]);
if (fbp->once == 0) {
#ifndef OLD_DES_RANDOM_KEY
des_init_random_number_generator(&fbp->krbdes_key);
#endif
fbp->once = 1;
}
des_key_sched(&fbp->krbdes_key, fbp->krbdes_sched);
/*
* Now look to see if krbdes_start() was was waiting for
* the key to show up. If so, go ahead an call it now
* that we have the key.
*/
if (fbp->need_start) {
fbp->need_start = 0;
fb64_start(fbp, DIR_ENCRYPT, server);
}
}
/*
* We only accept a keyid of 0. If we get a keyid of
* 0, then mark the state as SUCCESS.
*/
int cfb64_keyid(int dir, unsigned char *kp, int *lenp)
{
return(fb64_keyid(dir, kp, lenp, &fb[CFB]));
}
int ofb64_keyid(int dir, unsigned char *kp, int *lenp)
{
return(fb64_keyid(dir, kp, lenp, &fb[OFB]));
}
int fb64_keyid(int dir, unsigned char *kp, int *lenp, struct fb *fbp)
{
int state = fbp->state[dir-1];
if (*lenp != 1 || (*kp != '\0')) {
*lenp = 0;
return(state);
}
if (state == FAILED)
state = IN_PROGRESS;
state &= ~NO_KEYID;
return(fbp->state[dir-1] = state);
}
void fb64_printsub(unsigned char *data, int cnt,
unsigned char *buf, int buflen, char *type)
{
char lbuf[32];
int i;
char *cp;
buf[buflen-1] = '\0'; /* make sure it's NULL terminated */
buflen -= 1;
switch(data[2]) {
case FB64_IV:
snprintf(lbuf, sizeof(lbuf), "%s_IV", type);
cp = lbuf;
goto common;
case FB64_IV_OK:
snprintf(lbuf, sizeof(lbuf), "%s_IV_OK", type);
cp = lbuf;
goto common;
case FB64_IV_BAD:
snprintf(lbuf, sizeof(lbuf), "%s_IV_BAD", type);
cp = lbuf;
goto common;
default:
snprintf(lbuf, sizeof(lbuf), " %d (unknown)", data[2]);
cp = lbuf;
common:
for (; (buflen > 0) && (*buf = *cp++); buf++)
buflen--;
for (i = 3; i < cnt; i++) {
snprintf(lbuf, sizeof(lbuf), " %d", data[i]);
for (cp = lbuf; (buflen > 0) && (*buf = *cp++); buf++)
buflen--;
}
break;
}
}
void cfb64_printsub(unsigned char *data, int cnt,
unsigned char *buf, int buflen)
{
fb64_printsub(data, cnt, buf, buflen, "CFB64");
}
void ofb64_printsub(unsigned char *data, int cnt,
unsigned char *buf, int buflen)
{
fb64_printsub(data, cnt, buf, buflen, "OFB64");
}
void fb64_stream_iv(des_cblock seed, struct stinfo *stp)
{
memcpy(stp->str_iv, seed,sizeof(des_cblock));
memcpy(stp->str_output, seed, sizeof(des_cblock));
des_key_sched(&stp->str_ikey, stp->str_sched);
stp->str_index = sizeof(des_cblock);
}
void fb64_stream_key(des_cblock key, struct stinfo *stp)
{
memcpy(stp->str_ikey, key, sizeof(des_cblock));
des_key_sched((des_cblock*)key, stp->str_sched);
memcpy(stp->str_output, stp->str_iv, sizeof(des_cblock));
stp->str_index = sizeof(des_cblock);
}
/*
* DES 64 bit Cipher Feedback
*
* key --->+-----+
* +->| DES |--+
* | +-----+ |
* | v
* INPUT --(--------->(+)+---> DATA
* | |
* +-------------+
*
*
* Given:
* iV: Initial vector, 64 bits (8 bytes) long.
* Dn: the nth chunk of 64 bits (8 bytes) of data to encrypt (decrypt).
* On: the nth chunk of 64 bits (8 bytes) of encrypted (decrypted) output.
*
* V0 = DES(iV, key)
* On = Dn ^ Vn
* V(n+1) = DES(On, key)
*/
void cfb64_encrypt(unsigned char *s, int c)
{
struct stinfo *stp = &fb[CFB].streams[DIR_ENCRYPT-1];
int index;
index = stp->str_index;
while (c-- > 0) {
if (index == sizeof(des_cblock)) {
des_cblock b;
des_ecb_encrypt(&stp->str_output, &b,stp->str_sched, 1);
memcpy(stp->str_feed, b, sizeof(des_cblock));
index = 0;
}
/* On encryption, we store (feed ^ data) which is cypher */
*s = stp->str_output[index] = (stp->str_feed[index] ^ *s);
s++;
index++;
}
stp->str_index = index;
}
int cfb64_decrypt(int data)
{
struct stinfo *stp = &fb[CFB].streams[DIR_DECRYPT-1];
int index;
if (data == -1) {
/*
* Back up one byte. It is assumed that we will
* never back up more than one byte. If we do, this
* may or may not work.
*/
if (stp->str_index)
--stp->str_index;
return(0);
}
index = stp->str_index++;
if (index == sizeof(des_cblock)) {
des_cblock b;
des_ecb_encrypt(&stp->str_output,&b, stp->str_sched, 1);
memcpy(stp->str_feed, b, sizeof(des_cblock));
stp->str_index = 1; /* Next time will be 1 */
index = 0; /* But now use 0 */
}
/* On decryption we store (data) which is cypher. */
stp->str_output[index] = data;
return(data ^ stp->str_feed[index]);
}
/*
* DES 64 bit Output Feedback
*
* key --->+-----+
* +->| DES |--+
* | +-----+ |
* +-----------+
* v
* INPUT -------->(+) ----> DATA
*
* Given:
* iV: Initial vector, 64 bits (8 bytes) long.
* Dn: the nth chunk of 64 bits (8 bytes) of data to encrypt (decrypt).
* On: the nth chunk of 64 bits (8 bytes) of encrypted (decrypted) output.
*
* V0 = DES(iV, key)
* V(n+1) = DES(Vn, key)
* On = Dn ^ Vn
*/
void ofb64_encrypt(unsigned char *s, int c)
{
struct stinfo *stp = &fb[OFB].streams[DIR_ENCRYPT-1];
int index;
index = stp->str_index;
while (c-- > 0) {
if (index == sizeof(des_cblock)) {
des_cblock b;
des_ecb_encrypt(&stp->str_feed,&b, stp->str_sched, 1);
memcpy(stp->str_feed, b, sizeof(des_cblock));
index = 0;
}
*s++ ^= stp->str_feed[index];
index++;
}
stp->str_index = index;
}
int ofb64_decrypt(int data)
{
struct stinfo *stp = &fb[OFB].streams[DIR_DECRYPT-1];
int index;
if (data == -1) {
/*
* Back up one byte. It is assumed that we will
* never back up more than one byte. If we do, this
* may or may not work.
*/
if (stp->str_index)
--stp->str_index;
return(0);
}
index = stp->str_index++;
if (index == sizeof(des_cblock)) {
des_cblock b;
des_ecb_encrypt(&stp->str_feed,&b,stp->str_sched, 1);
memcpy(stp->str_feed, b, sizeof(des_cblock));
stp->str_index = 1; /* Next time will be 1 */
index = 0; /* But now use 0 */
}
return(data ^ stp->str_feed[index]);
}
#endif
|
the_stack_data/45451533.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fill_zeroes.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmurakam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/13 09:19:03 by mmurakam #+# #+# */
/* Updated: 2019/10/13 15:16:36 by mmurakam ### ########.fr */
/* */
/* ************************************************************************** */
void fill_with_zeroes(int **square)
{
int line;
int col;
line = 0;
col = 0;
while (col < 4)
{
line = 0;
while (line < 4)
{
square[col][line] = '0';
line++;
}
col++;
}
}
|
the_stack_data/24365.c | // RUN: %clang_cc1 -emit-llvm -o %t %s
// RUN: not grep __builtin %t
// RUN: %clang_cc1 %s -emit-llvm -o - -triple x86_64-darwin-apple | FileCheck %s
int printf(const char *, ...);
void p(char *str, int x) {
printf("%s: %d\n", str, x);
}
void q(char *str, double x) {
printf("%s: %f\n", str, x);
}
void r(char *str, void *ptr) {
printf("%s: %p\n", str, ptr);
}
int random(void);
int main() {
int N = random();
#define P(n,args) p(#n #args, __builtin_##n args)
#define Q(n,args) q(#n #args, __builtin_##n args)
#define R(n,args) r(#n #args, __builtin_##n args)
#define V(n,args) p(#n #args, (__builtin_##n args, 0))
P(types_compatible_p, (int, float));
P(choose_expr, (0, 10, 20));
P(constant_p, (sizeof(10)));
P(expect, (N == 12, 0));
V(prefetch, (&N));
V(prefetch, (&N, 1));
V(prefetch, (&N, 1, 0));
// Numeric Constants
Q(huge_val, ());
Q(huge_valf, ());
Q(huge_vall, ());
Q(inf, ());
Q(inff, ());
Q(infl, ());
P(fpclassify, (0, 1, 2, 3, 4, 1.0));
P(fpclassify, (0, 1, 2, 3, 4, 1.0f));
P(fpclassify, (0, 1, 2, 3, 4, 1.0l));
// FIXME:
// P(isinf_sign, (1.0));
Q(nan, (""));
Q(nanf, (""));
Q(nanl, (""));
Q(nans, (""));
Q(nan, ("10"));
Q(nanf, ("10"));
Q(nanl, ("10"));
Q(nans, ("10"));
P(isgreater, (1., 2.));
P(isgreaterequal, (1., 2.));
P(isless, (1., 2.));
P(islessequal, (1., 2.));
P(islessgreater, (1., 2.));
P(isunordered, (1., 2.));
P(isnan, (1.));
// Bitwise & Numeric Functions
P(abs, (N));
P(clz, (N));
P(clzl, (N));
P(clzll, (N));
P(ctz, (N));
P(ctzl, (N));
P(ctzll, (N));
P(ffs, (N));
P(ffsl, (N));
P(ffsll, (N));
P(parity, (N));
P(parityl, (N));
P(parityll, (N));
P(popcount, (N));
P(popcountl, (N));
P(popcountll, (N));
Q(powi, (1.2f, N));
Q(powif, (1.2f, N));
Q(powil, (1.2f, N));
// Lib functions
int a, b, n = random(); // Avoid optimizing out.
char s0[10], s1[] = "Hello";
V(strcat, (s0, s1));
V(strcmp, (s0, s1));
V(strncat, (s0, s1, n));
V(strchr, (s0, s1[0]));
V(strrchr, (s0, s1[0]));
V(strcpy, (s0, s1));
V(strncpy, (s0, s1, n));
// Object size checking
V(__memset_chk, (s0, 0, sizeof s0, n));
V(__memcpy_chk, (s0, s1, sizeof s0, n));
V(__memmove_chk, (s0, s1, sizeof s0, n));
V(__mempcpy_chk, (s0, s1, sizeof s0, n));
V(__strncpy_chk, (s0, s1, sizeof s0, n));
V(__strcpy_chk, (s0, s1, n));
s0[0] = 0;
V(__strcat_chk, (s0, s1, n));
P(object_size, (s0, 0));
P(object_size, (s0, 1));
P(object_size, (s0, 2));
P(object_size, (s0, 3));
// Whatever
P(bswap16, (N));
P(bswap32, (N));
P(bswap64, (N));
// FIXME
// V(clear_cache, (&N, &N+1));
V(trap, ());
R(extract_return_addr, (&N));
P(signbit, (1.0));
return 0;
}
void foo() {
__builtin_strcat(0, 0);
}
// CHECK: define void @bar(
void bar() {
float f;
double d;
long double ld;
// LLVM's hex representation of float constants is really unfortunate;
// basically it does a float-to-double "conversion" and then prints the
// hex form of that. That gives us weird artifacts like exponents
// that aren't numerically similar to the original exponent and
// significand bit-patterns that are offset by three bits (because
// the exponent was expanded from 8 bits to 11).
//
// 0xAE98 == 1010111010011000
// 0x15D3 == 1010111010011
f = __builtin_huge_valf(); // CHECK: float 0x7FF0000000000000
d = __builtin_huge_val(); // CHECK: double 0x7FF0000000000000
ld = __builtin_huge_vall(); // CHECK: x86_fp80 0xK7FFF8000000000000000
f = __builtin_nanf(""); // CHECK: float 0x7FF8000000000000
d = __builtin_nan(""); // CHECK: double 0x7FF8000000000000
ld = __builtin_nanl(""); // CHECK: x86_fp80 0xK7FFFC000000000000000
f = __builtin_nanf("0xAE98"); // CHECK: float 0x7FF815D300000000
d = __builtin_nan("0xAE98"); // CHECK: double 0x7FF800000000AE98
ld = __builtin_nanl("0xAE98"); // CHECK: x86_fp80 0xK7FFFC00000000000AE98
f = __builtin_nansf(""); // CHECK: float 0x7FF4000000000000
d = __builtin_nans(""); // CHECK: double 0x7FF4000000000000
ld = __builtin_nansl(""); // CHECK: x86_fp80 0xK7FFFA000000000000000
f = __builtin_nansf("0xAE98"); // CHECK: float 0x7FF015D300000000
d = __builtin_nans("0xAE98"); // CHECK: double 0x7FF000000000AE98
ld = __builtin_nansl("0xAE98");// CHECK: x86_fp80 0xK7FFF800000000000AE98
}
// CHECK: }
// CHECK: define void @test_float_builtins
void test_float_builtins(float F, double D, long double LD) {
volatile int res;
res = __builtin_isinf(F);
// CHECK: call float @fabsf(float
// CHECK: fcmp oeq float {{.*}}, 0x7FF0000000000000
res = __builtin_isinf(D);
// CHECK: call double @fabs(double
// CHECK: fcmp oeq double {{.*}}, 0x7FF0000000000000
res = __builtin_isinf(LD);
// CHECK: call x86_fp80 @fabsl(x86_fp80
// CHECK: fcmp oeq x86_fp80 {{.*}}, 0xK7FFF8000000000000000
res = __builtin_isfinite(F);
// CHECK: fcmp oeq float
// CHECK: call float @fabsf
// CHECK: fcmp une float {{.*}}, 0x7FF0000000000000
// CHECK: and i1
res = __builtin_isnormal(F);
// CHECK: fcmp oeq float
// CHECK: call float @fabsf
// CHECK: fcmp ult float {{.*}}, 0x7FF0000000000000
// CHECK: fcmp uge float {{.*}}, 0x3810000000000000
// CHECK: and i1
// CHECK: and i1
}
// CHECK: define void @test_builtin_longjmp
void test_builtin_longjmp(void **buffer) {
// CHECK: [[BITCAST:%.*]] = bitcast
// CHECK-NEXT: call void @llvm.eh.sjlj.longjmp(i8* [[BITCAST]])
__builtin_longjmp(buffer, 1);
// CHECK-NEXT: unreachable
}
// CHECK: define i64 @test_builtin_readcyclecounter
long long test_builtin_readcyclecounter() {
// CHECK: call i64 @llvm.readcyclecounter()
return __builtin_readcyclecounter();
}
|
the_stack_data/175141864.c | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
int main() {
volatile long long a = 0x0000000000000001L;
if (__builtin_ctzll(a) != 0) {
return 1;
}
volatile long long b = 0x0000000000000002;
if (__builtin_ctzll(b) != 1) {
return 1;
}
volatile long long c = 0x0000000080000000;
if (__builtin_ctzll(c) != 31) {
return 1;
}
volatile long long d = 0x0000000100000000;
if (__builtin_ctzll(d) != 32) {
return 1;
}
volatile long long e = 0x8000000000000000;
if (__builtin_ctzll(e) != 63) {
return 1;
}
return 0;
}
|
the_stack_data/237641863.c | /* This source code was extracted from the Q8 package created and placed
in the PUBLIC DOMAIN by Doug Gwyn <[email protected]>
last edit: 1999/11/05 [email protected]
Implements subclause 7.24 of ISO/IEC 9899:1999 (E).
It supports an encoding where all char codes are mapped
to the *same* code values within a wchar_t or wint_t,
so long as no other wchar_t codes are used by the program.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
wchar_t *
wmemmove(s1, s2, n)
register wchar_t *s1;
register const wchar_t *s2;
register size_t n;
{
wchar_t *orig_s1 = s1;
if ( s1 == NULL || s2 == NULL || n == 0 )
return orig_s1; /* robust */
/* XXX -- The following test works only within a flat address space! */
if ( s2 >= s1 )
for ( ; n > 0; --n )
*s1++ = *s2++;
else {
s1 += n;
s2 += n;
for ( ; n > 0; --n )
*--s1 = *--s2;
}
return orig_s1;
}
|
the_stack_data/372642.c | #include <stdlib.h>
#include <ctype.h>
long long atoll(const char *s)
{
long long n=0;
int neg=0;
while (isspace(*s)) s++;
switch (*s) {
case '-': neg=1;
case '+': s++;
}
/* Compute n as a negative number to avoid overflow on LLONG_MIN */
while (isdigit(*s))
n = 10*n - (*s++ - '0');
return neg ? n : -n;
}
|
the_stack_data/132410.c | /*
** EPITECH PROJECT, 2017
** my_strlen
** File description:
** task03
*/
int my_strlen(char const *str)
{
int size = 0;
while (str[size])
size++;
return (size);
}
|
the_stack_data/115356.c | #include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <time.h>
#include <sys/select.h>
#include <sys/time.h>
int main(int argc, char** argv){
struct addrinfo* result=NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_DGRAM;// UDP
hints.ai_flags = AI_NUMERICHOST;
int rc = getaddrinfo(argv[1], argv[2] , &hints, &result);
// OPEN SOCKET
int udp_socket = socket(result->ai_family,result->ai_socktype,0);
// LINK IT TO AN ADDRESS (Allow to receive)
bind(udp_socket,(struct sockaddr *)result->ai_addr, result->ai_addrlen);
freeaddrinfo(result);
struct sockaddr_storage src_addr;
socklen_t addrlen = sizeof(src_addr);
char buf[2];
while (1){
fd_set set;
FD_ZERO(&set);
FD_SET(udp_socket, &set);
FD_SET(0, &set);
int fds = select(udp_socket + 1, &set, NULL, NULL, NULL); //Maximum + 1
time_t act = time(0);
struct tm* buf_hora;
buf_hora = localtime(&act);
if (FD_ISSET(udp_socket, &set)){
int bytes = recvfrom(udp_socket, buf, 1, 0,(struct sockaddr *)&src_addr , &addrlen);
buf[1] = '\0';
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
getnameinfo((struct sockaddr *)&src_addr, addrlen, host, NI_MAXHOST, serv, NI_MAXSERV, NI_NUMERICHOST|NI_NUMERICSERV);
printf("I received %i bytes from %s:%s\n", bytes, host, serv);
} else {
scanf("%s", buf);
}
if (buf[0] == 't'){
char s[10];
strftime(s, 10, "%T", buf_hora); s[9]='\0';
if (FD_ISSET(udp_socket, &set))
sendto(udp_socket, s, 9, 0,(struct sockaddr *)&src_addr, addrlen);
else
printf("%s\n", s);
}
else if (buf[0] == 'd'){
char s[11];
strftime(s, 11, "%F", buf_hora); s[10]='\0';
if (FD_ISSET(udp_socket, &set))
sendto(udp_socket, s, 11, 0,(struct sockaddr *)&src_addr, addrlen);
else printf("%s\n", s);
}
else if (buf[0] != 'q'){
printf("Invalid comand %s\n", buf);
if (FD_ISSET(udp_socket, &set))
sendto(udp_socket, buf, 2, 0,(struct sockaddr *)&src_addr, addrlen);
}
if (buf[0] == 'q') {
printf("Exiting \n");
break;
}
}
close(udp_socket);
}
|
the_stack_data/414883.c | /* Copyright 2013-2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
void _prlog(int log_level __attribute__((unused)), const char* fmt, ...) __attribute__((format (printf, 2, 3)));
#ifndef pr_fmt
#define pr_fmt(fmt) fmt
#endif
#define prlog(l, f, ...) do { _prlog(l, pr_fmt(f), ##__VA_ARGS__); } while(0)
void _prlog(int log_level __attribute__((unused)), const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
/* Add any stub functions required for linking here. */
static void stub_function(void)
{
abort();
}
#define STUB(fnname) \
void fnname(void) __attribute__((weak, alias ("stub_function")))
STUB(fdt_begin_node);
STUB(fdt_property);
STUB(fdt_end_node);
STUB(fdt_create);
STUB(fdt_add_reservemap_entry);
STUB(fdt_finish_reservemap);
STUB(fdt_strerror);
STUB(fdt_check_header);
STUB(_fdt_check_node_offset);
STUB(fdt_next_tag);
STUB(fdt_string);
STUB(fdt_get_name);
STUB(dt_first);
STUB(dt_next);
STUB(dt_has_node_property);
STUB(dt_get_address);
STUB(add_chip_dev_associativity);
|
the_stack_data/150140703.c | #include <unistd.h>
int main(int argc, char **argv)
{
int i;
i = 0;
if (argc > 0)
{
while (argv[0][i] != '\0')
{
write (1, &argv[0][i], 1);
i++;
}
write(1, "\n", 1);
}
return (0);
}
|
the_stack_data/132952329.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype;
char mtext[80];
};
int main(int argc, char *argv[])
{
int qid ;
int msgkey = 1234;
qid = msgget(msgkey, IPC_CREAT | 0666);
if (qid == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
struct msgbuf msg;
time_t t;
for (int i = 0; i < 12; i++) {
msg.mtype = (i%4) + 1;
time(&t);
snprintf(msg.mtext, sizeof(msg.mtext), "msgtype = %ld, a message at %s", msg.mtype, ctime(&t));
if (msgsnd(qid, (void *) &msg, sizeof(msg.mtext), IPC_NOWAIT) == -1) {
perror("msgsnd error");
exit(EXIT_FAILURE);
}
printf("sent: %s\n", msg.mtext);
sleep(1);
}
return 0;
}
|
the_stack_data/133798.c | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static struct
{
const char* argv0;
bool all : 1;
} opt;
static struct
{
struct path
{
char* str;
size_t len;
} * array;
size_t len;
} paths;
static void split_paths(size_t extra)
{
const char * path_env, *ptr;
struct path* ent;
size_t i, j;
path_env = getenv("PATH");
if(!path_env || !path_env[0])
{
fprintf(stderr, "%s: no PATH variable found\n", opt.argv0);
exit(-1);
}
paths.len = 1;
for(i = 0; path_env[i]; i++)
{
if(path_env[i] == ':')
paths.len++;
}
paths.array = malloc(sizeof(struct path) * paths.len);
if(!paths.array)
{
fprintf(stderr, "%s: unable to allocate: %s\n", opt.argv0, strerror(errno));
exit(-1);
}
j = 0;
ptr = path_env;
for(i = 0; path_env[i]; i++)
{
if(path_env[i] == ':')
{
ent = &paths.array[j++];
ent->len = path_env + i - ptr;
ent->str = malloc(ent->len + extra);
if(!ent->str)
{
fprintf(stderr, "%s: unable to allocate: %s\n", opt.argv0, strerror(errno));
exit(-1);
}
memcpy(ent->str, ptr, ent->len);
ptr = path_env + i + 1;
ent->str[ent->len] = '\0';
}
}
ent = &paths.array[j];
ent->len = path_env + i - ptr;
ent->str = malloc(ent->len + extra);
if(!ent->str)
{
fprintf(stderr, "%s: unable to allocate: %s\n", opt.argv0, strerror(errno));
exit(-1);
}
memcpy(ent->str, ptr, ent->len);
}
static void setup(int i, int argc, const char* argv[])
{
size_t len, max;
max = 0;
for(; i < argc; i++)
{
len = strlen(argv[i]);
if(len > max)
max = len;
}
split_paths(max + 2);
}
static void which(const char* program)
{
struct path* ent;
size_t i;
int found;
found = 0;
for(i = 0; i < paths.len; i++)
{
ent = &paths.array[i];
ent->str[ent->len] = '/';
strcpy(ent->str + ent->len + 1, program);
if(access(ent->str, X_OK))
continue;
puts(ent->str);
if(!opt.all)
return;
found = 1;
}
if(!found)
{
printf("%s not found\n", program);
}
}
/* Usage: which [-a] PROGRAM... */
int main(int argc, const char* argv[])
{
int i;
opt.argv0 = argv[0];
for(i = 1; i < argc; i++)
{
if(argv[i][0] != '-')
break;
else if(!strcmp(argv[i], "-a"))
opt.all = 1;
}
setup(i, argc, argv);
for(; i < argc; i++)
which(argv[i]);
return 0;
}
|
the_stack_data/156393861.c | /* { dg-do compile } */
/* { dg-options "-pedantic-errors -std=c89 -Wvla" } */
extern void
func (int i, int array[i]); /* { dg-error "ISO C90 forbids variable.* array 'array'" } */
|
the_stack_data/59513048.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
#include <stdlib.h>
#include <string.h>
static void *calloc_model(size_t nmemb, size_t size) {
void *ptr = malloc(nmemb * size);
return memset(ptr, 0, nmemb * size);
}
extern int __VERIFIER_nondet_int(void);
struct L4 {
struct L4 *next;
struct L5 *down;
};
struct L3 {
struct L4 *down;
struct L3 *next;
};
struct L2 {
struct L2 *next;
struct L3 *down;
};
struct L1 {
struct L2 *down;
struct L1 *next;
};
struct L0 {
struct L0 *next;
struct L1 *down;
};
static void* zalloc_or_die(unsigned size)
{
void *ptr = calloc_model(1U, size);
if (ptr)
return ptr;
abort();
}
static void l4_insert(struct L4 **list)
{
struct L4 *item = zalloc_or_die(sizeof *item);
item->down = zalloc_or_die(119U);
item->next = *list;
*list = item;
}
static void l3_insert(struct L3 **list)
{
struct L3 *item = zalloc_or_die(sizeof *item);
do
l4_insert(&item->down);
while (__VERIFIER_nondet_int());
item->next = *list;
*list = item;
}
static void l2_insert(struct L2 **list)
{
struct L2 *item = zalloc_or_die(sizeof *item);
do
l3_insert(&item->down);
while (__VERIFIER_nondet_int());
item->next = *list;
*list = item;
}
static void l1_insert(struct L1 **list)
{
struct L1 *item = zalloc_or_die(sizeof *item);
do
l2_insert(&item->down);
while (__VERIFIER_nondet_int());
item->next = *list;
*list = item;
}
static void l0_insert(struct L0 **list)
{
struct L0 *item = zalloc_or_die(sizeof *item);
do
l1_insert(&item->down);
while (__VERIFIER_nondet_int());
item->next = *list;
*list = item;
}
static void l4_destroy(struct L4 *list, int level)
{
do {
if (5 == level)
free(list->down);
struct L4 *next = list->next;
if (4 == level)
free(list);
list = next;
}
while (list);
}
static void l3_destroy(struct L3 *list, int level)
{
do {
if (3 < level)
l4_destroy(list->down, level);
struct L3 *next = list->next;
if (3 == level)
free(list);
list = next;
}
while (list);
}
static void l2_destroy(struct L2 *list, int level)
{
do {
if (2 < level)
l3_destroy(list->down, level);
struct L2 *next = list->next;
if (2 == level)
free(list);
list = next;
}
while (list);
}
static void l1_destroy(struct L1 *list, int level)
{
do {
if (1 < level)
l2_destroy(list->down, level);
struct L1 *next = list->next;
if (1 == level)
free(list);
list = next;
}
while (list);
}
static void l0_destroy(struct L0 *list, int level)
{
do {
if (0 < level)
l1_destroy(list->down, level);
struct L0 *next = list->next;
if (0 == level)
free(list);
list = next;
}
while (list);
}
int main()
{
static struct L0 *list;
do
l0_insert(&list);
while (__VERIFIER_nondet_int());
l0_destroy(list, /* level */ 5);
l0_destroy(list, /* level */ 4);
l0_destroy(list, /* level */ 3);
l0_destroy(list, /* level */ 2);
l0_destroy(list, /* level */ 2);
l0_destroy(list, /* level */ 1);
l0_destroy(list, /* level */ 0);
return !!list;
}
|
the_stack_data/130943.c | #include <stdio.h>
#include <string.h>
int main(){
char str_a[20]; //A 20-element character array
char *pointer; //A pointer meant for character array
char *pointer2; //And yet another one
strcpy(str_a, "Hello, World!\n");
pointer = str_a; // Set the first pointer to the start of the array.
printf(pointer); //print it
pointer2 = pointer + 2; //Set teh second one 2 bytes further in.
printf(pointer2); //print it
strcpy(pointer2, "y you guys!\n"); //Copy into that spot.
printf(pointer); //Print again.
}
|
the_stack_data/51538.c | /*
* catan_generic.c
*
* $Id$
*
* Compute the complex arctan corresponding to a complex tangent value;
* a generic implementation for catan(), catanf(), and catanl().
*
* Written by Keith Marshall <[email protected]>
* This is an adaptation of an original contribution by Danny Smith
* Copyright (C) 2003-2005, 2015, MinGW.org Project
*
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice, this permission notice, and the following
* disclaimer shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*
* This is a generic implementation for all of the catan(), catanl(),
* and catanh() functions; each is to be compiled separately, i.e.
*
* gcc -D FUNCTION=catan -o catan.o catan_generic.c
* gcc -D FUNCTION=catanl -o catanl.o catan_generic.c
* gcc -D FUNCTION=catanf -o catanf.o catan_generic.c
*
*/
#include <math.h>
#include <complex.h>
#ifndef FUNCTION
/* If user neglected to specify it, the default compilation is for
* the catan() function.
*/
# define FUNCTION catan
#endif
#define argtype_catan double
#define argtype_catanl long double
#define argtype_catanf float
#define PASTE(PREFIX,SUFFIX) PREFIX##SUFFIX
#define mapname(PREFIX,SUFFIX) PASTE(PREFIX,SUFFIX)
#define ARGTYPE(FUNCTION) PASTE(argtype_,FUNCTION)
#define ARGCAST(VALUE) mapname(argcast_,FUNCTION)(VALUE)
#define argcast_catan(VALUE) VALUE
#define argcast_catanl(VALUE) PASTE(VALUE,L)
#define argcast_catanf(VALUE) PASTE(VALUE,F)
#define mapfunc(NAME) mapname(mapfunc_,FUNCTION)(NAME)
#define mapfunc_catan(NAME) NAME
#define mapfunc_catanl(NAME) PASTE(NAME,l)
#define mapfunc_catanf(NAME) PASTE(NAME,f)
/* Define the generic function implementation.
*/
ARGTYPE(FUNCTION) complex FUNCTION( ARGTYPE(FUNCTION) complex Z )
{
ARGTYPE(FUNCTION) x = __real__ Z; /* real part of Z saved as x */
ARGTYPE(FUNCTION) y = __imag__ Z; /* imaginary part of Z saved as iy */
/* Having thus saved the original value of Z as separate real and
* imaginary parts, we may reuse Z to accumulate the arctan value,
* noting that...
*/
if( isfinite( mapfunc(hypot)( x, y )) )
{
/* ...for any complex number with finite modulus, its argtan may
* be computed as:
*
* catan(Z) = (clog(1.0 + iZ) - clog(1.0 - iZ)) / 2.0i
*
* For computational convenience, we may introduce an additional
* intermediate accumulator variable...
*/
ARGTYPE(FUNCTION) complex tmp;
/* ...in which we initially compute the (1.0 - iZ) term...
*/
__real__ tmp = ARGCAST(1.0) + y;
__imag__ tmp = -x;
/* ...while computing (1.0 + iZ) directly in Z itself.
*/
__real__ Z = ARGCAST(1.0) - y;
__imag__ Z = x;
/* We may then compute and combine the complex logarithms
* of this pair of sub-expressions, while we simultaneously
* perform the REAL division by 2.0...
*/
tmp = ARGCAST(0.5) * (mapfunc(clog)( Z ) - mapfunc(clog)( tmp ));
/* ...and finally, the division by i has the effect of
* exchanging the real and imaginary parts of the result,
* with a change of sign in the resultant imaginary part.
*/
__real__ Z = __imag__ tmp;
__imag__ Z = -(__real__ tmp);
}
else
{ /* Conversely, if the modulus of Z is in any way undefined,
* we return a real value, with modulus of PI / 2.0, and with
* the same sign as the original real part of Z.
*/
__real__ Z = mapfunc(copysign)( ARGCAST(M_PI_2), x );
__imag__ Z = ARGCAST(0.0);
}
/* In either case, Z now represents the arctan of its original
* value, which we are required to return.
*/
return Z;
}
/* $RCSfile$: end of file */
|
the_stack_data/211126.c | /* Taxonomy Classification: 0000010000000000000000 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 1 array
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 0 no overflow
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of software in source and binary forms, with or without
modification, are permitted provided that the following conditions are met.
- Redistributions of source code must retain the above copyright notice,
this set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS".
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
int main(int argc, char *argv[])
{
char buf[5][10];
/* OK */
buf[4][9] = 'A';
return 0;
}
|
the_stack_data/236660.c | #include <fenv.h>
/* __fesetround wrapper for arch independent argument check */
int __fesetround(int);
int fesetround(int r)
{
if (r & ~(
FE_TONEAREST
#ifdef FE_DOWNWARD
|FE_DOWNWARD
#endif
#ifdef FE_UPWARD
|FE_UPWARD
#endif
#ifdef FE_TOWARDZERO
|FE_TOWARDZERO
#endif
))
return -1;
return __fesetround(r);
}
|
the_stack_data/220456119.c | void do_tests() {
#ifdef __PROFILE_FUNCTIONS__
mixed *hmm = function_profile(this_object());
ASSERT(sizeof(hmm) == 1);
ASSERT(hmm[0]["calls"]);
ASSERT(!undefinedp(hmm[0]["self"]));
ASSERT(!undefinedp(hmm[0]["children"]));
ASSERT(hmm[0]["name"] == "do_tests");
#endif
}
|
the_stack_data/170453155.c | // WARNING in binder_transaction_buffer_release (2)
// https://syzkaller.appspot.com/bug?id=e113a0b970b7b3f394ba
// status:6
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/futex.h>
#include <linux/if_addr.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_tun.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/tcp.h>
#include <linux/veth.h>
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) &&
(addr < prog_start || addr > prog_end)) {
_longjmp(segv_env, 1);
}
exit(sig);
}
static void install_segv_handler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i;
for (i = 0; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (hdr->nlmsg_type == NLMSG_DONE) {
*reply_len = 0;
return 0;
}
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev,
const void* addr, int addrsize)
{
struct ifaddrmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120;
hdr.ifa_scope = RT_SCOPE_UNIVERSE;
hdr.ifa_index = if_nametoindex(dev);
netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize);
netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize);
return netlink_send(nlmsg, sock);
}
static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in_addr in_addr;
inet_pton(AF_INET, addr, &in_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr));
(void)err;
}
static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in6_addr in6_addr;
inet_pton(AF_INET6, addr, &in6_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr));
(void)err;
}
static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name,
const void* addr, int addrsize, const void* mac,
int macsize)
{
struct ndmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ndm_ifindex = if_nametoindex(name);
hdr.ndm_state = NUD_PERMANENT;
netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, NDA_DST, addr, addrsize);
netlink_attr(nlmsg, NDA_LLADDR, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int tunfd = -1;
#define TUN_IFACE "syz_tun"
#define LOCAL_MAC 0xaaaaaaaaaaaa
#define REMOTE_MAC 0xaaaaaaaaaabb
#define LOCAL_IPV4 "172.20.20.170"
#define REMOTE_IPV4 "172.20.20.187"
#define LOCAL_IPV6 "fe80::aa"
#define REMOTE_IPV6 "fe80::bb"
#define IFF_NAPI 0x0010
static void initialize_tun(void)
{
tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
if (tunfd == -1) {
printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n");
printf("otherwise fuzzing or reproducing might not work as intended\n");
return;
}
const int kTunFd = 240;
if (dup2(tunfd, kTunFd) < 0)
exit(1);
close(tunfd);
tunfd = kTunFd;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ);
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) {
exit(1);
}
char sysctl[64];
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE);
write_file(sysctl, "0");
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE);
write_file(sysctl, "0");
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4);
netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6);
uint64_t macaddr = REMOTE_MAC;
struct in_addr in_addr;
inet_pton(AF_INET, REMOTE_IPV4, &in_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr),
&macaddr, ETH_ALEN);
struct in6_addr in6_addr;
inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr),
&macaddr, ETH_ALEN);
macaddr = LOCAL_MAC;
netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN,
NULL);
close(sock);
}
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
NONFAILING(strncpy(buf, (char*)a0, sizeof(buf) - 1));
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setsid();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
static int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
sandbox_common();
drop_caps();
if (unshare(CLONE_NEWNET)) {
}
initialize_tun();
loop();
exit(1);
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void loop(void)
{
int i, call, thread;
for (call = 0; call < 11; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
event_timedwait(&th->done, 45);
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
}
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
void execute_call(int call)
{
intptr_t res = 0;
switch (call) {
case 0:
NONFAILING(memcpy((void*)0x20000000, "/dev/binder#\000", 13));
res = syz_open_dev(0x20000000, 0, 0);
if (res != -1)
r[0] = res;
break;
case 1:
syscall(__NR_ioctl, r[0], 0x40046207, 0ul);
break;
case 2:
res = syz_open_dev(0, 0, 0);
if (res != -1)
r[1] = res;
break;
case 3:
NONFAILING(*(uint64_t*)0x20000200 = 1);
NONFAILING(*(uint64_t*)0x20000208 = 0);
NONFAILING(*(uint64_t*)0x20000210 = 0x20001740);
NONFAILING(memcpy((void*)0x20001740, "\x04\x63\x04\x40", 4));
NONFAILING(*(uint64_t*)0x20000218 = 0);
NONFAILING(*(uint64_t*)0x20000220 = 0);
NONFAILING(*(uint64_t*)0x20000228 = 0);
syscall(__NR_ioctl, r[1], 0xc0306201, 0x20000200ul);
break;
case 4:
res = syscall(__NR_dup2, r[1], r[0]);
if (res != -1)
r[2] = res;
break;
case 5:
NONFAILING(*(uint64_t*)0x20000240 = 4);
NONFAILING(*(uint64_t*)0x20000248 = 0);
NONFAILING(*(uint64_t*)0x20000250 = 0x200003c0);
NONFAILING(memcpy((void*)0x200003c0, "\vc", 2));
NONFAILING(*(uint64_t*)0x20000258 = 1);
NONFAILING(*(uint64_t*)0x20000260 = 0);
NONFAILING(*(uint64_t*)0x20000268 = 0x20000140);
NONFAILING(memcpy((void*)0x20000140, "\x0e", 1));
syscall(__NR_ioctl, r[2], 0xc0306201, 0x20000240ul);
break;
case 6:
syscall(__NR_mmap, 0x20ffc000ul, 0x3000ul, 1ul, 0x11ul, r[1], 0ul);
break;
case 7:
syscall(__NR_ioctl, r[2], 0x40046207, 0ul);
break;
case 8:
NONFAILING(*(uint32_t*)0x20000040 = 0);
NONFAILING(*(uint32_t*)0x20000044 = 0);
NONFAILING(*(uint32_t*)0x20000048 = 0);
NONFAILING(*(uint32_t*)0x2000004c = 0);
NONFAILING(*(uint8_t*)0x20000050 = 0);
NONFAILING(memcpy((void*)0x20000051, "\x22\x1f\xa7\xb1\xae\xef\x0c\xf2\x4c"
"\x0a\x4e\x69\xa0\x0b\xfd\xd4\xe4\xa0"
"\x02",
19));
syscall(__NR_ioctl, -1, 0x5404, 0x20000040ul);
break;
case 9:
NONFAILING(*(uint64_t*)0x20000280 = 0xd);
NONFAILING(*(uint64_t*)0x20000288 = 0);
NONFAILING(*(uint64_t*)0x20000290 = 0x20000040);
NONFAILING(memcpy((void*)0x20000040,
"\x05\x63\x04\x40\x00\x00\x00\x00\x00\x63\x40\x40\x01",
13));
NONFAILING(*(uint64_t*)0x20000298 = 0);
NONFAILING(*(uint64_t*)0x200002a0 = 0);
NONFAILING(*(uint64_t*)0x200002a8 = 0);
syscall(__NR_ioctl, r[2], 0xc0306201, 0x20000280ul);
break;
case 10:
NONFAILING(*(uint64_t*)0x20000540 = 0x4c);
NONFAILING(*(uint64_t*)0x20000548 = 0);
NONFAILING(*(uint64_t*)0x20000550 = 0x20000180);
NONFAILING(*(uint32_t*)0x20000180 = 0x40486312);
NONFAILING(*(uint32_t*)0x20000184 = 0);
NONFAILING(*(uint32_t*)0x20000188 = 0);
NONFAILING(*(uint64_t*)0x2000018c = 0);
NONFAILING(*(uint32_t*)0x20000194 = 0);
NONFAILING(*(uint32_t*)0x20000198 = 0);
NONFAILING(*(uint32_t*)0x2000019c = 0);
NONFAILING(*(uint32_t*)0x200001a0 = 0);
NONFAILING(*(uint64_t*)0x200001a4 = 0x58);
NONFAILING(*(uint64_t*)0x200001ac = 0x18);
NONFAILING(*(uint64_t*)0x200001b4 = 0x20000340);
NONFAILING(*(uint32_t*)0x20000340 = 0x66642a85);
NONFAILING(*(uint32_t*)0x20000344 = 0);
NONFAILING(*(uint64_t*)0x20000348 = 0);
NONFAILING(*(uint64_t*)0x20000350 = 0);
NONFAILING(*(uint32_t*)0x20000358 = 0x70742a85);
NONFAILING(*(uint32_t*)0x2000035c = 0);
NONFAILING(*(uint64_t*)0x20000360 = 0x200002c0);
NONFAILING(*(uint64_t*)0x20000368 = 0x4d);
NONFAILING(*(uint64_t*)0x20000370 = 0);
NONFAILING(*(uint64_t*)0x20000378 = 0);
NONFAILING(*(uint32_t*)0x20000380 = 0x77682a85);
NONFAILING(*(uint32_t*)0x20000384 = 0);
NONFAILING(*(uint32_t*)0x20000388 = 0);
NONFAILING(*(uint64_t*)0x20000390 = 0);
NONFAILING(*(uint64_t*)0x200001bc = 0x20000100);
NONFAILING(*(uint64_t*)0x20000100 = 0);
NONFAILING(*(uint64_t*)0x20000108 = 0x18);
NONFAILING(*(uint64_t*)0x20000110 = 0x40);
NONFAILING(*(uint64_t*)0x200001c4 = 0);
NONFAILING(*(uint64_t*)0x20000558 = 0);
NONFAILING(*(uint64_t*)0x20000560 = 2);
NONFAILING(*(uint64_t*)0x20000568 = 0);
syscall(__NR_ioctl, r[2], 0xc0306201, 0x20000540ul);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
install_segv_handler();
do_sandbox_none();
return 0;
}
|
the_stack_data/96738.c | /*
* Copyright 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.
*/
/*
* Stub routine for `sigsuspend' for porting support.
*/
#include <errno.h>
#include <signal.h>
int sigsuspend(const sigset_t *mask) {
errno = ENOSYS;
return -1;
}
|
the_stack_data/67326621.c | #include <stdio.h>
int n, nn[12][12];
int ans = 99999999;
int dist[12][12];
void bt(int x, int y, int dep, int cost){
if(dep==3){
if(ans>cost) ans = cost;
return;
}
for(int i=x;i<n-1;i++){
for(int j=1;j<n-1;j++){
if(!dist[i][j] && !dist[i-1][j] && !dist[i+1][j] && !dist[i][j-1] && !dist[i][j+1]){
int ncost = cost + nn[i][j] + nn[i-1][j] + nn[i+1][j] + nn[i][j-1] + nn[i][j+1];
dist[i][j] = dist[i-1][j] = dist[i+1][j] = dist[i][j-1] = dist[i][j+1] = 1;
bt(i, j, dep+1, ncost);
dist[i][j] = dist[i-1][j] = dist[i+1][j] = dist[i][j-1] = dist[i][j+1] = 0;
}
}
}
}
int main(void){
scanf("%d", &n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d", &nn[i][j]);
}
}
bt(1, 1, 0, 0);
printf("%d", ans);
return 0;
}
|
the_stack_data/306397.c | //--Make sure we can run DSA on it!
//RUN: clang %s -c -emit-llvm -o - | \
//RUN: dsaopt -dsa-bu -dsa-td -disable-output
#include <stdlib.h>
struct InfoStruct {
int count;
int valid;
float factor;
};
void initialize(struct InfoStruct **arr, int size) {
struct InfoStruct *temp = *arr;
while(temp < (*arr + size)) {
temp->count = 0;
temp->valid = 0;
temp->factor = 0.0;
temp++;
}
}
void process(struct InfoStruct **arr, int loc, int count, float fact) {
struct InfoStruct *ptr = *arr;
struct InfoStruct obj;
obj.count = count;
obj.factor = fact;
obj.valid = 1;
ptr[loc]=obj;
}
int main() {
struct InfoStruct* InfoArray= (struct InfoStruct*)malloc(sizeof(struct InfoStruct) * 10);
initialize(&InfoArray, 10);
process(&InfoArray, 4, 3, 5.5);
}
|
the_stack_data/1150856.c | int main()
{
int a = 32;
int b = a + 4;
int c = 0;
c = a + b;
return c;
} |
the_stack_data/69332.c | /*
* Copyright (c) 2019 Alexander Bluhm <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/udp.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
sig_atomic_t alarm_signaled;
int udp_family;
int udp_socket = -1;
FILE *ssh_stream;
pid_t ssh_pid;
void alarm_handler(int);
void udp_bind(const char *, const char *);
void udp_connect(const char *, const char *);
void udp_getsockname(char **, char **);
void udp_setbuffersize(int, int);
void udp_send(const char *, size_t, unsigned long);
void udp_receive(char *, size_t);
void udp_close(void);
void ssh_bind(const char *, const char *, const char *, const char *,
int, size_t , int);
void ssh_connect(const char *, const char *, const char *, const char *,
int, size_t , int);
void ssh_pipe(char **);
void ssh_getpeername(char **, char **);
void ssh_wait(void);
static void
usage(void)
{
fprintf(stderr, "usage: udpbench [-b bufsize] [-d delaypacket] "
"[-l length] [-p port] [-R remoteprog] [-r remotessh] "
"[-t timeout] send|recv [hostname]\n"
" -b bufsize set size of send or receive buffer\n"
" -d delaypacket delay sending to packets per second rate\n"
" -l length set length of udp payload\n"
" -p port udp port, default 12345, random 0\n"
" -R remoteprog path of udpperf tool on remote side\n"
" -r remotessh ssh host to start udpperf on remote side\n"
" -t timeout send duration or receive timeout, default 1\n"
" send|recv send or receive mode for local side\n"
" hostname address of receiving side\n"
);
exit(2);
}
int
main(int argc, char *argv[])
{
struct sigaction act;
const char *errstr;
char *udppayload;
size_t udplength = 0;
int ch, buffersize = 0, timeout = 1, sendmode;
unsigned long delaypacket = 0;
const char *progname = argv[0];
char *hostname = NULL, *service = "12345", *remotessh = NULL;
char *localaddr, *localport;
#ifdef __OpenBSD__
if (pledge("stdio dns inet proc exec", NULL) == -1)
err(1, "pledge");
#endif
if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
err(1, "setvbuf");
while ((ch = getopt(argc, argv, "b:d:l:p:R:r:t:")) != -1) {
switch (ch) {
case 'b':
buffersize = strtonum(optarg, 0, INT_MAX, &errstr);
if (errstr != NULL)
errx(1, "buffer size is %s: %s",
errstr, optarg);
break;
case 'd':
delaypacket = strtonum(optarg, 0, LONG_MAX, &errstr);
if (errstr != NULL)
errx(1, "delay packets per second is %s: %s",
errstr, optarg);
break;
case 'l':
udplength = strtonum(optarg, 0, IP_MAXPACKET, &errstr);
if (errstr != NULL)
errx(1, "payload length is %s: %s",
errstr, optarg);
break;
case 'p':
service = optarg;
break;
case 'R':
progname = optarg;
break;
case 'r':
remotessh = optarg;
break;
case 't':
timeout = strtonum(optarg, 0, INT_MAX, &errstr);
if (errstr != NULL)
errx(1, "timeout is %s: %s",
errstr, optarg);
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc > 2)
usage();
if (argc < 1)
errx(1, "send or recv required");
if (strcmp(argv[0], "send") == 0)
sendmode = 1;
else if (strcmp(argv[0], "recv") == 0)
sendmode = 0;
else
errx(1, "bad send or recv: %s", argv[0]);
if (sendmode && argc < 2)
errx(1, "hostname required for send");
if (argc >= 2)
hostname = argv[1];
#ifdef __OpenBSD__
if (remotessh == NULL) {
if (pledge("stdio dns inet", NULL) == -1)
err(1, "pledge");
}
#endif
memset(&act, 0, sizeof(act));
act.sa_handler = alarm_handler;
act.sa_flags = SA_RESETHAND;
if (sigaction(SIGALRM, &act, NULL) == -1)
err(1, "sigaction");
udppayload = malloc(udplength + 1);
if (udppayload == NULL)
err(1, "malloc udp payload");
if (sendmode) {
arc4random_buf(udppayload, udplength);
if (remotessh != NULL) {
ssh_bind(remotessh, progname, hostname, service,
buffersize, udplength, timeout);
#ifdef __OpenBSD__
if (pledge("stdio dns inet", NULL) == -1)
err(1, "pledge");
#endif
ssh_getpeername(&hostname, &service);
}
udp_connect(hostname, service);
udp_getsockname(NULL, NULL);
udp_setbuffersize(SO_SNDBUF, buffersize);
if (timeout > 0)
alarm(timeout);
udp_send(udppayload, udplength, delaypacket);
if (remotessh != NULL) {
free(hostname);
free(service);
}
} else {
udp_bind(hostname, service);
udp_getsockname(&localaddr, &localport);
udp_setbuffersize(SO_RCVBUF, buffersize);
if (remotessh != NULL) {
ssh_connect(remotessh, progname, localaddr, localport,
buffersize, udplength, timeout);
#ifdef __OpenBSD__
if (pledge("stdio dns inet", NULL) == -1)
err(1, "pledge");
#endif
ssh_getpeername(NULL, NULL);
}
if (timeout > 0)
alarm(timeout + 2);
udp_receive(udppayload, udplength);
free(localaddr);
free(localport);
}
if (remotessh != NULL)
ssh_wait();
udp_close();
free(udppayload);
return 0;
}
void
alarm_handler(int sig)
{
alarm_signaled = 1;
}
void
udp_bind(const char *host, const char *service)
{
struct addrinfo hints, *res, *res0;
int error;
int save_errno;
const char *cause = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_PASSIVE;
error = getaddrinfo(host, service, &hints, &res0);
if (error)
errx(1, "getaddrinfo: %s", gai_strerror(error));
udp_socket = -1;
for (res = res0; res; res = res->ai_next) {
udp_socket = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (udp_socket == -1) {
cause = "socket";
continue;
}
if (bind(udp_socket, res->ai_addr, res->ai_addrlen) == -1) {
cause = "bind";
save_errno = errno;
close(udp_socket);
errno = save_errno;
udp_socket = -1;
continue;
}
break; /* okay we got one */
}
if (udp_socket == -1)
err(1, "%s", cause);
udp_family = res->ai_family;
freeaddrinfo(res0);
}
void
udp_connect(const char *host, const char *service)
{
struct addrinfo hints, *res, *res0;
int error;
int save_errno;
const char *cause = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
error = getaddrinfo(host, service, &hints, &res0);
if (error)
errx(1, "getaddrinfo: %s", gai_strerror(error));
udp_socket = -1;
for (res = res0; res; res = res->ai_next) {
udp_socket = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (udp_socket == -1) {
cause = "socket";
continue;
}
if (connect(udp_socket, res->ai_addr, res->ai_addrlen) == -1) {
cause = "connect";
save_errno = errno;
close(udp_socket);
errno = save_errno;
udp_socket = -1;
continue;
}
break; /* okay we got one */
}
if (udp_socket == -1)
err(1, "%s", cause);
udp_family = res->ai_family;
freeaddrinfo(res0);
}
void
udp_getsockname(char **addr, char **port)
{
struct sockaddr_storage ss;
struct sockaddr *sa = (struct sockaddr *)&ss;
char host[NI_MAXHOST], serv[NI_MAXSERV];
socklen_t len;
int error;
len = sizeof(ss);
if (getsockname(udp_socket, sa, &len) == -1)
err(1, "getsockname");
error = getnameinfo(sa, len, host, sizeof(host), serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV | NI_DGRAM);
if (error)
errx(1, "getnameinfo: %s", gai_strerror(error));
if (addr != NULL) {
*addr = strdup(host);
if (*addr == NULL)
err(1, "strdup addr");
}
if (port != NULL) {
*port = strdup(serv);
if (*port == NULL)
err(1, "strdup port");
}
printf("sockname: %s %s\n", host, serv);
}
void
udp_setbuffersize(int name, int size)
{
socklen_t len;
/* use default */
if (size == 0)
return;
len = sizeof(size);
if (setsockopt(udp_socket, SOL_SOCKET, name, &size, len) == -1)
err(1, "setsockopt buffer size %d", size);
}
void
udp_send(const char *payload, size_t udplen, unsigned long delaypacket)
{
struct timeval begin, end, duration;
struct timespec wait;
unsigned long syscall, packet;
size_t length;
double bits, expectduration, waittime;
if (gettimeofday(&begin, NULL) == -1)
err(1, "gettimeofday begin");
timerclear(&end);
syscall = 0;
packet = 0;
while (!alarm_signaled) {
syscall++;
if (send(udp_socket, payload, udplen, 0) == -1) {
if (errno == ENOBUFS)
continue;
err(1, "send");
}
packet++;
if (delaypacket) {
if (!timerisset(&end)) {
if (gettimeofday(&end, NULL) == -1)
err(1, "gettimeofday delay");
}
timersub(&end, &begin, &duration);
if (!timerisset(&duration))
duration.tv_usec = 1;
expectduration = (double)packet / (double)delaypacket;
waittime = expectduration - (double)duration.tv_sec -
(double)duration.tv_usec / 1000000.;
wait.tv_sec = waittime;
wait.tv_nsec = (waittime - (double)wait.tv_sec) *
1000000000.;
if (wait.tv_sec > 0 || wait.tv_nsec > 0) {
nanosleep(&wait, NULL);
if (gettimeofday(&end, NULL) == -1)
err(1, "gettimeofday delay");
}
}
}
if (gettimeofday(&end, NULL) == -1)
err(1, "gettimeofday end");
length = (udp_family == AF_INET) ?
sizeof(struct ip) : sizeof(struct ip6_hdr);
length += sizeof(struct udphdr) + udplen;
timersub(&end, &begin, &duration);
bits = (double)packet * length * 8;
bits /= (double)duration.tv_sec + (double)duration.tv_usec / 1000000.;
printf("send: syscall %lu, packet %lu, length %zu, "
"duration %lld.%06ld, bit/s %g\n", syscall, packet, length,
(long long)duration.tv_sec, duration.tv_usec, bits);
}
void
udp_receive(char *payload, size_t udplen)
{
struct timeval begin, idle, end, duration, timeo;
unsigned long syscall, packet, bored;
size_t length;
ssize_t rcvlen;
socklen_t len;
double bits;
/* wait for the first packet to start timing */
rcvlen = recv(udp_socket, payload, udplen + 1, 0);
if (rcvlen == -1)
err(1, "recv 1");
if (gettimeofday(&begin, NULL) == -1)
err(1, "gettimeofday begin");
timerclear(&idle);
timeo.tv_sec = 0;
timeo.tv_usec = 100000;
len = sizeof(timeo);
if (setsockopt(udp_socket, SOL_SOCKET, SO_RCVTIMEO, &timeo, len) == -1)
err(1, "setsockopt recv timeout");
syscall = 1;
packet = 1;
bored = 0;
while (!alarm_signaled) {
syscall++;
if (recv(udp_socket, payload, udplen + 1, 0) == -1) {
if (errno == EWOULDBLOCK) {
bored++;
if (bored == 1) {
if (gettimeofday(&idle, NULL) == -1)
err(1, "gettimeofday idle");
/* packet was seen before timeout */
timersub(&idle, &timeo, &idle);
}
if (bored * timeo.tv_usec > 1000000) {
/* more than a second idle time */
break;
}
continue;
}
if (errno == EINTR)
continue;
err(1, "recv");
}
bored = 0;
packet++;
}
if (gettimeofday(&end, NULL) == -1)
err(1, "gettimeofday end");
length = (udp_family == AF_INET) ?
sizeof(struct ip) : sizeof(struct ip6_hdr);
length += sizeof(struct udphdr) + rcvlen;
if (timerisset(&idle)) {
timersub(&idle, &begin, &duration);
timersub(&end, &idle, &idle);
} else {
timersub(&end, &begin, &duration);
}
bits = (double)packet * length * 8;
bits /= (double)duration.tv_sec + (double)duration.tv_usec / 1000000.;
printf("recv: syscall %lu, packet %lu, length %zu, "
"duration %lld.%06ld, bit/s %g\n", syscall, packet, length,
(long long)duration.tv_sec, duration.tv_usec, bits);
if (idle.tv_sec < 1)
errx(1, "not enough idle time: %lld.%06ld",
(long long)idle.tv_sec, idle.tv_usec);
}
void
udp_close(void)
{
if (close(udp_socket) == -1)
err(1, "close");
}
void
ssh_bind(const char *remotessh, const char *progname,
const char *hostname, const char *service,
int buffersize, size_t udplength, int timeout)
{
char *argv[14];
argv[0] = "ssh";
argv[1] = (char *)remotessh;
argv[2] = (char *)progname;
argv[3] = "-b";
if (asprintf(&argv[4], "%d", buffersize) == -1)
err(1, "asprintf buffer size");
argv[5] = "-l";
if (asprintf(&argv[6], "%zu", udplength) == -1)
err(1, "asprintf udp length");
argv[7] = "-p";
argv[8] = (char *)service;
argv[9] = "-t";
if (asprintf(&argv[10], "%d", timeout + 2) == -1)
err(1, "asprintf timeout");
argv[11] = "recv";
argv[12] = (char *)hostname;
argv[13] = NULL;
ssh_pipe(argv);
free(argv[4]);
free(argv[6]);
free(argv[10]);
}
void
ssh_connect(const char *remotessh, const char *progname,
const char *hostname, const char *service,
int buffersize, size_t udplength, int timeout)
{
char *argv[14];
argv[0] = "ssh";
argv[1] = (char *)remotessh;
argv[2] = (char *)progname;
argv[3] = "-b";
if (asprintf(&argv[4], "%d", buffersize) == -1)
err(1, "asprintf buffer size");
argv[5] = "-l";
if (asprintf(&argv[6], "%zu", udplength) == -1)
err(1, "asprintf udp length");
argv[7] = "-p";
argv[8] = (char *)service;
argv[9] = "-t";
if (asprintf(&argv[10], "%d", timeout) == -1)
err(1, "asprintf timeout");
argv[11] = "send";
argv[12] = (char *)hostname;
argv[13] = NULL;
ssh_pipe(argv);
free(argv[4]);
free(argv[6]);
free(argv[10]);
}
void
ssh_pipe(char *argv[])
{
int fp[2];
if (pipe(fp) == -1)
err(1, "pipe");
ssh_pid = fork();
if (ssh_pid == -1)
err(1, "fork");
if (ssh_pid == 0) {
if (close(fp[0]) == -1)
err(255, "ssh close read pipe");
if (dup2(fp[1], 1) == -1)
err(255, "dup2 pipe");
if (close(fp[1]) == -1)
err(255, "ssh close write pipe");
execvp("ssh", argv);
err(255, "ssh exec");
}
if (close(fp[1]) == -1)
err(1, "close write pipe");
ssh_stream = fdopen(fp[0], "r");
if (ssh_stream == NULL)
err(1, "fdopen");
}
void
ssh_getpeername(char **addr, char **port)
{
char *line, *str, **wp, *words[4];
size_t n;
ssize_t len;
line = NULL;
n = 0;
len = getline(&line, &n, ssh_stream);
if (len < 0) {
if (ferror(ssh_stream))
err(1, "getline sockname");
else
errx(1, "getline sockname empty");
}
if (len > 0 && line[len-1] == '\n')
line[len-1] = '\0';
str = line;
for (wp = &words[0]; wp < &words[4]; wp++)
*wp = strsep(&str, " ");
if (words[0] == NULL || strcmp("sockname:", words[0]) != 0)
errx(1, "ssh no sockname: %s", line);
if (words[1] == NULL)
errx(1, "ssh no addr");
if (addr != NULL) {
*addr = strdup(words[1]);
if (*addr == NULL)
err(1, "strdup addr");
}
if (words[2] == NULL)
errx(1, "ssh no port");
if (port != NULL) {
*port = strdup(words[2]);
if (*port == NULL)
err(1, "strdup port");
}
if (words[3] != NULL)
errx(1, "ssh bad sockname: %s", words[3]);
printf("peername: %s %s\n", words[1], words[2]);
free(line);
}
void
ssh_wait(void)
{
char *line;
size_t n;
ssize_t len;
int status;
line = NULL;
n = 0;
len = getline(&line, &n, ssh_stream);
if (len < 0) {
if (ferror(ssh_stream))
err(1, "getline status");
else
errx(1, "getline status empty");
}
if (len > 0 && line[len-1] == '\n')
line[len-1] = '\0';
printf("%s\n", line);
free(line);
if (waitpid(ssh_pid, &status, 0) == -1)
err(1, "waitpid");
if (status != 0)
errx(1, "ssh failed: %d", status);
}
|
the_stack_data/237643530.c | #include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <assert.h>
int input(const char* msg)
{
char s[20];
printf("%s\n", msg);
char* input = gets(s);
int num_input = 0;
for (int i = 0; i < strlen(input); i++)
num_input = num_input * 10 + (input[i] - '0');
return num_input;
}
long long factorial(int x)
{
if (x == 0)
return 1;
long long fact = 1;
for (int i = 1; i <= x; i++)
fact *= i;
return fact;
}
int main(int argc, char** argv)
{
//1
{
int x, y, z;
x = input("Enter x");
y = input("Enter y");
z = (x > y) ? (x - y) : (y - x + 1);
printf("z = %d\n\n", z);
}
//7
{
int x, fx;
x = input("Enter x");
fx = (-2 <= x && x > 2) ? (x * x) : (4);
printf("f(x) = %d\n\n", fx);
}
//14
{
int x;
double z;
x = input("Enter x");
z = x;
for (int fact = 3; fact <= 13; fact += 2)
z += -(pow(x, fact) / factorial(fact));
printf("factorial order = %f\n\n", z);
}
//23
{
int curr;
int count = 0;
int numbers[50];
while (count < 50)
{
curr = input("Enter number (max-50, 9999-exit)");
if (curr != 9999)
numbers[count] = curr;
else
break;
count++;
}
int psum = 0, ncount = 0;
for (int i = 0; i < count; i++)
(numbers[i] >= 0) ?
psum += numbers[i] : ncount++;
printf("a) sum of all positive nums: %d\n", psum);
printf("b) count of negative nums: %d\n", ncount);
}
return 0;
} |
the_stack_data/248581949.c | #include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#else
#include <unistd.h>
#endif
/* Who cares about stack sizes in test programs anyway */
#define LINE_LENGTH 4096
static int
intrp_copyfile (char * src, char * dest)
{
#ifdef _WIN32
if (!CopyFile (src, dest, FALSE))
return 1;
return 0;
#else
return execlp ("cp", "cp", src, dest, NULL);
#endif
}
static void
parser_get_line (FILE * f, char line[LINE_LENGTH])
{
if (!fgets (line, LINE_LENGTH, f))
fprintf (stderr, "%s\n", strerror (errno));
}
int
main (int argc, char * argv[])
{
FILE *f = NULL;
char line[LINE_LENGTH];
if (argc != 4) {
fprintf (stderr, "Invalid number of arguments: %i\n", argc);
goto err;
}
if ((f = fopen (argv[1], "r")) == NULL) {
fprintf (stderr, "%s\n", strerror (errno));
goto err;
}
parser_get_line (f, line);
if (!line || line[0] != '#' || line[1] != '!') {
fprintf (stderr, "Invalid script\n");
goto err;
}
parser_get_line (f, line);
if (!line || strncmp (line, "copy", 4) != 0) {
fprintf (stderr, "Syntax error: %s\n", line);
goto err;
}
return intrp_copyfile (argv[2], argv[3]);
err:
fclose (f);
return 1;
}
|
the_stack_data/20450248.c | /* This is a heavily customized and minimized copy of Lua 5.1.5. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
/******************************************************************************
* Copyright (C) 1994-2012 Lua.org, PUC-Rio. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
int _CRT_glob = 0;
#include <stddef.h>
#include <stdarg.h>
#include <limits.h>
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <errno.h>
#include <time.h>
typedef enum{
TM_INDEX,
TM_NEWINDEX,
TM_GC,
TM_MODE,
TM_EQ,
TM_ADD,
TM_SUB,
TM_MUL,
TM_DIV,
TM_MOD,
TM_POW,
TM_UNM,
TM_LEN,
TM_LT,
TM_LE,
TM_CONCAT,
TM_CALL,
TM_N
}TMS;
enum OpMode{iABC,iABx,iAsBx};
typedef enum{
OP_MOVE,
OP_LOADK,
OP_LOADBOOL,
OP_LOADNIL,
OP_GETUPVAL,
OP_GETGLOBAL,
OP_GETTABLE,
OP_SETGLOBAL,
OP_SETUPVAL,
OP_SETTABLE,
OP_NEWTABLE,
OP_SELF,
OP_ADD,
OP_SUB,
OP_MUL,
OP_DIV,
OP_MOD,
OP_POW,
OP_UNM,
OP_NOT,
OP_LEN,
OP_CONCAT,
OP_JMP,
OP_EQ,
OP_LT,
OP_LE,
OP_TEST,
OP_TESTSET,
OP_CALL,
OP_TAILCALL,
OP_RETURN,
OP_FORLOOP,
OP_FORPREP,
OP_TFORLOOP,
OP_SETLIST,
OP_CLOSE,
OP_CLOSURE,
OP_VARARG
}OpCode;
enum OpArgMask{
OpArgN,
OpArgU,
OpArgR,
OpArgK
};
typedef enum{
VVOID,
VNIL,
VTRUE,
VFALSE,
VK,
VKNUM,
VLOCAL,
VUPVAL,
VGLOBAL,
VINDEXED,
VJMP,
VRELOCABLE,
VNONRELOC,
VCALL,
VVARARG
}expkind;
enum RESERVED{
TK_AND=257,TK_BREAK,
TK_DO,TK_ELSE,TK_ELSEIF,TK_END,TK_FALSE,TK_FOR,TK_FUNCTION,
TK_IF,TK_IN,TK_LOCAL,TK_NIL,TK_NOT,TK_OR,TK_REPEAT,
TK_RETURN,TK_THEN,TK_TRUE,TK_UNTIL,TK_WHILE,
TK_CONCAT,TK_DOTS,TK_EQ,TK_GE,TK_LE,TK_NE,TK_NUMBER,
TK_NAME,TK_STRING,TK_EOS
};
typedef enum BinOpr{
OPR_ADD,OPR_SUB,OPR_MUL,OPR_DIV,OPR_MOD,OPR_POW,
OPR_CONCAT,
OPR_NE,OPR_EQ,
OPR_LT,OPR_LE,OPR_GT,OPR_GE,
OPR_AND,OPR_OR,
OPR_NOBINOPR
}BinOpr;
typedef enum UnOpr{OPR_MINUS,OPR_NOT,OPR_LEN,OPR_NOUNOPR}UnOpr;
#define LUA_QL(x)"'"x"'"
#define luai_apicheck(L,o){(void)L;}
#define lua_number2str(s,n)sprintf((s),"%.14g",(n))
#define lua_str2number(s,p)strtod((s),(p))
#define luai_numadd(a,b)((a)+(b))
#define luai_numsub(a,b)((a)-(b))
#define luai_nummul(a,b)((a)*(b))
#define luai_numdiv(a,b)((a)/(b))
#define luai_nummod(a,b)((a)-floor((a)/(b))*(b))
#define luai_numpow(a,b)(pow(a,b))
#define luai_numunm(a)(-(a))
#define luai_numeq(a,b)((a)==(b))
#define luai_numlt(a,b)((a)<(b))
#define luai_numle(a,b)((a)<=(b))
#define luai_numisnan(a)(!luai_numeq((a),(a)))
#define lua_number2int(i,d)((i)=(int)(d))
#define lua_number2integer(i,d)((i)=(lua_Integer)(d))
#define LUAI_THROW(L,c)longjmp((c)->b,1)
#define LUAI_TRY(L,c,a)if(setjmp((c)->b)==0){a}
#define lua_pclose(L,file)((void)((void)L,file),0)
#define lua_upvalueindex(i)((-10002)-(i))
typedef struct lua_State lua_State;
typedef int(*lua_CFunction)(lua_State*L);
typedef const char*(*lua_Reader)(lua_State*L,void*ud,size_t*sz);
typedef void*(*lua_Alloc)(void*ud,void*ptr,size_t osize,size_t nsize);
typedef double lua_Number;
typedef ptrdiff_t lua_Integer;
static void lua_settop(lua_State*L,int idx);
static int lua_type(lua_State*L,int idx);
static const char* lua_tolstring(lua_State*L,int idx,size_t*len);
static size_t lua_objlen(lua_State*L,int idx);
static void lua_pushlstring(lua_State*L,const char*s,size_t l);
static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n);
static void lua_createtable(lua_State*L,int narr,int nrec);
static void lua_setfield(lua_State*L,int idx,const char*k);
#define lua_pop(L,n)lua_settop(L,-(n)-1)
#define lua_newtable(L)lua_createtable(L,0,0)
#define lua_pushcfunction(L,f)lua_pushcclosure(L,(f),0)
#define lua_strlen(L,i)lua_objlen(L,(i))
#define lua_isfunction(L,n)(lua_type(L,(n))==6)
#define lua_istable(L,n)(lua_type(L,(n))==5)
#define lua_isnil(L,n)(lua_type(L,(n))==0)
#define lua_isboolean(L,n)(lua_type(L,(n))==1)
#define lua_isnone(L,n)(lua_type(L,(n))==(-1))
#define lua_isnoneornil(L,n)(lua_type(L,(n))<=0)
#define lua_pushliteral(L,s)lua_pushlstring(L,""s,(sizeof(s)/sizeof(char))-1)
#define lua_setglobal(L,s)lua_setfield(L,(-10002),(s))
#define lua_tostring(L,i)lua_tolstring(L,(i),NULL)
typedef struct lua_Debug lua_Debug;
typedef void(*lua_Hook)(lua_State*L,lua_Debug*ar);
struct lua_Debug{
int event;
const char*name;
const char*namewhat;
const char*what;
const char*source;
int currentline;
int nups;
int linedefined;
int lastlinedefined;
char short_src[60];
int i_ci;
};
typedef unsigned int lu_int32;
typedef size_t lu_mem;
typedef ptrdiff_t l_mem;
typedef unsigned char lu_byte;
#define IntPoint(p)((unsigned int)(lu_mem)(p))
typedef union{double u;void*s;long l;}L_Umaxalign;
typedef double l_uacNumber;
#define check_exp(c,e)(e)
#define UNUSED(x)((void)(x))
#define cast(t,exp)((t)(exp))
#define cast_byte(i)cast(lu_byte,(i))
#define cast_num(i)cast(lua_Number,(i))
#define cast_int(i)cast(int,(i))
typedef lu_int32 Instruction;
#define condhardstacktests(x)((void)0)
typedef union GCObject GCObject;
typedef struct GCheader{
GCObject*next;lu_byte tt;lu_byte marked;
}GCheader;
typedef union{
GCObject*gc;
void*p;
lua_Number n;
int b;
}Value;
typedef struct lua_TValue{
Value value;int tt;
}TValue;
#define ttisnil(o)(ttype(o)==0)
#define ttisnumber(o)(ttype(o)==3)
#define ttisstring(o)(ttype(o)==4)
#define ttistable(o)(ttype(o)==5)
#define ttisfunction(o)(ttype(o)==6)
#define ttisboolean(o)(ttype(o)==1)
#define ttisuserdata(o)(ttype(o)==7)
#define ttisthread(o)(ttype(o)==8)
#define ttislightuserdata(o)(ttype(o)==2)
#define ttype(o)((o)->tt)
#define gcvalue(o)check_exp(iscollectable(o),(o)->value.gc)
#define pvalue(o)check_exp(ttislightuserdata(o),(o)->value.p)
#define nvalue(o)check_exp(ttisnumber(o),(o)->value.n)
#define rawtsvalue(o)check_exp(ttisstring(o),&(o)->value.gc->ts)
#define tsvalue(o)(&rawtsvalue(o)->tsv)
#define rawuvalue(o)check_exp(ttisuserdata(o),&(o)->value.gc->u)
#define uvalue(o)(&rawuvalue(o)->uv)
#define clvalue(o)check_exp(ttisfunction(o),&(o)->value.gc->cl)
#define hvalue(o)check_exp(ttistable(o),&(o)->value.gc->h)
#define bvalue(o)check_exp(ttisboolean(o),(o)->value.b)
#define thvalue(o)check_exp(ttisthread(o),&(o)->value.gc->th)
#define l_isfalse(o)(ttisnil(o)||(ttisboolean(o)&&bvalue(o)==0))
#define checkconsistency(obj)
#define checkliveness(g,obj)
#define setnilvalue(obj)((obj)->tt=0)
#define setnvalue(obj,x){TValue*i_o=(obj);i_o->value.n=(x);i_o->tt=3;}
#define setbvalue(obj,x){TValue*i_o=(obj);i_o->value.b=(x);i_o->tt=1;}
#define setsvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=4;checkliveness(G(L),i_o);}
#define setuvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=7;checkliveness(G(L),i_o);}
#define setthvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=8;checkliveness(G(L),i_o);}
#define setclvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=6;checkliveness(G(L),i_o);}
#define sethvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=5;checkliveness(G(L),i_o);}
#define setptvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=(8+1);checkliveness(G(L),i_o);}
#define setobj(L,obj1,obj2){const TValue*o2=(obj2);TValue*o1=(obj1);o1->value=o2->value;o1->tt=o2->tt;checkliveness(G(L),o1);}
#define setttype(obj,tt)(ttype(obj)=(tt))
#define iscollectable(o)(ttype(o)>=4)
typedef TValue*StkId;
typedef union TString{
L_Umaxalign dummy;
struct{
GCObject*next;lu_byte tt;lu_byte marked;
lu_byte reserved;
unsigned int hash;
size_t len;
}tsv;
}TString;
#define getstr(ts)cast(const char*,(ts)+1)
#define svalue(o)getstr(rawtsvalue(o))
typedef union Udata{
L_Umaxalign dummy;
struct{
GCObject*next;lu_byte tt;lu_byte marked;
struct Table*metatable;
struct Table*env;
size_t len;
}uv;
}Udata;
typedef struct Proto{
GCObject*next;lu_byte tt;lu_byte marked;
TValue*k;
Instruction*code;
struct Proto**p;
int*lineinfo;
struct LocVar*locvars;
TString**upvalues;
TString*source;
int sizeupvalues;
int sizek;
int sizecode;
int sizelineinfo;
int sizep;
int sizelocvars;
int linedefined;
int lastlinedefined;
GCObject*gclist;
lu_byte nups;
lu_byte numparams;
lu_byte is_vararg;
lu_byte maxstacksize;
}Proto;
typedef struct LocVar{
TString*varname;
int startpc;
int endpc;
}LocVar;
typedef struct UpVal{
GCObject*next;lu_byte tt;lu_byte marked;
TValue*v;
union{
TValue value;
struct{
struct UpVal*prev;
struct UpVal*next;
}l;
}u;
}UpVal;
typedef struct CClosure{
GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env;
lua_CFunction f;
TValue upvalue[1];
}CClosure;
typedef struct LClosure{
GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env;
struct Proto*p;
UpVal*upvals[1];
}LClosure;
typedef union Closure{
CClosure c;
LClosure l;
}Closure;
#define iscfunction(o)(ttype(o)==6&&clvalue(o)->c.isC)
typedef union TKey{
struct{
Value value;int tt;
struct Node*next;
}nk;
TValue tvk;
}TKey;
typedef struct Node{
TValue i_val;
TKey i_key;
}Node;
typedef struct Table{
GCObject*next;lu_byte tt;lu_byte marked;
lu_byte flags;
lu_byte lsizenode;
struct Table*metatable;
TValue*array;
Node*node;
Node*lastfree;
GCObject*gclist;
int sizearray;
}Table;
#define lmod(s,size)(check_exp((size&(size-1))==0,(cast(int,(s)&((size)-1)))))
#define twoto(x)((size_t)1<<(x))
#define sizenode(t)(twoto((t)->lsizenode))
static const TValue luaO_nilobject_;
#define ceillog2(x)(luaO_log2((x)-1)+1)
static int luaO_log2(unsigned int x);
#define gfasttm(g,et,e)((et)==NULL?NULL:((et)->flags&(1u<<(e)))?NULL:luaT_gettm(et,e,(g)->tmname[e]))
#define fasttm(l,et,e)gfasttm(G(l),et,e)
static const TValue*luaT_gettm(Table*events,TMS event,TString*ename);
#define luaM_reallocv(L,b,on,n,e)((cast(size_t,(n)+1)<=((size_t)(~(size_t)0)-2)/(e))?luaM_realloc_(L,(b),(on)*(e),(n)*(e)):luaM_toobig(L))
#define luaM_freemem(L,b,s)luaM_realloc_(L,(b),(s),0)
#define luaM_free(L,b)luaM_realloc_(L,(b),sizeof(*(b)),0)
#define luaM_freearray(L,b,n,t)luaM_reallocv(L,(b),n,0,sizeof(t))
#define luaM_malloc(L,t)luaM_realloc_(L,NULL,0,(t))
#define luaM_new(L,t)cast(t*,luaM_malloc(L,sizeof(t)))
#define luaM_newvector(L,n,t)cast(t*,luaM_reallocv(L,NULL,0,n,sizeof(t)))
#define luaM_growvector(L,v,nelems,size,t,limit,e)if((nelems)+1>(size))((v)=cast(t*,luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
#define luaM_reallocvector(L,v,oldn,n,t)((v)=cast(t*,luaM_reallocv(L,v,oldn,n,sizeof(t))))
static void*luaM_realloc_(lua_State*L,void*block,size_t oldsize,
size_t size);
static void*luaM_toobig(lua_State*L);
static void*luaM_growaux_(lua_State*L,void*block,int*size,
size_t size_elem,int limit,
const char*errormsg);
typedef struct Zio ZIO;
#define char2int(c)cast(int,cast(unsigned char,(c)))
#define zgetc(z)(((z)->n--)>0?char2int(*(z)->p++):luaZ_fill(z))
typedef struct Mbuffer{
char*buffer;
size_t n;
size_t buffsize;
}Mbuffer;
#define luaZ_initbuffer(L,buff)((buff)->buffer=NULL,(buff)->buffsize=0)
#define luaZ_buffer(buff)((buff)->buffer)
#define luaZ_sizebuffer(buff)((buff)->buffsize)
#define luaZ_bufflen(buff)((buff)->n)
#define luaZ_resetbuffer(buff)((buff)->n=0)
#define luaZ_resizebuffer(L,buff,size)(luaM_reallocvector(L,(buff)->buffer,(buff)->buffsize,size,char),(buff)->buffsize=size)
#define luaZ_freebuffer(L,buff)luaZ_resizebuffer(L,buff,0)
struct Zio{
size_t n;
const char*p;
lua_Reader reader;
void*data;
lua_State*L;
};
static int luaZ_fill(ZIO*z);
struct lua_longjmp;
#define gt(L)(&L->l_gt)
#define registry(L)(&G(L)->l_registry)
typedef struct stringtable{
GCObject**hash;
lu_int32 nuse;
int size;
}stringtable;
typedef struct CallInfo{
StkId base;
StkId func;
StkId top;
const Instruction*savedpc;
int nresults;
int tailcalls;
}CallInfo;
#define curr_func(L)(clvalue(L->ci->func))
#define ci_func(ci)(clvalue((ci)->func))
#define f_isLua(ci)(!ci_func(ci)->c.isC)
#define isLua(ci)(ttisfunction((ci)->func)&&f_isLua(ci))
typedef struct global_State{
stringtable strt;
lua_Alloc frealloc;
void*ud;
lu_byte currentwhite;
lu_byte gcstate;
int sweepstrgc;
GCObject*rootgc;
GCObject**sweepgc;
GCObject*gray;
GCObject*grayagain;
GCObject*weak;
GCObject*tmudata;
Mbuffer buff;
lu_mem GCthreshold;
lu_mem totalbytes;
lu_mem estimate;
lu_mem gcdept;
int gcpause;
int gcstepmul;
lua_CFunction panic;
TValue l_registry;
struct lua_State*mainthread;
UpVal uvhead;
struct Table*mt[(8+1)];
TString*tmname[TM_N];
}global_State;
struct lua_State{
GCObject*next;lu_byte tt;lu_byte marked;
lu_byte status;
StkId top;
StkId base;
global_State*l_G;
CallInfo*ci;
const Instruction*savedpc;
StkId stack_last;
StkId stack;
CallInfo*end_ci;
CallInfo*base_ci;
int stacksize;
int size_ci;
unsigned short nCcalls;
unsigned short baseCcalls;
lu_byte hookmask;
lu_byte allowhook;
int basehookcount;
int hookcount;
lua_Hook hook;
TValue l_gt;
TValue env;
GCObject*openupval;
GCObject*gclist;
struct lua_longjmp*errorJmp;
ptrdiff_t errfunc;
};
#define G(L)(L->l_G)
union GCObject{
GCheader gch;
union TString ts;
union Udata u;
union Closure cl;
struct Table h;
struct Proto p;
struct UpVal uv;
struct lua_State th;
};
#define rawgco2ts(o)check_exp((o)->gch.tt==4,&((o)->ts))
#define gco2ts(o)(&rawgco2ts(o)->tsv)
#define rawgco2u(o)check_exp((o)->gch.tt==7,&((o)->u))
#define gco2u(o)(&rawgco2u(o)->uv)
#define gco2cl(o)check_exp((o)->gch.tt==6,&((o)->cl))
#define gco2h(o)check_exp((o)->gch.tt==5,&((o)->h))
#define gco2p(o)check_exp((o)->gch.tt==(8+1),&((o)->p))
#define gco2uv(o)check_exp((o)->gch.tt==(8+2),&((o)->uv))
#define ngcotouv(o)check_exp((o)==NULL||(o)->gch.tt==(8+2),&((o)->uv))
#define gco2th(o)check_exp((o)->gch.tt==8,&((o)->th))
#define obj2gco(v)(cast(GCObject*,(v)))
static void luaE_freethread(lua_State*L,lua_State*L1);
#define pcRel(pc,p)(cast(int,(pc)-(p)->code)-1)
#define getline_(f,pc)(((f)->lineinfo)?(f)->lineinfo[pc]:0)
#define resethookcount(L)(L->hookcount=L->basehookcount)
static void luaG_typeerror(lua_State*L,const TValue*o,
const char*opname);
static void luaG_runerror(lua_State*L,const char*fmt,...);
#define luaD_checkstack(L,n)if((char*)L->stack_last-(char*)L->top<=(n)*(int)sizeof(TValue))luaD_growstack(L,n);else condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1));
#define incr_top(L){luaD_checkstack(L,1);L->top++;}
#define savestack(L,p)((char*)(p)-(char*)L->stack)
#define restorestack(L,n)((TValue*)((char*)L->stack+(n)))
#define saveci(L,p)((char*)(p)-(char*)L->base_ci)
#define restoreci(L,n)((CallInfo*)((char*)L->base_ci+(n)))
typedef void(*Pfunc)(lua_State*L,void*ud);
static int luaD_poscall(lua_State*L,StkId firstResult);
static void luaD_reallocCI(lua_State*L,int newsize);
static void luaD_reallocstack(lua_State*L,int newsize);
static void luaD_growstack(lua_State*L,int n);
static void luaD_throw(lua_State*L,int errcode);
static void*luaM_growaux_(lua_State*L,void*block,int*size,size_t size_elems,
int limit,const char*errormsg){
void*newblock;
int newsize;
if(*size>=limit/2){
if(*size>=limit)
luaG_runerror(L,errormsg);
newsize=limit;
}
else{
newsize=(*size)*2;
if(newsize<4)
newsize=4;
}
newblock=luaM_reallocv(L,block,*size,newsize,size_elems);
*size=newsize;
return newblock;
}
static void*luaM_toobig(lua_State*L){
luaG_runerror(L,"memory allocation error: block too big");
return NULL;
}
static void*luaM_realloc_(lua_State*L,void*block,size_t osize,size_t nsize){
global_State*g=G(L);
block=(*g->frealloc)(g->ud,block,osize,nsize);
if(block==NULL&&nsize>0)
luaD_throw(L,4);
g->totalbytes=(g->totalbytes-osize)+nsize;
return block;
}
#define resetbits(x,m)((x)&=cast(lu_byte,~(m)))
#define setbits(x,m)((x)|=(m))
#define testbits(x,m)((x)&(m))
#define bitmask(b)(1<<(b))
#define bit2mask(b1,b2)(bitmask(b1)|bitmask(b2))
#define l_setbit(x,b)setbits(x,bitmask(b))
#define resetbit(x,b)resetbits(x,bitmask(b))
#define testbit(x,b)testbits(x,bitmask(b))
#define set2bits(x,b1,b2)setbits(x,(bit2mask(b1,b2)))
#define reset2bits(x,b1,b2)resetbits(x,(bit2mask(b1,b2)))
#define test2bits(x,b1,b2)testbits(x,(bit2mask(b1,b2)))
#define iswhite(x)test2bits((x)->gch.marked,0,1)
#define isblack(x)testbit((x)->gch.marked,2)
#define isgray(x)(!isblack(x)&&!iswhite(x))
#define otherwhite(g)(g->currentwhite^bit2mask(0,1))
#define isdead(g,v)((v)->gch.marked&otherwhite(g)&bit2mask(0,1))
#define changewhite(x)((x)->gch.marked^=bit2mask(0,1))
#define gray2black(x)l_setbit((x)->gch.marked,2)
#define valiswhite(x)(iscollectable(x)&&iswhite(gcvalue(x)))
#define luaC_white(g)cast(lu_byte,(g)->currentwhite&bit2mask(0,1))
#define luaC_checkGC(L){condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1));if(G(L)->totalbytes>=G(L)->GCthreshold)luaC_step(L);}
#define luaC_barrier(L,p,v){if(valiswhite(v)&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),gcvalue(v));}
#define luaC_barriert(L,t,v){if(valiswhite(v)&&isblack(obj2gco(t)))luaC_barrierback(L,t);}
#define luaC_objbarrier(L,p,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),obj2gco(o));}
#define luaC_objbarriert(L,t,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(t)))luaC_barrierback(L,t);}
static void luaC_step(lua_State*L);
static void luaC_link(lua_State*L,GCObject*o,lu_byte tt);
static void luaC_linkupval(lua_State*L,UpVal*uv);
static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v);
static void luaC_barrierback(lua_State*L,Table*t);
#define sizestring(s)(sizeof(union TString)+((s)->len+1)*sizeof(char))
#define sizeudata(u)(sizeof(union Udata)+(u)->len)
#define luaS_new(L,s)(luaS_newlstr(L,s,strlen(s)))
#define luaS_newliteral(L,s)(luaS_newlstr(L,""s,(sizeof(s)/sizeof(char))-1))
#define luaS_fix(s)l_setbit((s)->tsv.marked,5)
static TString*luaS_newlstr(lua_State*L,const char*str,size_t l);
#define tostring(L,o)((ttype(o)==4)||(luaV_tostring(L,o)))
#define tonumber(o,n)(ttype(o)==3||(((o)=luaV_tonumber(o,n))!=NULL))
#define equalobj(L,o1,o2)(ttype(o1)==ttype(o2)&&luaV_equalval(L,o1,o2))
static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2);
static const TValue*luaV_tonumber(const TValue*obj,TValue*n);
static int luaV_tostring(lua_State*L,StkId obj);
static void luaV_execute(lua_State*L,int nexeccalls);
static void luaV_concat(lua_State*L,int total,int last);
static const TValue luaO_nilobject_={{NULL},0};
static int luaO_int2fb(unsigned int x){
int e=0;
while(x>=16){
x=(x+1)>>1;
e++;
}
if(x<8)return x;
else return((e+1)<<3)|(cast_int(x)-8);
}
static int luaO_fb2int(int x){
int e=(x>>3)&31;
if(e==0)return x;
else return((x&7)+8)<<(e-1);
}
static int luaO_log2(unsigned int x){
static const lu_byte log_2[256]={
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
int l=-1;
while(x>=256){l+=8;x>>=8;}
return l+log_2[x];
}
static int luaO_rawequalObj(const TValue*t1,const TValue*t2){
if(ttype(t1)!=ttype(t2))return 0;
else switch(ttype(t1)){
case 0:
return 1;
case 3:
return luai_numeq(nvalue(t1),nvalue(t2));
case 1:
return bvalue(t1)==bvalue(t2);
case 2:
return pvalue(t1)==pvalue(t2);
default:
return gcvalue(t1)==gcvalue(t2);
}
}
static int luaO_str2d(const char*s,lua_Number*result){
char*endptr;
*result=lua_str2number(s,&endptr);
if(endptr==s)return 0;
if(*endptr=='x'||*endptr=='X')
*result=cast_num(strtoul(s,&endptr,16));
if(*endptr=='\0')return 1;
while(isspace(cast(unsigned char,*endptr)))endptr++;
if(*endptr!='\0')return 0;
return 1;
}
static void pushstr(lua_State*L,const char*str){
setsvalue(L,L->top,luaS_new(L,str));
incr_top(L);
}
static const char*luaO_pushvfstring(lua_State*L,const char*fmt,va_list argp){
int n=1;
pushstr(L,"");
for(;;){
const char*e=strchr(fmt,'%');
if(e==NULL)break;
setsvalue(L,L->top,luaS_newlstr(L,fmt,e-fmt));
incr_top(L);
switch(*(e+1)){
case's':{
const char*s=va_arg(argp,char*);
if(s==NULL)s="(null)";
pushstr(L,s);
break;
}
case'c':{
char buff[2];
buff[0]=cast(char,va_arg(argp,int));
buff[1]='\0';
pushstr(L,buff);
break;
}
case'd':{
setnvalue(L->top,cast_num(va_arg(argp,int)));
incr_top(L);
break;
}
case'f':{
setnvalue(L->top,cast_num(va_arg(argp,l_uacNumber)));
incr_top(L);
break;
}
case'p':{
char buff[4*sizeof(void*)+8];
sprintf(buff,"%p",va_arg(argp,void*));
pushstr(L,buff);
break;
}
case'%':{
pushstr(L,"%");
break;
}
default:{
char buff[3];
buff[0]='%';
buff[1]=*(e+1);
buff[2]='\0';
pushstr(L,buff);
break;
}
}
n+=2;
fmt=e+2;
}
pushstr(L,fmt);
luaV_concat(L,n+1,cast_int(L->top-L->base)-1);
L->top-=n;
return svalue(L->top-1);
}
static const char*luaO_pushfstring(lua_State*L,const char*fmt,...){
const char*msg;
va_list argp;
va_start(argp,fmt);
msg=luaO_pushvfstring(L,fmt,argp);
va_end(argp);
return msg;
}
static void luaO_chunkid(char*out,const char*source,size_t bufflen){
if(*source=='='){
strncpy(out,source+1,bufflen);
out[bufflen-1]='\0';
}
else{
if(*source=='@'){
size_t l;
source++;
bufflen-=sizeof(" '...' ");
l=strlen(source);
strcpy(out,"");
if(l>bufflen){
source+=(l-bufflen);
strcat(out,"...");
}
strcat(out,source);
}
else{
size_t len=strcspn(source,"\n\r");
bufflen-=sizeof(" [string \"...\"] ");
if(len>bufflen)len=bufflen;
strcpy(out,"[string \"");
if(source[len]!='\0'){
strncat(out,source,len);
strcat(out,"...");
}
else
strcat(out,source);
strcat(out,"\"]");
}
}
}
#define gnode(t,i)(&(t)->node[i])
#define gkey(n)(&(n)->i_key.nk)
#define gval(n)(&(n)->i_val)
#define gnext(n)((n)->i_key.nk.next)
#define key2tval(n)(&(n)->i_key.tvk)
static TValue*luaH_setnum(lua_State*L,Table*t,int key);
static const TValue*luaH_getstr(Table*t,TString*key);
static TValue*luaH_set(lua_State*L,Table*t,const TValue*key);
static const char*const luaT_typenames[]={
"nil","boolean","userdata","number",
"string","table","function","userdata","thread",
"proto","upval"
};
static void luaT_init(lua_State*L){
static const char*const luaT_eventname[]={
"__index","__newindex",
"__gc","__mode","__eq",
"__add","__sub","__mul","__div","__mod",
"__pow","__unm","__len","__lt","__le",
"__concat","__call"
};
int i;
for(i=0;i<TM_N;i++){
G(L)->tmname[i]=luaS_new(L,luaT_eventname[i]);
luaS_fix(G(L)->tmname[i]);
}
}
static const TValue*luaT_gettm(Table*events,TMS event,TString*ename){
const TValue*tm=luaH_getstr(events,ename);
if(ttisnil(tm)){
events->flags|=cast_byte(1u<<event);
return NULL;
}
else return tm;
}
static const TValue*luaT_gettmbyobj(lua_State*L,const TValue*o,TMS event){
Table*mt;
switch(ttype(o)){
case 5:
mt=hvalue(o)->metatable;
break;
case 7:
mt=uvalue(o)->metatable;
break;
default:
mt=G(L)->mt[ttype(o)];
}
return(mt?luaH_getstr(mt,G(L)->tmname[event]):(&luaO_nilobject_));
}
#define sizeCclosure(n)(cast(int,sizeof(CClosure))+cast(int,sizeof(TValue)*((n)-1)))
#define sizeLclosure(n)(cast(int,sizeof(LClosure))+cast(int,sizeof(TValue*)*((n)-1)))
static Closure*luaF_newCclosure(lua_State*L,int nelems,Table*e){
Closure*c=cast(Closure*,luaM_malloc(L,sizeCclosure(nelems)));
luaC_link(L,obj2gco(c),6);
c->c.isC=1;
c->c.env=e;
c->c.nupvalues=cast_byte(nelems);
return c;
}
static Closure*luaF_newLclosure(lua_State*L,int nelems,Table*e){
Closure*c=cast(Closure*,luaM_malloc(L,sizeLclosure(nelems)));
luaC_link(L,obj2gco(c),6);
c->l.isC=0;
c->l.env=e;
c->l.nupvalues=cast_byte(nelems);
while(nelems--)c->l.upvals[nelems]=NULL;
return c;
}
static UpVal*luaF_newupval(lua_State*L){
UpVal*uv=luaM_new(L,UpVal);
luaC_link(L,obj2gco(uv),(8+2));
uv->v=&uv->u.value;
setnilvalue(uv->v);
return uv;
}
static UpVal*luaF_findupval(lua_State*L,StkId level){
global_State*g=G(L);
GCObject**pp=&L->openupval;
UpVal*p;
UpVal*uv;
while(*pp!=NULL&&(p=ngcotouv(*pp))->v>=level){
if(p->v==level){
if(isdead(g,obj2gco(p)))
changewhite(obj2gco(p));
return p;
}
pp=&p->next;
}
uv=luaM_new(L,UpVal);
uv->tt=(8+2);
uv->marked=luaC_white(g);
uv->v=level;
uv->next=*pp;
*pp=obj2gco(uv);
uv->u.l.prev=&g->uvhead;
uv->u.l.next=g->uvhead.u.l.next;
uv->u.l.next->u.l.prev=uv;
g->uvhead.u.l.next=uv;
return uv;
}
static void unlinkupval(UpVal*uv){
uv->u.l.next->u.l.prev=uv->u.l.prev;
uv->u.l.prev->u.l.next=uv->u.l.next;
}
static void luaF_freeupval(lua_State*L,UpVal*uv){
if(uv->v!=&uv->u.value)
unlinkupval(uv);
luaM_free(L,uv);
}
static void luaF_close(lua_State*L,StkId level){
UpVal*uv;
global_State*g=G(L);
while(L->openupval!=NULL&&(uv=ngcotouv(L->openupval))->v>=level){
GCObject*o=obj2gco(uv);
L->openupval=uv->next;
if(isdead(g,o))
luaF_freeupval(L,uv);
else{
unlinkupval(uv);
setobj(L,&uv->u.value,uv->v);
uv->v=&uv->u.value;
luaC_linkupval(L,uv);
}
}
}
static Proto*luaF_newproto(lua_State*L){
Proto*f=luaM_new(L,Proto);
luaC_link(L,obj2gco(f),(8+1));
f->k=NULL;
f->sizek=0;
f->p=NULL;
f->sizep=0;
f->code=NULL;
f->sizecode=0;
f->sizelineinfo=0;
f->sizeupvalues=0;
f->nups=0;
f->upvalues=NULL;
f->numparams=0;
f->is_vararg=0;
f->maxstacksize=0;
f->lineinfo=NULL;
f->sizelocvars=0;
f->locvars=NULL;
f->linedefined=0;
f->lastlinedefined=0;
f->source=NULL;
return f;
}
static void luaF_freeproto(lua_State*L,Proto*f){
luaM_freearray(L,f->code,f->sizecode,Instruction);
luaM_freearray(L,f->p,f->sizep,Proto*);
luaM_freearray(L,f->k,f->sizek,TValue);
luaM_freearray(L,f->lineinfo,f->sizelineinfo,int);
luaM_freearray(L,f->locvars,f->sizelocvars,struct LocVar);
luaM_freearray(L,f->upvalues,f->sizeupvalues,TString*);
luaM_free(L,f);
}
static void luaF_freeclosure(lua_State*L,Closure*c){
int size=(c->c.isC)?sizeCclosure(c->c.nupvalues):
sizeLclosure(c->l.nupvalues);
luaM_freemem(L,c,size);
}
#define MASK1(n,p)((~((~(Instruction)0)<<n))<<p)
#define MASK0(n,p)(~MASK1(n,p))
#define GET_OPCODE(i)(cast(OpCode,((i)>>0)&MASK1(6,0)))
#define SET_OPCODE(i,o)((i)=(((i)&MASK0(6,0))|((cast(Instruction,o)<<0)&MASK1(6,0))))
#define GETARG_A(i)(cast(int,((i)>>(0+6))&MASK1(8,0)))
#define SETARG_A(i,u)((i)=(((i)&MASK0(8,(0+6)))|((cast(Instruction,u)<<(0+6))&MASK1(8,(0+6)))))
#define GETARG_B(i)(cast(int,((i)>>(((0+6)+8)+9))&MASK1(9,0)))
#define SETARG_B(i,b)((i)=(((i)&MASK0(9,(((0+6)+8)+9)))|((cast(Instruction,b)<<(((0+6)+8)+9))&MASK1(9,(((0+6)+8)+9)))))
#define GETARG_C(i)(cast(int,((i)>>((0+6)+8))&MASK1(9,0)))
#define SETARG_C(i,b)((i)=(((i)&MASK0(9,((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1(9,((0+6)+8)))))
#define GETARG_Bx(i)(cast(int,((i)>>((0+6)+8))&MASK1((9+9),0)))
#define SETARG_Bx(i,b)((i)=(((i)&MASK0((9+9),((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1((9+9),((0+6)+8)))))
#define GETARG_sBx(i)(GETARG_Bx(i)-(((1<<(9+9))-1)>>1))
#define SETARG_sBx(i,b)SETARG_Bx((i),cast(unsigned int,(b)+(((1<<(9+9))-1)>>1)))
#define CREATE_ABC(o,a,b,c)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,b)<<(((0+6)+8)+9))|(cast(Instruction,c)<<((0+6)+8)))
#define CREATE_ABx(o,a,bc)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,bc)<<((0+6)+8)))
#define ISK(x)((x)&(1<<(9-1)))
#define INDEXK(r)((int)(r)&~(1<<(9-1)))
#define RKASK(x)((x)|(1<<(9-1)))
static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)];
#define getBMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>4)&3))
#define getCMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>2)&3))
#define testTMode(m)(luaP_opmodes[m]&(1<<7))
typedef struct expdesc{
expkind k;
union{
struct{int info,aux;}s;
lua_Number nval;
}u;
int t;
int f;
}expdesc;
typedef struct upvaldesc{
lu_byte k;
lu_byte info;
}upvaldesc;
struct BlockCnt;
typedef struct FuncState{
Proto*f;
Table*h;
struct FuncState*prev;
struct LexState*ls;
struct lua_State*L;
struct BlockCnt*bl;
int pc;
int lasttarget;
int jpc;
int freereg;
int nk;
int np;
short nlocvars;
lu_byte nactvar;
upvaldesc upvalues[60];
unsigned short actvar[200];
}FuncState;
static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff,
const char*name);
struct lua_longjmp{
struct lua_longjmp*previous;
jmp_buf b;
volatile int status;
};
static void luaD_seterrorobj(lua_State*L,int errcode,StkId oldtop){
switch(errcode){
case 4:{
setsvalue(L,oldtop,luaS_newliteral(L,"not enough memory"));
break;
}
case 5:{
setsvalue(L,oldtop,luaS_newliteral(L,"error in error handling"));
break;
}
case 3:
case 2:{
setobj(L,oldtop,L->top-1);
break;
}
}
L->top=oldtop+1;
}
static void restore_stack_limit(lua_State*L){
if(L->size_ci>20000){
int inuse=cast_int(L->ci-L->base_ci);
if(inuse+1<20000)
luaD_reallocCI(L,20000);
}
}
static void resetstack(lua_State*L,int status){
L->ci=L->base_ci;
L->base=L->ci->base;
luaF_close(L,L->base);
luaD_seterrorobj(L,status,L->base);
L->nCcalls=L->baseCcalls;
L->allowhook=1;
restore_stack_limit(L);
L->errfunc=0;
L->errorJmp=NULL;
}
static void luaD_throw(lua_State*L,int errcode){
if(L->errorJmp){
L->errorJmp->status=errcode;
LUAI_THROW(L,L->errorJmp);
}
else{
L->status=cast_byte(errcode);
if(G(L)->panic){
resetstack(L,errcode);
G(L)->panic(L);
}
exit(EXIT_FAILURE);
}
}
static int luaD_rawrunprotected(lua_State*L,Pfunc f,void*ud){
struct lua_longjmp lj;
lj.status=0;
lj.previous=L->errorJmp;
L->errorJmp=&lj;
LUAI_TRY(L,&lj,
(*f)(L,ud);
);
L->errorJmp=lj.previous;
return lj.status;
}
static void correctstack(lua_State*L,TValue*oldstack){
CallInfo*ci;
GCObject*up;
L->top=(L->top-oldstack)+L->stack;
for(up=L->openupval;up!=NULL;up=up->gch.next)
gco2uv(up)->v=(gco2uv(up)->v-oldstack)+L->stack;
for(ci=L->base_ci;ci<=L->ci;ci++){
ci->top=(ci->top-oldstack)+L->stack;
ci->base=(ci->base-oldstack)+L->stack;
ci->func=(ci->func-oldstack)+L->stack;
}
L->base=(L->base-oldstack)+L->stack;
}
static void luaD_reallocstack(lua_State*L,int newsize){
TValue*oldstack=L->stack;
int realsize=newsize+1+5;
luaM_reallocvector(L,L->stack,L->stacksize,realsize,TValue);
L->stacksize=realsize;
L->stack_last=L->stack+newsize;
correctstack(L,oldstack);
}
static void luaD_reallocCI(lua_State*L,int newsize){
CallInfo*oldci=L->base_ci;
luaM_reallocvector(L,L->base_ci,L->size_ci,newsize,CallInfo);
L->size_ci=newsize;
L->ci=(L->ci-oldci)+L->base_ci;
L->end_ci=L->base_ci+L->size_ci-1;
}
static void luaD_growstack(lua_State*L,int n){
if(n<=L->stacksize)
luaD_reallocstack(L,2*L->stacksize);
else
luaD_reallocstack(L,L->stacksize+n);
}
static CallInfo*growCI(lua_State*L){
if(L->size_ci>20000)
luaD_throw(L,5);
else{
luaD_reallocCI(L,2*L->size_ci);
if(L->size_ci>20000)
luaG_runerror(L,"stack overflow");
}
return++L->ci;
}
static StkId adjust_varargs(lua_State*L,Proto*p,int actual){
int i;
int nfixargs=p->numparams;
Table*htab=NULL;
StkId base,fixed;
for(;actual<nfixargs;++actual)
setnilvalue(L->top++);
fixed=L->top-actual;
base=L->top;
for(i=0;i<nfixargs;i++){
setobj(L,L->top++,fixed+i);
setnilvalue(fixed+i);
}
if(htab){
sethvalue(L,L->top++,htab);
}
return base;
}
static StkId tryfuncTM(lua_State*L,StkId func){
const TValue*tm=luaT_gettmbyobj(L,func,TM_CALL);
StkId p;
ptrdiff_t funcr=savestack(L,func);
if(!ttisfunction(tm))
luaG_typeerror(L,func,"call");
for(p=L->top;p>func;p--)setobj(L,p,p-1);
incr_top(L);
func=restorestack(L,funcr);
setobj(L,func,tm);
return func;
}
#define inc_ci(L)((L->ci==L->end_ci)?growCI(L):(condhardstacktests(luaD_reallocCI(L,L->size_ci)),++L->ci))
static int luaD_precall(lua_State*L,StkId func,int nresults){
LClosure*cl;
ptrdiff_t funcr;
if(!ttisfunction(func))
func=tryfuncTM(L,func);
funcr=savestack(L,func);
cl=&clvalue(func)->l;
L->ci->savedpc=L->savedpc;
if(!cl->isC){
CallInfo*ci;
StkId st,base;
Proto*p=cl->p;
luaD_checkstack(L,p->maxstacksize);
func=restorestack(L,funcr);
if(!p->is_vararg){
base=func+1;
if(L->top>base+p->numparams)
L->top=base+p->numparams;
}
else{
int nargs=cast_int(L->top-func)-1;
base=adjust_varargs(L,p,nargs);
func=restorestack(L,funcr);
}
ci=inc_ci(L);
ci->func=func;
L->base=ci->base=base;
ci->top=L->base+p->maxstacksize;
L->savedpc=p->code;
ci->tailcalls=0;
ci->nresults=nresults;
for(st=L->top;st<ci->top;st++)
setnilvalue(st);
L->top=ci->top;
return 0;
}
else{
CallInfo*ci;
int n;
luaD_checkstack(L,20);
ci=inc_ci(L);
ci->func=restorestack(L,funcr);
L->base=ci->base=ci->func+1;
ci->top=L->top+20;
ci->nresults=nresults;
n=(*curr_func(L)->c.f)(L);
if(n<0)
return 2;
else{
luaD_poscall(L,L->top-n);
return 1;
}
}
}
static int luaD_poscall(lua_State*L,StkId firstResult){
StkId res;
int wanted,i;
CallInfo*ci;
ci=L->ci--;
res=ci->func;
wanted=ci->nresults;
L->base=(ci-1)->base;
L->savedpc=(ci-1)->savedpc;
for(i=wanted;i!=0&&firstResult<L->top;i--)
setobj(L,res++,firstResult++);
while(i-->0)
setnilvalue(res++);
L->top=res;
return(wanted-(-1));
}
static void luaD_call(lua_State*L,StkId func,int nResults){
if(++L->nCcalls>=200){
if(L->nCcalls==200)
luaG_runerror(L,"C stack overflow");
else if(L->nCcalls>=(200+(200>>3)))
luaD_throw(L,5);
}
if(luaD_precall(L,func,nResults)==0)
luaV_execute(L,1);
L->nCcalls--;
luaC_checkGC(L);
}
static int luaD_pcall(lua_State*L,Pfunc func,void*u,
ptrdiff_t old_top,ptrdiff_t ef){
int status;
unsigned short oldnCcalls=L->nCcalls;
ptrdiff_t old_ci=saveci(L,L->ci);
lu_byte old_allowhooks=L->allowhook;
ptrdiff_t old_errfunc=L->errfunc;
L->errfunc=ef;
status=luaD_rawrunprotected(L,func,u);
if(status!=0){
StkId oldtop=restorestack(L,old_top);
luaF_close(L,oldtop);
luaD_seterrorobj(L,status,oldtop);
L->nCcalls=oldnCcalls;
L->ci=restoreci(L,old_ci);
L->base=L->ci->base;
L->savedpc=L->ci->savedpc;
L->allowhook=old_allowhooks;
restore_stack_limit(L);
}
L->errfunc=old_errfunc;
return status;
}
struct SParser{
ZIO*z;
Mbuffer buff;
const char*name;
};
static void f_parser(lua_State*L,void*ud){
int i;
Proto*tf;
Closure*cl;
struct SParser*p=cast(struct SParser*,ud);
luaC_checkGC(L);
tf=luaY_parser(L,p->z,
&p->buff,p->name);
cl=luaF_newLclosure(L,tf->nups,hvalue(gt(L)));
cl->l.p=tf;
for(i=0;i<tf->nups;i++)
cl->l.upvals[i]=luaF_newupval(L);
setclvalue(L,L->top,cl);
incr_top(L);
}
static int luaD_protectedparser(lua_State*L,ZIO*z,const char*name){
struct SParser p;
int status;
p.z=z;p.name=name;
luaZ_initbuffer(L,&p.buff);
status=luaD_pcall(L,f_parser,&p,savestack(L,L->top),L->errfunc);
luaZ_freebuffer(L,&p.buff);
return status;
}
static void luaS_resize(lua_State*L,int newsize){
GCObject**newhash;
stringtable*tb;
int i;
if(G(L)->gcstate==2)
return;
newhash=luaM_newvector(L,newsize,GCObject*);
tb=&G(L)->strt;
for(i=0;i<newsize;i++)newhash[i]=NULL;
for(i=0;i<tb->size;i++){
GCObject*p=tb->hash[i];
while(p){
GCObject*next=p->gch.next;
unsigned int h=gco2ts(p)->hash;
int h1=lmod(h,newsize);
p->gch.next=newhash[h1];
newhash[h1]=p;
p=next;
}
}
luaM_freearray(L,tb->hash,tb->size,TString*);
tb->size=newsize;
tb->hash=newhash;
}
static TString*newlstr(lua_State*L,const char*str,size_t l,
unsigned int h){
TString*ts;
stringtable*tb;
if(l+1>(((size_t)(~(size_t)0)-2)-sizeof(TString))/sizeof(char))
luaM_toobig(L);
ts=cast(TString*,luaM_malloc(L,(l+1)*sizeof(char)+sizeof(TString)));
ts->tsv.len=l;
ts->tsv.hash=h;
ts->tsv.marked=luaC_white(G(L));
ts->tsv.tt=4;
ts->tsv.reserved=0;
memcpy(ts+1,str,l*sizeof(char));
((char*)(ts+1))[l]='\0';
tb=&G(L)->strt;
h=lmod(h,tb->size);
ts->tsv.next=tb->hash[h];
tb->hash[h]=obj2gco(ts);
tb->nuse++;
if(tb->nuse>cast(lu_int32,tb->size)&&tb->size<=(INT_MAX-2)/2)
luaS_resize(L,tb->size*2);
return ts;
}
static TString*luaS_newlstr(lua_State*L,const char*str,size_t l){
GCObject*o;
unsigned int h=cast(unsigned int,l);
size_t step=(l>>5)+1;
size_t l1;
for(l1=l;l1>=step;l1-=step)
h=h^((h<<5)+(h>>2)+cast(unsigned char,str[l1-1]));
for(o=G(L)->strt.hash[lmod(h,G(L)->strt.size)];
o!=NULL;
o=o->gch.next){
TString*ts=rawgco2ts(o);
if(ts->tsv.len==l&&(memcmp(str,getstr(ts),l)==0)){
if(isdead(G(L),o))changewhite(o);
return ts;
}
}
return newlstr(L,str,l,h);
}
static Udata*luaS_newudata(lua_State*L,size_t s,Table*e){
Udata*u;
if(s>((size_t)(~(size_t)0)-2)-sizeof(Udata))
luaM_toobig(L);
u=cast(Udata*,luaM_malloc(L,s+sizeof(Udata)));
u->uv.marked=luaC_white(G(L));
u->uv.tt=7;
u->uv.len=s;
u->uv.metatable=NULL;
u->uv.env=e;
u->uv.next=G(L)->mainthread->next;
G(L)->mainthread->next=obj2gco(u);
return u;
}
#define hashpow2(t,n)(gnode(t,lmod((n),sizenode(t))))
#define hashstr(t,str)hashpow2(t,(str)->tsv.hash)
#define hashboolean(t,p)hashpow2(t,p)
#define hashmod(t,n)(gnode(t,((n)%((sizenode(t)-1)|1))))
#define hashpointer(t,p)hashmod(t,IntPoint(p))
static const Node dummynode_={
{{NULL},0},
{{{NULL},0,NULL}}
};
static Node*hashnum(const Table*t,lua_Number n){
unsigned int a[cast_int(sizeof(lua_Number)/sizeof(int))];
int i;
if(luai_numeq(n,0))
return gnode(t,0);
memcpy(a,&n,sizeof(a));
for(i=1;i<cast_int(sizeof(lua_Number)/sizeof(int));i++)a[0]+=a[i];
return hashmod(t,a[0]);
}
static Node*mainposition(const Table*t,const TValue*key){
switch(ttype(key)){
case 3:
return hashnum(t,nvalue(key));
case 4:
return hashstr(t,rawtsvalue(key));
case 1:
return hashboolean(t,bvalue(key));
case 2:
return hashpointer(t,pvalue(key));
default:
return hashpointer(t,gcvalue(key));
}
}
static int arrayindex(const TValue*key){
if(ttisnumber(key)){
lua_Number n=nvalue(key);
int k;
lua_number2int(k,n);
if(luai_numeq(cast_num(k),n))
return k;
}
return-1;
}
static int findindex(lua_State*L,Table*t,StkId key){
int i;
if(ttisnil(key))return-1;
i=arrayindex(key);
if(0<i&&i<=t->sizearray)
return i-1;
else{
Node*n=mainposition(t,key);
do{
if(luaO_rawequalObj(key2tval(n),key)||
(ttype(gkey(n))==(8+3)&&iscollectable(key)&&
gcvalue(gkey(n))==gcvalue(key))){
i=cast_int(n-gnode(t,0));
return i+t->sizearray;
}
else n=gnext(n);
}while(n);
luaG_runerror(L,"invalid key to "LUA_QL("next"));
return 0;
}
}
static int luaH_next(lua_State*L,Table*t,StkId key){
int i=findindex(L,t,key);
for(i++;i<t->sizearray;i++){
if(!ttisnil(&t->array[i])){
setnvalue(key,cast_num(i+1));
setobj(L,key+1,&t->array[i]);
return 1;
}
}
for(i-=t->sizearray;i<(int)sizenode(t);i++){
if(!ttisnil(gval(gnode(t,i)))){
setobj(L,key,key2tval(gnode(t,i)));
setobj(L,key+1,gval(gnode(t,i)));
return 1;
}
}
return 0;
}
static int computesizes(int nums[],int*narray){
int i;
int twotoi;
int a=0;
int na=0;
int n=0;
for(i=0,twotoi=1;twotoi/2<*narray;i++,twotoi*=2){
if(nums[i]>0){
a+=nums[i];
if(a>twotoi/2){
n=twotoi;
na=a;
}
}
if(a==*narray)break;
}
*narray=n;
return na;
}
static int countint(const TValue*key,int*nums){
int k=arrayindex(key);
if(0<k&&k<=(1<<(32-2))){
nums[ceillog2(k)]++;
return 1;
}
else
return 0;
}
static int numusearray(const Table*t,int*nums){
int lg;
int ttlg;
int ause=0;
int i=1;
for(lg=0,ttlg=1;lg<=(32-2);lg++,ttlg*=2){
int lc=0;
int lim=ttlg;
if(lim>t->sizearray){
lim=t->sizearray;
if(i>lim)
break;
}
for(;i<=lim;i++){
if(!ttisnil(&t->array[i-1]))
lc++;
}
nums[lg]+=lc;
ause+=lc;
}
return ause;
}
static int numusehash(const Table*t,int*nums,int*pnasize){
int totaluse=0;
int ause=0;
int i=sizenode(t);
while(i--){
Node*n=&t->node[i];
if(!ttisnil(gval(n))){
ause+=countint(key2tval(n),nums);
totaluse++;
}
}
*pnasize+=ause;
return totaluse;
}
static void setarrayvector(lua_State*L,Table*t,int size){
int i;
luaM_reallocvector(L,t->array,t->sizearray,size,TValue);
for(i=t->sizearray;i<size;i++)
setnilvalue(&t->array[i]);
t->sizearray=size;
}
static void setnodevector(lua_State*L,Table*t,int size){
int lsize;
if(size==0){
t->node=cast(Node*,(&dummynode_));
lsize=0;
}
else{
int i;
lsize=ceillog2(size);
if(lsize>(32-2))
luaG_runerror(L,"table overflow");
size=twoto(lsize);
t->node=luaM_newvector(L,size,Node);
for(i=0;i<size;i++){
Node*n=gnode(t,i);
gnext(n)=NULL;
setnilvalue(gkey(n));
setnilvalue(gval(n));
}
}
t->lsizenode=cast_byte(lsize);
t->lastfree=gnode(t,size);
}
static void resize(lua_State*L,Table*t,int nasize,int nhsize){
int i;
int oldasize=t->sizearray;
int oldhsize=t->lsizenode;
Node*nold=t->node;
if(nasize>oldasize)
setarrayvector(L,t,nasize);
setnodevector(L,t,nhsize);
if(nasize<oldasize){
t->sizearray=nasize;
for(i=nasize;i<oldasize;i++){
if(!ttisnil(&t->array[i]))
setobj(L,luaH_setnum(L,t,i+1),&t->array[i]);
}
luaM_reallocvector(L,t->array,oldasize,nasize,TValue);
}
for(i=twoto(oldhsize)-1;i>=0;i--){
Node*old=nold+i;
if(!ttisnil(gval(old)))
setobj(L,luaH_set(L,t,key2tval(old)),gval(old));
}
if(nold!=(&dummynode_))
luaM_freearray(L,nold,twoto(oldhsize),Node);
}
static void luaH_resizearray(lua_State*L,Table*t,int nasize){
int nsize=(t->node==(&dummynode_))?0:sizenode(t);
resize(L,t,nasize,nsize);
}
static void rehash(lua_State*L,Table*t,const TValue*ek){
int nasize,na;
int nums[(32-2)+1];
int i;
int totaluse;
for(i=0;i<=(32-2);i++)nums[i]=0;
nasize=numusearray(t,nums);
totaluse=nasize;
totaluse+=numusehash(t,nums,&nasize);
nasize+=countint(ek,nums);
totaluse++;
na=computesizes(nums,&nasize);
resize(L,t,nasize,totaluse-na);
}
static Table*luaH_new(lua_State*L,int narray,int nhash){
Table*t=luaM_new(L,Table);
luaC_link(L,obj2gco(t),5);
t->metatable=NULL;
t->flags=cast_byte(~0);
t->array=NULL;
t->sizearray=0;
t->lsizenode=0;
t->node=cast(Node*,(&dummynode_));
setarrayvector(L,t,narray);
setnodevector(L,t,nhash);
return t;
}
static void luaH_free(lua_State*L,Table*t){
if(t->node!=(&dummynode_))
luaM_freearray(L,t->node,sizenode(t),Node);
luaM_freearray(L,t->array,t->sizearray,TValue);
luaM_free(L,t);
}
static Node*getfreepos(Table*t){
while(t->lastfree-->t->node){
if(ttisnil(gkey(t->lastfree)))
return t->lastfree;
}
return NULL;
}
static TValue*newkey(lua_State*L,Table*t,const TValue*key){
Node*mp=mainposition(t,key);
if(!ttisnil(gval(mp))||mp==(&dummynode_)){
Node*othern;
Node*n=getfreepos(t);
if(n==NULL){
rehash(L,t,key);
return luaH_set(L,t,key);
}
othern=mainposition(t,key2tval(mp));
if(othern!=mp){
while(gnext(othern)!=mp)othern=gnext(othern);
gnext(othern)=n;
*n=*mp;
gnext(mp)=NULL;
setnilvalue(gval(mp));
}
else{
gnext(n)=gnext(mp);
gnext(mp)=n;
mp=n;
}
}
gkey(mp)->value=key->value;gkey(mp)->tt=key->tt;
luaC_barriert(L,t,key);
return gval(mp);
}
static const TValue*luaH_getnum(Table*t,int key){
if(cast(unsigned int,key-1)<cast(unsigned int,t->sizearray))
return&t->array[key-1];
else{
lua_Number nk=cast_num(key);
Node*n=hashnum(t,nk);
do{
if(ttisnumber(gkey(n))&&luai_numeq(nvalue(gkey(n)),nk))
return gval(n);
else n=gnext(n);
}while(n);
return(&luaO_nilobject_);
}
}
static const TValue*luaH_getstr(Table*t,TString*key){
Node*n=hashstr(t,key);
do{
if(ttisstring(gkey(n))&&rawtsvalue(gkey(n))==key)
return gval(n);
else n=gnext(n);
}while(n);
return(&luaO_nilobject_);
}
static const TValue*luaH_get(Table*t,const TValue*key){
switch(ttype(key)){
case 0:return(&luaO_nilobject_);
case 4:return luaH_getstr(t,rawtsvalue(key));
case 3:{
int k;
lua_Number n=nvalue(key);
lua_number2int(k,n);
if(luai_numeq(cast_num(k),nvalue(key)))
return luaH_getnum(t,k);
}
default:{
Node*n=mainposition(t,key);
do{
if(luaO_rawequalObj(key2tval(n),key))
return gval(n);
else n=gnext(n);
}while(n);
return(&luaO_nilobject_);
}
}
}
static TValue*luaH_set(lua_State*L,Table*t,const TValue*key){
const TValue*p=luaH_get(t,key);
t->flags=0;
if(p!=(&luaO_nilobject_))
return cast(TValue*,p);
else{
if(ttisnil(key))luaG_runerror(L,"table index is nil");
else if(ttisnumber(key)&&luai_numisnan(nvalue(key)))
luaG_runerror(L,"table index is NaN");
return newkey(L,t,key);
}
}
static TValue*luaH_setnum(lua_State*L,Table*t,int key){
const TValue*p=luaH_getnum(t,key);
if(p!=(&luaO_nilobject_))
return cast(TValue*,p);
else{
TValue k;
setnvalue(&k,cast_num(key));
return newkey(L,t,&k);
}
}
static TValue*luaH_setstr(lua_State*L,Table*t,TString*key){
const TValue*p=luaH_getstr(t,key);
if(p!=(&luaO_nilobject_))
return cast(TValue*,p);
else{
TValue k;
setsvalue(L,&k,key);
return newkey(L,t,&k);
}
}
static int unbound_search(Table*t,unsigned int j){
unsigned int i=j;
j++;
while(!ttisnil(luaH_getnum(t,j))){
i=j;
j*=2;
if(j>cast(unsigned int,(INT_MAX-2))){
i=1;
while(!ttisnil(luaH_getnum(t,i)))i++;
return i-1;
}
}
while(j-i>1){
unsigned int m=(i+j)/2;
if(ttisnil(luaH_getnum(t,m)))j=m;
else i=m;
}
return i;
}
static int luaH_getn(Table*t){
unsigned int j=t->sizearray;
if(j>0&&ttisnil(&t->array[j-1])){
unsigned int i=0;
while(j-i>1){
unsigned int m=(i+j)/2;
if(ttisnil(&t->array[m-1]))j=m;
else i=m;
}
return i;
}
else if(t->node==(&dummynode_))
return j;
else return unbound_search(t,j);
}
#define makewhite(g,x)((x)->gch.marked=cast_byte(((x)->gch.marked&cast_byte(~(bitmask(2)|bit2mask(0,1))))|luaC_white(g)))
#define white2gray(x)reset2bits((x)->gch.marked,0,1)
#define black2gray(x)resetbit((x)->gch.marked,2)
#define stringmark(s)reset2bits((s)->tsv.marked,0,1)
#define isfinalized(u)testbit((u)->marked,3)
#define markfinalized(u)l_setbit((u)->marked,3)
#define markvalue(g,o){checkconsistency(o);if(iscollectable(o)&&iswhite(gcvalue(o)))reallymarkobject(g,gcvalue(o));}
#define markobject(g,t){if(iswhite(obj2gco(t)))reallymarkobject(g,obj2gco(t));}
#define setthreshold(g)(g->GCthreshold=(g->estimate/100)*g->gcpause)
static void removeentry(Node*n){
if(iscollectable(gkey(n)))
setttype(gkey(n),(8+3));
}
static void reallymarkobject(global_State*g,GCObject*o){
white2gray(o);
switch(o->gch.tt){
case 4:{
return;
}
case 7:{
Table*mt=gco2u(o)->metatable;
gray2black(o);
if(mt)markobject(g,mt);
markobject(g,gco2u(o)->env);
return;
}
case(8+2):{
UpVal*uv=gco2uv(o);
markvalue(g,uv->v);
if(uv->v==&uv->u.value)
gray2black(o);
return;
}
case 6:{
gco2cl(o)->c.gclist=g->gray;
g->gray=o;
break;
}
case 5:{
gco2h(o)->gclist=g->gray;
g->gray=o;
break;
}
case 8:{
gco2th(o)->gclist=g->gray;
g->gray=o;
break;
}
case(8+1):{
gco2p(o)->gclist=g->gray;
g->gray=o;
break;
}
default:;
}
}
static void marktmu(global_State*g){
GCObject*u=g->tmudata;
if(u){
do{
u=u->gch.next;
makewhite(g,u);
reallymarkobject(g,u);
}while(u!=g->tmudata);
}
}
static size_t luaC_separateudata(lua_State*L,int all){
global_State*g=G(L);
size_t deadmem=0;
GCObject**p=&g->mainthread->next;
GCObject*curr;
while((curr=*p)!=NULL){
if(!(iswhite(curr)||all)||isfinalized(gco2u(curr)))
p=&curr->gch.next;
else if(fasttm(L,gco2u(curr)->metatable,TM_GC)==NULL){
markfinalized(gco2u(curr));
p=&curr->gch.next;
}
else{
deadmem+=sizeudata(gco2u(curr));
markfinalized(gco2u(curr));
*p=curr->gch.next;
if(g->tmudata==NULL)
g->tmudata=curr->gch.next=curr;
else{
curr->gch.next=g->tmudata->gch.next;
g->tmudata->gch.next=curr;
g->tmudata=curr;
}
}
}
return deadmem;
}
static int traversetable(global_State*g,Table*h){
int i;
int weakkey=0;
int weakvalue=0;
const TValue*mode;
if(h->metatable)
markobject(g,h->metatable);
mode=gfasttm(g,h->metatable,TM_MODE);
if(mode&&ttisstring(mode)){
weakkey=(strchr(svalue(mode),'k')!=NULL);
weakvalue=(strchr(svalue(mode),'v')!=NULL);
if(weakkey||weakvalue){
h->marked&=~(bitmask(3)|bitmask(4));
h->marked|=cast_byte((weakkey<<3)|
(weakvalue<<4));
h->gclist=g->weak;
g->weak=obj2gco(h);
}
}
if(weakkey&&weakvalue)return 1;
if(!weakvalue){
i=h->sizearray;
while(i--)
markvalue(g,&h->array[i]);
}
i=sizenode(h);
while(i--){
Node*n=gnode(h,i);
if(ttisnil(gval(n)))
removeentry(n);
else{
if(!weakkey)markvalue(g,gkey(n));
if(!weakvalue)markvalue(g,gval(n));
}
}
return weakkey||weakvalue;
}
static void traverseproto(global_State*g,Proto*f){
int i;
if(f->source)stringmark(f->source);
for(i=0;i<f->sizek;i++)
markvalue(g,&f->k[i]);
for(i=0;i<f->sizeupvalues;i++){
if(f->upvalues[i])
stringmark(f->upvalues[i]);
}
for(i=0;i<f->sizep;i++){
if(f->p[i])
markobject(g,f->p[i]);
}
for(i=0;i<f->sizelocvars;i++){
if(f->locvars[i].varname)
stringmark(f->locvars[i].varname);
}
}
static void traverseclosure(global_State*g,Closure*cl){
markobject(g,cl->c.env);
if(cl->c.isC){
int i;
for(i=0;i<cl->c.nupvalues;i++)
markvalue(g,&cl->c.upvalue[i]);
}
else{
int i;
markobject(g,cl->l.p);
for(i=0;i<cl->l.nupvalues;i++)
markobject(g,cl->l.upvals[i]);
}
}
static void checkstacksizes(lua_State*L,StkId max){
int ci_used=cast_int(L->ci-L->base_ci);
int s_used=cast_int(max-L->stack);
if(L->size_ci>20000)
return;
if(4*ci_used<L->size_ci&&2*8<L->size_ci)
luaD_reallocCI(L,L->size_ci/2);
condhardstacktests(luaD_reallocCI(L,ci_used+1));
if(4*s_used<L->stacksize&&
2*((2*20)+5)<L->stacksize)
luaD_reallocstack(L,L->stacksize/2);
condhardstacktests(luaD_reallocstack(L,s_used));
}
static void traversestack(global_State*g,lua_State*l){
StkId o,lim;
CallInfo*ci;
markvalue(g,gt(l));
lim=l->top;
for(ci=l->base_ci;ci<=l->ci;ci++){
if(lim<ci->top)lim=ci->top;
}
for(o=l->stack;o<l->top;o++)
markvalue(g,o);
for(;o<=lim;o++)
setnilvalue(o);
checkstacksizes(l,lim);
}
static l_mem propagatemark(global_State*g){
GCObject*o=g->gray;
gray2black(o);
switch(o->gch.tt){
case 5:{
Table*h=gco2h(o);
g->gray=h->gclist;
if(traversetable(g,h))
black2gray(o);
return sizeof(Table)+sizeof(TValue)*h->sizearray+
sizeof(Node)*sizenode(h);
}
case 6:{
Closure*cl=gco2cl(o);
g->gray=cl->c.gclist;
traverseclosure(g,cl);
return(cl->c.isC)?sizeCclosure(cl->c.nupvalues):
sizeLclosure(cl->l.nupvalues);
}
case 8:{
lua_State*th=gco2th(o);
g->gray=th->gclist;
th->gclist=g->grayagain;
g->grayagain=o;
black2gray(o);
traversestack(g,th);
return sizeof(lua_State)+sizeof(TValue)*th->stacksize+
sizeof(CallInfo)*th->size_ci;
}
case(8+1):{
Proto*p=gco2p(o);
g->gray=p->gclist;
traverseproto(g,p);
return sizeof(Proto)+sizeof(Instruction)*p->sizecode+
sizeof(Proto*)*p->sizep+
sizeof(TValue)*p->sizek+
sizeof(int)*p->sizelineinfo+
sizeof(LocVar)*p->sizelocvars+
sizeof(TString*)*p->sizeupvalues;
}
default:return 0;
}
}
static size_t propagateall(global_State*g){
size_t m=0;
while(g->gray)m+=propagatemark(g);
return m;
}
static int iscleared(const TValue*o,int iskey){
if(!iscollectable(o))return 0;
if(ttisstring(o)){
stringmark(rawtsvalue(o));
return 0;
}
return iswhite(gcvalue(o))||
(ttisuserdata(o)&&(!iskey&&isfinalized(uvalue(o))));
}
static void cleartable(GCObject*l){
while(l){
Table*h=gco2h(l);
int i=h->sizearray;
if(testbit(h->marked,4)){
while(i--){
TValue*o=&h->array[i];
if(iscleared(o,0))
setnilvalue(o);
}
}
i=sizenode(h);
while(i--){
Node*n=gnode(h,i);
if(!ttisnil(gval(n))&&
(iscleared(key2tval(n),1)||iscleared(gval(n),0))){
setnilvalue(gval(n));
removeentry(n);
}
}
l=h->gclist;
}
}
static void freeobj(lua_State*L,GCObject*o){
switch(o->gch.tt){
case(8+1):luaF_freeproto(L,gco2p(o));break;
case 6:luaF_freeclosure(L,gco2cl(o));break;
case(8+2):luaF_freeupval(L,gco2uv(o));break;
case 5:luaH_free(L,gco2h(o));break;
case 8:{
luaE_freethread(L,gco2th(o));
break;
}
case 4:{
G(L)->strt.nuse--;
luaM_freemem(L,o,sizestring(gco2ts(o)));
break;
}
case 7:{
luaM_freemem(L,o,sizeudata(gco2u(o)));
break;
}
default:;
}
}
#define sweepwholelist(L,p)sweeplist(L,p,((lu_mem)(~(lu_mem)0)-2))
static GCObject**sweeplist(lua_State*L,GCObject**p,lu_mem count){
GCObject*curr;
global_State*g=G(L);
int deadmask=otherwhite(g);
while((curr=*p)!=NULL&&count-->0){
if(curr->gch.tt==8)
sweepwholelist(L,&gco2th(curr)->openupval);
if((curr->gch.marked^bit2mask(0,1))&deadmask){
makewhite(g,curr);
p=&curr->gch.next;
}
else{
*p=curr->gch.next;
if(curr==g->rootgc)
g->rootgc=curr->gch.next;
freeobj(L,curr);
}
}
return p;
}
static void checkSizes(lua_State*L){
global_State*g=G(L);
if(g->strt.nuse<cast(lu_int32,g->strt.size/4)&&
g->strt.size>32*2)
luaS_resize(L,g->strt.size/2);
if(luaZ_sizebuffer(&g->buff)>32*2){
size_t newsize=luaZ_sizebuffer(&g->buff)/2;
luaZ_resizebuffer(L,&g->buff,newsize);
}
}
static void GCTM(lua_State*L){
global_State*g=G(L);
GCObject*o=g->tmudata->gch.next;
Udata*udata=rawgco2u(o);
const TValue*tm;
if(o==g->tmudata)
g->tmudata=NULL;
else
g->tmudata->gch.next=udata->uv.next;
udata->uv.next=g->mainthread->next;
g->mainthread->next=o;
makewhite(g,o);
tm=fasttm(L,udata->uv.metatable,TM_GC);
if(tm!=NULL){
lu_byte oldah=L->allowhook;
lu_mem oldt=g->GCthreshold;
L->allowhook=0;
g->GCthreshold=2*g->totalbytes;
setobj(L,L->top,tm);
setuvalue(L,L->top+1,udata);
L->top+=2;
luaD_call(L,L->top-2,0);
L->allowhook=oldah;
g->GCthreshold=oldt;
}
}
static void luaC_callGCTM(lua_State*L){
while(G(L)->tmudata)
GCTM(L);
}
static void luaC_freeall(lua_State*L){
global_State*g=G(L);
int i;
g->currentwhite=bit2mask(0,1)|bitmask(6);
sweepwholelist(L,&g->rootgc);
for(i=0;i<g->strt.size;i++)
sweepwholelist(L,&g->strt.hash[i]);
}
static void markmt(global_State*g){
int i;
for(i=0;i<(8+1);i++)
if(g->mt[i])markobject(g,g->mt[i]);
}
static void markroot(lua_State*L){
global_State*g=G(L);
g->gray=NULL;
g->grayagain=NULL;
g->weak=NULL;
markobject(g,g->mainthread);
markvalue(g,gt(g->mainthread));
markvalue(g,registry(L));
markmt(g);
g->gcstate=1;
}
static void remarkupvals(global_State*g){
UpVal*uv;
for(uv=g->uvhead.u.l.next;uv!=&g->uvhead;uv=uv->u.l.next){
if(isgray(obj2gco(uv)))
markvalue(g,uv->v);
}
}
static void atomic(lua_State*L){
global_State*g=G(L);
size_t udsize;
remarkupvals(g);
propagateall(g);
g->gray=g->weak;
g->weak=NULL;
markobject(g,L);
markmt(g);
propagateall(g);
g->gray=g->grayagain;
g->grayagain=NULL;
propagateall(g);
udsize=luaC_separateudata(L,0);
marktmu(g);
udsize+=propagateall(g);
cleartable(g->weak);
g->currentwhite=cast_byte(otherwhite(g));
g->sweepstrgc=0;
g->sweepgc=&g->rootgc;
g->gcstate=2;
g->estimate=g->totalbytes-udsize;
}
static l_mem singlestep(lua_State*L){
global_State*g=G(L);
switch(g->gcstate){
case 0:{
markroot(L);
return 0;
}
case 1:{
if(g->gray)
return propagatemark(g);
else{
atomic(L);
return 0;
}
}
case 2:{
lu_mem old=g->totalbytes;
sweepwholelist(L,&g->strt.hash[g->sweepstrgc++]);
if(g->sweepstrgc>=g->strt.size)
g->gcstate=3;
g->estimate-=old-g->totalbytes;
return 10;
}
case 3:{
lu_mem old=g->totalbytes;
g->sweepgc=sweeplist(L,g->sweepgc,40);
if(*g->sweepgc==NULL){
checkSizes(L);
g->gcstate=4;
}
g->estimate-=old-g->totalbytes;
return 40*10;
}
case 4:{
if(g->tmudata){
GCTM(L);
if(g->estimate>100)
g->estimate-=100;
return 100;
}
else{
g->gcstate=0;
g->gcdept=0;
return 0;
}
}
default:return 0;
}
}
static void luaC_step(lua_State*L){
global_State*g=G(L);
l_mem lim=(1024u/100)*g->gcstepmul;
if(lim==0)
lim=(((lu_mem)(~(lu_mem)0)-2)-1)/2;
g->gcdept+=g->totalbytes-g->GCthreshold;
do{
lim-=singlestep(L);
if(g->gcstate==0)
break;
}while(lim>0);
if(g->gcstate!=0){
if(g->gcdept<1024u)
g->GCthreshold=g->totalbytes+1024u;
else{
g->gcdept-=1024u;
g->GCthreshold=g->totalbytes;
}
}
else{
setthreshold(g);
}
}
static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v){
global_State*g=G(L);
if(g->gcstate==1)
reallymarkobject(g,v);
else
makewhite(g,o);
}
static void luaC_barrierback(lua_State*L,Table*t){
global_State*g=G(L);
GCObject*o=obj2gco(t);
black2gray(o);
t->gclist=g->grayagain;
g->grayagain=o;
}
static void luaC_link(lua_State*L,GCObject*o,lu_byte tt){
global_State*g=G(L);
o->gch.next=g->rootgc;
g->rootgc=o;
o->gch.marked=luaC_white(g);
o->gch.tt=tt;
}
static void luaC_linkupval(lua_State*L,UpVal*uv){
global_State*g=G(L);
GCObject*o=obj2gco(uv);
o->gch.next=g->rootgc;
g->rootgc=o;
if(isgray(o)){
if(g->gcstate==1){
gray2black(o);
luaC_barrier(L,uv,uv->v);
}
else{
makewhite(g,o);
}
}
}
typedef union{
lua_Number r;
TString*ts;
}SemInfo;
typedef struct Token{
int token;
SemInfo seminfo;
}Token;
typedef struct LexState{
int current;
int linenumber;
int lastline;
Token t;
Token lookahead;
struct FuncState*fs;
struct lua_State*L;
ZIO*z;
Mbuffer*buff;
TString*source;
char decpoint;
}LexState;
static void luaX_init(lua_State*L);
static void luaX_lexerror(LexState*ls,const char*msg,int token);
#define state_size(x)(sizeof(x)+0)
#define fromstate(l)(cast(lu_byte*,(l))-0)
#define tostate(l)(cast(lua_State*,cast(lu_byte*,l)+0))
typedef struct LG{
lua_State l;
global_State g;
}LG;
static void stack_init(lua_State*L1,lua_State*L){
L1->base_ci=luaM_newvector(L,8,CallInfo);
L1->ci=L1->base_ci;
L1->size_ci=8;
L1->end_ci=L1->base_ci+L1->size_ci-1;
L1->stack=luaM_newvector(L,(2*20)+5,TValue);
L1->stacksize=(2*20)+5;
L1->top=L1->stack;
L1->stack_last=L1->stack+(L1->stacksize-5)-1;
L1->ci->func=L1->top;
setnilvalue(L1->top++);
L1->base=L1->ci->base=L1->top;
L1->ci->top=L1->top+20;
}
static void freestack(lua_State*L,lua_State*L1){
luaM_freearray(L,L1->base_ci,L1->size_ci,CallInfo);
luaM_freearray(L,L1->stack,L1->stacksize,TValue);
}
static void f_luaopen(lua_State*L,void*ud){
global_State*g=G(L);
UNUSED(ud);
stack_init(L,L);
sethvalue(L,gt(L),luaH_new(L,0,2));
sethvalue(L,registry(L),luaH_new(L,0,2));
luaS_resize(L,32);
luaT_init(L);
luaX_init(L);
luaS_fix(luaS_newliteral(L,"not enough memory"));
g->GCthreshold=4*g->totalbytes;
}
static void preinit_state(lua_State*L,global_State*g){
G(L)=g;
L->stack=NULL;
L->stacksize=0;
L->errorJmp=NULL;
L->hook=NULL;
L->hookmask=0;
L->basehookcount=0;
L->allowhook=1;
resethookcount(L);
L->openupval=NULL;
L->size_ci=0;
L->nCcalls=L->baseCcalls=0;
L->status=0;
L->base_ci=L->ci=NULL;
L->savedpc=NULL;
L->errfunc=0;
setnilvalue(gt(L));
}
static void close_state(lua_State*L){
global_State*g=G(L);
luaF_close(L,L->stack);
luaC_freeall(L);
luaM_freearray(L,G(L)->strt.hash,G(L)->strt.size,TString*);
luaZ_freebuffer(L,&g->buff);
freestack(L,L);
(*g->frealloc)(g->ud,fromstate(L),state_size(LG),0);
}
static void luaE_freethread(lua_State*L,lua_State*L1){
luaF_close(L1,L1->stack);
freestack(L,L1);
luaM_freemem(L,fromstate(L1),state_size(lua_State));
}
static lua_State*lua_newstate(lua_Alloc f,void*ud){
int i;
lua_State*L;
global_State*g;
void*l=(*f)(ud,NULL,0,state_size(LG));
if(l==NULL)return NULL;
L=tostate(l);
g=&((LG*)L)->g;
L->next=NULL;
L->tt=8;
g->currentwhite=bit2mask(0,5);
L->marked=luaC_white(g);
set2bits(L->marked,5,6);
preinit_state(L,g);
g->frealloc=f;
g->ud=ud;
g->mainthread=L;
g->uvhead.u.l.prev=&g->uvhead;
g->uvhead.u.l.next=&g->uvhead;
g->GCthreshold=0;
g->strt.size=0;
g->strt.nuse=0;
g->strt.hash=NULL;
setnilvalue(registry(L));
luaZ_initbuffer(L,&g->buff);
g->panic=NULL;
g->gcstate=0;
g->rootgc=obj2gco(L);
g->sweepstrgc=0;
g->sweepgc=&g->rootgc;
g->gray=NULL;
g->grayagain=NULL;
g->weak=NULL;
g->tmudata=NULL;
g->totalbytes=sizeof(LG);
g->gcpause=200;
g->gcstepmul=200;
g->gcdept=0;
for(i=0;i<(8+1);i++)g->mt[i]=NULL;
if(luaD_rawrunprotected(L,f_luaopen,NULL)!=0){
close_state(L);
L=NULL;
}
else
{}
return L;
}
static void callallgcTM(lua_State*L,void*ud){
UNUSED(ud);
luaC_callGCTM(L);
}
static void lua_close(lua_State*L){
L=G(L)->mainthread;
luaF_close(L,L->stack);
luaC_separateudata(L,1);
L->errfunc=0;
do{
L->ci=L->base_ci;
L->base=L->top=L->ci->base;
L->nCcalls=L->baseCcalls=0;
}while(luaD_rawrunprotected(L,callallgcTM,NULL)!=0);
close_state(L);
}
#define getcode(fs,e)((fs)->f->code[(e)->u.s.info])
#define luaK_codeAsBx(fs,o,A,sBx)luaK_codeABx(fs,o,A,(sBx)+(((1<<(9+9))-1)>>1))
#define luaK_setmultret(fs,e)luaK_setreturns(fs,e,(-1))
static int luaK_codeABx(FuncState*fs,OpCode o,int A,unsigned int Bx);
static int luaK_codeABC(FuncState*fs,OpCode o,int A,int B,int C);
static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults);
static void luaK_patchtohere(FuncState*fs,int list);
static void luaK_concat(FuncState*fs,int*l1,int l2);
static int currentpc(lua_State*L,CallInfo*ci){
if(!isLua(ci))return-1;
if(ci==L->ci)
ci->savedpc=L->savedpc;
return pcRel(ci->savedpc,ci_func(ci)->l.p);
}
static int currentline(lua_State*L,CallInfo*ci){
int pc=currentpc(L,ci);
if(pc<0)
return-1;
else
return getline_(ci_func(ci)->l.p,pc);
}
static int lua_getstack(lua_State*L,int level,lua_Debug*ar){
int status;
CallInfo*ci;
for(ci=L->ci;level>0&&ci>L->base_ci;ci--){
level--;
if(f_isLua(ci))
level-=ci->tailcalls;
}
if(level==0&&ci>L->base_ci){
status=1;
ar->i_ci=cast_int(ci-L->base_ci);
}
else if(level<0){
status=1;
ar->i_ci=0;
}
else status=0;
return status;
}
static Proto*getluaproto(CallInfo*ci){
return(isLua(ci)?ci_func(ci)->l.p:NULL);
}
static void funcinfo(lua_Debug*ar,Closure*cl){
if(cl->c.isC){
ar->source="=[C]";
ar->linedefined=-1;
ar->lastlinedefined=-1;
ar->what="C";
}
else{
ar->source=getstr(cl->l.p->source);
ar->linedefined=cl->l.p->linedefined;
ar->lastlinedefined=cl->l.p->lastlinedefined;
ar->what=(ar->linedefined==0)?"main":"Lua";
}
luaO_chunkid(ar->short_src,ar->source,60);
}
static void info_tailcall(lua_Debug*ar){
ar->name=ar->namewhat="";
ar->what="tail";
ar->lastlinedefined=ar->linedefined=ar->currentline=-1;
ar->source="=(tail call)";
luaO_chunkid(ar->short_src,ar->source,60);
ar->nups=0;
}
static void collectvalidlines(lua_State*L,Closure*f){
if(f==NULL||f->c.isC){
setnilvalue(L->top);
}
else{
Table*t=luaH_new(L,0,0);
int*lineinfo=f->l.p->lineinfo;
int i;
for(i=0;i<f->l.p->sizelineinfo;i++)
setbvalue(luaH_setnum(L,t,lineinfo[i]),1);
sethvalue(L,L->top,t);
}
incr_top(L);
}
static int auxgetinfo(lua_State*L,const char*what,lua_Debug*ar,
Closure*f,CallInfo*ci){
int status=1;
if(f==NULL){
info_tailcall(ar);
return status;
}
for(;*what;what++){
switch(*what){
case'S':{
funcinfo(ar,f);
break;
}
case'l':{
ar->currentline=(ci)?currentline(L,ci):-1;
break;
}
case'u':{
ar->nups=f->c.nupvalues;
break;
}
case'n':{
ar->namewhat=(ci)?NULL:NULL;
if(ar->namewhat==NULL){
ar->namewhat="";
ar->name=NULL;
}
break;
}
case'L':
case'f':
break;
default:status=0;
}
}
return status;
}
static int lua_getinfo(lua_State*L,const char*what,lua_Debug*ar){
int status;
Closure*f=NULL;
CallInfo*ci=NULL;
if(*what=='>'){
StkId func=L->top-1;
luai_apicheck(L,ttisfunction(func));
what++;
f=clvalue(func);
L->top--;
}
else if(ar->i_ci!=0){
ci=L->base_ci+ar->i_ci;
f=clvalue(ci->func);
}
status=auxgetinfo(L,what,ar,f,ci);
if(strchr(what,'f')){
if(f==NULL)setnilvalue(L->top);
else setclvalue(L,L->top,f);
incr_top(L);
}
if(strchr(what,'L'))
collectvalidlines(L,f);
return status;
}
static int isinstack(CallInfo*ci,const TValue*o){
StkId p;
for(p=ci->base;p<ci->top;p++)
if(o==p)return 1;
return 0;
}
static void luaG_typeerror(lua_State*L,const TValue*o,const char*op){
const char*name=NULL;
const char*t=luaT_typenames[ttype(o)];
const char*kind=(isinstack(L->ci,o))?
NULL:
NULL;
if(kind)
luaG_runerror(L,"attempt to %s %s "LUA_QL("%s")" (a %s value)",
op,kind,name,t);
else
luaG_runerror(L,"attempt to %s a %s value",op,t);
}
static void luaG_concaterror(lua_State*L,StkId p1,StkId p2){
if(ttisstring(p1)||ttisnumber(p1))p1=p2;
luaG_typeerror(L,p1,"concatenate");
}
static void luaG_aritherror(lua_State*L,const TValue*p1,const TValue*p2){
TValue temp;
if(luaV_tonumber(p1,&temp)==NULL)
p2=p1;
luaG_typeerror(L,p2,"perform arithmetic on");
}
static int luaG_ordererror(lua_State*L,const TValue*p1,const TValue*p2){
const char*t1=luaT_typenames[ttype(p1)];
const char*t2=luaT_typenames[ttype(p2)];
if(t1[2]==t2[2])
luaG_runerror(L,"attempt to compare two %s values",t1);
else
luaG_runerror(L,"attempt to compare %s with %s",t1,t2);
return 0;
}
static void addinfo(lua_State*L,const char*msg){
CallInfo*ci=L->ci;
if(isLua(ci)){
char buff[60];
int line=currentline(L,ci);
luaO_chunkid(buff,getstr(getluaproto(ci)->source),60);
luaO_pushfstring(L,"%s:%d: %s",buff,line,msg);
}
}
static void luaG_errormsg(lua_State*L){
if(L->errfunc!=0){
StkId errfunc=restorestack(L,L->errfunc);
if(!ttisfunction(errfunc))luaD_throw(L,5);
setobj(L,L->top,L->top-1);
setobj(L,L->top-1,errfunc);
incr_top(L);
luaD_call(L,L->top-2,1);
}
luaD_throw(L,2);
}
static void luaG_runerror(lua_State*L,const char*fmt,...){
va_list argp;
va_start(argp,fmt);
addinfo(L,luaO_pushvfstring(L,fmt,argp));
va_end(argp);
luaG_errormsg(L);
}
static int luaZ_fill(ZIO*z){
size_t size;
lua_State*L=z->L;
const char*buff;
buff=z->reader(L,z->data,&size);
if(buff==NULL||size==0)return(-1);
z->n=size-1;
z->p=buff;
return char2int(*(z->p++));
}
static void luaZ_init(lua_State*L,ZIO*z,lua_Reader reader,void*data){
z->L=L;
z->reader=reader;
z->data=data;
z->n=0;
z->p=NULL;
}
static char*luaZ_openspace(lua_State*L,Mbuffer*buff,size_t n){
if(n>buff->buffsize){
if(n<32)n=32;
luaZ_resizebuffer(L,buff,n);
}
return buff->buffer;
}
#define opmode(t,a,b,c,m)(((t)<<7)|((a)<<6)|((b)<<4)|((c)<<2)|(m))
static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)]={
opmode(0,1,OpArgR,OpArgN,iABC)
,opmode(0,1,OpArgK,OpArgN,iABx)
,opmode(0,1,OpArgU,OpArgU,iABC)
,opmode(0,1,OpArgR,OpArgN,iABC)
,opmode(0,1,OpArgU,OpArgN,iABC)
,opmode(0,1,OpArgK,OpArgN,iABx)
,opmode(0,1,OpArgR,OpArgK,iABC)
,opmode(0,0,OpArgK,OpArgN,iABx)
,opmode(0,0,OpArgU,OpArgN,iABC)
,opmode(0,0,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgU,OpArgU,iABC)
,opmode(0,1,OpArgR,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgK,OpArgK,iABC)
,opmode(0,1,OpArgR,OpArgN,iABC)
,opmode(0,1,OpArgR,OpArgN,iABC)
,opmode(0,1,OpArgR,OpArgN,iABC)
,opmode(0,1,OpArgR,OpArgR,iABC)
,opmode(0,0,OpArgR,OpArgN,iAsBx)
,opmode(1,0,OpArgK,OpArgK,iABC)
,opmode(1,0,OpArgK,OpArgK,iABC)
,opmode(1,0,OpArgK,OpArgK,iABC)
,opmode(1,1,OpArgR,OpArgU,iABC)
,opmode(1,1,OpArgR,OpArgU,iABC)
,opmode(0,1,OpArgU,OpArgU,iABC)
,opmode(0,1,OpArgU,OpArgU,iABC)
,opmode(0,0,OpArgU,OpArgN,iABC)
,opmode(0,1,OpArgR,OpArgN,iAsBx)
,opmode(0,1,OpArgR,OpArgN,iAsBx)
,opmode(1,0,OpArgN,OpArgU,iABC)
,opmode(0,0,OpArgU,OpArgU,iABC)
,opmode(0,0,OpArgN,OpArgN,iABC)
,opmode(0,1,OpArgU,OpArgN,iABx)
,opmode(0,1,OpArgU,OpArgN,iABC)
};
#define next(ls)(ls->current=zgetc(ls->z))
#define currIsNewline(ls)(ls->current=='\n'||ls->current=='\r')
static const char*const luaX_tokens[]={
"and","break","do","else","elseif",
"end","false","for","function","if",
"in","local","nil","not","or","repeat",
"return","then","true","until","while",
"..","...","==",">=","<=","~=",
"<number>","<name>","<string>","<eof>",
NULL
};
#define save_and_next(ls)(save(ls,ls->current),next(ls))
static void save(LexState*ls,int c){
Mbuffer*b=ls->buff;
if(b->n+1>b->buffsize){
size_t newsize;
if(b->buffsize>=((size_t)(~(size_t)0)-2)/2)
luaX_lexerror(ls,"lexical element too long",0);
newsize=b->buffsize*2;
luaZ_resizebuffer(ls->L,b,newsize);
}
b->buffer[b->n++]=cast(char,c);
}
static void luaX_init(lua_State*L){
int i;
for(i=0;i<(cast(int,TK_WHILE-257+1));i++){
TString*ts=luaS_new(L,luaX_tokens[i]);
luaS_fix(ts);
ts->tsv.reserved=cast_byte(i+1);
}
}
static const char*luaX_token2str(LexState*ls,int token){
if(token<257){
return(iscntrl(token))?luaO_pushfstring(ls->L,"char(%d)",token):
luaO_pushfstring(ls->L,"%c",token);
}
else
return luaX_tokens[token-257];
}
static const char*txtToken(LexState*ls,int token){
switch(token){
case TK_NAME:
case TK_STRING:
case TK_NUMBER:
save(ls,'\0');
return luaZ_buffer(ls->buff);
default:
return luaX_token2str(ls,token);
}
}
static void luaX_lexerror(LexState*ls,const char*msg,int token){
char buff[80];
luaO_chunkid(buff,getstr(ls->source),80);
msg=luaO_pushfstring(ls->L,"%s:%d: %s",buff,ls->linenumber,msg);
if(token)
luaO_pushfstring(ls->L,"%s near "LUA_QL("%s"),msg,txtToken(ls,token));
luaD_throw(ls->L,3);
}
static void luaX_syntaxerror(LexState*ls,const char*msg){
luaX_lexerror(ls,msg,ls->t.token);
}
static TString*luaX_newstring(LexState*ls,const char*str,size_t l){
lua_State*L=ls->L;
TString*ts=luaS_newlstr(L,str,l);
TValue*o=luaH_setstr(L,ls->fs->h,ts);
if(ttisnil(o)){
setbvalue(o,1);
luaC_checkGC(L);
}
return ts;
}
static void inclinenumber(LexState*ls){
int old=ls->current;
next(ls);
if(currIsNewline(ls)&&ls->current!=old)
next(ls);
if(++ls->linenumber>=(INT_MAX-2))
luaX_syntaxerror(ls,"chunk has too many lines");
}
static void luaX_setinput(lua_State*L,LexState*ls,ZIO*z,TString*source){
ls->decpoint='.';
ls->L=L;
ls->lookahead.token=TK_EOS;
ls->z=z;
ls->fs=NULL;
ls->linenumber=1;
ls->lastline=1;
ls->source=source;
luaZ_resizebuffer(ls->L,ls->buff,32);
next(ls);
}
static int check_next(LexState*ls,const char*set){
if(!strchr(set,ls->current))
return 0;
save_and_next(ls);
return 1;
}
static void buffreplace(LexState*ls,char from,char to){
size_t n=luaZ_bufflen(ls->buff);
char*p=luaZ_buffer(ls->buff);
while(n--)
if(p[n]==from)p[n]=to;
}
static void read_numeral(LexState*ls,SemInfo*seminfo){
do{
save_and_next(ls);
}while(isdigit(ls->current)||ls->current=='.');
if(check_next(ls,"Ee"))
check_next(ls,"+-");
while(isalnum(ls->current)||ls->current=='_')
save_and_next(ls);
save(ls,'\0');
buffreplace(ls,'.',ls->decpoint);
if(!luaO_str2d(luaZ_buffer(ls->buff),&seminfo->r))
luaX_lexerror(ls,"malformed number",TK_NUMBER);
}
static int skip_sep(LexState*ls){
int count=0;
int s=ls->current;
save_and_next(ls);
while(ls->current=='='){
save_and_next(ls);
count++;
}
return(ls->current==s)?count:(-count)-1;
}
static void read_long_string(LexState*ls,SemInfo*seminfo,int sep){
int cont=0;
(void)(cont);
save_and_next(ls);
if(currIsNewline(ls))
inclinenumber(ls);
for(;;){
switch(ls->current){
case(-1):
luaX_lexerror(ls,(seminfo)?"unfinished long string":
"unfinished long comment",TK_EOS);
break;
case']':{
if(skip_sep(ls)==sep){
save_and_next(ls);
goto endloop;
}
break;
}
case'\n':
case'\r':{
save(ls,'\n');
inclinenumber(ls);
if(!seminfo)luaZ_resetbuffer(ls->buff);
break;
}
default:{
if(seminfo)save_and_next(ls);
else next(ls);
}
}
}endloop:
if(seminfo)
seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+(2+sep),
luaZ_bufflen(ls->buff)-2*(2+sep));
}
static void read_string(LexState*ls,int del,SemInfo*seminfo){
save_and_next(ls);
while(ls->current!=del){
switch(ls->current){
case(-1):
luaX_lexerror(ls,"unfinished string",TK_EOS);
continue;
case'\n':
case'\r':
luaX_lexerror(ls,"unfinished string",TK_STRING);
continue;
case'\\':{
int c;
next(ls);
switch(ls->current){
case'a':c='\a';break;
case'b':c='\b';break;
case'f':c='\f';break;
case'n':c='\n';break;
case'r':c='\r';break;
case't':c='\t';break;
case'v':c='\v';break;
case'\n':
case'\r':save(ls,'\n');inclinenumber(ls);continue;
case(-1):continue;
default:{
if(!isdigit(ls->current))
save_and_next(ls);
else{
int i=0;
c=0;
do{
c=10*c+(ls->current-'0');
next(ls);
}while(++i<3&&isdigit(ls->current));
if(c>UCHAR_MAX)
luaX_lexerror(ls,"escape sequence too large",TK_STRING);
save(ls,c);
}
continue;
}
}
save(ls,c);
next(ls);
continue;
}
default:
save_and_next(ls);
}
}
save_and_next(ls);
seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+1,
luaZ_bufflen(ls->buff)-2);
}
static int llex(LexState*ls,SemInfo*seminfo){
luaZ_resetbuffer(ls->buff);
for(;;){
switch(ls->current){
case'\n':
case'\r':{
inclinenumber(ls);
continue;
}
case'-':{
next(ls);
if(ls->current!='-')return'-';
next(ls);
if(ls->current=='['){
int sep=skip_sep(ls);
luaZ_resetbuffer(ls->buff);
if(sep>=0){
read_long_string(ls,NULL,sep);
luaZ_resetbuffer(ls->buff);
continue;
}
}
while(!currIsNewline(ls)&&ls->current!=(-1))
next(ls);
continue;
}
case'[':{
int sep=skip_sep(ls);
if(sep>=0){
read_long_string(ls,seminfo,sep);
return TK_STRING;
}
else if(sep==-1)return'[';
else luaX_lexerror(ls,"invalid long string delimiter",TK_STRING);
}
case'=':{
next(ls);
if(ls->current!='=')return'=';
else{next(ls);return TK_EQ;}
}
case'<':{
next(ls);
if(ls->current!='=')return'<';
else{next(ls);return TK_LE;}
}
case'>':{
next(ls);
if(ls->current!='=')return'>';
else{next(ls);return TK_GE;}
}
case'~':{
next(ls);
if(ls->current!='=')return'~';
else{next(ls);return TK_NE;}
}
case'"':
case'\'':{
read_string(ls,ls->current,seminfo);
return TK_STRING;
}
case'.':{
save_and_next(ls);
if(check_next(ls,".")){
if(check_next(ls,"."))
return TK_DOTS;
else return TK_CONCAT;
}
else if(!isdigit(ls->current))return'.';
else{
read_numeral(ls,seminfo);
return TK_NUMBER;
}
}
case(-1):{
return TK_EOS;
}
default:{
if(isspace(ls->current)){
next(ls);
continue;
}
else if(isdigit(ls->current)){
read_numeral(ls,seminfo);
return TK_NUMBER;
}
else if(isalpha(ls->current)||ls->current=='_'){
TString*ts;
do{
save_and_next(ls);
}while(isalnum(ls->current)||ls->current=='_');
ts=luaX_newstring(ls,luaZ_buffer(ls->buff),
luaZ_bufflen(ls->buff));
if(ts->tsv.reserved>0)
return ts->tsv.reserved-1+257;
else{
seminfo->ts=ts;
return TK_NAME;
}
}
else{
int c=ls->current;
next(ls);
return c;
}
}
}
}
}
static void luaX_next(LexState*ls){
ls->lastline=ls->linenumber;
if(ls->lookahead.token!=TK_EOS){
ls->t=ls->lookahead;
ls->lookahead.token=TK_EOS;
}
else
ls->t.token=llex(ls,&ls->t.seminfo);
}
static void luaX_lookahead(LexState*ls){
ls->lookahead.token=llex(ls,&ls->lookahead.seminfo);
}
#define hasjumps(e)((e)->t!=(e)->f)
static int isnumeral(expdesc*e){
return(e->k==VKNUM&&e->t==(-1)&&e->f==(-1));
}
static void luaK_nil(FuncState*fs,int from,int n){
Instruction*previous;
if(fs->pc>fs->lasttarget){
if(fs->pc==0){
if(from>=fs->nactvar)
return;
}
else{
previous=&fs->f->code[fs->pc-1];
if(GET_OPCODE(*previous)==OP_LOADNIL){
int pfrom=GETARG_A(*previous);
int pto=GETARG_B(*previous);
if(pfrom<=from&&from<=pto+1){
if(from+n-1>pto)
SETARG_B(*previous,from+n-1);
return;
}
}
}
}
luaK_codeABC(fs,OP_LOADNIL,from,from+n-1,0);
}
static int luaK_jump(FuncState*fs){
int jpc=fs->jpc;
int j;
fs->jpc=(-1);
j=luaK_codeAsBx(fs,OP_JMP,0,(-1));
luaK_concat(fs,&j,jpc);
return j;
}
static void luaK_ret(FuncState*fs,int first,int nret){
luaK_codeABC(fs,OP_RETURN,first,nret+1,0);
}
static int condjump(FuncState*fs,OpCode op,int A,int B,int C){
luaK_codeABC(fs,op,A,B,C);
return luaK_jump(fs);
}
static void fixjump(FuncState*fs,int pc,int dest){
Instruction*jmp=&fs->f->code[pc];
int offset=dest-(pc+1);
if(abs(offset)>(((1<<(9+9))-1)>>1))
luaX_syntaxerror(fs->ls,"control structure too long");
SETARG_sBx(*jmp,offset);
}
static int luaK_getlabel(FuncState*fs){
fs->lasttarget=fs->pc;
return fs->pc;
}
static int getjump(FuncState*fs,int pc){
int offset=GETARG_sBx(fs->f->code[pc]);
if(offset==(-1))
return(-1);
else
return(pc+1)+offset;
}
static Instruction*getjumpcontrol(FuncState*fs,int pc){
Instruction*pi=&fs->f->code[pc];
if(pc>=1&&testTMode(GET_OPCODE(*(pi-1))))
return pi-1;
else
return pi;
}
static int need_value(FuncState*fs,int list){
for(;list!=(-1);list=getjump(fs,list)){
Instruction i=*getjumpcontrol(fs,list);
if(GET_OPCODE(i)!=OP_TESTSET)return 1;
}
return 0;
}
static int patchtestreg(FuncState*fs,int node,int reg){
Instruction*i=getjumpcontrol(fs,node);
if(GET_OPCODE(*i)!=OP_TESTSET)
return 0;
if(reg!=((1<<8)-1)&®!=GETARG_B(*i))
SETARG_A(*i,reg);
else
*i=CREATE_ABC(OP_TEST,GETARG_B(*i),0,GETARG_C(*i));
return 1;
}
static void removevalues(FuncState*fs,int list){
for(;list!=(-1);list=getjump(fs,list))
patchtestreg(fs,list,((1<<8)-1));
}
static void patchlistaux(FuncState*fs,int list,int vtarget,int reg,
int dtarget){
while(list!=(-1)){
int next=getjump(fs,list);
if(patchtestreg(fs,list,reg))
fixjump(fs,list,vtarget);
else
fixjump(fs,list,dtarget);
list=next;
}
}
static void dischargejpc(FuncState*fs){
patchlistaux(fs,fs->jpc,fs->pc,((1<<8)-1),fs->pc);
fs->jpc=(-1);
}
static void luaK_patchlist(FuncState*fs,int list,int target){
if(target==fs->pc)
luaK_patchtohere(fs,list);
else{
patchlistaux(fs,list,target,((1<<8)-1),target);
}
}
static void luaK_patchtohere(FuncState*fs,int list){
luaK_getlabel(fs);
luaK_concat(fs,&fs->jpc,list);
}
static void luaK_concat(FuncState*fs,int*l1,int l2){
if(l2==(-1))return;
else if(*l1==(-1))
*l1=l2;
else{
int list=*l1;
int next;
while((next=getjump(fs,list))!=(-1))
list=next;
fixjump(fs,list,l2);
}
}
static void luaK_checkstack(FuncState*fs,int n){
int newstack=fs->freereg+n;
if(newstack>fs->f->maxstacksize){
if(newstack>=250)
luaX_syntaxerror(fs->ls,"function or expression too complex");
fs->f->maxstacksize=cast_byte(newstack);
}
}
static void luaK_reserveregs(FuncState*fs,int n){
luaK_checkstack(fs,n);
fs->freereg+=n;
}
static void freereg(FuncState*fs,int reg){
if(!ISK(reg)&®>=fs->nactvar){
fs->freereg--;
}
}
static void freeexp(FuncState*fs,expdesc*e){
if(e->k==VNONRELOC)
freereg(fs,e->u.s.info);
}
static int addk(FuncState*fs,TValue*k,TValue*v){
lua_State*L=fs->L;
TValue*idx=luaH_set(L,fs->h,k);
Proto*f=fs->f;
int oldsize=f->sizek;
if(ttisnumber(idx)){
return cast_int(nvalue(idx));
}
else{
setnvalue(idx,cast_num(fs->nk));
luaM_growvector(L,f->k,fs->nk,f->sizek,TValue,
((1<<(9+9))-1),"constant table overflow");
while(oldsize<f->sizek)setnilvalue(&f->k[oldsize++]);
setobj(L,&f->k[fs->nk],v);
luaC_barrier(L,f,v);
return fs->nk++;
}
}
static int luaK_stringK(FuncState*fs,TString*s){
TValue o;
setsvalue(fs->L,&o,s);
return addk(fs,&o,&o);
}
static int luaK_numberK(FuncState*fs,lua_Number r){
TValue o;
setnvalue(&o,r);
return addk(fs,&o,&o);
}
static int boolK(FuncState*fs,int b){
TValue o;
setbvalue(&o,b);
return addk(fs,&o,&o);
}
static int nilK(FuncState*fs){
TValue k,v;
setnilvalue(&v);
sethvalue(fs->L,&k,fs->h);
return addk(fs,&k,&v);
}
static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults){
if(e->k==VCALL){
SETARG_C(getcode(fs,e),nresults+1);
}
else if(e->k==VVARARG){
SETARG_B(getcode(fs,e),nresults+1);
SETARG_A(getcode(fs,e),fs->freereg);
luaK_reserveregs(fs,1);
}
}
static void luaK_setoneret(FuncState*fs,expdesc*e){
if(e->k==VCALL){
e->k=VNONRELOC;
e->u.s.info=GETARG_A(getcode(fs,e));
}
else if(e->k==VVARARG){
SETARG_B(getcode(fs,e),2);
e->k=VRELOCABLE;
}
}
static void luaK_dischargevars(FuncState*fs,expdesc*e){
switch(e->k){
case VLOCAL:{
e->k=VNONRELOC;
break;
}
case VUPVAL:{
e->u.s.info=luaK_codeABC(fs,OP_GETUPVAL,0,e->u.s.info,0);
e->k=VRELOCABLE;
break;
}
case VGLOBAL:{
e->u.s.info=luaK_codeABx(fs,OP_GETGLOBAL,0,e->u.s.info);
e->k=VRELOCABLE;
break;
}
case VINDEXED:{
freereg(fs,e->u.s.aux);
freereg(fs,e->u.s.info);
e->u.s.info=luaK_codeABC(fs,OP_GETTABLE,0,e->u.s.info,e->u.s.aux);
e->k=VRELOCABLE;
break;
}
case VVARARG:
case VCALL:{
luaK_setoneret(fs,e);
break;
}
default:break;
}
}
static int code_label(FuncState*fs,int A,int b,int jump){
luaK_getlabel(fs);
return luaK_codeABC(fs,OP_LOADBOOL,A,b,jump);
}
static void discharge2reg(FuncState*fs,expdesc*e,int reg){
luaK_dischargevars(fs,e);
switch(e->k){
case VNIL:{
luaK_nil(fs,reg,1);
break;
}
case VFALSE:case VTRUE:{
luaK_codeABC(fs,OP_LOADBOOL,reg,e->k==VTRUE,0);
break;
}
case VK:{
luaK_codeABx(fs,OP_LOADK,reg,e->u.s.info);
break;
}
case VKNUM:{
luaK_codeABx(fs,OP_LOADK,reg,luaK_numberK(fs,e->u.nval));
break;
}
case VRELOCABLE:{
Instruction*pc=&getcode(fs,e);
SETARG_A(*pc,reg);
break;
}
case VNONRELOC:{
if(reg!=e->u.s.info)
luaK_codeABC(fs,OP_MOVE,reg,e->u.s.info,0);
break;
}
default:{
return;
}
}
e->u.s.info=reg;
e->k=VNONRELOC;
}
static void discharge2anyreg(FuncState*fs,expdesc*e){
if(e->k!=VNONRELOC){
luaK_reserveregs(fs,1);
discharge2reg(fs,e,fs->freereg-1);
}
}
static void exp2reg(FuncState*fs,expdesc*e,int reg){
discharge2reg(fs,e,reg);
if(e->k==VJMP)
luaK_concat(fs,&e->t,e->u.s.info);
if(hasjumps(e)){
int final;
int p_f=(-1);
int p_t=(-1);
if(need_value(fs,e->t)||need_value(fs,e->f)){
int fj=(e->k==VJMP)?(-1):luaK_jump(fs);
p_f=code_label(fs,reg,0,1);
p_t=code_label(fs,reg,1,0);
luaK_patchtohere(fs,fj);
}
final=luaK_getlabel(fs);
patchlistaux(fs,e->f,final,reg,p_f);
patchlistaux(fs,e->t,final,reg,p_t);
}
e->f=e->t=(-1);
e->u.s.info=reg;
e->k=VNONRELOC;
}
static void luaK_exp2nextreg(FuncState*fs,expdesc*e){
luaK_dischargevars(fs,e);
freeexp(fs,e);
luaK_reserveregs(fs,1);
exp2reg(fs,e,fs->freereg-1);
}
static int luaK_exp2anyreg(FuncState*fs,expdesc*e){
luaK_dischargevars(fs,e);
if(e->k==VNONRELOC){
if(!hasjumps(e))return e->u.s.info;
if(e->u.s.info>=fs->nactvar){
exp2reg(fs,e,e->u.s.info);
return e->u.s.info;
}
}
luaK_exp2nextreg(fs,e);
return e->u.s.info;
}
static void luaK_exp2val(FuncState*fs,expdesc*e){
if(hasjumps(e))
luaK_exp2anyreg(fs,e);
else
luaK_dischargevars(fs,e);
}
static int luaK_exp2RK(FuncState*fs,expdesc*e){
luaK_exp2val(fs,e);
switch(e->k){
case VKNUM:
case VTRUE:
case VFALSE:
case VNIL:{
if(fs->nk<=((1<<(9-1))-1)){
e->u.s.info=(e->k==VNIL)?nilK(fs):
(e->k==VKNUM)?luaK_numberK(fs,e->u.nval):
boolK(fs,(e->k==VTRUE));
e->k=VK;
return RKASK(e->u.s.info);
}
else break;
}
case VK:{
if(e->u.s.info<=((1<<(9-1))-1))
return RKASK(e->u.s.info);
else break;
}
default:break;
}
return luaK_exp2anyreg(fs,e);
}
static void luaK_storevar(FuncState*fs,expdesc*var,expdesc*ex){
switch(var->k){
case VLOCAL:{
freeexp(fs,ex);
exp2reg(fs,ex,var->u.s.info);
return;
}
case VUPVAL:{
int e=luaK_exp2anyreg(fs,ex);
luaK_codeABC(fs,OP_SETUPVAL,e,var->u.s.info,0);
break;
}
case VGLOBAL:{
int e=luaK_exp2anyreg(fs,ex);
luaK_codeABx(fs,OP_SETGLOBAL,e,var->u.s.info);
break;
}
case VINDEXED:{
int e=luaK_exp2RK(fs,ex);
luaK_codeABC(fs,OP_SETTABLE,var->u.s.info,var->u.s.aux,e);
break;
}
default:{
break;
}
}
freeexp(fs,ex);
}
static void luaK_self(FuncState*fs,expdesc*e,expdesc*key){
int func;
luaK_exp2anyreg(fs,e);
freeexp(fs,e);
func=fs->freereg;
luaK_reserveregs(fs,2);
luaK_codeABC(fs,OP_SELF,func,e->u.s.info,luaK_exp2RK(fs,key));
freeexp(fs,key);
e->u.s.info=func;
e->k=VNONRELOC;
}
static void invertjump(FuncState*fs,expdesc*e){
Instruction*pc=getjumpcontrol(fs,e->u.s.info);
SETARG_A(*pc,!(GETARG_A(*pc)));
}
static int jumponcond(FuncState*fs,expdesc*e,int cond){
if(e->k==VRELOCABLE){
Instruction ie=getcode(fs,e);
if(GET_OPCODE(ie)==OP_NOT){
fs->pc--;
return condjump(fs,OP_TEST,GETARG_B(ie),0,!cond);
}
}
discharge2anyreg(fs,e);
freeexp(fs,e);
return condjump(fs,OP_TESTSET,((1<<8)-1),e->u.s.info,cond);
}
static void luaK_goiftrue(FuncState*fs,expdesc*e){
int pc;
luaK_dischargevars(fs,e);
switch(e->k){
case VK:case VKNUM:case VTRUE:{
pc=(-1);
break;
}
case VJMP:{
invertjump(fs,e);
pc=e->u.s.info;
break;
}
default:{
pc=jumponcond(fs,e,0);
break;
}
}
luaK_concat(fs,&e->f,pc);
luaK_patchtohere(fs,e->t);
e->t=(-1);
}
static void luaK_goiffalse(FuncState*fs,expdesc*e){
int pc;
luaK_dischargevars(fs,e);
switch(e->k){
case VNIL:case VFALSE:{
pc=(-1);
break;
}
case VJMP:{
pc=e->u.s.info;
break;
}
default:{
pc=jumponcond(fs,e,1);
break;
}
}
luaK_concat(fs,&e->t,pc);
luaK_patchtohere(fs,e->f);
e->f=(-1);
}
static void codenot(FuncState*fs,expdesc*e){
luaK_dischargevars(fs,e);
switch(e->k){
case VNIL:case VFALSE:{
e->k=VTRUE;
break;
}
case VK:case VKNUM:case VTRUE:{
e->k=VFALSE;
break;
}
case VJMP:{
invertjump(fs,e);
break;
}
case VRELOCABLE:
case VNONRELOC:{
discharge2anyreg(fs,e);
freeexp(fs,e);
e->u.s.info=luaK_codeABC(fs,OP_NOT,0,e->u.s.info,0);
e->k=VRELOCABLE;
break;
}
default:{
break;
}
}
{int temp=e->f;e->f=e->t;e->t=temp;}
removevalues(fs,e->f);
removevalues(fs,e->t);
}
static void luaK_indexed(FuncState*fs,expdesc*t,expdesc*k){
t->u.s.aux=luaK_exp2RK(fs,k);
t->k=VINDEXED;
}
static int constfolding(OpCode op,expdesc*e1,expdesc*e2){
lua_Number v1,v2,r;
if(!isnumeral(e1)||!isnumeral(e2))return 0;
v1=e1->u.nval;
v2=e2->u.nval;
switch(op){
case OP_ADD:r=luai_numadd(v1,v2);break;
case OP_SUB:r=luai_numsub(v1,v2);break;
case OP_MUL:r=luai_nummul(v1,v2);break;
case OP_DIV:
if(v2==0)return 0;
r=luai_numdiv(v1,v2);break;
case OP_MOD:
if(v2==0)return 0;
r=luai_nummod(v1,v2);break;
case OP_POW:r=luai_numpow(v1,v2);break;
case OP_UNM:r=luai_numunm(v1);break;
case OP_LEN:return 0;
default:r=0;break;
}
if(luai_numisnan(r))return 0;
e1->u.nval=r;
return 1;
}
static void codearith(FuncState*fs,OpCode op,expdesc*e1,expdesc*e2){
if(constfolding(op,e1,e2))
return;
else{
int o2=(op!=OP_UNM&&op!=OP_LEN)?luaK_exp2RK(fs,e2):0;
int o1=luaK_exp2RK(fs,e1);
if(o1>o2){
freeexp(fs,e1);
freeexp(fs,e2);
}
else{
freeexp(fs,e2);
freeexp(fs,e1);
}
e1->u.s.info=luaK_codeABC(fs,op,0,o1,o2);
e1->k=VRELOCABLE;
}
}
static void codecomp(FuncState*fs,OpCode op,int cond,expdesc*e1,
expdesc*e2){
int o1=luaK_exp2RK(fs,e1);
int o2=luaK_exp2RK(fs,e2);
freeexp(fs,e2);
freeexp(fs,e1);
if(cond==0&&op!=OP_EQ){
int temp;
temp=o1;o1=o2;o2=temp;
cond=1;
}
e1->u.s.info=condjump(fs,op,cond,o1,o2);
e1->k=VJMP;
}
static void luaK_prefix(FuncState*fs,UnOpr op,expdesc*e){
expdesc e2;
e2.t=e2.f=(-1);e2.k=VKNUM;e2.u.nval=0;
switch(op){
case OPR_MINUS:{
if(!isnumeral(e))
luaK_exp2anyreg(fs,e);
codearith(fs,OP_UNM,e,&e2);
break;
}
case OPR_NOT:codenot(fs,e);break;
case OPR_LEN:{
luaK_exp2anyreg(fs,e);
codearith(fs,OP_LEN,e,&e2);
break;
}
default:;
}
}
static void luaK_infix(FuncState*fs,BinOpr op,expdesc*v){
switch(op){
case OPR_AND:{
luaK_goiftrue(fs,v);
break;
}
case OPR_OR:{
luaK_goiffalse(fs,v);
break;
}
case OPR_CONCAT:{
luaK_exp2nextreg(fs,v);
break;
}
case OPR_ADD:case OPR_SUB:case OPR_MUL:case OPR_DIV:
case OPR_MOD:case OPR_POW:{
if(!isnumeral(v))luaK_exp2RK(fs,v);
break;
}
default:{
luaK_exp2RK(fs,v);
break;
}
}
}
static void luaK_posfix(FuncState*fs,BinOpr op,expdesc*e1,expdesc*e2){
switch(op){
case OPR_AND:{
luaK_dischargevars(fs,e2);
luaK_concat(fs,&e2->f,e1->f);
*e1=*e2;
break;
}
case OPR_OR:{
luaK_dischargevars(fs,e2);
luaK_concat(fs,&e2->t,e1->t);
*e1=*e2;
break;
}
case OPR_CONCAT:{
luaK_exp2val(fs,e2);
if(e2->k==VRELOCABLE&&GET_OPCODE(getcode(fs,e2))==OP_CONCAT){
freeexp(fs,e1);
SETARG_B(getcode(fs,e2),e1->u.s.info);
e1->k=VRELOCABLE;e1->u.s.info=e2->u.s.info;
}
else{
luaK_exp2nextreg(fs,e2);
codearith(fs,OP_CONCAT,e1,e2);
}
break;
}
case OPR_ADD:codearith(fs,OP_ADD,e1,e2);break;
case OPR_SUB:codearith(fs,OP_SUB,e1,e2);break;
case OPR_MUL:codearith(fs,OP_MUL,e1,e2);break;
case OPR_DIV:codearith(fs,OP_DIV,e1,e2);break;
case OPR_MOD:codearith(fs,OP_MOD,e1,e2);break;
case OPR_POW:codearith(fs,OP_POW,e1,e2);break;
case OPR_EQ:codecomp(fs,OP_EQ,1,e1,e2);break;
case OPR_NE:codecomp(fs,OP_EQ,0,e1,e2);break;
case OPR_LT:codecomp(fs,OP_LT,1,e1,e2);break;
case OPR_LE:codecomp(fs,OP_LE,1,e1,e2);break;
case OPR_GT:codecomp(fs,OP_LT,0,e1,e2);break;
case OPR_GE:codecomp(fs,OP_LE,0,e1,e2);break;
default:;
}
}
static void luaK_fixline(FuncState*fs,int line){
fs->f->lineinfo[fs->pc-1]=line;
}
static int luaK_code(FuncState*fs,Instruction i,int line){
Proto*f=fs->f;
dischargejpc(fs);
luaM_growvector(fs->L,f->code,fs->pc,f->sizecode,Instruction,
(INT_MAX-2),"code size overflow");
f->code[fs->pc]=i;
luaM_growvector(fs->L,f->lineinfo,fs->pc,f->sizelineinfo,int,
(INT_MAX-2),"code size overflow");
f->lineinfo[fs->pc]=line;
return fs->pc++;
}
static int luaK_codeABC(FuncState*fs,OpCode o,int a,int b,int c){
return luaK_code(fs,CREATE_ABC(o,a,b,c),fs->ls->lastline);
}
static int luaK_codeABx(FuncState*fs,OpCode o,int a,unsigned int bc){
return luaK_code(fs,CREATE_ABx(o,a,bc),fs->ls->lastline);
}
static void luaK_setlist(FuncState*fs,int base,int nelems,int tostore){
int c=(nelems-1)/50+1;
int b=(tostore==(-1))?0:tostore;
if(c<=((1<<9)-1))
luaK_codeABC(fs,OP_SETLIST,base,b,c);
else{
luaK_codeABC(fs,OP_SETLIST,base,b,0);
luaK_code(fs,cast(Instruction,c),fs->ls->lastline);
}
fs->freereg=base+1;
}
#define hasmultret(k)((k)==VCALL||(k)==VVARARG)
#define getlocvar(fs,i)((fs)->f->locvars[(fs)->actvar[i]])
#define luaY_checklimit(fs,v,l,m)if((v)>(l))errorlimit(fs,l,m)
typedef struct BlockCnt{
struct BlockCnt*previous;
int breaklist;
lu_byte nactvar;
lu_byte upval;
lu_byte isbreakable;
}BlockCnt;
static void chunk(LexState*ls);
static void expr(LexState*ls,expdesc*v);
static void anchor_token(LexState*ls){
if(ls->t.token==TK_NAME||ls->t.token==TK_STRING){
TString*ts=ls->t.seminfo.ts;
luaX_newstring(ls,getstr(ts),ts->tsv.len);
}
}
static void error_expected(LexState*ls,int token){
luaX_syntaxerror(ls,
luaO_pushfstring(ls->L,LUA_QL("%s")" expected",luaX_token2str(ls,token)));
}
static void errorlimit(FuncState*fs,int limit,const char*what){
const char*msg=(fs->f->linedefined==0)?
luaO_pushfstring(fs->L,"main function has more than %d %s",limit,what):
luaO_pushfstring(fs->L,"function at line %d has more than %d %s",
fs->f->linedefined,limit,what);
luaX_lexerror(fs->ls,msg,0);
}
static int testnext(LexState*ls,int c){
if(ls->t.token==c){
luaX_next(ls);
return 1;
}
else return 0;
}
static void check(LexState*ls,int c){
if(ls->t.token!=c)
error_expected(ls,c);
}
static void checknext(LexState*ls,int c){
check(ls,c);
luaX_next(ls);
}
#define check_condition(ls,c,msg){if(!(c))luaX_syntaxerror(ls,msg);}
static void check_match(LexState*ls,int what,int who,int where){
if(!testnext(ls,what)){
if(where==ls->linenumber)
error_expected(ls,what);
else{
luaX_syntaxerror(ls,luaO_pushfstring(ls->L,
LUA_QL("%s")" expected (to close "LUA_QL("%s")" at line %d)",
luaX_token2str(ls,what),luaX_token2str(ls,who),where));
}
}
}
static TString*str_checkname(LexState*ls){
TString*ts;
check(ls,TK_NAME);
ts=ls->t.seminfo.ts;
luaX_next(ls);
return ts;
}
static void init_exp(expdesc*e,expkind k,int i){
e->f=e->t=(-1);
e->k=k;
e->u.s.info=i;
}
static void codestring(LexState*ls,expdesc*e,TString*s){
init_exp(e,VK,luaK_stringK(ls->fs,s));
}
static void checkname(LexState*ls,expdesc*e){
codestring(ls,e,str_checkname(ls));
}
static int registerlocalvar(LexState*ls,TString*varname){
FuncState*fs=ls->fs;
Proto*f=fs->f;
int oldsize=f->sizelocvars;
luaM_growvector(ls->L,f->locvars,fs->nlocvars,f->sizelocvars,
LocVar,SHRT_MAX,"too many local variables");
while(oldsize<f->sizelocvars)f->locvars[oldsize++].varname=NULL;
f->locvars[fs->nlocvars].varname=varname;
luaC_objbarrier(ls->L,f,varname);
return fs->nlocvars++;
}
#define new_localvarliteral(ls,v,n)new_localvar(ls,luaX_newstring(ls,""v,(sizeof(v)/sizeof(char))-1),n)
static void new_localvar(LexState*ls,TString*name,int n){
FuncState*fs=ls->fs;
luaY_checklimit(fs,fs->nactvar+n+1,200,"local variables");
fs->actvar[fs->nactvar+n]=cast(unsigned short,registerlocalvar(ls,name));
}
static void adjustlocalvars(LexState*ls,int nvars){
FuncState*fs=ls->fs;
fs->nactvar=cast_byte(fs->nactvar+nvars);
for(;nvars;nvars--){
getlocvar(fs,fs->nactvar-nvars).startpc=fs->pc;
}
}
static void removevars(LexState*ls,int tolevel){
FuncState*fs=ls->fs;
while(fs->nactvar>tolevel)
getlocvar(fs,--fs->nactvar).endpc=fs->pc;
}
static int indexupvalue(FuncState*fs,TString*name,expdesc*v){
int i;
Proto*f=fs->f;
int oldsize=f->sizeupvalues;
for(i=0;i<f->nups;i++){
if(fs->upvalues[i].k==v->k&&fs->upvalues[i].info==v->u.s.info){
return i;
}
}
luaY_checklimit(fs,f->nups+1,60,"upvalues");
luaM_growvector(fs->L,f->upvalues,f->nups,f->sizeupvalues,
TString*,(INT_MAX-2),"");
while(oldsize<f->sizeupvalues)f->upvalues[oldsize++]=NULL;
f->upvalues[f->nups]=name;
luaC_objbarrier(fs->L,f,name);
fs->upvalues[f->nups].k=cast_byte(v->k);
fs->upvalues[f->nups].info=cast_byte(v->u.s.info);
return f->nups++;
}
static int searchvar(FuncState*fs,TString*n){
int i;
for(i=fs->nactvar-1;i>=0;i--){
if(n==getlocvar(fs,i).varname)
return i;
}
return-1;
}
static void markupval(FuncState*fs,int level){
BlockCnt*bl=fs->bl;
while(bl&&bl->nactvar>level)bl=bl->previous;
if(bl)bl->upval=1;
}
static int singlevaraux(FuncState*fs,TString*n,expdesc*var,int base){
if(fs==NULL){
init_exp(var,VGLOBAL,((1<<8)-1));
return VGLOBAL;
}
else{
int v=searchvar(fs,n);
if(v>=0){
init_exp(var,VLOCAL,v);
if(!base)
markupval(fs,v);
return VLOCAL;
}
else{
if(singlevaraux(fs->prev,n,var,0)==VGLOBAL)
return VGLOBAL;
var->u.s.info=indexupvalue(fs,n,var);
var->k=VUPVAL;
return VUPVAL;
}
}
}
static void singlevar(LexState*ls,expdesc*var){
TString*varname=str_checkname(ls);
FuncState*fs=ls->fs;
if(singlevaraux(fs,varname,var,1)==VGLOBAL)
var->u.s.info=luaK_stringK(fs,varname);
}
static void adjust_assign(LexState*ls,int nvars,int nexps,expdesc*e){
FuncState*fs=ls->fs;
int extra=nvars-nexps;
if(hasmultret(e->k)){
extra++;
if(extra<0)extra=0;
luaK_setreturns(fs,e,extra);
if(extra>1)luaK_reserveregs(fs,extra-1);
}
else{
if(e->k!=VVOID)luaK_exp2nextreg(fs,e);
if(extra>0){
int reg=fs->freereg;
luaK_reserveregs(fs,extra);
luaK_nil(fs,reg,extra);
}
}
}
static void enterlevel(LexState*ls){
if(++ls->L->nCcalls>200)
luaX_lexerror(ls,"chunk has too many syntax levels",0);
}
#define leavelevel(ls)((ls)->L->nCcalls--)
static void enterblock(FuncState*fs,BlockCnt*bl,lu_byte isbreakable){
bl->breaklist=(-1);
bl->isbreakable=isbreakable;
bl->nactvar=fs->nactvar;
bl->upval=0;
bl->previous=fs->bl;
fs->bl=bl;
}
static void leaveblock(FuncState*fs){
BlockCnt*bl=fs->bl;
fs->bl=bl->previous;
removevars(fs->ls,bl->nactvar);
if(bl->upval)
luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0);
fs->freereg=fs->nactvar;
luaK_patchtohere(fs,bl->breaklist);
}
static void pushclosure(LexState*ls,FuncState*func,expdesc*v){
FuncState*fs=ls->fs;
Proto*f=fs->f;
int oldsize=f->sizep;
int i;
luaM_growvector(ls->L,f->p,fs->np,f->sizep,Proto*,
((1<<(9+9))-1),"constant table overflow");
while(oldsize<f->sizep)f->p[oldsize++]=NULL;
f->p[fs->np++]=func->f;
luaC_objbarrier(ls->L,f,func->f);
init_exp(v,VRELOCABLE,luaK_codeABx(fs,OP_CLOSURE,0,fs->np-1));
for(i=0;i<func->f->nups;i++){
OpCode o=(func->upvalues[i].k==VLOCAL)?OP_MOVE:OP_GETUPVAL;
luaK_codeABC(fs,o,0,func->upvalues[i].info,0);
}
}
static void open_func(LexState*ls,FuncState*fs){
lua_State*L=ls->L;
Proto*f=luaF_newproto(L);
fs->f=f;
fs->prev=ls->fs;
fs->ls=ls;
fs->L=L;
ls->fs=fs;
fs->pc=0;
fs->lasttarget=-1;
fs->jpc=(-1);
fs->freereg=0;
fs->nk=0;
fs->np=0;
fs->nlocvars=0;
fs->nactvar=0;
fs->bl=NULL;
f->source=ls->source;
f->maxstacksize=2;
fs->h=luaH_new(L,0,0);
sethvalue(L,L->top,fs->h);
incr_top(L);
setptvalue(L,L->top,f);
incr_top(L);
}
static void close_func(LexState*ls){
lua_State*L=ls->L;
FuncState*fs=ls->fs;
Proto*f=fs->f;
removevars(ls,0);
luaK_ret(fs,0,0);
luaM_reallocvector(L,f->code,f->sizecode,fs->pc,Instruction);
f->sizecode=fs->pc;
luaM_reallocvector(L,f->lineinfo,f->sizelineinfo,fs->pc,int);
f->sizelineinfo=fs->pc;
luaM_reallocvector(L,f->k,f->sizek,fs->nk,TValue);
f->sizek=fs->nk;
luaM_reallocvector(L,f->p,f->sizep,fs->np,Proto*);
f->sizep=fs->np;
luaM_reallocvector(L,f->locvars,f->sizelocvars,fs->nlocvars,LocVar);
f->sizelocvars=fs->nlocvars;
luaM_reallocvector(L,f->upvalues,f->sizeupvalues,f->nups,TString*);
f->sizeupvalues=f->nups;
ls->fs=fs->prev;
if(fs)anchor_token(ls);
L->top-=2;
}
static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff,const char*name){
struct LexState lexstate;
struct FuncState funcstate;
lexstate.buff=buff;
luaX_setinput(L,&lexstate,z,luaS_new(L,name));
open_func(&lexstate,&funcstate);
funcstate.f->is_vararg=2;
luaX_next(&lexstate);
chunk(&lexstate);
check(&lexstate,TK_EOS);
close_func(&lexstate);
return funcstate.f;
}
static void field(LexState*ls,expdesc*v){
FuncState*fs=ls->fs;
expdesc key;
luaK_exp2anyreg(fs,v);
luaX_next(ls);
checkname(ls,&key);
luaK_indexed(fs,v,&key);
}
static void yindex(LexState*ls,expdesc*v){
luaX_next(ls);
expr(ls,v);
luaK_exp2val(ls->fs,v);
checknext(ls,']');
}
struct ConsControl{
expdesc v;
expdesc*t;
int nh;
int na;
int tostore;
};
static void recfield(LexState*ls,struct ConsControl*cc){
FuncState*fs=ls->fs;
int reg=ls->fs->freereg;
expdesc key,val;
int rkkey;
if(ls->t.token==TK_NAME){
luaY_checklimit(fs,cc->nh,(INT_MAX-2),"items in a constructor");
checkname(ls,&key);
}
else
yindex(ls,&key);
cc->nh++;
checknext(ls,'=');
rkkey=luaK_exp2RK(fs,&key);
expr(ls,&val);
luaK_codeABC(fs,OP_SETTABLE,cc->t->u.s.info,rkkey,luaK_exp2RK(fs,&val));
fs->freereg=reg;
}
static void closelistfield(FuncState*fs,struct ConsControl*cc){
if(cc->v.k==VVOID)return;
luaK_exp2nextreg(fs,&cc->v);
cc->v.k=VVOID;
if(cc->tostore==50){
luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore);
cc->tostore=0;
}
}
static void lastlistfield(FuncState*fs,struct ConsControl*cc){
if(cc->tostore==0)return;
if(hasmultret(cc->v.k)){
luaK_setmultret(fs,&cc->v);
luaK_setlist(fs,cc->t->u.s.info,cc->na,(-1));
cc->na--;
}
else{
if(cc->v.k!=VVOID)
luaK_exp2nextreg(fs,&cc->v);
luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore);
}
}
static void listfield(LexState*ls,struct ConsControl*cc){
expr(ls,&cc->v);
luaY_checklimit(ls->fs,cc->na,(INT_MAX-2),"items in a constructor");
cc->na++;
cc->tostore++;
}
static void constructor(LexState*ls,expdesc*t){
FuncState*fs=ls->fs;
int line=ls->linenumber;
int pc=luaK_codeABC(fs,OP_NEWTABLE,0,0,0);
struct ConsControl cc;
cc.na=cc.nh=cc.tostore=0;
cc.t=t;
init_exp(t,VRELOCABLE,pc);
init_exp(&cc.v,VVOID,0);
luaK_exp2nextreg(ls->fs,t);
checknext(ls,'{');
do{
if(ls->t.token=='}')break;
closelistfield(fs,&cc);
switch(ls->t.token){
case TK_NAME:{
luaX_lookahead(ls);
if(ls->lookahead.token!='=')
listfield(ls,&cc);
else
recfield(ls,&cc);
break;
}
case'[':{
recfield(ls,&cc);
break;
}
default:{
listfield(ls,&cc);
break;
}
}
}while(testnext(ls,',')||testnext(ls,';'));
check_match(ls,'}','{',line);
lastlistfield(fs,&cc);
SETARG_B(fs->f->code[pc],luaO_int2fb(cc.na));
SETARG_C(fs->f->code[pc],luaO_int2fb(cc.nh));
}
static void parlist(LexState*ls){
FuncState*fs=ls->fs;
Proto*f=fs->f;
int nparams=0;
f->is_vararg=0;
if(ls->t.token!=')'){
do{
switch(ls->t.token){
case TK_NAME:{
new_localvar(ls,str_checkname(ls),nparams++);
break;
}
case TK_DOTS:{
luaX_next(ls);
f->is_vararg|=2;
break;
}
default:luaX_syntaxerror(ls,"<name> or "LUA_QL("...")" expected");
}
}while(!f->is_vararg&&testnext(ls,','));
}
adjustlocalvars(ls,nparams);
f->numparams=cast_byte(fs->nactvar-(f->is_vararg&1));
luaK_reserveregs(fs,fs->nactvar);
}
static void body(LexState*ls,expdesc*e,int needself,int line){
FuncState new_fs;
open_func(ls,&new_fs);
new_fs.f->linedefined=line;
checknext(ls,'(');
if(needself){
new_localvarliteral(ls,"self",0);
adjustlocalvars(ls,1);
}
parlist(ls);
checknext(ls,')');
chunk(ls);
new_fs.f->lastlinedefined=ls->linenumber;
check_match(ls,TK_END,TK_FUNCTION,line);
close_func(ls);
pushclosure(ls,&new_fs,e);
}
static int explist1(LexState*ls,expdesc*v){
int n=1;
expr(ls,v);
while(testnext(ls,',')){
luaK_exp2nextreg(ls->fs,v);
expr(ls,v);
n++;
}
return n;
}
static void funcargs(LexState*ls,expdesc*f){
FuncState*fs=ls->fs;
expdesc args;
int base,nparams;
int line=ls->linenumber;
switch(ls->t.token){
case'(':{
if(line!=ls->lastline)
luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
luaX_next(ls);
if(ls->t.token==')')
args.k=VVOID;
else{
explist1(ls,&args);
luaK_setmultret(fs,&args);
}
check_match(ls,')','(',line);
break;
}
case'{':{
constructor(ls,&args);
break;
}
case TK_STRING:{
codestring(ls,&args,ls->t.seminfo.ts);
luaX_next(ls);
break;
}
default:{
luaX_syntaxerror(ls,"function arguments expected");
return;
}
}
base=f->u.s.info;
if(hasmultret(args.k))
nparams=(-1);
else{
if(args.k!=VVOID)
luaK_exp2nextreg(fs,&args);
nparams=fs->freereg-(base+1);
}
init_exp(f,VCALL,luaK_codeABC(fs,OP_CALL,base,nparams+1,2));
luaK_fixline(fs,line);
fs->freereg=base+1;
}
static void prefixexp(LexState*ls,expdesc*v){
switch(ls->t.token){
case'(':{
int line=ls->linenumber;
luaX_next(ls);
expr(ls,v);
check_match(ls,')','(',line);
luaK_dischargevars(ls->fs,v);
return;
}
case TK_NAME:{
singlevar(ls,v);
return;
}
default:{
luaX_syntaxerror(ls,"unexpected symbol");
return;
}
}
}
static void primaryexp(LexState*ls,expdesc*v){
FuncState*fs=ls->fs;
prefixexp(ls,v);
for(;;){
switch(ls->t.token){
case'.':{
field(ls,v);
break;
}
case'[':{
expdesc key;
luaK_exp2anyreg(fs,v);
yindex(ls,&key);
luaK_indexed(fs,v,&key);
break;
}
case':':{
expdesc key;
luaX_next(ls);
checkname(ls,&key);
luaK_self(fs,v,&key);
funcargs(ls,v);
break;
}
case'(':case TK_STRING:case'{':{
luaK_exp2nextreg(fs,v);
funcargs(ls,v);
break;
}
default:return;
}
}
}
static void simpleexp(LexState*ls,expdesc*v){
switch(ls->t.token){
case TK_NUMBER:{
init_exp(v,VKNUM,0);
v->u.nval=ls->t.seminfo.r;
break;
}
case TK_STRING:{
codestring(ls,v,ls->t.seminfo.ts);
break;
}
case TK_NIL:{
init_exp(v,VNIL,0);
break;
}
case TK_TRUE:{
init_exp(v,VTRUE,0);
break;
}
case TK_FALSE:{
init_exp(v,VFALSE,0);
break;
}
case TK_DOTS:{
FuncState*fs=ls->fs;
check_condition(ls,fs->f->is_vararg,
"cannot use "LUA_QL("...")" outside a vararg function");
fs->f->is_vararg&=~4;
init_exp(v,VVARARG,luaK_codeABC(fs,OP_VARARG,0,1,0));
break;
}
case'{':{
constructor(ls,v);
return;
}
case TK_FUNCTION:{
luaX_next(ls);
body(ls,v,0,ls->linenumber);
return;
}
default:{
primaryexp(ls,v);
return;
}
}
luaX_next(ls);
}
static UnOpr getunopr(int op){
switch(op){
case TK_NOT:return OPR_NOT;
case'-':return OPR_MINUS;
case'#':return OPR_LEN;
default:return OPR_NOUNOPR;
}
}
static BinOpr getbinopr(int op){
switch(op){
case'+':return OPR_ADD;
case'-':return OPR_SUB;
case'*':return OPR_MUL;
case'/':return OPR_DIV;
case'%':return OPR_MOD;
case'^':return OPR_POW;
case TK_CONCAT:return OPR_CONCAT;
case TK_NE:return OPR_NE;
case TK_EQ:return OPR_EQ;
case'<':return OPR_LT;
case TK_LE:return OPR_LE;
case'>':return OPR_GT;
case TK_GE:return OPR_GE;
case TK_AND:return OPR_AND;
case TK_OR:return OPR_OR;
default:return OPR_NOBINOPR;
}
}
static const struct{
lu_byte left;
lu_byte right;
}priority[]={
{6,6},{6,6},{7,7},{7,7},{7,7},
{10,9},{5,4},
{3,3},{3,3},
{3,3},{3,3},{3,3},{3,3},
{2,2},{1,1}
};
static BinOpr subexpr(LexState*ls,expdesc*v,unsigned int limit){
BinOpr op;
UnOpr uop;
enterlevel(ls);
uop=getunopr(ls->t.token);
if(uop!=OPR_NOUNOPR){
luaX_next(ls);
subexpr(ls,v,8);
luaK_prefix(ls->fs,uop,v);
}
else simpleexp(ls,v);
op=getbinopr(ls->t.token);
while(op!=OPR_NOBINOPR&&priority[op].left>limit){
expdesc v2;
BinOpr nextop;
luaX_next(ls);
luaK_infix(ls->fs,op,v);
nextop=subexpr(ls,&v2,priority[op].right);
luaK_posfix(ls->fs,op,v,&v2);
op=nextop;
}
leavelevel(ls);
return op;
}
static void expr(LexState*ls,expdesc*v){
subexpr(ls,v,0);
}
static int block_follow(int token){
switch(token){
case TK_ELSE:case TK_ELSEIF:case TK_END:
case TK_UNTIL:case TK_EOS:
return 1;
default:return 0;
}
}
static void block(LexState*ls){
FuncState*fs=ls->fs;
BlockCnt bl;
enterblock(fs,&bl,0);
chunk(ls);
leaveblock(fs);
}
struct LHS_assign{
struct LHS_assign*prev;
expdesc v;
};
static void check_conflict(LexState*ls,struct LHS_assign*lh,expdesc*v){
FuncState*fs=ls->fs;
int extra=fs->freereg;
int conflict=0;
for(;lh;lh=lh->prev){
if(lh->v.k==VINDEXED){
if(lh->v.u.s.info==v->u.s.info){
conflict=1;
lh->v.u.s.info=extra;
}
if(lh->v.u.s.aux==v->u.s.info){
conflict=1;
lh->v.u.s.aux=extra;
}
}
}
if(conflict){
luaK_codeABC(fs,OP_MOVE,fs->freereg,v->u.s.info,0);
luaK_reserveregs(fs,1);
}
}
static void assignment(LexState*ls,struct LHS_assign*lh,int nvars){
expdesc e;
check_condition(ls,VLOCAL<=lh->v.k&&lh->v.k<=VINDEXED,
"syntax error");
if(testnext(ls,',')){
struct LHS_assign nv;
nv.prev=lh;
primaryexp(ls,&nv.v);
if(nv.v.k==VLOCAL)
check_conflict(ls,lh,&nv.v);
luaY_checklimit(ls->fs,nvars,200-ls->L->nCcalls,
"variables in assignment");
assignment(ls,&nv,nvars+1);
}
else{
int nexps;
checknext(ls,'=');
nexps=explist1(ls,&e);
if(nexps!=nvars){
adjust_assign(ls,nvars,nexps,&e);
if(nexps>nvars)
ls->fs->freereg-=nexps-nvars;
}
else{
luaK_setoneret(ls->fs,&e);
luaK_storevar(ls->fs,&lh->v,&e);
return;
}
}
init_exp(&e,VNONRELOC,ls->fs->freereg-1);
luaK_storevar(ls->fs,&lh->v,&e);
}
static int cond(LexState*ls){
expdesc v;
expr(ls,&v);
if(v.k==VNIL)v.k=VFALSE;
luaK_goiftrue(ls->fs,&v);
return v.f;
}
static void breakstat(LexState*ls){
FuncState*fs=ls->fs;
BlockCnt*bl=fs->bl;
int upval=0;
while(bl&&!bl->isbreakable){
upval|=bl->upval;
bl=bl->previous;
}
if(!bl)
luaX_syntaxerror(ls,"no loop to break");
if(upval)
luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0);
luaK_concat(fs,&bl->breaklist,luaK_jump(fs));
}
static void whilestat(LexState*ls,int line){
FuncState*fs=ls->fs;
int whileinit;
int condexit;
BlockCnt bl;
luaX_next(ls);
whileinit=luaK_getlabel(fs);
condexit=cond(ls);
enterblock(fs,&bl,1);
checknext(ls,TK_DO);
block(ls);
luaK_patchlist(fs,luaK_jump(fs),whileinit);
check_match(ls,TK_END,TK_WHILE,line);
leaveblock(fs);
luaK_patchtohere(fs,condexit);
}
static void repeatstat(LexState*ls,int line){
int condexit;
FuncState*fs=ls->fs;
int repeat_init=luaK_getlabel(fs);
BlockCnt bl1,bl2;
enterblock(fs,&bl1,1);
enterblock(fs,&bl2,0);
luaX_next(ls);
chunk(ls);
check_match(ls,TK_UNTIL,TK_REPEAT,line);
condexit=cond(ls);
if(!bl2.upval){
leaveblock(fs);
luaK_patchlist(ls->fs,condexit,repeat_init);
}
else{
breakstat(ls);
luaK_patchtohere(ls->fs,condexit);
leaveblock(fs);
luaK_patchlist(ls->fs,luaK_jump(fs),repeat_init);
}
leaveblock(fs);
}
static int exp1(LexState*ls){
expdesc e;
int k;
expr(ls,&e);
k=e.k;
luaK_exp2nextreg(ls->fs,&e);
return k;
}
static void forbody(LexState*ls,int base,int line,int nvars,int isnum){
BlockCnt bl;
FuncState*fs=ls->fs;
int prep,endfor;
adjustlocalvars(ls,3);
checknext(ls,TK_DO);
prep=isnum?luaK_codeAsBx(fs,OP_FORPREP,base,(-1)):luaK_jump(fs);
enterblock(fs,&bl,0);
adjustlocalvars(ls,nvars);
luaK_reserveregs(fs,nvars);
block(ls);
leaveblock(fs);
luaK_patchtohere(fs,prep);
endfor=(isnum)?luaK_codeAsBx(fs,OP_FORLOOP,base,(-1)):
luaK_codeABC(fs,OP_TFORLOOP,base,0,nvars);
luaK_fixline(fs,line);
luaK_patchlist(fs,(isnum?endfor:luaK_jump(fs)),prep+1);
}
static void fornum(LexState*ls,TString*varname,int line){
FuncState*fs=ls->fs;
int base=fs->freereg;
new_localvarliteral(ls,"(for index)",0);
new_localvarliteral(ls,"(for limit)",1);
new_localvarliteral(ls,"(for step)",2);
new_localvar(ls,varname,3);
checknext(ls,'=');
exp1(ls);
checknext(ls,',');
exp1(ls);
if(testnext(ls,','))
exp1(ls);
else{
luaK_codeABx(fs,OP_LOADK,fs->freereg,luaK_numberK(fs,1));
luaK_reserveregs(fs,1);
}
forbody(ls,base,line,1,1);
}
static void forlist(LexState*ls,TString*indexname){
FuncState*fs=ls->fs;
expdesc e;
int nvars=0;
int line;
int base=fs->freereg;
new_localvarliteral(ls,"(for generator)",nvars++);
new_localvarliteral(ls,"(for state)",nvars++);
new_localvarliteral(ls,"(for control)",nvars++);
new_localvar(ls,indexname,nvars++);
while(testnext(ls,','))
new_localvar(ls,str_checkname(ls),nvars++);
checknext(ls,TK_IN);
line=ls->linenumber;
adjust_assign(ls,3,explist1(ls,&e),&e);
luaK_checkstack(fs,3);
forbody(ls,base,line,nvars-3,0);
}
static void forstat(LexState*ls,int line){
FuncState*fs=ls->fs;
TString*varname;
BlockCnt bl;
enterblock(fs,&bl,1);
luaX_next(ls);
varname=str_checkname(ls);
switch(ls->t.token){
case'=':fornum(ls,varname,line);break;
case',':case TK_IN:forlist(ls,varname);break;
default:luaX_syntaxerror(ls,LUA_QL("=")" or "LUA_QL("in")" expected");
}
check_match(ls,TK_END,TK_FOR,line);
leaveblock(fs);
}
static int test_then_block(LexState*ls){
int condexit;
luaX_next(ls);
condexit=cond(ls);
checknext(ls,TK_THEN);
block(ls);
return condexit;
}
static void ifstat(LexState*ls,int line){
FuncState*fs=ls->fs;
int flist;
int escapelist=(-1);
flist=test_then_block(ls);
while(ls->t.token==TK_ELSEIF){
luaK_concat(fs,&escapelist,luaK_jump(fs));
luaK_patchtohere(fs,flist);
flist=test_then_block(ls);
}
if(ls->t.token==TK_ELSE){
luaK_concat(fs,&escapelist,luaK_jump(fs));
luaK_patchtohere(fs,flist);
luaX_next(ls);
block(ls);
}
else
luaK_concat(fs,&escapelist,flist);
luaK_patchtohere(fs,escapelist);
check_match(ls,TK_END,TK_IF,line);
}
static void localfunc(LexState*ls){
expdesc v,b;
FuncState*fs=ls->fs;
new_localvar(ls,str_checkname(ls),0);
init_exp(&v,VLOCAL,fs->freereg);
luaK_reserveregs(fs,1);
adjustlocalvars(ls,1);
body(ls,&b,0,ls->linenumber);
luaK_storevar(fs,&v,&b);
getlocvar(fs,fs->nactvar-1).startpc=fs->pc;
}
static void localstat(LexState*ls){
int nvars=0;
int nexps;
expdesc e;
do{
new_localvar(ls,str_checkname(ls),nvars++);
}while(testnext(ls,','));
if(testnext(ls,'='))
nexps=explist1(ls,&e);
else{
e.k=VVOID;
nexps=0;
}
adjust_assign(ls,nvars,nexps,&e);
adjustlocalvars(ls,nvars);
}
static int funcname(LexState*ls,expdesc*v){
int needself=0;
singlevar(ls,v);
while(ls->t.token=='.')
field(ls,v);
if(ls->t.token==':'){
needself=1;
field(ls,v);
}
return needself;
}
static void funcstat(LexState*ls,int line){
int needself;
expdesc v,b;
luaX_next(ls);
needself=funcname(ls,&v);
body(ls,&b,needself,line);
luaK_storevar(ls->fs,&v,&b);
luaK_fixline(ls->fs,line);
}
static void exprstat(LexState*ls){
FuncState*fs=ls->fs;
struct LHS_assign v;
primaryexp(ls,&v.v);
if(v.v.k==VCALL)
SETARG_C(getcode(fs,&v.v),1);
else{
v.prev=NULL;
assignment(ls,&v,1);
}
}
static void retstat(LexState*ls){
FuncState*fs=ls->fs;
expdesc e;
int first,nret;
luaX_next(ls);
if(block_follow(ls->t.token)||ls->t.token==';')
first=nret=0;
else{
nret=explist1(ls,&e);
if(hasmultret(e.k)){
luaK_setmultret(fs,&e);
if(e.k==VCALL&&nret==1){
SET_OPCODE(getcode(fs,&e),OP_TAILCALL);
}
first=fs->nactvar;
nret=(-1);
}
else{
if(nret==1)
first=luaK_exp2anyreg(fs,&e);
else{
luaK_exp2nextreg(fs,&e);
first=fs->nactvar;
}
}
}
luaK_ret(fs,first,nret);
}
static int statement(LexState*ls){
int line=ls->linenumber;
switch(ls->t.token){
case TK_IF:{
ifstat(ls,line);
return 0;
}
case TK_WHILE:{
whilestat(ls,line);
return 0;
}
case TK_DO:{
luaX_next(ls);
block(ls);
check_match(ls,TK_END,TK_DO,line);
return 0;
}
case TK_FOR:{
forstat(ls,line);
return 0;
}
case TK_REPEAT:{
repeatstat(ls,line);
return 0;
}
case TK_FUNCTION:{
funcstat(ls,line);
return 0;
}
case TK_LOCAL:{
luaX_next(ls);
if(testnext(ls,TK_FUNCTION))
localfunc(ls);
else
localstat(ls);
return 0;
}
case TK_RETURN:{
retstat(ls);
return 1;
}
case TK_BREAK:{
luaX_next(ls);
breakstat(ls);
return 1;
}
default:{
exprstat(ls);
return 0;
}
}
}
static void chunk(LexState*ls){
int islast=0;
enterlevel(ls);
while(!islast&&!block_follow(ls->t.token)){
islast=statement(ls);
testnext(ls,';');
ls->fs->freereg=ls->fs->nactvar;
}
leavelevel(ls);
}
static const TValue*luaV_tonumber(const TValue*obj,TValue*n){
lua_Number num;
if(ttisnumber(obj))return obj;
if(ttisstring(obj)&&luaO_str2d(svalue(obj),&num)){
setnvalue(n,num);
return n;
}
else
return NULL;
}
static int luaV_tostring(lua_State*L,StkId obj){
if(!ttisnumber(obj))
return 0;
else{
char s[32];
lua_Number n=nvalue(obj);
lua_number2str(s,n);
setsvalue(L,obj,luaS_new(L,s));
return 1;
}
}
static void callTMres(lua_State*L,StkId res,const TValue*f,
const TValue*p1,const TValue*p2){
ptrdiff_t result=savestack(L,res);
setobj(L,L->top,f);
setobj(L,L->top+1,p1);
setobj(L,L->top+2,p2);
luaD_checkstack(L,3);
L->top+=3;
luaD_call(L,L->top-3,1);
res=restorestack(L,result);
L->top--;
setobj(L,res,L->top);
}
static void callTM(lua_State*L,const TValue*f,const TValue*p1,
const TValue*p2,const TValue*p3){
setobj(L,L->top,f);
setobj(L,L->top+1,p1);
setobj(L,L->top+2,p2);
setobj(L,L->top+3,p3);
luaD_checkstack(L,4);
L->top+=4;
luaD_call(L,L->top-4,0);
}
static void luaV_gettable(lua_State*L,const TValue*t,TValue*key,StkId val){
int loop;
for(loop=0;loop<100;loop++){
const TValue*tm;
if(ttistable(t)){
Table*h=hvalue(t);
const TValue*res=luaH_get(h,key);
if(!ttisnil(res)||
(tm=fasttm(L,h->metatable,TM_INDEX))==NULL){
setobj(L,val,res);
return;
}
}
else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_INDEX)))
luaG_typeerror(L,t,"index");
if(ttisfunction(tm)){
callTMres(L,val,tm,t,key);
return;
}
t=tm;
}
luaG_runerror(L,"loop in gettable");
}
static void luaV_settable(lua_State*L,const TValue*t,TValue*key,StkId val){
int loop;
TValue temp;
for(loop=0;loop<100;loop++){
const TValue*tm;
if(ttistable(t)){
Table*h=hvalue(t);
TValue*oldval=luaH_set(L,h,key);
if(!ttisnil(oldval)||
(tm=fasttm(L,h->metatable,TM_NEWINDEX))==NULL){
setobj(L,oldval,val);
h->flags=0;
luaC_barriert(L,h,val);
return;
}
}
else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_NEWINDEX)))
luaG_typeerror(L,t,"index");
if(ttisfunction(tm)){
callTM(L,tm,t,key,val);
return;
}
setobj(L,&temp,tm);
t=&temp;
}
luaG_runerror(L,"loop in settable");
}
static int call_binTM(lua_State*L,const TValue*p1,const TValue*p2,
StkId res,TMS event){
const TValue*tm=luaT_gettmbyobj(L,p1,event);
if(ttisnil(tm))
tm=luaT_gettmbyobj(L,p2,event);
if(ttisnil(tm))return 0;
callTMres(L,res,tm,p1,p2);
return 1;
}
static const TValue*get_compTM(lua_State*L,Table*mt1,Table*mt2,
TMS event){
const TValue*tm1=fasttm(L,mt1,event);
const TValue*tm2;
if(tm1==NULL)return NULL;
if(mt1==mt2)return tm1;
tm2=fasttm(L,mt2,event);
if(tm2==NULL)return NULL;
if(luaO_rawequalObj(tm1,tm2))
return tm1;
return NULL;
}
static int call_orderTM(lua_State*L,const TValue*p1,const TValue*p2,
TMS event){
const TValue*tm1=luaT_gettmbyobj(L,p1,event);
const TValue*tm2;
if(ttisnil(tm1))return-1;
tm2=luaT_gettmbyobj(L,p2,event);
if(!luaO_rawequalObj(tm1,tm2))
return-1;
callTMres(L,L->top,tm1,p1,p2);
return!l_isfalse(L->top);
}
static int l_strcmp(const TString*ls,const TString*rs){
const char*l=getstr(ls);
size_t ll=ls->tsv.len;
const char*r=getstr(rs);
size_t lr=rs->tsv.len;
for(;;){
int temp=strcoll(l,r);
if(temp!=0)return temp;
else{
size_t len=strlen(l);
if(len==lr)
return(len==ll)?0:1;
else if(len==ll)
return-1;
len++;
l+=len;ll-=len;r+=len;lr-=len;
}
}
}
static int luaV_lessthan(lua_State*L,const TValue*l,const TValue*r){
int res;
if(ttype(l)!=ttype(r))
return luaG_ordererror(L,l,r);
else if(ttisnumber(l))
return luai_numlt(nvalue(l),nvalue(r));
else if(ttisstring(l))
return l_strcmp(rawtsvalue(l),rawtsvalue(r))<0;
else if((res=call_orderTM(L,l,r,TM_LT))!=-1)
return res;
return luaG_ordererror(L,l,r);
}
static int lessequal(lua_State*L,const TValue*l,const TValue*r){
int res;
if(ttype(l)!=ttype(r))
return luaG_ordererror(L,l,r);
else if(ttisnumber(l))
return luai_numle(nvalue(l),nvalue(r));
else if(ttisstring(l))
return l_strcmp(rawtsvalue(l),rawtsvalue(r))<=0;
else if((res=call_orderTM(L,l,r,TM_LE))!=-1)
return res;
else if((res=call_orderTM(L,r,l,TM_LT))!=-1)
return!res;
return luaG_ordererror(L,l,r);
}
static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2){
const TValue*tm;
switch(ttype(t1)){
case 0:return 1;
case 3:return luai_numeq(nvalue(t1),nvalue(t2));
case 1:return bvalue(t1)==bvalue(t2);
case 2:return pvalue(t1)==pvalue(t2);
case 7:{
if(uvalue(t1)==uvalue(t2))return 1;
tm=get_compTM(L,uvalue(t1)->metatable,uvalue(t2)->metatable,
TM_EQ);
break;
}
case 5:{
if(hvalue(t1)==hvalue(t2))return 1;
tm=get_compTM(L,hvalue(t1)->metatable,hvalue(t2)->metatable,TM_EQ);
break;
}
default:return gcvalue(t1)==gcvalue(t2);
}
if(tm==NULL)return 0;
callTMres(L,L->top,tm,t1,t2);
return!l_isfalse(L->top);
}
static void luaV_concat(lua_State*L,int total,int last){
do{
StkId top=L->base+last+1;
int n=2;
if(!(ttisstring(top-2)||ttisnumber(top-2))||!tostring(L,top-1)){
if(!call_binTM(L,top-2,top-1,top-2,TM_CONCAT))
luaG_concaterror(L,top-2,top-1);
}else if(tsvalue(top-1)->len==0)
(void)tostring(L,top-2);
else{
size_t tl=tsvalue(top-1)->len;
char*buffer;
int i;
for(n=1;n<total&&tostring(L,top-n-1);n++){
size_t l=tsvalue(top-n-1)->len;
if(l>=((size_t)(~(size_t)0)-2)-tl)luaG_runerror(L,"string length overflow");
tl+=l;
}
buffer=luaZ_openspace(L,&G(L)->buff,tl);
tl=0;
for(i=n;i>0;i--){
size_t l=tsvalue(top-i)->len;
memcpy(buffer+tl,svalue(top-i),l);
tl+=l;
}
setsvalue(L,top-n,luaS_newlstr(L,buffer,tl));
}
total-=n-1;
last-=n-1;
}while(total>1);
}
static void Arith(lua_State*L,StkId ra,const TValue*rb,
const TValue*rc,TMS op){
TValue tempb,tempc;
const TValue*b,*c;
if((b=luaV_tonumber(rb,&tempb))!=NULL&&
(c=luaV_tonumber(rc,&tempc))!=NULL){
lua_Number nb=nvalue(b),nc=nvalue(c);
switch(op){
case TM_ADD:setnvalue(ra,luai_numadd(nb,nc));break;
case TM_SUB:setnvalue(ra,luai_numsub(nb,nc));break;
case TM_MUL:setnvalue(ra,luai_nummul(nb,nc));break;
case TM_DIV:setnvalue(ra,luai_numdiv(nb,nc));break;
case TM_MOD:setnvalue(ra,luai_nummod(nb,nc));break;
case TM_POW:setnvalue(ra,luai_numpow(nb,nc));break;
case TM_UNM:setnvalue(ra,luai_numunm(nb));break;
default:break;
}
}
else if(!call_binTM(L,rb,rc,ra,op))
luaG_aritherror(L,rb,rc);
}
#define runtime_check(L,c){if(!(c))break;}
#define RA(i)(base+GETARG_A(i))
#define RB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgR,base+GETARG_B(i))
#define RKB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_B(i))?k+INDEXK(GETARG_B(i)):base+GETARG_B(i))
#define RKC(i)check_exp(getCMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_C(i))?k+INDEXK(GETARG_C(i)):base+GETARG_C(i))
#define KBx(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,k+GETARG_Bx(i))
#define dojump(L,pc,i){(pc)+=(i);}
#define Protect(x){L->savedpc=pc;{x;};base=L->base;}
#define arith_op(op,tm){TValue*rb=RKB(i);TValue*rc=RKC(i);if(ttisnumber(rb)&&ttisnumber(rc)){lua_Number nb=nvalue(rb),nc=nvalue(rc);setnvalue(ra,op(nb,nc));}else Protect(Arith(L,ra,rb,rc,tm));}
static void luaV_execute(lua_State*L,int nexeccalls){
LClosure*cl;
StkId base;
TValue*k;
const Instruction*pc;
reentry:
pc=L->savedpc;
cl=&clvalue(L->ci->func)->l;
base=L->base;
k=cl->p->k;
for(;;){
const Instruction i=*pc++;
StkId ra;
ra=RA(i);
switch(GET_OPCODE(i)){
case OP_MOVE:{
setobj(L,ra,RB(i));
continue;
}
case OP_LOADK:{
setobj(L,ra,KBx(i));
continue;
}
case OP_LOADBOOL:{
setbvalue(ra,GETARG_B(i));
if(GETARG_C(i))pc++;
continue;
}
case OP_LOADNIL:{
TValue*rb=RB(i);
do{
setnilvalue(rb--);
}while(rb>=ra);
continue;
}
case OP_GETUPVAL:{
int b=GETARG_B(i);
setobj(L,ra,cl->upvals[b]->v);
continue;
}
case OP_GETGLOBAL:{
TValue g;
TValue*rb=KBx(i);
sethvalue(L,&g,cl->env);
Protect(luaV_gettable(L,&g,rb,ra));
continue;
}
case OP_GETTABLE:{
Protect(luaV_gettable(L,RB(i),RKC(i),ra));
continue;
}
case OP_SETGLOBAL:{
TValue g;
sethvalue(L,&g,cl->env);
Protect(luaV_settable(L,&g,KBx(i),ra));
continue;
}
case OP_SETUPVAL:{
UpVal*uv=cl->upvals[GETARG_B(i)];
setobj(L,uv->v,ra);
luaC_barrier(L,uv,ra);
continue;
}
case OP_SETTABLE:{
Protect(luaV_settable(L,ra,RKB(i),RKC(i)));
continue;
}
case OP_NEWTABLE:{
int b=GETARG_B(i);
int c=GETARG_C(i);
sethvalue(L,ra,luaH_new(L,luaO_fb2int(b),luaO_fb2int(c)));
Protect(luaC_checkGC(L));
continue;
}
case OP_SELF:{
StkId rb=RB(i);
setobj(L,ra+1,rb);
Protect(luaV_gettable(L,rb,RKC(i),ra));
continue;
}
case OP_ADD:{
arith_op(luai_numadd,TM_ADD);
continue;
}
case OP_SUB:{
arith_op(luai_numsub,TM_SUB);
continue;
}
case OP_MUL:{
arith_op(luai_nummul,TM_MUL);
continue;
}
case OP_DIV:{
arith_op(luai_numdiv,TM_DIV);
continue;
}
case OP_MOD:{
arith_op(luai_nummod,TM_MOD);
continue;
}
case OP_POW:{
arith_op(luai_numpow,TM_POW);
continue;
}
case OP_UNM:{
TValue*rb=RB(i);
if(ttisnumber(rb)){
lua_Number nb=nvalue(rb);
setnvalue(ra,luai_numunm(nb));
}
else{
Protect(Arith(L,ra,rb,rb,TM_UNM));
}
continue;
}
case OP_NOT:{
int res=l_isfalse(RB(i));
setbvalue(ra,res);
continue;
}
case OP_LEN:{
const TValue*rb=RB(i);
switch(ttype(rb)){
case 5:{
setnvalue(ra,cast_num(luaH_getn(hvalue(rb))));
break;
}
case 4:{
setnvalue(ra,cast_num(tsvalue(rb)->len));
break;
}
default:{
Protect(
if(!call_binTM(L,rb,(&luaO_nilobject_),ra,TM_LEN))
luaG_typeerror(L,rb,"get length of");
)
}
}
continue;
}
case OP_CONCAT:{
int b=GETARG_B(i);
int c=GETARG_C(i);
Protect(luaV_concat(L,c-b+1,c);luaC_checkGC(L));
setobj(L,RA(i),base+b);
continue;
}
case OP_JMP:{
dojump(L,pc,GETARG_sBx(i));
continue;
}
case OP_EQ:{
TValue*rb=RKB(i);
TValue*rc=RKC(i);
Protect(
if(equalobj(L,rb,rc)==GETARG_A(i))
dojump(L,pc,GETARG_sBx(*pc));
)
pc++;
continue;
}
case OP_LT:{
Protect(
if(luaV_lessthan(L,RKB(i),RKC(i))==GETARG_A(i))
dojump(L,pc,GETARG_sBx(*pc));
)
pc++;
continue;
}
case OP_LE:{
Protect(
if(lessequal(L,RKB(i),RKC(i))==GETARG_A(i))
dojump(L,pc,GETARG_sBx(*pc));
)
pc++;
continue;
}
case OP_TEST:{
if(l_isfalse(ra)!=GETARG_C(i))
dojump(L,pc,GETARG_sBx(*pc));
pc++;
continue;
}
case OP_TESTSET:{
TValue*rb=RB(i);
if(l_isfalse(rb)!=GETARG_C(i)){
setobj(L,ra,rb);
dojump(L,pc,GETARG_sBx(*pc));
}
pc++;
continue;
}
case OP_CALL:{
int b=GETARG_B(i);
int nresults=GETARG_C(i)-1;
if(b!=0)L->top=ra+b;
L->savedpc=pc;
switch(luaD_precall(L,ra,nresults)){
case 0:{
nexeccalls++;
goto reentry;
}
case 1:{
if(nresults>=0)L->top=L->ci->top;
base=L->base;
continue;
}
default:{
return;
}
}
}
case OP_TAILCALL:{
int b=GETARG_B(i);
if(b!=0)L->top=ra+b;
L->savedpc=pc;
switch(luaD_precall(L,ra,(-1))){
case 0:{
CallInfo*ci=L->ci-1;
int aux;
StkId func=ci->func;
StkId pfunc=(ci+1)->func;
if(L->openupval)luaF_close(L,ci->base);
L->base=ci->base=ci->func+((ci+1)->base-pfunc);
for(aux=0;pfunc+aux<L->top;aux++)
setobj(L,func+aux,pfunc+aux);
ci->top=L->top=func+aux;
ci->savedpc=L->savedpc;
ci->tailcalls++;
L->ci--;
goto reentry;
}
case 1:{
base=L->base;
continue;
}
default:{
return;
}
}
}
case OP_RETURN:{
int b=GETARG_B(i);
if(b!=0)L->top=ra+b-1;
if(L->openupval)luaF_close(L,base);
L->savedpc=pc;
b=luaD_poscall(L,ra);
if(--nexeccalls==0)
return;
else{
if(b)L->top=L->ci->top;
goto reentry;
}
}
case OP_FORLOOP:{
lua_Number step=nvalue(ra+2);
lua_Number idx=luai_numadd(nvalue(ra),step);
lua_Number limit=nvalue(ra+1);
if(luai_numlt(0,step)?luai_numle(idx,limit)
:luai_numle(limit,idx)){
dojump(L,pc,GETARG_sBx(i));
setnvalue(ra,idx);
setnvalue(ra+3,idx);
}
continue;
}
case OP_FORPREP:{
const TValue*init=ra;
const TValue*plimit=ra+1;
const TValue*pstep=ra+2;
L->savedpc=pc;
if(!tonumber(init,ra))
luaG_runerror(L,LUA_QL("for")" initial value must be a number");
else if(!tonumber(plimit,ra+1))
luaG_runerror(L,LUA_QL("for")" limit must be a number");
else if(!tonumber(pstep,ra+2))
luaG_runerror(L,LUA_QL("for")" step must be a number");
setnvalue(ra,luai_numsub(nvalue(ra),nvalue(pstep)));
dojump(L,pc,GETARG_sBx(i));
continue;
}
case OP_TFORLOOP:{
StkId cb=ra+3;
setobj(L,cb+2,ra+2);
setobj(L,cb+1,ra+1);
setobj(L,cb,ra);
L->top=cb+3;
Protect(luaD_call(L,cb,GETARG_C(i)));
L->top=L->ci->top;
cb=RA(i)+3;
if(!ttisnil(cb)){
setobj(L,cb-1,cb);
dojump(L,pc,GETARG_sBx(*pc));
}
pc++;
continue;
}
case OP_SETLIST:{
int n=GETARG_B(i);
int c=GETARG_C(i);
int last;
Table*h;
if(n==0){
n=cast_int(L->top-ra)-1;
L->top=L->ci->top;
}
if(c==0)c=cast_int(*pc++);
runtime_check(L,ttistable(ra));
h=hvalue(ra);
last=((c-1)*50)+n;
if(last>h->sizearray)
luaH_resizearray(L,h,last);
for(;n>0;n--){
TValue*val=ra+n;
setobj(L,luaH_setnum(L,h,last--),val);
luaC_barriert(L,h,val);
}
continue;
}
case OP_CLOSE:{
luaF_close(L,ra);
continue;
}
case OP_CLOSURE:{
Proto*p;
Closure*ncl;
int nup,j;
p=cl->p->p[GETARG_Bx(i)];
nup=p->nups;
ncl=luaF_newLclosure(L,nup,cl->env);
ncl->l.p=p;
for(j=0;j<nup;j++,pc++){
if(GET_OPCODE(*pc)==OP_GETUPVAL)
ncl->l.upvals[j]=cl->upvals[GETARG_B(*pc)];
else{
ncl->l.upvals[j]=luaF_findupval(L,base+GETARG_B(*pc));
}
}
setclvalue(L,ra,ncl);
Protect(luaC_checkGC(L));
continue;
}
case OP_VARARG:{
int b=GETARG_B(i)-1;
int j;
CallInfo*ci=L->ci;
int n=cast_int(ci->base-ci->func)-cl->p->numparams-1;
if(b==(-1)){
Protect(luaD_checkstack(L,n));
ra=RA(i);
b=n;
L->top=ra+n;
}
for(j=0;j<b;j++){
if(j<n){
setobj(L,ra+j,ci->base-n+j);
}
else{
setnilvalue(ra+j);
}
}
continue;
}
}
}
}
#define api_checknelems(L,n)luai_apicheck(L,(n)<=(L->top-L->base))
#define api_checkvalidindex(L,i)luai_apicheck(L,(i)!=(&luaO_nilobject_))
#define api_incr_top(L){luai_apicheck(L,L->top<L->ci->top);L->top++;}
static TValue*index2adr(lua_State*L,int idx){
if(idx>0){
TValue*o=L->base+(idx-1);
luai_apicheck(L,idx<=L->ci->top-L->base);
if(o>=L->top)return cast(TValue*,(&luaO_nilobject_));
else return o;
}
else if(idx>(-10000)){
luai_apicheck(L,idx!=0&&-idx<=L->top-L->base);
return L->top+idx;
}
else switch(idx){
case(-10000):return registry(L);
case(-10001):{
Closure*func=curr_func(L);
sethvalue(L,&L->env,func->c.env);
return&L->env;
}
case(-10002):return gt(L);
default:{
Closure*func=curr_func(L);
idx=(-10002)-idx;
return(idx<=func->c.nupvalues)
?&func->c.upvalue[idx-1]
:cast(TValue*,(&luaO_nilobject_));
}
}
}
static Table*getcurrenv(lua_State*L){
if(L->ci==L->base_ci)
return hvalue(gt(L));
else{
Closure*func=curr_func(L);
return func->c.env;
}
}
static int lua_checkstack(lua_State*L,int size){
int res=1;
if(size>8000||(L->top-L->base+size)>8000)
res=0;
else if(size>0){
luaD_checkstack(L,size);
if(L->ci->top<L->top+size)
L->ci->top=L->top+size;
}
return res;
}
static lua_CFunction lua_atpanic(lua_State*L,lua_CFunction panicf){
lua_CFunction old;
old=G(L)->panic;
G(L)->panic=panicf;
return old;
}
static int lua_gettop(lua_State*L){
return cast_int(L->top-L->base);
}
static void lua_settop(lua_State*L,int idx){
if(idx>=0){
luai_apicheck(L,idx<=L->stack_last-L->base);
while(L->top<L->base+idx)
setnilvalue(L->top++);
L->top=L->base+idx;
}
else{
luai_apicheck(L,-(idx+1)<=(L->top-L->base));
L->top+=idx+1;
}
}
static void lua_remove(lua_State*L,int idx){
StkId p;
p=index2adr(L,idx);
api_checkvalidindex(L,p);
while(++p<L->top)setobj(L,p-1,p);
L->top--;
}
static void lua_insert(lua_State*L,int idx){
StkId p;
StkId q;
p=index2adr(L,idx);
api_checkvalidindex(L,p);
for(q=L->top;q>p;q--)setobj(L,q,q-1);
setobj(L,p,L->top);
}
static void lua_replace(lua_State*L,int idx){
StkId o;
if(idx==(-10001)&&L->ci==L->base_ci)
luaG_runerror(L,"no calling environment");
api_checknelems(L,1);
o=index2adr(L,idx);
api_checkvalidindex(L,o);
if(idx==(-10001)){
Closure*func=curr_func(L);
luai_apicheck(L,ttistable(L->top-1));
func->c.env=hvalue(L->top-1);
luaC_barrier(L,func,L->top-1);
}
else{
setobj(L,o,L->top-1);
if(idx<(-10002))
luaC_barrier(L,curr_func(L),L->top-1);
}
L->top--;
}
static void lua_pushvalue(lua_State*L,int idx){
setobj(L,L->top,index2adr(L,idx));
api_incr_top(L);
}
static int lua_type(lua_State*L,int idx){
StkId o=index2adr(L,idx);
return(o==(&luaO_nilobject_))?(-1):ttype(o);
}
static const char*lua_typename(lua_State*L,int t){
UNUSED(L);
return(t==(-1))?"no value":luaT_typenames[t];
}
static int lua_iscfunction(lua_State*L,int idx){
StkId o=index2adr(L,idx);
return iscfunction(o);
}
static int lua_isnumber(lua_State*L,int idx){
TValue n;
const TValue*o=index2adr(L,idx);
return tonumber(o,&n);
}
static int lua_isstring(lua_State*L,int idx){
int t=lua_type(L,idx);
return(t==4||t==3);
}
static int lua_rawequal(lua_State*L,int index1,int index2){
StkId o1=index2adr(L,index1);
StkId o2=index2adr(L,index2);
return(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0
:luaO_rawequalObj(o1,o2);
}
static int lua_lessthan(lua_State*L,int index1,int index2){
StkId o1,o2;
int i;
o1=index2adr(L,index1);
o2=index2adr(L,index2);
i=(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0
:luaV_lessthan(L,o1,o2);
return i;
}
static lua_Number lua_tonumber(lua_State*L,int idx){
TValue n;
const TValue*o=index2adr(L,idx);
if(tonumber(o,&n))
return nvalue(o);
else
return 0;
}
static lua_Integer lua_tointeger(lua_State*L,int idx){
TValue n;
const TValue*o=index2adr(L,idx);
if(tonumber(o,&n)){
lua_Integer res;
lua_Number num=nvalue(o);
lua_number2integer(res,num);
return res;
}
else
return 0;
}
static int lua_toboolean(lua_State*L,int idx){
const TValue*o=index2adr(L,idx);
return!l_isfalse(o);
}
static const char*lua_tolstring(lua_State*L,int idx,size_t*len){
StkId o=index2adr(L,idx);
if(!ttisstring(o)){
if(!luaV_tostring(L,o)){
if(len!=NULL)*len=0;
return NULL;
}
luaC_checkGC(L);
o=index2adr(L,idx);
}
if(len!=NULL)*len=tsvalue(o)->len;
return svalue(o);
}
static size_t lua_objlen(lua_State*L,int idx){
StkId o=index2adr(L,idx);
switch(ttype(o)){
case 4:return tsvalue(o)->len;
case 7:return uvalue(o)->len;
case 5:return luaH_getn(hvalue(o));
case 3:{
size_t l;
l=(luaV_tostring(L,o)?tsvalue(o)->len:0);
return l;
}
default:return 0;
}
}
static lua_CFunction lua_tocfunction(lua_State*L,int idx){
StkId o=index2adr(L,idx);
return(!iscfunction(o))?NULL:clvalue(o)->c.f;
}
static void*lua_touserdata(lua_State*L,int idx){
StkId o=index2adr(L,idx);
switch(ttype(o)){
case 7:return(rawuvalue(o)+1);
case 2:return pvalue(o);
default:return NULL;
}
}
static void lua_pushnil(lua_State*L){
setnilvalue(L->top);
api_incr_top(L);
}
static void lua_pushnumber(lua_State*L,lua_Number n){
setnvalue(L->top,n);
api_incr_top(L);
}
static void lua_pushinteger(lua_State*L,lua_Integer n){
setnvalue(L->top,cast_num(n));
api_incr_top(L);
}
static void lua_pushlstring(lua_State*L,const char*s,size_t len){
luaC_checkGC(L);
setsvalue(L,L->top,luaS_newlstr(L,s,len));
api_incr_top(L);
}
static void lua_pushstring(lua_State*L,const char*s){
if(s==NULL)
lua_pushnil(L);
else
lua_pushlstring(L,s,strlen(s));
}
static const char*lua_pushvfstring(lua_State*L,const char*fmt,
va_list argp){
const char*ret;
luaC_checkGC(L);
ret=luaO_pushvfstring(L,fmt,argp);
return ret;
}
static const char*lua_pushfstring(lua_State*L,const char*fmt,...){
const char*ret;
va_list argp;
luaC_checkGC(L);
va_start(argp,fmt);
ret=luaO_pushvfstring(L,fmt,argp);
va_end(argp);
return ret;
}
static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n){
Closure*cl;
luaC_checkGC(L);
api_checknelems(L,n);
cl=luaF_newCclosure(L,n,getcurrenv(L));
cl->c.f=fn;
L->top-=n;
while(n--)
setobj(L,&cl->c.upvalue[n],L->top+n);
setclvalue(L,L->top,cl);
api_incr_top(L);
}
static void lua_pushboolean(lua_State*L,int b){
setbvalue(L->top,(b!=0));
api_incr_top(L);
}
static int lua_pushthread(lua_State*L){
setthvalue(L,L->top,L);
api_incr_top(L);
return(G(L)->mainthread==L);
}
static void lua_gettable(lua_State*L,int idx){
StkId t;
t=index2adr(L,idx);
api_checkvalidindex(L,t);
luaV_gettable(L,t,L->top-1,L->top-1);
}
static void lua_getfield(lua_State*L,int idx,const char*k){
StkId t;
TValue key;
t=index2adr(L,idx);
api_checkvalidindex(L,t);
setsvalue(L,&key,luaS_new(L,k));
luaV_gettable(L,t,&key,L->top);
api_incr_top(L);
}
static void lua_rawget(lua_State*L,int idx){
StkId t;
t=index2adr(L,idx);
luai_apicheck(L,ttistable(t));
setobj(L,L->top-1,luaH_get(hvalue(t),L->top-1));
}
static void lua_rawgeti(lua_State*L,int idx,int n){
StkId o;
o=index2adr(L,idx);
luai_apicheck(L,ttistable(o));
setobj(L,L->top,luaH_getnum(hvalue(o),n));
api_incr_top(L);
}
static void lua_createtable(lua_State*L,int narray,int nrec){
luaC_checkGC(L);
sethvalue(L,L->top,luaH_new(L,narray,nrec));
api_incr_top(L);
}
static int lua_getmetatable(lua_State*L,int objindex){
const TValue*obj;
Table*mt=NULL;
int res;
obj=index2adr(L,objindex);
switch(ttype(obj)){
case 5:
mt=hvalue(obj)->metatable;
break;
case 7:
mt=uvalue(obj)->metatable;
break;
default:
mt=G(L)->mt[ttype(obj)];
break;
}
if(mt==NULL)
res=0;
else{
sethvalue(L,L->top,mt);
api_incr_top(L);
res=1;
}
return res;
}
static void lua_getfenv(lua_State*L,int idx){
StkId o;
o=index2adr(L,idx);
api_checkvalidindex(L,o);
switch(ttype(o)){
case 6:
sethvalue(L,L->top,clvalue(o)->c.env);
break;
case 7:
sethvalue(L,L->top,uvalue(o)->env);
break;
case 8:
setobj(L,L->top,gt(thvalue(o)));
break;
default:
setnilvalue(L->top);
break;
}
api_incr_top(L);
}
static void lua_settable(lua_State*L,int idx){
StkId t;
api_checknelems(L,2);
t=index2adr(L,idx);
api_checkvalidindex(L,t);
luaV_settable(L,t,L->top-2,L->top-1);
L->top-=2;
}
static void lua_setfield(lua_State*L,int idx,const char*k){
StkId t;
TValue key;
api_checknelems(L,1);
t=index2adr(L,idx);
api_checkvalidindex(L,t);
setsvalue(L,&key,luaS_new(L,k));
luaV_settable(L,t,&key,L->top-1);
L->top--;
}
static void lua_rawset(lua_State*L,int idx){
StkId t;
api_checknelems(L,2);
t=index2adr(L,idx);
luai_apicheck(L,ttistable(t));
setobj(L,luaH_set(L,hvalue(t),L->top-2),L->top-1);
luaC_barriert(L,hvalue(t),L->top-1);
L->top-=2;
}
static void lua_rawseti(lua_State*L,int idx,int n){
StkId o;
api_checknelems(L,1);
o=index2adr(L,idx);
luai_apicheck(L,ttistable(o));
setobj(L,luaH_setnum(L,hvalue(o),n),L->top-1);
luaC_barriert(L,hvalue(o),L->top-1);
L->top--;
}
static int lua_setmetatable(lua_State*L,int objindex){
TValue*obj;
Table*mt;
api_checknelems(L,1);
obj=index2adr(L,objindex);
api_checkvalidindex(L,obj);
if(ttisnil(L->top-1))
mt=NULL;
else{
luai_apicheck(L,ttistable(L->top-1));
mt=hvalue(L->top-1);
}
switch(ttype(obj)){
case 5:{
hvalue(obj)->metatable=mt;
if(mt)
luaC_objbarriert(L,hvalue(obj),mt);
break;
}
case 7:{
uvalue(obj)->metatable=mt;
if(mt)
luaC_objbarrier(L,rawuvalue(obj),mt);
break;
}
default:{
G(L)->mt[ttype(obj)]=mt;
break;
}
}
L->top--;
return 1;
}
static int lua_setfenv(lua_State*L,int idx){
StkId o;
int res=1;
api_checknelems(L,1);
o=index2adr(L,idx);
api_checkvalidindex(L,o);
luai_apicheck(L,ttistable(L->top-1));
switch(ttype(o)){
case 6:
clvalue(o)->c.env=hvalue(L->top-1);
break;
case 7:
uvalue(o)->env=hvalue(L->top-1);
break;
case 8:
sethvalue(L,gt(thvalue(o)),hvalue(L->top-1));
break;
default:
res=0;
break;
}
if(res)luaC_objbarrier(L,gcvalue(o),hvalue(L->top-1));
L->top--;
return res;
}
#define adjustresults(L,nres){if(nres==(-1)&&L->top>=L->ci->top)L->ci->top=L->top;}
#define checkresults(L,na,nr)luai_apicheck(L,(nr)==(-1)||(L->ci->top-L->top>=(nr)-(na)))
static void lua_call(lua_State*L,int nargs,int nresults){
StkId func;
api_checknelems(L,nargs+1);
checkresults(L,nargs,nresults);
func=L->top-(nargs+1);
luaD_call(L,func,nresults);
adjustresults(L,nresults);
}
struct CallS{
StkId func;
int nresults;
};
static void f_call(lua_State*L,void*ud){
struct CallS*c=cast(struct CallS*,ud);
luaD_call(L,c->func,c->nresults);
}
static int lua_pcall(lua_State*L,int nargs,int nresults,int errfunc){
struct CallS c;
int status;
ptrdiff_t func;
api_checknelems(L,nargs+1);
checkresults(L,nargs,nresults);
if(errfunc==0)
func=0;
else{
StkId o=index2adr(L,errfunc);
api_checkvalidindex(L,o);
func=savestack(L,o);
}
c.func=L->top-(nargs+1);
c.nresults=nresults;
status=luaD_pcall(L,f_call,&c,savestack(L,c.func),func);
adjustresults(L,nresults);
return status;
}
static int lua_load(lua_State*L,lua_Reader reader,void*data,
const char*chunkname){
ZIO z;
int status;
if(!chunkname)chunkname="?";
luaZ_init(L,&z,reader,data);
status=luaD_protectedparser(L,&z,chunkname);
return status;
}
static int lua_error(lua_State*L){
api_checknelems(L,1);
luaG_errormsg(L);
return 0;
}
static int lua_next(lua_State*L,int idx){
StkId t;
int more;
t=index2adr(L,idx);
luai_apicheck(L,ttistable(t));
more=luaH_next(L,hvalue(t),L->top-1);
if(more){
api_incr_top(L);
}
else
L->top-=1;
return more;
}
static void lua_concat(lua_State*L,int n){
api_checknelems(L,n);
if(n>=2){
luaC_checkGC(L);
luaV_concat(L,n,cast_int(L->top-L->base)-1);
L->top-=(n-1);
}
else if(n==0){
setsvalue(L,L->top,luaS_newlstr(L,"",0));
api_incr_top(L);
}
}
static void*lua_newuserdata(lua_State*L,size_t size){
Udata*u;
luaC_checkGC(L);
u=luaS_newudata(L,size,getcurrenv(L));
setuvalue(L,L->top,u);
api_incr_top(L);
return u+1;
}
#define luaL_getn(L,i)((int)lua_objlen(L,i))
#define luaL_setn(L,i,j)((void)0)
typedef struct luaL_Reg{
const char*name;
lua_CFunction func;
}luaL_Reg;
static void luaI_openlib(lua_State*L,const char*libname,
const luaL_Reg*l,int nup);
static int luaL_argerror(lua_State*L,int numarg,const char*extramsg);
static const char* luaL_checklstring(lua_State*L,int numArg,
size_t*l);
static const char* luaL_optlstring(lua_State*L,int numArg,
const char*def,size_t*l);
static lua_Integer luaL_checkinteger(lua_State*L,int numArg);
static lua_Integer luaL_optinteger(lua_State*L,int nArg,
lua_Integer def);
static int luaL_error(lua_State*L,const char*fmt,...);
static const char* luaL_findtable(lua_State*L,int idx,
const char*fname,int szhint);
#define luaL_argcheck(L,cond,numarg,extramsg)((void)((cond)||luaL_argerror(L,(numarg),(extramsg))))
#define luaL_checkstring(L,n)(luaL_checklstring(L,(n),NULL))
#define luaL_optstring(L,n,d)(luaL_optlstring(L,(n),(d),NULL))
#define luaL_checkint(L,n)((int)luaL_checkinteger(L,(n)))
#define luaL_optint(L,n,d)((int)luaL_optinteger(L,(n),(d)))
#define luaL_typename(L,i)lua_typename(L,lua_type(L,(i)))
#define luaL_getmetatable(L,n)(lua_getfield(L,(-10000),(n)))
#define luaL_opt(L,f,n,d)(lua_isnoneornil(L,(n))?(d):f(L,(n)))
typedef struct luaL_Buffer{
char*p;
int lvl;
lua_State*L;
char buffer[BUFSIZ];
}luaL_Buffer;
#define luaL_addchar(B,c)((void)((B)->p<((B)->buffer+BUFSIZ)||luaL_prepbuffer(B)),(*(B)->p++=(char)(c)))
#define luaL_addsize(B,n)((B)->p+=(n))
static char* luaL_prepbuffer(luaL_Buffer*B);
static int luaL_argerror(lua_State*L,int narg,const char*extramsg){
lua_Debug ar;
if(!lua_getstack(L,0,&ar))
return luaL_error(L,"bad argument #%d (%s)",narg,extramsg);
lua_getinfo(L,"n",&ar);
if(strcmp(ar.namewhat,"method")==0){
narg--;
if(narg==0)
return luaL_error(L,"calling "LUA_QL("%s")" on bad self (%s)",
ar.name,extramsg);
}
if(ar.name==NULL)
ar.name="?";
return luaL_error(L,"bad argument #%d to "LUA_QL("%s")" (%s)",
narg,ar.name,extramsg);
}
static int luaL_typerror(lua_State*L,int narg,const char*tname){
const char*msg=lua_pushfstring(L,"%s expected, got %s",
tname,luaL_typename(L,narg));
return luaL_argerror(L,narg,msg);
}
static void tag_error(lua_State*L,int narg,int tag){
luaL_typerror(L,narg,lua_typename(L,tag));
}
static void luaL_where(lua_State*L,int level){
lua_Debug ar;
if(lua_getstack(L,level,&ar)){
lua_getinfo(L,"Sl",&ar);
if(ar.currentline>0){
lua_pushfstring(L,"%s:%d: ",ar.short_src,ar.currentline);
return;
}
}
lua_pushliteral(L,"");
}
static int luaL_error(lua_State*L,const char*fmt,...){
va_list argp;
va_start(argp,fmt);
luaL_where(L,1);
lua_pushvfstring(L,fmt,argp);
va_end(argp);
lua_concat(L,2);
return lua_error(L);
}
static int luaL_newmetatable(lua_State*L,const char*tname){
lua_getfield(L,(-10000),tname);
if(!lua_isnil(L,-1))
return 0;
lua_pop(L,1);
lua_newtable(L);
lua_pushvalue(L,-1);
lua_setfield(L,(-10000),tname);
return 1;
}
static void*luaL_checkudata(lua_State*L,int ud,const char*tname){
void*p=lua_touserdata(L,ud);
if(p!=NULL){
if(lua_getmetatable(L,ud)){
lua_getfield(L,(-10000),tname);
if(lua_rawequal(L,-1,-2)){
lua_pop(L,2);
return p;
}
}
}
luaL_typerror(L,ud,tname);
return NULL;
}
static void luaL_checkstack(lua_State*L,int space,const char*mes){
if(!lua_checkstack(L,space))
luaL_error(L,"stack overflow (%s)",mes);
}
static void luaL_checktype(lua_State*L,int narg,int t){
if(lua_type(L,narg)!=t)
tag_error(L,narg,t);
}
static void luaL_checkany(lua_State*L,int narg){
if(lua_type(L,narg)==(-1))
luaL_argerror(L,narg,"value expected");
}
static const char*luaL_checklstring(lua_State*L,int narg,size_t*len){
const char*s=lua_tolstring(L,narg,len);
if(!s)tag_error(L,narg,4);
return s;
}
static const char*luaL_optlstring(lua_State*L,int narg,
const char*def,size_t*len){
if(lua_isnoneornil(L,narg)){
if(len)
*len=(def?strlen(def):0);
return def;
}
else return luaL_checklstring(L,narg,len);
}
static lua_Number luaL_checknumber(lua_State*L,int narg){
lua_Number d=lua_tonumber(L,narg);
if(d==0&&!lua_isnumber(L,narg))
tag_error(L,narg,3);
return d;
}
static lua_Integer luaL_checkinteger(lua_State*L,int narg){
lua_Integer d=lua_tointeger(L,narg);
if(d==0&&!lua_isnumber(L,narg))
tag_error(L,narg,3);
return d;
}
static lua_Integer luaL_optinteger(lua_State*L,int narg,
lua_Integer def){
return luaL_opt(L,luaL_checkinteger,narg,def);
}
static int luaL_getmetafield(lua_State*L,int obj,const char*event){
if(!lua_getmetatable(L,obj))
return 0;
lua_pushstring(L,event);
lua_rawget(L,-2);
if(lua_isnil(L,-1)){
lua_pop(L,2);
return 0;
}
else{
lua_remove(L,-2);
return 1;
}
}
static void luaL_register(lua_State*L,const char*libname,
const luaL_Reg*l){
luaI_openlib(L,libname,l,0);
}
static int libsize(const luaL_Reg*l){
int size=0;
for(;l->name;l++)size++;
return size;
}
static void luaI_openlib(lua_State*L,const char*libname,
const luaL_Reg*l,int nup){
if(libname){
int size=libsize(l);
luaL_findtable(L,(-10000),"_LOADED",1);
lua_getfield(L,-1,libname);
if(!lua_istable(L,-1)){
lua_pop(L,1);
if(luaL_findtable(L,(-10002),libname,size)!=NULL)
luaL_error(L,"name conflict for module "LUA_QL("%s"),libname);
lua_pushvalue(L,-1);
lua_setfield(L,-3,libname);
}
lua_remove(L,-2);
lua_insert(L,-(nup+1));
}
for(;l->name;l++){
int i;
for(i=0;i<nup;i++)
lua_pushvalue(L,-nup);
lua_pushcclosure(L,l->func,nup);
lua_setfield(L,-(nup+2),l->name);
}
lua_pop(L,nup);
}
static const char*luaL_findtable(lua_State*L,int idx,
const char*fname,int szhint){
const char*e;
lua_pushvalue(L,idx);
do{
e=strchr(fname,'.');
if(e==NULL)e=fname+strlen(fname);
lua_pushlstring(L,fname,e-fname);
lua_rawget(L,-2);
if(lua_isnil(L,-1)){
lua_pop(L,1);
lua_createtable(L,0,(*e=='.'?1:szhint));
lua_pushlstring(L,fname,e-fname);
lua_pushvalue(L,-2);
lua_settable(L,-4);
}
else if(!lua_istable(L,-1)){
lua_pop(L,2);
return fname;
}
lua_remove(L,-2);
fname=e+1;
}while(*e=='.');
return NULL;
}
#define bufflen(B)((B)->p-(B)->buffer)
#define bufffree(B)((size_t)(BUFSIZ-bufflen(B)))
static int emptybuffer(luaL_Buffer*B){
size_t l=bufflen(B);
if(l==0)return 0;
else{
lua_pushlstring(B->L,B->buffer,l);
B->p=B->buffer;
B->lvl++;
return 1;
}
}
static void adjuststack(luaL_Buffer*B){
if(B->lvl>1){
lua_State*L=B->L;
int toget=1;
size_t toplen=lua_strlen(L,-1);
do{
size_t l=lua_strlen(L,-(toget+1));
if(B->lvl-toget+1>=(20/2)||toplen>l){
toplen+=l;
toget++;
}
else break;
}while(toget<B->lvl);
lua_concat(L,toget);
B->lvl=B->lvl-toget+1;
}
}
static char*luaL_prepbuffer(luaL_Buffer*B){
if(emptybuffer(B))
adjuststack(B);
return B->buffer;
}
static void luaL_addlstring(luaL_Buffer*B,const char*s,size_t l){
while(l--)
luaL_addchar(B,*s++);
}
static void luaL_pushresult(luaL_Buffer*B){
emptybuffer(B);
lua_concat(B->L,B->lvl);
B->lvl=1;
}
static void luaL_addvalue(luaL_Buffer*B){
lua_State*L=B->L;
size_t vl;
const char*s=lua_tolstring(L,-1,&vl);
if(vl<=bufffree(B)){
memcpy(B->p,s,vl);
B->p+=vl;
lua_pop(L,1);
}
else{
if(emptybuffer(B))
lua_insert(L,-2);
B->lvl++;
adjuststack(B);
}
}
static void luaL_buffinit(lua_State*L,luaL_Buffer*B){
B->L=L;
B->p=B->buffer;
B->lvl=0;
}
typedef struct LoadF{
int extraline;
FILE*f;
char buff[BUFSIZ];
}LoadF;
static const char*getF(lua_State*L,void*ud,size_t*size){
LoadF*lf=(LoadF*)ud;
(void)L;
if(lf->extraline){
lf->extraline=0;
*size=1;
return"\n";
}
if(feof(lf->f))return NULL;
*size=fread(lf->buff,1,sizeof(lf->buff),lf->f);
return(*size>0)?lf->buff:NULL;
}
static int errfile(lua_State*L,const char*what,int fnameindex){
const char*serr=strerror(errno);
const char*filename=lua_tostring(L,fnameindex)+1;
lua_pushfstring(L,"cannot %s %s: %s",what,filename,serr);
lua_remove(L,fnameindex);
return(5+1);
}
static int luaL_loadfile(lua_State*L,const char*filename){
LoadF lf;
int status,readstatus;
int c;
int fnameindex=lua_gettop(L)+1;
lf.extraline=0;
if(filename==NULL){
lua_pushliteral(L,"=stdin");
lf.f=stdin;
}
else{
lua_pushfstring(L,"@%s",filename);
lf.f=fopen(filename,"r");
if(lf.f==NULL)return errfile(L,"open",fnameindex);
}
c=getc(lf.f);
if(c=='#'){
lf.extraline=1;
while((c=getc(lf.f))!=EOF&&c!='\n');
if(c=='\n')c=getc(lf.f);
}
if(c=="\033Lua"[0]&&filename){
lf.f=freopen(filename,"rb",lf.f);
if(lf.f==NULL)return errfile(L,"reopen",fnameindex);
while((c=getc(lf.f))!=EOF&&c!="\033Lua"[0]);
lf.extraline=0;
}
ungetc(c,lf.f);
status=lua_load(L,getF,&lf,lua_tostring(L,-1));
readstatus=ferror(lf.f);
if(filename)fclose(lf.f);
if(readstatus){
lua_settop(L,fnameindex);
return errfile(L,"read",fnameindex);
}
lua_remove(L,fnameindex);
return status;
}
typedef struct LoadS{
const char*s;
size_t size;
}LoadS;
static const char*getS(lua_State*L,void*ud,size_t*size){
LoadS*ls=(LoadS*)ud;
(void)L;
if(ls->size==0)return NULL;
*size=ls->size;
ls->size=0;
return ls->s;
}
static int luaL_loadbuffer(lua_State*L,const char*buff,size_t size,
const char*name){
LoadS ls;
ls.s=buff;
ls.size=size;
return lua_load(L,getS,&ls,name);
}
static void*l_alloc(void*ud,void*ptr,size_t osize,size_t nsize){
(void)ud;
(void)osize;
if(nsize==0){
free(ptr);
return NULL;
}
else
return realloc(ptr,nsize);
}
static int panic(lua_State*L){
(void)L;
fprintf(stderr,"PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L,-1));
return 0;
}
static lua_State*luaL_newstate(void){
lua_State*L=lua_newstate(l_alloc,NULL);
if(L)lua_atpanic(L,&panic);
return L;
}
static int luaB_tonumber(lua_State*L){
int base=luaL_optint(L,2,10);
if(base==10){
luaL_checkany(L,1);
if(lua_isnumber(L,1)){
lua_pushnumber(L,lua_tonumber(L,1));
return 1;
}
}
else{
const char*s1=luaL_checkstring(L,1);
char*s2;
unsigned long n;
luaL_argcheck(L,2<=base&&base<=36,2,"base out of range");
n=strtoul(s1,&s2,base);
if(s1!=s2){
while(isspace((unsigned char)(*s2)))s2++;
if(*s2=='\0'){
lua_pushnumber(L,(lua_Number)n);
return 1;
}
}
}
lua_pushnil(L);
return 1;
}
static int luaB_error(lua_State*L){
int level=luaL_optint(L,2,1);
lua_settop(L,1);
if(lua_isstring(L,1)&&level>0){
luaL_where(L,level);
lua_pushvalue(L,1);
lua_concat(L,2);
}
return lua_error(L);
}
static int luaB_setmetatable(lua_State*L){
int t=lua_type(L,2);
luaL_checktype(L,1,5);
luaL_argcheck(L,t==0||t==5,2,
"nil or table expected");
if(luaL_getmetafield(L,1,"__metatable"))
luaL_error(L,"cannot change a protected metatable");
lua_settop(L,2);
lua_setmetatable(L,1);
return 1;
}
static void getfunc(lua_State*L,int opt){
if(lua_isfunction(L,1))lua_pushvalue(L,1);
else{
lua_Debug ar;
int level=opt?luaL_optint(L,1,1):luaL_checkint(L,1);
luaL_argcheck(L,level>=0,1,"level must be non-negative");
if(lua_getstack(L,level,&ar)==0)
luaL_argerror(L,1,"invalid level");
lua_getinfo(L,"f",&ar);
if(lua_isnil(L,-1))
luaL_error(L,"no function environment for tail call at level %d",
level);
}
}
static int luaB_setfenv(lua_State*L){
luaL_checktype(L,2,5);
getfunc(L,0);
lua_pushvalue(L,2);
if(lua_isnumber(L,1)&&lua_tonumber(L,1)==0){
lua_pushthread(L);
lua_insert(L,-2);
lua_setfenv(L,-2);
return 0;
}
else if(lua_iscfunction(L,-2)||lua_setfenv(L,-2)==0)
luaL_error(L,
LUA_QL("setfenv")" cannot change environment of given object");
return 1;
}
static int luaB_rawget(lua_State*L){
luaL_checktype(L,1,5);
luaL_checkany(L,2);
lua_settop(L,2);
lua_rawget(L,1);
return 1;
}
static int luaB_type(lua_State*L){
luaL_checkany(L,1);
lua_pushstring(L,luaL_typename(L,1));
return 1;
}
static int luaB_next(lua_State*L){
luaL_checktype(L,1,5);
lua_settop(L,2);
if(lua_next(L,1))
return 2;
else{
lua_pushnil(L);
return 1;
}
}
static int luaB_pairs(lua_State*L){
luaL_checktype(L,1,5);
lua_pushvalue(L,lua_upvalueindex(1));
lua_pushvalue(L,1);
lua_pushnil(L);
return 3;
}
static int ipairsaux(lua_State*L){
int i=luaL_checkint(L,2);
luaL_checktype(L,1,5);
i++;
lua_pushinteger(L,i);
lua_rawgeti(L,1,i);
return(lua_isnil(L,-1))?0:2;
}
static int luaB_ipairs(lua_State*L){
luaL_checktype(L,1,5);
lua_pushvalue(L,lua_upvalueindex(1));
lua_pushvalue(L,1);
lua_pushinteger(L,0);
return 3;
}
static int load_aux(lua_State*L,int status){
if(status==0)
return 1;
else{
lua_pushnil(L);
lua_insert(L,-2);
return 2;
}
}
static int luaB_loadstring(lua_State*L){
size_t l;
const char*s=luaL_checklstring(L,1,&l);
const char*chunkname=luaL_optstring(L,2,s);
return load_aux(L,luaL_loadbuffer(L,s,l,chunkname));
}
static int luaB_loadfile(lua_State*L){
const char*fname=luaL_optstring(L,1,NULL);
return load_aux(L,luaL_loadfile(L,fname));
}
static int luaB_assert(lua_State*L){
luaL_checkany(L,1);
if(!lua_toboolean(L,1))
return luaL_error(L,"%s",luaL_optstring(L,2,"assertion failed!"));
return lua_gettop(L);
}
static int luaB_unpack(lua_State*L){
int i,e,n;
luaL_checktype(L,1,5);
i=luaL_optint(L,2,1);
e=luaL_opt(L,luaL_checkint,3,luaL_getn(L,1));
if(i>e)return 0;
n=e-i+1;
if(n<=0||!lua_checkstack(L,n))
return luaL_error(L,"too many results to unpack");
lua_rawgeti(L,1,i);
while(i++<e)
lua_rawgeti(L,1,i);
return n;
}
static int luaB_pcall(lua_State*L){
int status;
luaL_checkany(L,1);
status=lua_pcall(L,lua_gettop(L)-1,(-1),0);
lua_pushboolean(L,(status==0));
lua_insert(L,1);
return lua_gettop(L);
}
static int luaB_newproxy(lua_State*L){
lua_settop(L,1);
lua_newuserdata(L,0);
if(lua_toboolean(L,1)==0)
return 1;
else if(lua_isboolean(L,1)){
lua_newtable(L);
lua_pushvalue(L,-1);
lua_pushboolean(L,1);
lua_rawset(L,lua_upvalueindex(1));
}
else{
int validproxy=0;
if(lua_getmetatable(L,1)){
lua_rawget(L,lua_upvalueindex(1));
validproxy=lua_toboolean(L,-1);
lua_pop(L,1);
}
luaL_argcheck(L,validproxy,1,"boolean or proxy expected");
lua_getmetatable(L,1);
}
lua_setmetatable(L,2);
return 1;
}
static const luaL_Reg base_funcs[]={
{"assert",luaB_assert},
{"error",luaB_error},
{"loadfile",luaB_loadfile},
{"loadstring",luaB_loadstring},
{"next",luaB_next},
{"pcall",luaB_pcall},
{"rawget",luaB_rawget},
{"setfenv",luaB_setfenv},
{"setmetatable",luaB_setmetatable},
{"tonumber",luaB_tonumber},
{"type",luaB_type},
{"unpack",luaB_unpack},
{NULL,NULL}
};
static void auxopen(lua_State*L,const char*name,
lua_CFunction f,lua_CFunction u){
lua_pushcfunction(L,u);
lua_pushcclosure(L,f,1);
lua_setfield(L,-2,name);
}
static void base_open(lua_State*L){
lua_pushvalue(L,(-10002));
lua_setglobal(L,"_G");
luaL_register(L,"_G",base_funcs);
lua_pushliteral(L,"Lua 5.1");
lua_setglobal(L,"_VERSION");
auxopen(L,"ipairs",luaB_ipairs,ipairsaux);
auxopen(L,"pairs",luaB_pairs,luaB_next);
lua_createtable(L,0,1);
lua_pushvalue(L,-1);
lua_setmetatable(L,-2);
lua_pushliteral(L,"kv");
lua_setfield(L,-2,"__mode");
lua_pushcclosure(L,luaB_newproxy,1);
lua_setglobal(L,"newproxy");
}
static int luaopen_base(lua_State*L){
base_open(L);
return 1;
}
#define aux_getn(L,n)(luaL_checktype(L,n,5),luaL_getn(L,n))
static int tinsert(lua_State*L){
int e=aux_getn(L,1)+1;
int pos;
switch(lua_gettop(L)){
case 2:{
pos=e;
break;
}
case 3:{
int i;
pos=luaL_checkint(L,2);
if(pos>e)e=pos;
for(i=e;i>pos;i--){
lua_rawgeti(L,1,i-1);
lua_rawseti(L,1,i);
}
break;
}
default:{
return luaL_error(L,"wrong number of arguments to "LUA_QL("insert"));
}
}
luaL_setn(L,1,e);
lua_rawseti(L,1,pos);
return 0;
}
static int tremove(lua_State*L){
int e=aux_getn(L,1);
int pos=luaL_optint(L,2,e);
if(!(1<=pos&&pos<=e))
return 0;
luaL_setn(L,1,e-1);
lua_rawgeti(L,1,pos);
for(;pos<e;pos++){
lua_rawgeti(L,1,pos+1);
lua_rawseti(L,1,pos);
}
lua_pushnil(L);
lua_rawseti(L,1,e);
return 1;
}
static void addfield(lua_State*L,luaL_Buffer*b,int i){
lua_rawgeti(L,1,i);
if(!lua_isstring(L,-1))
luaL_error(L,"invalid value (%s) at index %d in table for "
LUA_QL("concat"),luaL_typename(L,-1),i);
luaL_addvalue(b);
}
static int tconcat(lua_State*L){
luaL_Buffer b;
size_t lsep;
int i,last;
const char*sep=luaL_optlstring(L,2,"",&lsep);
luaL_checktype(L,1,5);
i=luaL_optint(L,3,1);
last=luaL_opt(L,luaL_checkint,4,luaL_getn(L,1));
luaL_buffinit(L,&b);
for(;i<last;i++){
addfield(L,&b,i);
luaL_addlstring(&b,sep,lsep);
}
if(i==last)
addfield(L,&b,i);
luaL_pushresult(&b);
return 1;
}
static void set2(lua_State*L,int i,int j){
lua_rawseti(L,1,i);
lua_rawseti(L,1,j);
}
static int sort_comp(lua_State*L,int a,int b){
if(!lua_isnil(L,2)){
int res;
lua_pushvalue(L,2);
lua_pushvalue(L,a-1);
lua_pushvalue(L,b-2);
lua_call(L,2,1);
res=lua_toboolean(L,-1);
lua_pop(L,1);
return res;
}
else
return lua_lessthan(L,a,b);
}
static void auxsort(lua_State*L,int l,int u){
while(l<u){
int i,j;
lua_rawgeti(L,1,l);
lua_rawgeti(L,1,u);
if(sort_comp(L,-1,-2))
set2(L,l,u);
else
lua_pop(L,2);
if(u-l==1)break;
i=(l+u)/2;
lua_rawgeti(L,1,i);
lua_rawgeti(L,1,l);
if(sort_comp(L,-2,-1))
set2(L,i,l);
else{
lua_pop(L,1);
lua_rawgeti(L,1,u);
if(sort_comp(L,-1,-2))
set2(L,i,u);
else
lua_pop(L,2);
}
if(u-l==2)break;
lua_rawgeti(L,1,i);
lua_pushvalue(L,-1);
lua_rawgeti(L,1,u-1);
set2(L,i,u-1);
i=l;j=u-1;
for(;;){
while(lua_rawgeti(L,1,++i),sort_comp(L,-1,-2)){
if(i>u)luaL_error(L,"invalid order function for sorting");
lua_pop(L,1);
}
while(lua_rawgeti(L,1,--j),sort_comp(L,-3,-1)){
if(j<l)luaL_error(L,"invalid order function for sorting");
lua_pop(L,1);
}
if(j<i){
lua_pop(L,3);
break;
}
set2(L,i,j);
}
lua_rawgeti(L,1,u-1);
lua_rawgeti(L,1,i);
set2(L,u-1,i);
if(i-l<u-i){
j=l;i=i-1;l=i+2;
}
else{
j=i+1;i=u;u=j-2;
}
auxsort(L,j,i);
}
}
static int sort(lua_State*L){
int n=aux_getn(L,1);
luaL_checkstack(L,40,"");
if(!lua_isnoneornil(L,2))
luaL_checktype(L,2,6);
lua_settop(L,2);
auxsort(L,1,n);
return 0;
}
static const luaL_Reg tab_funcs[]={
{"concat",tconcat},
{"insert",tinsert},
{"remove",tremove},
{"sort",sort},
{NULL,NULL}
};
static int luaopen_table(lua_State*L){
luaL_register(L,"table",tab_funcs);
return 1;
}
static const char*const fnames[]={"input","output"};
static int pushresult(lua_State*L,int i,const char*filename){
int en=errno;
if(i){
lua_pushboolean(L,1);
return 1;
}
else{
lua_pushnil(L);
if(filename)
lua_pushfstring(L,"%s: %s",filename,strerror(en));
else
lua_pushfstring(L,"%s",strerror(en));
lua_pushinteger(L,en);
return 3;
}
}
static void fileerror(lua_State*L,int arg,const char*filename){
lua_pushfstring(L,"%s: %s",filename,strerror(errno));
luaL_argerror(L,arg,lua_tostring(L,-1));
}
#define tofilep(L)((FILE**)luaL_checkudata(L,1,"FILE*"))
static int io_type(lua_State*L){
void*ud;
luaL_checkany(L,1);
ud=lua_touserdata(L,1);
lua_getfield(L,(-10000),"FILE*");
if(ud==NULL||!lua_getmetatable(L,1)||!lua_rawequal(L,-2,-1))
lua_pushnil(L);
else if(*((FILE**)ud)==NULL)
lua_pushliteral(L,"closed file");
else
lua_pushliteral(L,"file");
return 1;
}
static FILE*tofile(lua_State*L){
FILE**f=tofilep(L);
if(*f==NULL)
luaL_error(L,"attempt to use a closed file");
return*f;
}
static FILE**newfile(lua_State*L){
FILE**pf=(FILE**)lua_newuserdata(L,sizeof(FILE*));
*pf=NULL;
luaL_getmetatable(L,"FILE*");
lua_setmetatable(L,-2);
return pf;
}
static int io_noclose(lua_State*L){
lua_pushnil(L);
lua_pushliteral(L,"cannot close standard file");
return 2;
}
static int io_pclose(lua_State*L){
FILE**p=tofilep(L);
int ok=lua_pclose(L,*p);
*p=NULL;
return pushresult(L,ok,NULL);
}
static int io_fclose(lua_State*L){
FILE**p=tofilep(L);
int ok=(fclose(*p)==0);
*p=NULL;
return pushresult(L,ok,NULL);
}
static int aux_close(lua_State*L){
lua_getfenv(L,1);
lua_getfield(L,-1,"__close");
return(lua_tocfunction(L,-1))(L);
}
static int io_close(lua_State*L){
if(lua_isnone(L,1))
lua_rawgeti(L,(-10001),2);
tofile(L);
return aux_close(L);
}
static int io_gc(lua_State*L){
FILE*f=*tofilep(L);
if(f!=NULL)
aux_close(L);
return 0;
}
static int io_open(lua_State*L){
const char*filename=luaL_checkstring(L,1);
const char*mode=luaL_optstring(L,2,"r");
FILE**pf=newfile(L);
*pf=fopen(filename,mode);
return(*pf==NULL)?pushresult(L,0,filename):1;
}
static FILE*getiofile(lua_State*L,int findex){
FILE*f;
lua_rawgeti(L,(-10001),findex);
f=*(FILE**)lua_touserdata(L,-1);
if(f==NULL)
luaL_error(L,"standard %s file is closed",fnames[findex-1]);
return f;
}
static int g_iofile(lua_State*L,int f,const char*mode){
if(!lua_isnoneornil(L,1)){
const char*filename=lua_tostring(L,1);
if(filename){
FILE**pf=newfile(L);
*pf=fopen(filename,mode);
if(*pf==NULL)
fileerror(L,1,filename);
}
else{
tofile(L);
lua_pushvalue(L,1);
}
lua_rawseti(L,(-10001),f);
}
lua_rawgeti(L,(-10001),f);
return 1;
}
static int io_input(lua_State*L){
return g_iofile(L,1,"r");
}
static int io_output(lua_State*L){
return g_iofile(L,2,"w");
}
static int io_readline(lua_State*L);
static void aux_lines(lua_State*L,int idx,int toclose){
lua_pushvalue(L,idx);
lua_pushboolean(L,toclose);
lua_pushcclosure(L,io_readline,2);
}
static int f_lines(lua_State*L){
tofile(L);
aux_lines(L,1,0);
return 1;
}
static int io_lines(lua_State*L){
if(lua_isnoneornil(L,1)){
lua_rawgeti(L,(-10001),1);
return f_lines(L);
}
else{
const char*filename=luaL_checkstring(L,1);
FILE**pf=newfile(L);
*pf=fopen(filename,"r");
if(*pf==NULL)
fileerror(L,1,filename);
aux_lines(L,lua_gettop(L),1);
return 1;
}
}
static int read_number(lua_State*L,FILE*f){
lua_Number d;
if(fscanf(f,"%lf",&d)==1){
lua_pushnumber(L,d);
return 1;
}
else{
lua_pushnil(L);
return 0;
}
}
static int test_eof(lua_State*L,FILE*f){
int c=getc(f);
ungetc(c,f);
lua_pushlstring(L,NULL,0);
return(c!=EOF);
}
static int read_line(lua_State*L,FILE*f){
luaL_Buffer b;
luaL_buffinit(L,&b);
for(;;){
size_t l;
char*p=luaL_prepbuffer(&b);
if(fgets(p,BUFSIZ,f)==NULL){
luaL_pushresult(&b);
return(lua_objlen(L,-1)>0);
}
l=strlen(p);
if(l==0||p[l-1]!='\n')
luaL_addsize(&b,l);
else{
luaL_addsize(&b,l-1);
luaL_pushresult(&b);
return 1;
}
}
}
static int read_chars(lua_State*L,FILE*f,size_t n){
size_t rlen;
size_t nr;
luaL_Buffer b;
luaL_buffinit(L,&b);
rlen=BUFSIZ;
do{
char*p=luaL_prepbuffer(&b);
if(rlen>n)rlen=n;
nr=fread(p,sizeof(char),rlen,f);
luaL_addsize(&b,nr);
n-=nr;
}while(n>0&&nr==rlen);
luaL_pushresult(&b);
return(n==0||lua_objlen(L,-1)>0);
}
static int g_read(lua_State*L,FILE*f,int first){
int nargs=lua_gettop(L)-1;
int success;
int n;
clearerr(f);
if(nargs==0){
success=read_line(L,f);
n=first+1;
}
else{
luaL_checkstack(L,nargs+20,"too many arguments");
success=1;
for(n=first;nargs--&&success;n++){
if(lua_type(L,n)==3){
size_t l=(size_t)lua_tointeger(L,n);
success=(l==0)?test_eof(L,f):read_chars(L,f,l);
}
else{
const char*p=lua_tostring(L,n);
luaL_argcheck(L,p&&p[0]=='*',n,"invalid option");
switch(p[1]){
case'n':
success=read_number(L,f);
break;
case'l':
success=read_line(L,f);
break;
case'a':
read_chars(L,f,~((size_t)0));
success=1;
break;
default:
return luaL_argerror(L,n,"invalid format");
}
}
}
}
if(ferror(f))
return pushresult(L,0,NULL);
if(!success){
lua_pop(L,1);
lua_pushnil(L);
}
return n-first;
}
static int io_read(lua_State*L){
return g_read(L,getiofile(L,1),1);
}
static int f_read(lua_State*L){
return g_read(L,tofile(L),2);
}
static int io_readline(lua_State*L){
FILE*f=*(FILE**)lua_touserdata(L,lua_upvalueindex(1));
int sucess;
if(f==NULL)
luaL_error(L,"file is already closed");
sucess=read_line(L,f);
if(ferror(f))
return luaL_error(L,"%s",strerror(errno));
if(sucess)return 1;
else{
if(lua_toboolean(L,lua_upvalueindex(2))){
lua_settop(L,0);
lua_pushvalue(L,lua_upvalueindex(1));
aux_close(L);
}
return 0;
}
}
static int g_write(lua_State*L,FILE*f,int arg){
int nargs=lua_gettop(L)-1;
int status=1;
for(;nargs--;arg++){
if(lua_type(L,arg)==3){
status=status&&
fprintf(f,"%.14g",lua_tonumber(L,arg))>0;
}
else{
size_t l;
const char*s=luaL_checklstring(L,arg,&l);
status=status&&(fwrite(s,sizeof(char),l,f)==l);
}
}
return pushresult(L,status,NULL);
}
static int io_write(lua_State*L){
return g_write(L,getiofile(L,2),1);
}
static int f_write(lua_State*L){
return g_write(L,tofile(L),2);
}
static int io_flush(lua_State*L){
return pushresult(L,fflush(getiofile(L,2))==0,NULL);
}
static int f_flush(lua_State*L){
return pushresult(L,fflush(tofile(L))==0,NULL);
}
static const luaL_Reg iolib[]={
{"close",io_close},
{"flush",io_flush},
{"input",io_input},
{"lines",io_lines},
{"open",io_open},
{"output",io_output},
{"read",io_read},
{"type",io_type},
{"write",io_write},
{NULL,NULL}
};
static const luaL_Reg flib[]={
{"close",io_close},
{"flush",f_flush},
{"lines",f_lines},
{"read",f_read},
{"write",f_write},
{"__gc",io_gc},
{NULL,NULL}
};
static void createmeta(lua_State*L){
luaL_newmetatable(L,"FILE*");
lua_pushvalue(L,-1);
lua_setfield(L,-2,"__index");
luaL_register(L,NULL,flib);
}
static void createstdfile(lua_State*L,FILE*f,int k,const char*fname){
*newfile(L)=f;
if(k>0){
lua_pushvalue(L,-1);
lua_rawseti(L,(-10001),k);
}
lua_pushvalue(L,-2);
lua_setfenv(L,-2);
lua_setfield(L,-3,fname);
}
static void newfenv(lua_State*L,lua_CFunction cls){
lua_createtable(L,0,1);
lua_pushcfunction(L,cls);
lua_setfield(L,-2,"__close");
}
static int luaopen_io(lua_State*L){
createmeta(L);
newfenv(L,io_fclose);
lua_replace(L,(-10001));
luaL_register(L,"io",iolib);
newfenv(L,io_noclose);
createstdfile(L,stdin,1,"stdin");
createstdfile(L,stdout,2,"stdout");
createstdfile(L,stderr,0,"stderr");
lua_pop(L,1);
lua_getfield(L,-1,"popen");
newfenv(L,io_pclose);
lua_setfenv(L,-2);
lua_pop(L,1);
return 1;
}
static int os_pushresult(lua_State*L,int i,const char*filename){
int en=errno;
if(i){
lua_pushboolean(L,1);
return 1;
}
else{
lua_pushnil(L);
lua_pushfstring(L,"%s: %s",filename,strerror(en));
lua_pushinteger(L,en);
return 3;
}
}
static int os_remove(lua_State*L){
const char*filename=luaL_checkstring(L,1);
return os_pushresult(L,remove(filename)==0,filename);
}
static int os_exit(lua_State*L){
exit(luaL_optint(L,1,EXIT_SUCCESS));
}
static const luaL_Reg syslib[]={
{"exit",os_exit},
{"remove",os_remove},
{NULL,NULL}
};
static int luaopen_os(lua_State*L){
luaL_register(L,"os",syslib);
return 1;
}
#define uchar(c)((unsigned char)(c))
static ptrdiff_t posrelat(ptrdiff_t pos,size_t len){
if(pos<0)pos+=(ptrdiff_t)len+1;
return(pos>=0)?pos:0;
}
static int str_sub(lua_State*L){
size_t l;
const char*s=luaL_checklstring(L,1,&l);
ptrdiff_t start=posrelat(luaL_checkinteger(L,2),l);
ptrdiff_t end=posrelat(luaL_optinteger(L,3,-1),l);
if(start<1)start=1;
if(end>(ptrdiff_t)l)end=(ptrdiff_t)l;
if(start<=end)
lua_pushlstring(L,s+start-1,end-start+1);
else lua_pushliteral(L,"");
return 1;
}
static int str_lower(lua_State*L){
size_t l;
size_t i;
luaL_Buffer b;
const char*s=luaL_checklstring(L,1,&l);
luaL_buffinit(L,&b);
for(i=0;i<l;i++)
luaL_addchar(&b,tolower(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
static int str_upper(lua_State*L){
size_t l;
size_t i;
luaL_Buffer b;
const char*s=luaL_checklstring(L,1,&l);
luaL_buffinit(L,&b);
for(i=0;i<l;i++)
luaL_addchar(&b,toupper(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
static int str_rep(lua_State*L){
size_t l;
luaL_Buffer b;
const char*s=luaL_checklstring(L,1,&l);
int n=luaL_checkint(L,2);
luaL_buffinit(L,&b);
while(n-->0)
luaL_addlstring(&b,s,l);
luaL_pushresult(&b);
return 1;
}
static int str_byte(lua_State*L){
size_t l;
const char*s=luaL_checklstring(L,1,&l);
ptrdiff_t posi=posrelat(luaL_optinteger(L,2,1),l);
ptrdiff_t pose=posrelat(luaL_optinteger(L,3,posi),l);
int n,i;
if(posi<=0)posi=1;
if((size_t)pose>l)pose=l;
if(posi>pose)return 0;
n=(int)(pose-posi+1);
if(posi+n<=pose)
luaL_error(L,"string slice too long");
luaL_checkstack(L,n,"string slice too long");
for(i=0;i<n;i++)
lua_pushinteger(L,uchar(s[posi+i-1]));
return n;
}
static int str_char(lua_State*L){
int n=lua_gettop(L);
int i;
luaL_Buffer b;
luaL_buffinit(L,&b);
for(i=1;i<=n;i++){
int c=luaL_checkint(L,i);
luaL_argcheck(L,uchar(c)==c,i,"invalid value");
luaL_addchar(&b,uchar(c));
}
luaL_pushresult(&b);
return 1;
}
typedef struct MatchState{
const char*src_init;
const char*src_end;
lua_State*L;
int level;
struct{
const char*init;
ptrdiff_t len;
}capture[32];
}MatchState;
static int check_capture(MatchState*ms,int l){
l-='1';
if(l<0||l>=ms->level||ms->capture[l].len==(-1))
return luaL_error(ms->L,"invalid capture index");
return l;
}
static int capture_to_close(MatchState*ms){
int level=ms->level;
for(level--;level>=0;level--)
if(ms->capture[level].len==(-1))return level;
return luaL_error(ms->L,"invalid pattern capture");
}
static const char*classend(MatchState*ms,const char*p){
switch(*p++){
case'%':{
if(*p=='\0')
luaL_error(ms->L,"malformed pattern (ends with "LUA_QL("%%")")");
return p+1;
}
case'[':{
if(*p=='^')p++;
do{
if(*p=='\0')
luaL_error(ms->L,"malformed pattern (missing "LUA_QL("]")")");
if(*(p++)=='%'&&*p!='\0')
p++;
}while(*p!=']');
return p+1;
}
default:{
return p;
}
}
}
static int match_class(int c,int cl){
int res;
switch(tolower(cl)){
case'a':res=isalpha(c);break;
case'c':res=iscntrl(c);break;
case'd':res=isdigit(c);break;
case'l':res=islower(c);break;
case'p':res=ispunct(c);break;
case's':res=isspace(c);break;
case'u':res=isupper(c);break;
case'w':res=isalnum(c);break;
case'x':res=isxdigit(c);break;
case'z':res=(c==0);break;
default:return(cl==c);
}
return(islower(cl)?res:!res);
}
static int matchbracketclass(int c,const char*p,const char*ec){
int sig=1;
if(*(p+1)=='^'){
sig=0;
p++;
}
while(++p<ec){
if(*p=='%'){
p++;
if(match_class(c,uchar(*p)))
return sig;
}
else if((*(p+1)=='-')&&(p+2<ec)){
p+=2;
if(uchar(*(p-2))<=c&&c<=uchar(*p))
return sig;
}
else if(uchar(*p)==c)return sig;
}
return!sig;
}
static int singlematch(int c,const char*p,const char*ep){
switch(*p){
case'.':return 1;
case'%':return match_class(c,uchar(*(p+1)));
case'[':return matchbracketclass(c,p,ep-1);
default:return(uchar(*p)==c);
}
}
static const char*match(MatchState*ms,const char*s,const char*p);
static const char*matchbalance(MatchState*ms,const char*s,
const char*p){
if(*p==0||*(p+1)==0)
luaL_error(ms->L,"unbalanced pattern");
if(*s!=*p)return NULL;
else{
int b=*p;
int e=*(p+1);
int cont=1;
while(++s<ms->src_end){
if(*s==e){
if(--cont==0)return s+1;
}
else if(*s==b)cont++;
}
}
return NULL;
}
static const char*max_expand(MatchState*ms,const char*s,
const char*p,const char*ep){
ptrdiff_t i=0;
while((s+i)<ms->src_end&&singlematch(uchar(*(s+i)),p,ep))
i++;
while(i>=0){
const char*res=match(ms,(s+i),ep+1);
if(res)return res;
i--;
}
return NULL;
}
static const char*min_expand(MatchState*ms,const char*s,
const char*p,const char*ep){
for(;;){
const char*res=match(ms,s,ep+1);
if(res!=NULL)
return res;
else if(s<ms->src_end&&singlematch(uchar(*s),p,ep))
s++;
else return NULL;
}
}
static const char*start_capture(MatchState*ms,const char*s,
const char*p,int what){
const char*res;
int level=ms->level;
if(level>=32)luaL_error(ms->L,"too many captures");
ms->capture[level].init=s;
ms->capture[level].len=what;
ms->level=level+1;
if((res=match(ms,s,p))==NULL)
ms->level--;
return res;
}
static const char*end_capture(MatchState*ms,const char*s,
const char*p){
int l=capture_to_close(ms);
const char*res;
ms->capture[l].len=s-ms->capture[l].init;
if((res=match(ms,s,p))==NULL)
ms->capture[l].len=(-1);
return res;
}
static const char*match_capture(MatchState*ms,const char*s,int l){
size_t len;
l=check_capture(ms,l);
len=ms->capture[l].len;
if((size_t)(ms->src_end-s)>=len&&
memcmp(ms->capture[l].init,s,len)==0)
return s+len;
else return NULL;
}
static const char*match(MatchState*ms,const char*s,const char*p){
init:
switch(*p){
case'(':{
if(*(p+1)==')')
return start_capture(ms,s,p+2,(-2));
else
return start_capture(ms,s,p+1,(-1));
}
case')':{
return end_capture(ms,s,p+1);
}
case'%':{
switch(*(p+1)){
case'b':{
s=matchbalance(ms,s,p+2);
if(s==NULL)return NULL;
p+=4;goto init;
}
case'f':{
const char*ep;char previous;
p+=2;
if(*p!='[')
luaL_error(ms->L,"missing "LUA_QL("[")" after "
LUA_QL("%%f")" in pattern");
ep=classend(ms,p);
previous=(s==ms->src_init)?'\0':*(s-1);
if(matchbracketclass(uchar(previous),p,ep-1)||
!matchbracketclass(uchar(*s),p,ep-1))return NULL;
p=ep;goto init;
}
default:{
if(isdigit(uchar(*(p+1)))){
s=match_capture(ms,s,uchar(*(p+1)));
if(s==NULL)return NULL;
p+=2;goto init;
}
goto dflt;
}
}
}
case'\0':{
return s;
}
case'$':{
if(*(p+1)=='\0')
return(s==ms->src_end)?s:NULL;
else goto dflt;
}
default:dflt:{
const char*ep=classend(ms,p);
int m=s<ms->src_end&&singlematch(uchar(*s),p,ep);
switch(*ep){
case'?':{
const char*res;
if(m&&((res=match(ms,s+1,ep+1))!=NULL))
return res;
p=ep+1;goto init;
}
case'*':{
return max_expand(ms,s,p,ep);
}
case'+':{
return(m?max_expand(ms,s+1,p,ep):NULL);
}
case'-':{
return min_expand(ms,s,p,ep);
}
default:{
if(!m)return NULL;
s++;p=ep;goto init;
}
}
}
}
}
static const char*lmemfind(const char*s1,size_t l1,
const char*s2,size_t l2){
if(l2==0)return s1;
else if(l2>l1)return NULL;
else{
const char*init;
l2--;
l1=l1-l2;
while(l1>0&&(init=(const char*)memchr(s1,*s2,l1))!=NULL){
init++;
if(memcmp(init,s2+1,l2)==0)
return init-1;
else{
l1-=init-s1;
s1=init;
}
}
return NULL;
}
}
static void push_onecapture(MatchState*ms,int i,const char*s,
const char*e){
if(i>=ms->level){
if(i==0)
lua_pushlstring(ms->L,s,e-s);
else
luaL_error(ms->L,"invalid capture index");
}
else{
ptrdiff_t l=ms->capture[i].len;
if(l==(-1))luaL_error(ms->L,"unfinished capture");
if(l==(-2))
lua_pushinteger(ms->L,ms->capture[i].init-ms->src_init+1);
else
lua_pushlstring(ms->L,ms->capture[i].init,l);
}
}
static int push_captures(MatchState*ms,const char*s,const char*e){
int i;
int nlevels=(ms->level==0&&s)?1:ms->level;
luaL_checkstack(ms->L,nlevels,"too many captures");
for(i=0;i<nlevels;i++)
push_onecapture(ms,i,s,e);
return nlevels;
}
static int str_find_aux(lua_State*L,int find){
size_t l1,l2;
const char*s=luaL_checklstring(L,1,&l1);
const char*p=luaL_checklstring(L,2,&l2);
ptrdiff_t init=posrelat(luaL_optinteger(L,3,1),l1)-1;
if(init<0)init=0;
else if((size_t)(init)>l1)init=(ptrdiff_t)l1;
if(find&&(lua_toboolean(L,4)||
strpbrk(p,"^$*+?.([%-")==NULL)){
const char*s2=lmemfind(s+init,l1-init,p,l2);
if(s2){
lua_pushinteger(L,s2-s+1);
lua_pushinteger(L,s2-s+l2);
return 2;
}
}
else{
MatchState ms;
int anchor=(*p=='^')?(p++,1):0;
const char*s1=s+init;
ms.L=L;
ms.src_init=s;
ms.src_end=s+l1;
do{
const char*res;
ms.level=0;
if((res=match(&ms,s1,p))!=NULL){
if(find){
lua_pushinteger(L,s1-s+1);
lua_pushinteger(L,res-s);
return push_captures(&ms,NULL,0)+2;
}
else
return push_captures(&ms,s1,res);
}
}while(s1++<ms.src_end&&!anchor);
}
lua_pushnil(L);
return 1;
}
static int str_find(lua_State*L){
return str_find_aux(L,1);
}
static int str_match(lua_State*L){
return str_find_aux(L,0);
}
static int gmatch_aux(lua_State*L){
MatchState ms;
size_t ls;
const char*s=lua_tolstring(L,lua_upvalueindex(1),&ls);
const char*p=lua_tostring(L,lua_upvalueindex(2));
const char*src;
ms.L=L;
ms.src_init=s;
ms.src_end=s+ls;
for(src=s+(size_t)lua_tointeger(L,lua_upvalueindex(3));
src<=ms.src_end;
src++){
const char*e;
ms.level=0;
if((e=match(&ms,src,p))!=NULL){
lua_Integer newstart=e-s;
if(e==src)newstart++;
lua_pushinteger(L,newstart);
lua_replace(L,lua_upvalueindex(3));
return push_captures(&ms,src,e);
}
}
return 0;
}
static int gmatch(lua_State*L){
luaL_checkstring(L,1);
luaL_checkstring(L,2);
lua_settop(L,2);
lua_pushinteger(L,0);
lua_pushcclosure(L,gmatch_aux,3);
return 1;
}
static void add_s(MatchState*ms,luaL_Buffer*b,const char*s,
const char*e){
size_t l,i;
const char*news=lua_tolstring(ms->L,3,&l);
for(i=0;i<l;i++){
if(news[i]!='%')
luaL_addchar(b,news[i]);
else{
i++;
if(!isdigit(uchar(news[i])))
luaL_addchar(b,news[i]);
else if(news[i]=='0')
luaL_addlstring(b,s,e-s);
else{
push_onecapture(ms,news[i]-'1',s,e);
luaL_addvalue(b);
}
}
}
}
static void add_value(MatchState*ms,luaL_Buffer*b,const char*s,
const char*e){
lua_State*L=ms->L;
switch(lua_type(L,3)){
case 3:
case 4:{
add_s(ms,b,s,e);
return;
}
case 6:{
int n;
lua_pushvalue(L,3);
n=push_captures(ms,s,e);
lua_call(L,n,1);
break;
}
case 5:{
push_onecapture(ms,0,s,e);
lua_gettable(L,3);
break;
}
}
if(!lua_toboolean(L,-1)){
lua_pop(L,1);
lua_pushlstring(L,s,e-s);
}
else if(!lua_isstring(L,-1))
luaL_error(L,"invalid replacement value (a %s)",luaL_typename(L,-1));
luaL_addvalue(b);
}
static int str_gsub(lua_State*L){
size_t srcl;
const char*src=luaL_checklstring(L,1,&srcl);
const char*p=luaL_checkstring(L,2);
int tr=lua_type(L,3);
int max_s=luaL_optint(L,4,srcl+1);
int anchor=(*p=='^')?(p++,1):0;
int n=0;
MatchState ms;
luaL_Buffer b;
luaL_argcheck(L,tr==3||tr==4||
tr==6||tr==5,3,
"string/function/table expected");
luaL_buffinit(L,&b);
ms.L=L;
ms.src_init=src;
ms.src_end=src+srcl;
while(n<max_s){
const char*e;
ms.level=0;
e=match(&ms,src,p);
if(e){
n++;
add_value(&ms,&b,src,e);
}
if(e&&e>src)
src=e;
else if(src<ms.src_end)
luaL_addchar(&b,*src++);
else break;
if(anchor)break;
}
luaL_addlstring(&b,src,ms.src_end-src);
luaL_pushresult(&b);
lua_pushinteger(L,n);
return 2;
}
static void addquoted(lua_State*L,luaL_Buffer*b,int arg){
size_t l;
const char*s=luaL_checklstring(L,arg,&l);
luaL_addchar(b,'"');
while(l--){
switch(*s){
case'"':case'\\':case'\n':{
luaL_addchar(b,'\\');
luaL_addchar(b,*s);
break;
}
case'\r':{
luaL_addlstring(b,"\\r",2);
break;
}
case'\0':{
luaL_addlstring(b,"\\000",4);
break;
}
default:{
luaL_addchar(b,*s);
break;
}
}
s++;
}
luaL_addchar(b,'"');
}
static const char*scanformat(lua_State*L,const char*strfrmt,char*form){
const char*p=strfrmt;
while(*p!='\0'&&strchr("-+ #0",*p)!=NULL)p++;
if((size_t)(p-strfrmt)>=sizeof("-+ #0"))
luaL_error(L,"invalid format (repeated flags)");
if(isdigit(uchar(*p)))p++;
if(isdigit(uchar(*p)))p++;
if(*p=='.'){
p++;
if(isdigit(uchar(*p)))p++;
if(isdigit(uchar(*p)))p++;
}
if(isdigit(uchar(*p)))
luaL_error(L,"invalid format (width or precision too long)");
*(form++)='%';
strncpy(form,strfrmt,p-strfrmt+1);
form+=p-strfrmt+1;
*form='\0';
return p;
}
static void addintlen(char*form){
size_t l=strlen(form);
char spec=form[l-1];
strcpy(form+l-1,"l");
form[l+sizeof("l")-2]=spec;
form[l+sizeof("l")-1]='\0';
}
static int str_format(lua_State*L){
int top=lua_gettop(L);
int arg=1;
size_t sfl;
const char*strfrmt=luaL_checklstring(L,arg,&sfl);
const char*strfrmt_end=strfrmt+sfl;
luaL_Buffer b;
luaL_buffinit(L,&b);
while(strfrmt<strfrmt_end){
if(*strfrmt!='%')
luaL_addchar(&b,*strfrmt++);
else if(*++strfrmt=='%')
luaL_addchar(&b,*strfrmt++);
else{
char form[(sizeof("-+ #0")+sizeof("l")+10)];
char buff[512];
if(++arg>top)
luaL_argerror(L,arg,"no value");
strfrmt=scanformat(L,strfrmt,form);
switch(*strfrmt++){
case'c':{
sprintf(buff,form,(int)luaL_checknumber(L,arg));
break;
}
case'd':case'i':{
addintlen(form);
sprintf(buff,form,(long)luaL_checknumber(L,arg));
break;
}
case'o':case'u':case'x':case'X':{
addintlen(form);
sprintf(buff,form,(unsigned long)luaL_checknumber(L,arg));
break;
}
case'e':case'E':case'f':
case'g':case'G':{
sprintf(buff,form,(double)luaL_checknumber(L,arg));
break;
}
case'q':{
addquoted(L,&b,arg);
continue;
}
case's':{
size_t l;
const char*s=luaL_checklstring(L,arg,&l);
if(!strchr(form,'.')&&l>=100){
lua_pushvalue(L,arg);
luaL_addvalue(&b);
continue;
}
else{
sprintf(buff,form,s);
break;
}
}
default:{
return luaL_error(L,"invalid option "LUA_QL("%%%c")" to "
LUA_QL("format"),*(strfrmt-1));
}
}
luaL_addlstring(&b,buff,strlen(buff));
}
}
luaL_pushresult(&b);
return 1;
}
static const luaL_Reg strlib[]={
{"byte",str_byte},
{"char",str_char},
{"find",str_find},
{"format",str_format},
{"gmatch",gmatch},
{"gsub",str_gsub},
{"lower",str_lower},
{"match",str_match},
{"rep",str_rep},
{"sub",str_sub},
{"upper",str_upper},
{NULL,NULL}
};
static void createmetatable(lua_State*L){
lua_createtable(L,0,1);
lua_pushliteral(L,"");
lua_pushvalue(L,-2);
lua_setmetatable(L,-2);
lua_pop(L,1);
lua_pushvalue(L,-2);
lua_setfield(L,-2,"__index");
lua_pop(L,1);
}
static int luaopen_string(lua_State*L){
luaL_register(L,"string",strlib);
createmetatable(L);
return 1;
}
static const luaL_Reg lualibs[]={
{"",luaopen_base},
{"table",luaopen_table},
{"io",luaopen_io},
{"os",luaopen_os},
{"string",luaopen_string},
{NULL,NULL}
};
static void luaL_openlibs(lua_State*L){
const luaL_Reg*lib=lualibs;
for(;lib->func;lib++){
lua_pushcfunction(L,lib->func);
lua_pushstring(L,lib->name);
lua_call(L,1,0);
}
}
typedef unsigned int UB;
static UB barg(lua_State*L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if(bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b)lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State*L){
BRET(barg(L,1))}
static int bnot(lua_State*L){
BRET(~barg(L,1))}
static int band(lua_State*L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State*L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State*L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State*L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State*L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State*L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State*L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State*L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State*L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State*L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char*hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[]={
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc,char**argv){
lua_State*L=luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L,"bit",bitlib);
if(argc<2)return sizeof(void*);
lua_createtable(L,0,1);
lua_pushstring(L,argv[1]);
lua_rawseti(L,-2,0);
lua_setglobal(L,"arg");
if(luaL_loadfile(L,argv[1]))
goto err;
for(i=2;i<argc;i++)
lua_pushstring(L,argv[i]);
if(lua_pcall(L,argc-2,0,0)){
err:
fprintf(stderr,"Error: %s\n",lua_tostring(L,-1));
return 1;
}
lua_close(L);
return 0;
}
|
the_stack_data/175143537.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/HardShrink.c"
#else
void THNN_(HardShrink_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
accreal lambda_)
{
real lambda = TH_CONVERT_ACCREAL_TO_REAL(lambda_);
THTensor_(resizeAs)(output, input);
TH_TENSOR_APPLY2(real, output, real, input,
if (*input_data > lambda)
*output_data = *input_data;
else if (*input_data < -lambda)
*output_data = *input_data;
else
*output_data = 0;
);
}
void THNN_(HardShrink_updateGradInput)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradInput,
accreal lambda_)
{
real lambda = TH_CONVERT_ACCREAL_TO_REAL(lambda_);
THNN_CHECK_NELEMENT(input, gradOutput);
THTensor_(resizeAs)(gradInput, input);
TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, input,
if (*input_data > lambda || *input_data < -lambda)
*gradInput_data = *gradOutput_data;
else
*gradInput_data = 0;
);
}
#endif
|
the_stack_data/61074632.c | #include <stdio.h>
#include <stdlib.h>
void main() {
int a = 0;
do
{
printf("%d\n", a);
a++;
} while (a<=10);
} |
the_stack_data/89674.c | int bar(int Y) { return 2 * Y; }
int foo(int X) {
#pragma spf metadata replace(bar(X))
return X + X;
}
int baz() { return foo(5); }
|
the_stack_data/165765181.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
{
state[0UL] = input[0UL] + 4284877637U;
local1 = 0UL;
while (local1 < 0U) {
state[local1] *= state[local1];
local1 += 2UL;
}
output[0UL] = state[0UL] * 809088178UL;
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 4242424242U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/86662.c | #include <stdio.h>
#include <math.h>
#include <stdbool.h>
double bessy0(double x);
double bessy1(double x);
double bessj0(double x);
double bessj1(double x);
double snippet (double n, double x) {
double j =0;
double by = 0;
double bym= 0;
double byp= 0;
double tox= 0;
if (n < 2)
return -1000;
tox=2.0*x;
by=bessy1(x);
bym=bessy0(x);
for (j=1;j<n;j++) {
byp=j*tox*by-bym;
bym=by;
by=byp;
}
return by;
}
double bessy0(double x){
double z,xx,y,ans,ans1,ans2;
if (x < 8.0) {
y=x*x;
ans1 = -2957821389.0+y*(7062834065.0+y*(-512359803.6
+y*(10879881.29+y*(-86327.92757+y*228.4622733))));
ans2=40076544269.0+y*(745249964.8+y*(7189466.438
+y*(47447.26470+y*(226.1030244+y*1.0))));
ans=(ans1/ans2)+0.636619772*bessj0(x)*log(x);
} else {
z=8.0/x;
y=z*z;
xx=x-0.785398164;
ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4
+y*(-0.2073370639e-5+y*0.2093887211e-6)));
ans2 = -0.1562499995e-1+y*(0.1430488765e-3
+y*(-0.6911147651e-5+y*(0.7621095161e-6
+y*(-0.934945152e-7))));
ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2);
}
return ans;
}
double bessy1(double x){
double z,xx,y,ans,ans1,ans2;
if (x < 8.0) {
y=x*x;
ans1=x*(-0.4900604943e13+y*(0.1275274390e13
+y*(-0.5153438139e11+y*(0.7349264551e9
+y*(-0.4237922726e7+y*0.8511937935e4)))));
ans2=0.2499580570e14+y*(0.4244419664e12
+y*(0.3733650367e10+y*(0.2245904002e8
+y*(0.1020426050e6+y*(0.3549632885e3+y)))));
ans=(ans1/ans2)+0.636619772*(bessj1(x)*log(x)-1.0/x);
} else {
z=8.0/x;
y=z*z;
xx=x-2.356194491;
ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4
+y*(0.2457520174e-5+y*(-0.240337019e-6))));
ans2=0.04687499995+y*(-0.2002690873e-3
+y*(0.8449199096e-5+y*(-0.88228987e-6
+y*0.105787412e-6)));
ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2);
}
return ans;
}
double bessj0(double x){
double ax,z,xx,y,ans,ans1,ans2;
if ((ax=fabs(x)) < 8.0) {
y=x*x;
ans1=57568490574.0+y*(-13362590354.0+y*(651619640.7
+y*(-11214424.18+y*(77392.33017+y*(-184.9052456)))));
ans2=57568490411.0+y*(1029532985.0+y*(9494680.718
+y*(59272.64853+y*(267.8532712+y*1.0))));
ans=ans1/ans2;
} else {
z=8.0/ax;
y=z*z;
xx=ax-0.785398164;
ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4
+y*(-0.2073370639e-5+y*0.2093887211e-6)));
ans2 = -0.1562499995e-1+y*(0.1430488765e-3
+y*(-0.6911147651e-5+y*(0.7621095161e-6
-y*0.934945152e-7)));
ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2);
}
return ans;
}
double bessj1(double x){
double ax,z,xx,y,ans,ans1,ans2;
if ((ax=fabs(x)) < 8.0) {
y=x*x;
ans1=x*(72362614232.0+y*(-7895059235.0+y*(242396853.1
+y*(-2972611.439+y*(15704.48260+y*(-30.16036606))))));
ans2=144725228442.0+y*(2300535178.0+y*(18583304.74
+y*(99447.43394+y*(376.9991397+y*1.0))));
ans=ans1/ans2;
} else {
z=8.0/ax;
y=z*z;
xx=ax-2.356194491;
ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4
+y*(0.2457520174e-5+y*(-0.240337019e-6))));
ans2=0.04687499995+y*(-0.2002690873e-3
+y*(0.8449199096e-5+y*(-0.88228987e-6
+y*0.105787412e-6)));
ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2);
if (x < 0.0) ans = -ans;
}
return ans;
} |
the_stack_data/308009.c |
#include <stdio.h>
int main()
{
int n,i,sum=0 ;
printf("Enter the n of numbers :");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
sum+=i;
}
printf("sum of numbers :%d",sum);
return 0;
}
|
the_stack_data/168893224.c | /* { dg-do compile } */
static int *** foo (int);
void
bar ()
{
int ***p = foo (2);
}
extern int *nd;
extern int ***tc;
extern int *ap;
extern int *as;
extern float ss;
static int ***
foo (int Fc)
{
int i, j, s, p, n, t;
n = 0;
for (s = 0; s < 4; s++)
n += nd[s];
for (i = 0; i < n; i++)
{
p = ap[i];
s = as[i];
for (j = 0; j < Fc; j++)
tc[p][s][j] = i * ss + j;
}
return (tc);
}
|
the_stack_data/165764209.c | /*
* p07.c * * usage: *
* ./a.out filename
*
* Intended behavior
*
* It first reads the contents of the file given
* in the command line, and print characters in it
* in the reverse order.
* Since the size of the file is unknown, it allocates
* memory dynamically and grows it when necessary
*/
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <assert.h>
int main(int argc, char ** argv)
{
/* try to read the whole contents of
the file into s */
FILE * fp = fopen(argv[1], "rb");
/* s is initially small (10 bytes) */
int begin = 0;
int end = 10;
char * s = (char *)malloc(end);
while (1) {
/* read as many bytes as s can store ((end - begin) bytes) */
int r = fread(s + begin, 1, end - begin, fp);
if (r < end - begin) {
/* reached end of file */
end = begin + r;
break;
}
/* s is full and we have not reached end of file.
we extend s by 10 bytes */
begin = end;
end += 10;
char *t = (char *)malloc(end); /* new buffer */
assert(t);
bcopy(s, t, end);
s = t;
}
/* print s from end to beginning */
int i;
for (i = end - 1; i >= 0; i--) {
putchar(s[i]);
}
free(s);
return 0;
}
|
the_stack_data/187644145.c | #include<stdio.h>
int main()
{
int i,ceil,floor;
double n;
while(scanf("%lf", &n)){
floor = (int)n;
if(floor == n){
ceil = floor;
}
else{
ceil = floor+1;
}
printf("%d %d\n", floor, ceil);
}
return 0;
}
|
the_stack_data/126704087.c | #include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<malloc.h>
#include<stdbool.h>
//数据结构
typedef
struct MyStruct
{
int* Allocated;
int* MaxNeed;
int* StillRequest;
bool search;
} Process;
#define Max 17 //已分配资源最大上限
#define Min 3 //已分配资源下限
#define times_one 1.7 //最大需求资源与已分配资源比例
#define times_two 1.2 //系统总资源与最大资源比例
Process* Pro;
int* Sysava;
int* secure_sequence;
int SUM[3];
void GetDataReady(int ProcessNum,int SourceNum)//进程资源初始化,包括初始已分配资源,最大需要资源,还需资源,系统资源
{
int i = 0, j = 0, temper = 0;
int seed = 0;
int temp = 0;
int sum = 0;
seed = clock()*clock()*clock()*clock()*time(NULL);
srand(seed);
Pro = (Process*)malloc(sizeof(Process)*ProcessNum);
Sysava = (int*)calloc(sizeof(int), SourceNum);
secure_sequence = (int *)malloc(sizeof(int)*ProcessNum);
for (i=0; i < ProcessNum; i++)
{
Pro[i].search = true;
Pro[i].Allocated = (int *)calloc(sizeof(int),SourceNum);
Pro[i].MaxNeed = (int *)calloc(sizeof(int),SourceNum);
Pro[i].StillRequest = (int *)calloc(sizeof(int),SourceNum);
for (j = 0; j < SourceNum; j++)
{
temp = rand() % (Max - Min + 1) + Min;
Pro[i].Allocated[j] = temp;
// printf_s("%d ", temp);
temp = rand() % (int)(Max*times_one - temp + 1) +temp;
Pro[i].MaxNeed[j] = temp;
Pro[i].StillRequest[j] = Pro[i].MaxNeed[j] - Pro[i].Allocated[j] + 3;
}
// printf_s("\n");
}
for (i = 0; i < SourceNum; i++)
{
j = 0;
temp = Pro[j].MaxNeed[0] - Pro[j].Allocated[0];
for (; j < ProcessNum; j++)
{
sum += Pro[j].Allocated[i];
if (Pro[j].MaxNeed[i] - Pro[j].Allocated[i] < temp)
temp = Pro[j].MaxNeed[i] - Pro[j].Allocated[i];
}
temper = rand() % (int)(times_two * (sum + temp ) - (sum + temp) + 1) + ((sum + temp));
Sysava[i] = temper;
Sysava[i] = Sysava[i] - sum;
SUM[i] = sum;
temp = 0;
temper = 0;
sum = 0;
}
/*for (i = 0; i < SourceNum; i++)
{
printf_s("%2d ", Sysava[i]);
}
printf_s("\n");*/
}
int SouceCheck(int *request,int SourceNum)
{
int i = 0;
for (i=0; i < SourceNum; i++)
{
//printf_s("request[SourceNum]=%d", request[SourceNum]);
if (request[i] > Pro[request[SourceNum]].StillRequest[i])
{
// printf_s("资源请求判断===%d====", Pro[request[SourceNum]].StillRequest[i]);
printf_s("资源请求不合法\n");
return 0;
}
}
return 1;
}
int Solve(int *request, int ProcessNum, int SourceNum)//解决问题
{
int i = 0, j = 0, m = 0, k = 0;
int solvenum = 0,circle=0;
bool flag = false;
secure_sequence = (int *)calloc(sizeof(int), ProcessNum);
int* temp = (int*)calloc(sizeof(int), ProcessNum);//结果序列,临时存储
int* systemp = (int*)calloc(sizeof(int), SourceNum);//系统资源状态
for (i = 0; i < ProcessNum; i++)
{
for (j = 0; j < SourceNum; j++)
{
printf_s("%2d ", Pro[i].Allocated[j]);
}
printf_s("---------------");
for (j = 0; j < SourceNum; j++)
{
printf_s("%2d ", Pro[i].MaxNeed[j]);
}
printf_s("--------------");
for (j = 0; j < SourceNum; j++)
{
printf_s("%2d ", Pro[i].StillRequest[j]);
}
printf_s("\n");
}
for (i = 0; i < SourceNum; i++)
{
printf_s("%2d ", Sysava[i]);
systemp[i] = Sysava[i];
}
printf_s("\n");
for (m = 0; m < ProcessNum; m++)
{
if (!Pro[m].search)
continue;
for (i = 0; i < SourceNum; i++)
{
if (Pro[m].StillRequest[i] > systemp[i])
{
flag = true;
break;
}
}
if (flag)
{
flag = false;
continue;
}
secure_sequence[solvenum] = m;
// printf_s("m== %d", m);
solvenum += 1;
for (i = 0; i < SourceNum; i++)
{
systemp[i] += Pro[m].Allocated[i];
Pro[m].StillRequest[i] = 0;
}
Pro[m].search = false;
m = -1;
}
if (solvenum == ProcessNum)
return 1;
else
{
return 0;
}
for (m = 0; m < SourceNum; m++)
{
if (Sysava[m] < 0) return 0;
}
//
}
void Show(int Processnum)//
{
int i = 0;
printf_s("\n");
for (; i < Processnum - 1; i++)
printf_s("%d------>", secure_sequence[i]+1);
printf_s("%d", secure_sequence[Processnum-1]+1);
}
int main()
{
int p_num = 5, s_num = 4;
int *request = (int *)calloc(sizeof(int), s_num + 1);
request[0] = 2;
request[1] = 4;
request[2] = 3;//表示请求的三种资源对应的个数
request[3] = 1;//表示编号为2(第三个资源)发出了请求
request[4] = 2;
/*GetDataReady(p_num, s_num);
while (!SouceCheck(request, s_num))
{
GetDataReady(p_num, s_num);
}
*/
do
{
GetDataReady(p_num, s_num);
while (!SouceCheck(request, s_num))
{
GetDataReady(p_num, s_num);
}
} while (!Solve(request, p_num, s_num));
Show(p_num);
scanf_s(" ");
} |
the_stack_data/41462.c | /* Copyright (c) 2019 CSC Training */
/* Copyright (c) 2021 ENCCS */
#include <stdio.h>
#include <math.h>
#define NX 102400
int main(void)
{
double vecA[NX],vecB[NX],vecC[NX];
double r=0.2;
/* Initialization of vectors */
for (int i = 0; i < NX; i++) {
vecA[i] = pow(r, i);
vecB[i] = 1.0;
}
/* dot product of two vectors */
#pragma omp target teams distribute
for (int i = 0; i < NX; i++) {
vecC[i] = vecA[i] * vecB[i];
}
double sum = 0.0;
/* calculate the sum */
for (int i = 0; i < NX; i++) {
sum += vecC[i];
}
printf("The sum is: %8.6f \n", sum);
return 0;
}
|
the_stack_data/66324.c | #include <stdio.h>
#pragma warning(disable : 4996)
int AddToTotal(int num){
static int total = 0;
total += num;
return total;
}
int main(void) {
int num, i;
for (i = 0; i < 3; i++) {
printf("enter %d:", i + 1);
scanf("%d", &num);
printf("total: %d\n", AddToTotal(num));
}
getch();
return 0;
} |
the_stack_data/95449811.c | #include <stdio.h>
int count(FILE *f);
int main(int argc, char **argv)
{
float num_1, num_2;
FILE *f, *g;
g = fopen("Out.txt", "w");
if (argc == 1)
{
fprintf(g, "No file name input!");
}
else
{
f = fopen(argv[1], "r");
if (!f)
fprintf(g, "File is not existed!");
else
{
if (fscanf(f, "%f%f", &num_1, &num_2) < 2)
fprintf(g, "File does not contain enough numbers!");
else
{
fprintf(g, "Number elements bigger than average(min, max): %d", count(f));
}
fclose(f);
}
}
fclose(g);
return 0;
}
|
the_stack_data/120819.c | #include <stdio.h>
int binarySearch(int arr[], int l, int index, int x)
{
if (index >= l) {
int mid = l + (index - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, index, x);
}
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
|
the_stack_data/243893392.c | #include <stdio.h>
#include <string.h> // for memset
int main()
{
char dataString[1023];
memset(dataString, 0, sizeof(dataString));
int i = 0;
while(1)
{
char c = getchar();
if(c == '.' || i > sizeof(dataString)/sizeof(dataString[0])) break;
else
{
dataString[i]=c;
if(i % 2 == 0) dataString[i]++;
else dataString[i]--;
i++;
}
}
printf("%s\n", dataString);
return 0;
}
|
the_stack_data/884243.c | #include <stdio.h>
#include <stdlib.h>
void toBin(int);
void toOct(int);
void toHex(int);
int main(){
printf("DECIM\t\tBINARIO\t\tOTTALE\t\tESADECIMALE\n");
for(int cnt = 1; cnt <= 20; cnt++ ){
printf("%d\t\t", cnt);
toBin(cnt);
printf("\t\t");
toOct(cnt);
printf("\t\t");
toHex(cnt);
printf("\n");
}
return 0;
}
void toBin(int num){
int numBin;
int resto;
int cnt = 1;
numBin = 0;
while(num != 0){
resto = num % 2;
numBin = (resto * cnt) + numBin;
num = num / 2;
cnt = cnt * 10;
}
printf("%d", numBin);
}
void toOct(int num){
int numOct;
int resto;
int cnt = 1;
numOct = 0;
while(num != 0){
resto = num % 8;
numOct = (resto * cnt) + numOct;
num = num / 8;
cnt = cnt * 10;
}
printf("%d", numOct);
}
void toHex(int num){
char *numHex;
int resto;
int cnt = 0;
int sentinella = num;
numHex = (char *)calloc(cnt, sizeof(int));
while(num != 0){
numHex = realloc(numHex, (cnt + 1) * sizeof(int));
resto = num % 16;
if(resto < 10){
resto = resto + 48;
} else {
resto = resto + 55;
}
numHex[cnt] = resto;
cnt++;
num = num / 16;
}
for(int cont = cnt - 1; cont >= 0; cont--){
printf("%c", numHex[cont]);
}
free(numHex);
} |
the_stack_data/154829134.c | #include <stdio.h>
int main()
{
double firstNumber, secondNumber, temp;
printf("Enter two number:\n");
scanf("%lf %lf", &firstNumber, &secondNumber);
temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
printf("After the swapping, A = %.2lf\n", firstNumber);
printf("After the swapping, B = %.2lf\n", secondNumber);
firstNumber = firstNumber - secondNumber;
secondNumber = firstNumber + secondNumber;
firstNumber = secondNumber - firstNumber;
printf("After the swapping, A = %.2lf\n", firstNumber);
printf("After the swapping, B = %.2lf\n", secondNumber);
return 0;
}
/*
Output:
Enter two number:
17 -199
After the swapping, A = -199.00
After the swapping, B = 17.00
After the swapping, A = 17.00
After the swapping, B = -199.00
*/
|
the_stack_data/79268.c | #include <stdio.h>
int main()
{
int age = 10;
int height = 72;
char name[100];
printf("I am %d years old.\n", age);
printf("I am %d inches tall.\n", height);
printf("Enter your name: ");
scanf("%s", name);
printf( "\nYou entered: %s ", name);
return 0;
}
|
the_stack_data/6429.c | /*
--------------------------------------------------
James William Fletcher ([email protected])
--------------------------------------------------
r_picmip 16 & force models to blue bones
You don't have to set `r_picmip` to 16 or above
but it does help.
You will however need to set `cg_forceModel 1`
and select a player model with uniform colour,
and I do consider the bright blue bones model
to be the best option. This is important for
the colour aimbot detections which train the
perceptrons.
This is created to only run on Linux under X11.
I created this initially because I just wanted
something fun to do, and I love playing Quake3
Instagib.
When I started looking into CNN's
such as AlexNet I decided I wanted to have a
go at a simple Perceptron implementation, thus
expanding on this project. I was supprised to
see gradient descent do such a good job.
Tested using the ioQuake3 client.
https://ioquake3.org/
--------------------------------------------------
Recommended Client Settings
--------------------------------------------------
cg_oldRail "1"
cg_noProjectileTrail "1"
cg_forceModel "1"
cg_railTrailTime "100"
cg_crosshairSize "24"
cg_drawFPS "1"
cg_draw2D "1"
cg_gibs "1"
cg_fov "160"
cg_zoomfov "90"
cg_drawGun "1"
cg_brassTime "0"
cg_drawCrosshair "7"
cg_drawCrosshairNames "1"
cg_marks "0"
cg_crosshairPulse "1"
cg_stepTime "100"
cg_centertime "3"
xp_noParticles "1"
xp_noShotgunTrail "1"
xp_noMip "2047"
xp_ambient "1"
xp_modelJump "0"
xp_corpse "3"
xp_crosshairColor "7"
xp_improvePrediction "1"
cm_playerCurveClip "1"
com_maxfps "600"
com_blood "0"
cg_autoswitch "0"
rate "25000"
snaps "40"
model "bones/default"
headmodel "bones/default"
team_model "bones/default"
team_headmodel "bones/default"
color1 "6"
color2 "5"
cg_predictItems "1"
r_picmip "16"
r_overBrightBits "1"
r_mode "-2"
r_fullscreen "1"
r_customwidth "1920"
r_customheight "1080"
r_simpleMipMaps "1"
r_railWidth "16"
r_railCoreWidth "6"
r_railSegmentLength "32"
cg_shadows "0"
com_zoneMegs "24"
com_hunkmegs "512"
--------------------------------------------------
^ Thats how I like to configure my Quake 3 client.
--------------------------------------------------
--------------------------------------------------
~~ MLP - Multi-Layer Perceptron learning ~~
--------------------------------------------------
- There is traditional Colour aim which is used to train
the perceptron based models.
- The "Deep Aim" option actually uses a MLP rather than
a DNN.
- The Neural Aim option only uses one perceptron per
pixel.
- To quickly train the MLP / Perceptrons just load a
a local server full of bots on extreme difficulty,
then go into first person spectator mode and leave
the colour autoshoot turned on. It will now flick
between bot views every time it detects a target.
Quake 3 always has been a game dominated by cheaters
augmenting their skills with bots, console commands,
wider fov, better gaming hardware, anything to gain
a competative advantage.
I can confidently say that most people playing on the
traditional servers are cheating to some extent, most
popularly is the autoshoot bot to the point now that
it should just be a built-in function of the game.
I have seen the owner of Elitez (https://elitez.eu)
servers using an autoshoot bot once himself while
configuring the server's anti-cheat system which will
boot you if you lower or remove the 100ms wait between
mouse triggers.
There is a simpler version of this bot which I uploaded to:
https://www.youtube.com/channel/UCYe31SWsmK3X9H3r1WM6OKQ
This just features Neural Aim.
--------------------------------------------------
~~ Notes ~~
--------------------------------------------------
- This bot only trains in Colour Aim or Neural Aim modes.
- This bot stops training itself in Deep Aim mode.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
/***************************************************
~~ Utils
*/
//https://www.cl.cam.ac.uk/~mgk25/ucs/keysymdef.h
int key_is_pressed(KeySym ks)
{
Display *dpy = XOpenDisplay(":0");
char keys_return[32];
XQueryKeymap(dpy, keys_return);
KeyCode kc2 = XKeysymToKeycode(dpy, ks);
int isPressed = !!(keys_return[kc2 >> 3] & (1 << (kc2 & 7)));
XCloseDisplay(dpy);
return isPressed;
}
void playTone()
{
if(system("/usr/bin/aplay --quiet /usr/share/sounds/a.wav") <= 0)
sleep(1);
}
void speakS(const char* text)
{
char s[256];
sprintf(s, "/usr/bin/espeak \"%s\"", text);
if(system(s) <= 0)
sleep(1);
}
void speakI(const int i)
{
char s[256];
sprintf(s, "/usr/bin/espeak %i", i);
if(system(s) <= 0)
sleep(1);
}
void speakF(const double f)
{
char s[256];
sprintf(s, "/usr/bin/espeak %.1f", f);
if(system(s) <= 0)
sleep(1);
}
/***************************************************
~~ Perceptron
*/
const unsigned int _nquality = 0; // 0 - low, 1 - high
double _probability = 0.7; // Minimum Probability from Neuron before Attacking
const double _lrate = 0.3; // Learning Rate
double pw[32][16] = {0};
float qRandFloat(const float min, const float max)
{
static time_t ls = 0;
if(time(0) > ls)
{
srand(time(0));
ls = time(0) + 33;
}
const float rv = (float)rand();
if(rv == 0)
return min;
return ( (rv / RAND_MAX) * (max-min) ) + min;
}
void randomWeights()
{
for(int i = 0; i < 32; i++)
for(int i2 = 0; i2 < 16; i2++)
pw[i][i2] = qRandFloat(-1, 1);
}
void dumpWeights()
{
printf("Weight Dump:\n");
for(int i = 0; i < 32; i++)
printf("%u: %f %f %f %f %f %f %f %f %f %f %f %f\n", i, pw[i][0], pw[i][1], pw[i][2], pw[i][3], pw[i][4], pw[i][5], pw[i][6], pw[i][7], pw[i][8], pw[i][9], pw[i][10], pw[i][11]);
}
void softmax_transform(double* w, const uint32_t n)
{
double d = 0;
for(size_t i = 0; i < n; i++)
d += exp(w[i]);
for(size_t i = 0; i < n; i++)
w[i] = exp(w[i]) / d;
}
double sigmoid(double x)
{
return 1 / (1 + exp((double) - x));
}
double fastSigmoid(double x)
{
return x / (1 + fabs(x));
}
double doPerceptron(double* in, const uint32_t n, double eo, double* w)
{
//~~ Query perceptron
//Sum inputs mutliplied by weights
double ro = 0;
for(size_t i = 0; i < n; i++)
ro += in[i] * w[i];
//Activation Function
if(_nquality == 1){ro = sigmoid(ro);} //Sigmoid function
if(ro < 0){ro = 0;} //ReLU
//~~ Teach perceptron
if(eo != -1)
{
const double error = eo - ro; //Error Gradient
for(size_t i = 0; i < n; i++)
w[i] += error * in[i] * _lrate;
}
//~~ Return output
return ro;
}
double doDeepResult(double* in, double eo)
{
//Output Array to Final Neuron
#define outputs 10
double h[outputs] = {0};
//Quaterize the 3x3 into 2x2x4
h[0] = doPerceptron((double[]){in[4], in[1], in[3], in[0]}, 4, eo, pw[9]);
h[1] = doPerceptron((double[]){in[4], in[1], in[2], in[5]}, 4, eo, pw[10]);
h[2] = doPerceptron((double[]){in[4], in[7], in[6], in[3]}, 4, eo, pw[11]);
h[3] = doPerceptron((double[]){in[4], in[7], in[8], in[5]}, 4, eo, pw[12]);
//3x3 to 1x3
h[4] = doPerceptron((double[]){in[0], in[1], in[2]}, 3, eo, pw[13]);
h[5] = doPerceptron((double[]){in[3], in[4], in[5]}, 3, eo, pw[14]);
h[6] = doPerceptron((double[]){in[6], in[7], in[8]}, 3, eo, pw[15]);
//3x3 to 1x3
h[7] = doPerceptron((double[]){in[0], in[3], in[6]}, 3, eo, pw[16]);
h[8] = doPerceptron((double[]){in[1], in[4], in[7]}, 3, eo, pw[17]);
h[9] = doPerceptron((double[]){in[2], in[5], in[8]}, 3, eo, pw[18]);
//Softmax before the final deciding neuron
if(_nquality == 1)
softmax_transform(h, outputs);
//Final neuron
return doPerceptron(h, outputs, eo, pw[19]);
}
/***************************************************
~~ Program Entry Point
*/
int main()
{
printf("James William Fletcher ([email protected])\nSet r_picmip 9 or higher\n & force player models ON\n & set your player model to aqua blue bones\n & select the only aiming reticule/cursor that doesnt obstruct the center of the screen\n\nKey-Mapping's:\nF10 - Preset Max Tollerance\nUP - Preset Medium Tollerance\nDOWN - Preset Low Tollerence\nLEFT - Manual Lower Tollerance\nRIGHT - Manual Higher Tollerance\n\nH - Retrain/Target on current center screen colour\nG - Same as H but uses an average of 9 surrounding colours\n\nF1 - Target Aqua Blue\nF2 - Target Blue\nF3 - Target Red\n\nLeft CTRL + Left ALT - Enable/Disable Auto-Shoot\n\nB - Deep Aim Only\nN - Neural Aim Only (trains Neural Net)\nM - Colour Aim Only (trains Neural Net)\n\nK - Reduce Neural Firing Probability\nL - Increase Neural Firing Probability\n\nR - Randomize Perceptron Weights\n\n");
//Variables
unsigned short lr=0, lg=0, lb=0;
unsigned short tr=57753,tg=65535,tb=65535;
unsigned short tol = 14000;
XColor c[9];
Display *d;
int si;
unsigned int x=0, y=0;
XEvent event;
memset(&event, 0x00, sizeof(event));
unsigned int enable = 0;
unsigned int mode = 2;
unsigned int liter = 0;
unsigned int pc = 0;
while(1)
{
//Loop every 10 ms (1,000 microsecond = 1 millisecond)
usleep(10000);
//Inputs / Keypress
if(key_is_pressed(XK_Control_L) && key_is_pressed(XK_Alt_L))
{
if(enable == 0)
{
enable = 1;
printf("\a\n");
usleep(300000);
printf("\aAUTO-SHOOT: ON\n");
speakS("on");
}
else
{
enable = 0;
printf("\aAUTO-SHOOT: OFF\n");
speakS("off");
}
}
//Enable / Disable entire bot
if(enable == 1)
{
//Open Display 0
d = XOpenDisplay((char *) NULL);
if(d == NULL)
continue;
//Get default screen
si = XDefaultScreen(d);
//Reset mouse event
memset(&event, 0x00, sizeof(event));
if(key_is_pressed(XK_Left))
{
tol -= 100;
printf("\aTOL: %i\n", tol);
pc++;
if(pc > 5)
{
pc = 0;
speakI(tol);
}
else
{
playTone();
}
}
if(key_is_pressed(XK_Right))
{
tol += 100;
printf("\aTOL: %i\n", tol);
pc++;
if(pc > 5)
{
pc = 0;
speakI(tol);
}
else
{
playTone();
}
}
if(key_is_pressed(XK_Down))
{
tol = 7333;
printf("\aTOL: %i\n", tol);
speakI(tol);
}
if(key_is_pressed(XK_Up))
{
tol = 14000;
printf("\aTOL: %i\n", tol);
speakI(tol);
}
if(key_is_pressed(XK_F10))
{
tol = 26000;
printf("\aTOL: %i\n", tol);
speakI(tol);
}
if(key_is_pressed(XK_F1)) //Aqua Blue
{
tr=57753; //53827 - 61680
tg=65535;
tb=65535;
printf("\a:: Aqua Blue\n");
speakS("Aqua Blue");
}
if(key_is_pressed(XK_F2)) //Blue
{
tr=18247;
tg=5397;
tb=37265;
printf("\a:: Blue\n");
speakS("Blue");
}
if(key_is_pressed(XK_F3)) //Red
{
tr=37265;
tg=4883;
tb=4112;
printf("\a:: Red\n");
speakS("Red");
}
if(key_is_pressed(XK_F4)) //Red 2
{
tr=35094;
tg=9766;
tb=3712;
printf("\a:: Red 2\n");
speakS("Red 2");
}
if(key_is_pressed(XK_F5))
{
tr=5482;
tg=65535;
tb=65535;
printf("\a:: OpenArena Blue\n");
speakS("Open Arena Blue");
}
if(key_is_pressed(XK_F6))
{
tr=65535;
tg=6453;
tb=0;
printf("\a:: OpenArena Red\n");
speakS("Open Arena Red");
}
if(key_is_pressed(XK_F7))
{
tr=65535;
tg=65535;
tb=65535;
printf("\a:: OpenArena White\n");
speakS("Open Arena White");
}
if(key_is_pressed(XK_B))
{
mode = 0;
printf("\aDeep Aim\n");
dumpWeights();
speakS("Deep Aim");
}
if(key_is_pressed(XK_N))
{
mode = 1;
printf("\aNeural Aim\n");
speakS("Neural Aim");
}
if(key_is_pressed(XK_M))
{
mode = 2;
printf("\aColour Aim\n");
speakS("Colour Aim");
}
if(key_is_pressed(XK_K))
{
_probability -= 0.1;
if(_probability < 0)
{
_probability = 0;
}
else
{
printf("\aProbability: %.2f\n", _probability);
speakF(_probability);
}
}
if(key_is_pressed(XK_L))
{
_probability += 0.1;
if(_probability > 6)
{
_probability = 6;
}
else
{
printf("\aProbability: %.2f\n", _probability);
speakF(_probability);
}
}
if(key_is_pressed(XK_J))
{
randomWeights();
speakS("Weights Randomised");
}
//Ready to press down mouse 1
event.type = ButtonPress;
event.xbutton.button = Button1;
event.xbutton.same_screen = True;
//Find target window
XQueryPointer(d, RootWindow(d, si), &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
event.xbutton.subwindow = event.xbutton.window;
while(event.xbutton.subwindow)
{
event.xbutton.window = event.xbutton.subwindow;
XQueryPointer(d, event.xbutton.window, &event.xbutton.root, &event.xbutton.subwindow, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
}
//Get Center Window
XWindowAttributes attr;
XGetWindowAttributes(d, event.xbutton.window, &attr);
x = attr.width/2;
y = attr.height/2;
//Get Image Block
XImage *i = XGetImage(d, event.xbutton.window, x-1, y-1, 3, 3, AllPlanes, XYPixmap);
if(i == NULL)
{
XCloseDisplay(d);
continue;
}
//Get Pixels
c[0].pixel = XGetPixel(i, 0, 0);
c[1].pixel = XGetPixel(i, 1, 0);
c[2].pixel = XGetPixel(i, 2, 0);
c[3].pixel = XGetPixel(i, 0, 1);
c[4].pixel = XGetPixel(i, 1, 1);
c[5].pixel = XGetPixel(i, 2, 1);
c[6].pixel = XGetPixel(i, 0, 2);
c[7].pixel = XGetPixel(i, 1, 2);
c[8].pixel = XGetPixel(i, 2, 2);
XFree(i);
//Get Colour Map
const Colormap map = XDefaultColormap(d, si);
//printf("M: %li %li\n", map, c[0].pixel);
//https://thestarman.pcministry.com/asm/6to64bits.htm
int ti = 0;
for(int i = 0; i < 9; i++)
if(c[0].pixel >= 16777216)
ti = 1;
if(ti == 1)
{
XCloseDisplay(d);
continue;
}
//For each pixel ...
int phi = 0;
int bhi = 0;
int shots = 0;
if(mode != 0)
{
for(int i = 0; i < 9; i++)
{
XQueryColor(d, map, &c[i]);
const unsigned short r = c[i].red;
const unsigned short g = c[i].green;
const unsigned short b = c[i].blue;
//Shoot if colour has locked on
int fire = 0;
if(mode == 2)
if(r > tr-tol && r < tr+tol && g > tg-tol && g < tg+tol && b > tb-tol && b < tb+tol)
fire = 1;
if(mode == 1)
{
const double ghit = doPerceptron((double[]){r/65535, g/65535, b/65535}, 3, -1, pw[i]);
if(ghit > _probability)
fire = 1;
}
if(fire == 1)
{
//Fire mouse down
XSendEvent(d, PointerWindow, True, 0xfff, &event);
XFlush(d);
//Wait 100ms (or ban for suspected cheating)
usleep(100000);
//Release mouse down
event.type = ButtonRelease;
event.xbutton.state = 0x100;
XSendEvent(d, PointerWindow, True, 0xfff, &event);
XFlush(d);
//printf("Colour Hit");
//Train Perceptron
const double hit = doPerceptron((double[]){r/65535, g/65535, b/65535}, 3, 1, pw[i]);
if(hit > 0)
{
//printf(", Perceptron Hit: %u, %lf", i, hit);
phi++;
}
//printf("\n");
liter++;
printf("LI: %u\n", liter);
shots++;
}
else
{
const double hit = doPerceptron((double[]){r/65535, g/65535, b/65535}, 3, 0, pw[i]);
if(hit > 0)
{
//printf("Bad Hit: %u, %lf\n", i, hit);
bhi++;
}
}
}
}
/*if(phi > 0)
printf("Total Good: %u / 9\n", phi);
if(bhi > 0)
printf("Total bad: %u / 9\n", bhi);*/
//Train DeepAim
if(mode != 0)
{
if(shots > 0)
{
//Compute Per Pixel Neuron outputs
double p[9]={0};
for(int i = 0; i < 9; i++)
{
XQueryColor(d, map, &c[i]);
const double r = c[i].red / 65535;
const double g = c[i].green / 65535;
const double b = c[i].blue / 65535;
p[i] = doPerceptron((double[]){r, g, b}, 3, -1, pw[i]);
}
//Compute the deep result
doDeepResult(p, 1);
}
else
{
//Compute Per Pixel Neuron outputs
double p[9]={0};
for(int i = 0; i < 9; i++)
{
XQueryColor(d, map, &c[i]);
const double r = c[i].red / 65535;
const double g = c[i].green / 65535;
const double b = c[i].blue / 65535;
p[i] = doPerceptron((double[]){r, g, b}, 3, -1, pw[i]);
}
//Compute the deep result
doDeepResult(p, 0);
}
}
//Deep Aim
if(mode == 0)
{
//Compute Per Pixel Neuron outputs
double p[9]={0};
for(int i = 0; i < 9; i++)
{
XQueryColor(d, map, &c[i]);
const double r = c[i].red / 65535;
const double g = c[i].green / 65535;
const double b = c[i].blue / 65535;
p[i] = doPerceptron((double[]){r, g, b}, 3, -1, pw[i]);
}
//Query Deep Result
const double deep_result = doDeepResult(p, -1);
//If the neuron/perceptron says fire, fire !
if(deep_result > _probability)
{
//Fire mouse down
XSendEvent(d, PointerWindow, True, 0xfff, &event);
XFlush(d);
//Wait 100ms (or ban for suspected cheating)
usleep(100000);
//Release mouse down
event.type = ButtonRelease;
event.xbutton.state = 0x100;
XSendEvent(d, PointerWindow, True, 0xfff, &event);
XFlush(d);
}
}
//Center Pixel Target
if(key_is_pressed(XK_H))
{
tr = c[4].red;
tg = c[4].green;
tb = c[4].blue;
printf("\aH-SET: %i %i %i\n", tr, tg, tb);
playTone();
}
//Average Target
if(key_is_pressed(XK_G))
{
tr = (c[0].red + c[1].red + c[2].red + c[3].red + c[4].red + c[5].red + c[6].red + c[7].red + c[8].red) / 9;
tg = (c[0].green + c[1].green + c[2].green + c[3].green + c[4].green + c[5].green + c[6].green + c[7].green + c[8].green) / 9;
tb = (c[0].blue + c[1].blue + c[2].blue + c[3].blue + c[4].blue + c[5].blue + c[6].blue + c[7].blue + c[8].blue) / 9;
printf("\aG-SET: %i %i %i\n", tr, tg, tb);
playTone();
}
//Close the display
XCloseDisplay(d);
}
}
//Done, never gets here in regular execution flow
return 0;
}
|
the_stack_data/3262139.c | struct point { int x, y; };
void foobar()
{
// These must be constants in there were in global scope (see test2016_18.c).
const int xvalue = 1;
const int yvalue = 1;
struct point p = { .y = yvalue, .x = xvalue };
}
|
the_stack_data/190117.c | /******************************************************************************
* The MIT License
*
* Copyright (c) 2010 Michael Hope.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*****************************************************************************/
#ifdef STM32F4
/**
* @file dmaF4.c
* @brief Direct Memory Access peripheral support
*/
#include "dma.h"
#include "bitband.h"
#include "util.h"
/*
* Devices
*/
static dma_dev dma1 = {
.regs = DMA1_BASE,
.clk_id = RCC_DMA1,
.handlers = {{ .handler = NULL, .irq_line = 11 },
{ .handler = NULL, .irq_line = 12 },
{ .handler = NULL, .irq_line = 13 },
{ .handler = NULL, .irq_line = 14 },
{ .handler = NULL, .irq_line = 15 },
{ .handler = NULL, .irq_line = 16 },
{ .handler = NULL, .irq_line = 17 },
{ .handler = NULL, .irq_line = 47 }}
};
/** DMA1 device */
dma_dev *DMA1 = &dma1;
static dma_dev dma2 = {
.regs = DMA2_BASE,
.clk_id = RCC_DMA2,
.handlers = {{ .handler = NULL, .irq_line = 56 },
{ .handler = NULL, .irq_line = 57 },
{ .handler = NULL, .irq_line = 58 },
{ .handler = NULL, .irq_line = 59 },
{ .handler = NULL, .irq_line = 60 },
{ .handler = NULL, .irq_line = 68 },
{ .handler = NULL, .irq_line = 69 },
{ .handler = NULL, .irq_line = 70 }} /* !@#$ */
};
/** DMA2 device */
dma_dev *DMA2 = &dma2;
/*
* Convenience routines
*/
/**
* @brief Initialize a DMA device.
* @param dev Device to initialize.
*/
void dma_init(dma_dev *dev) {
rcc_clk_enable(dev->clk_id);
}
/**
* @brief Attach an interrupt to a DMA transfer.
*
* Interrupts are enabled using appropriate mode flags in
* dma_setup_transfer().
*
* @param dev DMA device
* @param stream Stream to attach handler to
* @param handler Interrupt handler to call when channel interrupt fires.
* @see dma_setup_transfer()
* @see dma_detach_interrupt()
*/
void dma_attach_interrupt(dma_dev *dev,
dma_stream stream,
void (*handler)(void)) {
dev->handlers[stream].handler = handler;
nvic_irq_enable(dev->handlers[stream].irq_line);
}
/**
* @brief Detach a DMA transfer interrupt handler.
*
* After calling this function, the given channel's interrupts will be
* disabled.
*
* @param dev DMA device
* @param stream Stream whose handler to detach
* @sideeffect Clears interrupt enable bits in the channel's CCR register.
* @see dma_attach_interrupt()
*/
void dma_detach_interrupt(dma_dev *dev, dma_stream stream) {
nvic_irq_disable(dev->handlers[stream].irq_line);
dev->handlers[stream].handler = NULL;
}
const uint8 dma_isr_bits_shift[] = { 0, 6, 16, 22};
uint8 dma_get_isr_bit(dma_dev *dev, dma_stream stream, uint8_t mask) {
if ( stream&0xFC ) return ((dev->regs->HISR)>>dma_isr_bits_shift[stream&0x03]) & mask;
else return ((dev->regs->LISR)>>dma_isr_bits_shift[stream&0x03]) & mask;
}
void dma_clear_isr_bit(dma_dev *dev, dma_stream stream, uint8_t mask) {
if ( stream&0xFC ) dev->regs->HIFCR = (uint32)mask << dma_isr_bits_shift[stream&0x03];
else dev->regs->LIFCR = (uint32)mask << dma_isr_bits_shift[stream&0x03];
}
/*
* IRQ handlers
*/
static inline void dispatch_handler(dma_dev *dev, dma_stream stream) {
void (*handler)(void) = dev->handlers[stream].handler;
if (handler) {
handler();
dma_clear_isr_bits(dev, stream); /* in case handler doesn't */
}
}
//void __irq_dma1_stream0(void) {
void __irq_dma1_channel1(void) {
dispatch_handler(DMA1, DMA_STREAM0);
}
//void __irq_dma1_stream1(void) {
void __irq_dma1_channel2(void) {
dispatch_handler(DMA1, DMA_STREAM1);
}
//void __irq_dma1_stream2(void) {
void __irq_dma1_channel3(void) {
dispatch_handler(DMA1, DMA_STREAM2);
}
//void __irq_dma1_stream3(void) {
void __irq_dma1_channel4(void) {
dispatch_handler(DMA1, DMA_STREAM3);
}
//void __irq_dma1_stream4(void) {
void __irq_dma1_channel5(void) {
dispatch_handler(DMA1, DMA_STREAM4);
}
//void __irq_dma1_stream5(void) {
void __irq_dma1_channel6(void) {
dispatch_handler(DMA1, DMA_STREAM5);
}
//void __irq_dma1_stream6(void) {
void __irq_dma1_channel7(void) {
dispatch_handler(DMA1, DMA_STREAM6);
}
//void __irq_dma1_stream7(void) {
void __irq_adc3(void) {
dispatch_handler(DMA1, DMA_STREAM7);
}
//void __irq_dma2_stream0(void) {
void __irq_dma2_channel1(void) {
dispatch_handler(DMA2, DMA_STREAM0);
}
//void __irq_dma2_stream1(void) {
void __irq_dma2_channel2(void) {
dispatch_handler(DMA2, DMA_STREAM1);
}
//void __irq_dma2_stream2(void) {
void __irq_dma2_channel3(void) {
dispatch_handler(DMA2, DMA_STREAM2);
}
//void __irq_dma2_stream3(void) {
void __irq_dma2_channel4_5(void) {
dispatch_handler(DMA2, DMA_STREAM3);
}
//void __irq_dma2_stream4(void) {
void __irq_DMA2_Stream4_IRQHandler(void) {
dispatch_handler(DMA2, DMA_STREAM4);
}
//void __irq_dma2_stream5(void) {
void __irq_DMA2_Stream5_IRQHandler(void) {
dispatch_handler(DMA2, DMA_STREAM5);
}
//void __irq_dma2_stream6(void) {
void __irq_DMA2_Stream6_IRQHandler(void) {
dispatch_handler(DMA2, DMA_STREAM6);
}
//void __irq_dma2_stream7(void) {
void __irq_DMA2_Stream7_IRQHandler(void) {
dispatch_handler(DMA2, DMA_STREAM7);
}
#endif
|
the_stack_data/13579.c | #if 0
//ARGS: symbols --explain --locate */
//SYSCODE: = 16 | 2 | 1 */
// This pounds on macro expansion for performance reasons. This is currently
// heavily constrained by darwin's malloc.
// Function-like macros.
#define A0(A, B) A B
#define A1(A, B) A0(A,B) A0(A,B) A0(A,B) A0(A,B) A0(A,B) A0(A,B)
#define A2(A, B) A1(A,B) A1(A,B) A1(A,B) A1(A,B) A1(A,B) A1(A,B)
#define A3(A, B) A2(A,B) A2(A,B) A2(A,B) A2(A,B) A2(A,B) A2(A,B)
#define A4(A, B) A3(A,B) A3(A,B) A3(A,B) A3(A,B) A3(A,B) A3(A,B)
/*
#define A5(A, B) A4(A,B) A4(A,B) A4(A,B) A4(A,B) A4(A,B) A4(A,B)
#define A6(A, B) A5(A,B) A5(A,B) A5(A,B) A5(A,B) A5(A,B) A5(A,B)
#define A7(A, B) A6(A,B) A6(A,B) A6(A,B) A6(A,B) A6(A,B) A6(A,B)
#define A8(A, B) A7(A,B) A7(A,B) A7(A,B) A7(A,B) A7(A,B) A7(A,B)
*/
#endif
|
the_stack_data/633085.c | /****************************************************************************
* tools/nxstyle.c
*
* Copyright (C) 2015, 2018-2020 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <limits.h>
#include <unistd.h>
#include <libgen.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define NXSTYLE_VERSION "0.01"
#define LINE_SIZE 512
#define RANGE_NUMBER 4096
#define DEFAULT_WIDTH 78
#define FIRST_SECTION INCLUDED_FILES
#define LAST_SECTION PUBLIC_FUNCTION_PROTOTYPES
#define FATAL(m, l, o) message(FATAL, (m), (l), (o))
#define FATALFL(m, s) message(FATAL, (m), -1, -1)
#define WARN(m, l, o) message(WARN, (m), (l), (o))
#define ERROR(m, l, o) message(ERROR, (m), (l), (o))
#define ERRORFL(m, s) message(ERROR, (m), -1, -1)
#define INFO(m, l, o) message(INFO, (m), (l), (o))
#define INFOFL(m, s) message(INFO, (m), -1, -1)
/****************************************************************************
* Private types
****************************************************************************/
enum class_e
{
INFO,
WARN,
ERROR,
FATAL
};
const char *class_text[] =
{
"info",
"warning",
"error",
"fatal"
};
enum file_e
{
UNKNOWN = 0x00,
C_HEADER = 0x01,
C_SOURCE = 0x02
};
enum section_s
{
NO_SECTION = 0,
INCLUDED_FILES,
PRE_PROCESSOR_DEFINITIONS,
PUBLIC_TYPES,
PRIVATE_TYPES,
PRIVATE_DATA,
PUBLIC_DATA,
PRIVATE_FUNCTIONS,
PRIVATE_FUNCTION_PROTOTYPES,
INLINE_FUNCTIONS,
PUBLIC_FUNCTIONS,
PUBLIC_FUNCTION_PROTOTYPES
};
struct file_section_s
{
const char *name; /* File section name */
uint8_t ftype; /* File type where section found */
};
/****************************************************************************
* Private data
****************************************************************************/
static char *g_file_name = "";
static enum file_e g_file_type = UNKNOWN;
static enum section_s g_section = NO_SECTION;
static int g_maxline = DEFAULT_WIDTH;
static int g_status = 0;
static int g_verbose = 2;
static int g_rangenumber = 0;
static int g_rangestart[RANGE_NUMBER];
static int g_rangecount[RANGE_NUMBER];
static const struct file_section_s g_section_info[] =
{
{
" *\n", /* Index: NO_SECTION */
C_SOURCE | C_HEADER
},
{
" * Included Files\n", /* Index: INCLUDED_FILES */
C_SOURCE | C_HEADER
},
{
" * Pre-processor Definitions\n", /* Index: PRE_PROCESSOR_DEFINITIONS */
C_SOURCE | C_HEADER
},
{
" * Public Types\n", /* Index: PUBLIC_TYPES */
C_HEADER
},
{
" * Private Types\n", /* Index: PRIVATE_TYPES */
C_SOURCE
},
{
" * Private Data\n", /* Index: PRIVATE_DATA */
C_SOURCE
},
{
" * Public Data\n", /* Index: PUBLIC_DATA */
C_SOURCE | C_HEADER
},
{
" * Private Functions\n", /* Index: PRIVATE_FUNCTIONS */
C_SOURCE
},
{
" * Private Function Prototypes\n", /* Index: PRIVATE_FUNCTION_PROTOTYPES */
C_SOURCE
},
{
" * Inline Functions\n", /* Index: INLINE_FUNCTIONS */
C_SOURCE | C_HEADER
},
{
" * Public Functions\n", /* Index: PUBLIC_FUNCTIONS */
C_SOURCE
},
{
" * Public Function Prototypes\n", /* Index: PUBLIC_FUNCTION_PROTOTYPES */
C_HEADER
}
};
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: show_usage
*
* Description:
*
****************************************************************************/
static void show_usage(char *progname, int exitcode, char *what)
{
fprintf(stderr, "%s version %s\n\n", basename(progname), NXSTYLE_VERSION);
if (what)
{
fprintf(stderr, "%s\n", what);
}
fprintf(stderr, "Usage: %s [-m <excess>] [-v <level>] [-r <start,count>] <filename>\n",
basename(progname));
fprintf(stderr, " %s -h this help\n", basename(progname));
fprintf(stderr, " %s -v <level> where level is\n", basename(progname));
fprintf(stderr, " 0 - no output\n");
fprintf(stderr, " 1 - PASS/FAIL\n");
fprintf(stderr, " 2 - output each line (default)\n");
exit(exitcode);
}
/****************************************************************************
* Name: skip
*
* Description:
*
****************************************************************************/
static int skip(int lineno)
{
int i;
for (i = 0; i < g_rangenumber; i++)
{
if (lineno >= g_rangestart[i] && lineno < g_rangestart[i] + g_rangecount[i])
{
return 0;
}
}
return g_rangenumber != 0;
}
/****************************************************************************
* Name: message
*
* Description:
*
****************************************************************************/
static int message(enum class_e class, const char *text, int lineno, int ndx)
{
FILE *out = stdout;
if (skip(lineno))
{
return g_status;
}
if (class > INFO)
{
out = stderr;
g_status |= 1;
}
if (g_verbose == 2)
{
if (lineno == -1 && ndx == -1)
{
fprintf(out, "%s: %s: %s\n", g_file_name, class_text[class], text);
}
else
{
fprintf(out, "%s:%d:%d: %s: %s\n", g_file_name, lineno, ndx,
class_text[class], text);
}
}
return g_status;
}
/****************************************************************************
* Name: check_spaces_left
*
* Description:
*
****************************************************************************/
static void check_spaces_left(char *line, int lineno, int ndx)
{
/* Unary operator should generally be preceded by a space but make also
* follow a left parenthesis at the beginning of a parenthetical list or
* expression or follow a right parentheses in the case of a cast.
*/
if (ndx-- > 0 && line[ndx] != ' ' && line[ndx] != '(' && line[ndx] != ')')
{
ERROR("Operator/assignment must be preceded with whitespace",
lineno, ndx);
}
}
/****************************************************************************
* Name: check_spaces_leftright
*
* Description:
*
****************************************************************************/
static void check_spaces_leftright(char *line, int lineno, int ndx1, int ndx2)
{
if (ndx1 > 0 && line[ndx1 - 1] != ' ')
{
ERROR("Operator/assignment must be preceded with whitespace",
lineno, ndx1);
}
if (line[ndx2 + 1] != '\0' && line[ndx2 + 1] != '\n' && line[ndx2 + 1] != ' ')
{
ERROR("Operator/assignment must be followed with whitespace",
lineno, ndx2);
}
}
/****************************************************************************
* Name: block_comment_width
*
* Description:
* Get the width of a block comment
*
****************************************************************************/
static int block_comment_width(char *line)
{
int b;
int e;
int n;
/* Skip over any leading whitespace on the line */
for (b = 0; isspace(line[b]); b++)
{
}
/* Skip over any trailing whitespace at the end of the line */
for (e = strlen(line) - 1; isspace(line[e]); e--)
{
}
/* Number of characters on the line */
n = e - b + 1;
if (n < 4)
{
return 0;
}
/* The first line of a block comment starts with "[slash]***" and ends with
* "***"
*/
if (strncmp(&line[b], "/***", 4) == 0 &&
strncmp(&line[e - 2], "***", 3) == 0)
{
/* Return the the length of the line up to the final '*' */
return e + 1;
}
/* The last line of a block begins with whitespace then "***" and ends
* with "***[slash]"
*/
if (strncmp(&line[b], "***", 3) == 0 &&
strncmp(&line[e - 3], "***/", 4) == 0)
{
/* Return the the length of the line up to the final '*' */
return e;
}
/* But there is also a special single line comment that begins with "[slash]* "
* and ends with "***[slash]"
*/
if (strncmp(&line[b], "/*", 2) == 0 &&
strncmp(&line[e - 3], "***/", 4) == 0)
{
/* Return the the length of the line up to the final '*' */
return e;
}
/* Return zero if the line is not the first or last line of a block
* comment.
*/
return 0;
}
/****************************************************************************
* Name: get_line_width
*
* Description:
* Get the maximum line width by examining the width of the block comments.
*
****************************************************************************/
static int get_line_width(FILE *instream)
{
char line[LINE_SIZE]; /* The current line being examined */
int max = 0;
int min = INT_MAX;
int len;
while (fgets(line, LINE_SIZE, instream))
{
len = block_comment_width(line);
if (len > 0)
{
if (len > max)
{
max = len;
}
if (len < min)
{
min = len;
}
}
}
if (max < min)
{
ERRORFL("No block comments found", g_file_name);
return DEFAULT_WIDTH;
}
else if (max != min)
{
ERRORFL("Block comments have different lengths", g_file_name);
return DEFAULT_WIDTH;
}
return min;
}
/****************************************************************************
* Name: check_section_header
*
* Description:
* Check if the current line holds a section header
*
****************************************************************************/
static bool check_section_header(const char *line, int lineno)
{
int i;
/* Search g_section_info[] to find a matching section header line */
for (i = FIRST_SECTION; i <= LAST_SECTION; i++)
{
if (strcmp(line, g_section_info[i].name) == 0)
{
g_section = (enum section_s)i;
/* Verify that this section is appropriate for this file type */
if ((g_file_type & g_section_info[i].ftype) == 0)
{
ERROR("Invalid section for this file type", lineno, 3);
}
return true;
}
}
return false;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int main(int argc, char **argv, char **envp)
{
FILE *instream; /* File input stream */
char line[LINE_SIZE]; /* The current line being examined */
char buffer[100]; /* Localy format error strings */
char *lptr; /* Temporary pointer into line[] */
char *ext; /* Temporary file extension */
bool btabs; /* True: TAB characters found on the line */
bool bcrs; /* True: Carriage return found on the line */
bool bfunctions; /* True: In private or public functions */
bool bstatm; /* True: This line is beginning of a statement */
bool bfor; /* True: This line is beginning of a 'for' statement */
bool bswitch; /* True: Within a switch statement */
bool bstring; /* True: Within a string */
bool bquote; /* True: Backslash quoted character next */
bool bblank; /* Used to verify block comment terminator */
bool ppline; /* True: The next line the continuation of a pre-processor command */
bool bexternc; /* True: Within 'extern "C"' */
bool brhcomment; /* True: Comment to the right of code */
bool prevbrhcmt; /* True: previous line had comment to the right of code */
int lineno; /* Current line number */
int indent; /* Indentation level */
int ncomment; /* Comment nesting level on this line */
int prevncomment; /* Comment nesting level on the previous line */
int bnest; /* Brace nesting level on this line */
int prevbnest; /* Brace nesting level on the previous line */
int dnest; /* Data declaration nesting level on this line */
int prevdnest; /* Data declaration nesting level on the previous line */
int pnest; /* Parenthesis nesting level on this line */
int comment_lineno; /* Line on which the last comment was closed */
int blank_lineno; /* Line number of the last blank line */
int noblank_lineno; /* A blank line is not needed after this line */
int lbrace_lineno; /* Line number of last left brace */
int rbrace_lineno; /* Last line containing a right brace */
int externc_lineno; /* Last line where 'extern "C"' declared */
int linelen; /* Length of the line */
int excess;
int n;
int i;
int c;
excess = 0;
while ((c = getopt(argc, argv, ":hv:gm:r:")) != -1)
{
switch (c)
{
case 'm':
excess = atoi(optarg);
if (excess < 1)
{
show_usage(argv[0], 1, "Bad value for <excess>.");
excess = 0;
}
break;
case 'v':
g_verbose = atoi(optarg);
if (g_verbose < 0 || g_verbose > 2)
{
show_usage(argv[0], 1, "Bad value for <level>.");
}
break;
case 'r':
g_rangestart[g_rangenumber] = atoi(strtok(optarg, ","));
g_rangecount[g_rangenumber++] = atoi(strtok(NULL, ","));
break;
case 'h':
show_usage(argv[0], 0, NULL);
break;
case ':':
show_usage(argv[0], 1, "Missing argument.");
break;
case '?':
show_usage(argv[0], 1, "Unrecognized option.");
break;
default:
show_usage(argv[0], 0, NULL);
break;
}
}
if (optind < argc - 1 || argv[optind] == NULL)
{
show_usage(argv[0], 1, "No file name given.");
}
g_file_name = argv[optind];
instream = fopen(g_file_name, "r");
if (!instream)
{
FATALFL("Failed to open", g_file_name);
return 1;
}
/* Determine the line width */
g_maxline = get_line_width(instream) + excess;
rewind(instream);
/* Are we parsing a header file? */
ext = strrchr(g_file_name, '.');
if (ext == 0)
{
INFOFL("No file extension", g_file_name);
}
else if (strcmp(ext, ".h") == 0)
{
g_file_type = C_HEADER;
}
else if (strcmp(ext, ".c") == 0)
{
g_file_type = C_SOURCE;
}
if (g_file_type == UNKNOWN)
{
INFOFL("Unknown file extension", g_file_name);
return 0;
}
btabs = false; /* True: TAB characters found on the line */
bcrs = false; /* True: Carriage return found on the line */
bfunctions = false; /* True: In private or public functions */
bswitch = false; /* True: Within a switch statement */
bstring = false; /* True: Within a string */
ppline = false; /* True: Continuation of a pre-processor line */
bexternc = false; /* True: Within 'extern "C"' */
brhcomment = false; /* True: Comment to the right of code */
prevbrhcmt = false; /* True: Previous line had comment to the right of code */
lineno = 0; /* Current line number */
ncomment = 0; /* Comment nesting level on this line */
bnest = 0; /* Brace nesting level on this line */
dnest = 0; /* Data declaration nesting level on this line */
pnest = 0; /* Parenthesis nesting level on this line */
comment_lineno = -1; /* Line on which the last comment was closed */
blank_lineno = -1; /* Line number of the last blank line */
noblank_lineno = -1; /* A blank line is not needed after this line */
lbrace_lineno = -1; /* Line number of last left brace */
rbrace_lineno = -1; /* Last line containing a right brace */
externc_lineno = -1; /* Last line where 'extern "C"' declared */
/* Process each line in the input stream */
while (fgets(line, LINE_SIZE, instream))
{
lineno++;
indent = 0;
prevbnest = bnest; /* Brace nesting level on the previous line */
prevdnest = dnest; /* Data declaration nesting level on the previous line */
prevncomment = ncomment; /* Comment nesting level on the previous line */
bstatm = false; /* True: This line is beginning of a statement */
bfor = false; /* REVISIT: Implies for() is all on one line */
/* If we are not in a comment, then this certainly is not a right-hand comment. */
prevbrhcmt = brhcomment;
if (ncomment <= 0)
{
brhcomment = false;
}
/* Check for a blank line */
for (n = 0; line[n] != '\n' && isspace((int)line[n]); n++)
{
}
if (line[n] == '\n')
{
if (n > 0)
{
ERROR("Blank line contains whitespace", lineno, 1);
}
if (lineno == 1)
{
ERROR("File begins with a blank line", 1, 1);
}
else if (lineno == blank_lineno + 1)
{
ERROR("Too many blank lines", lineno, 1);
}
else if (lineno == lbrace_lineno + 1)
{
ERROR("Blank line follows left brace", lineno, 1);
}
blank_lineno = lineno;
continue;
}
else /* This line is non-blank */
{
/* Check for a missing blank line after a comment */
if (lineno == comment_lineno + 1)
{
/* No blank line should be present if the current line contains
* a right brace, a pre-processor line, the start of another
* comment.
*
* REVISIT: Generates a false alarm if the current line is also
* a comment. Generally it is acceptable for one comment to
* follow another with no space separation.
*
* REVISIT: prevbrhcmt is tested to case the preceding line
* contained comments to the right of the code. In such cases,
* the comments are normally aligned and do not follow normal
* indentation rules. However, this code will generate a false
* alarm if the comments are aligned to the right BUT the
* preceding line has no comment.
*/
if (line[n] != '}' /* && line[n] != '#' */ && !prevbrhcmt)
{
ERROR("Missing blank line after comment", comment_lineno,
1);
}
}
/* Files must begin with a comment (the file header).
* REVISIT: Logically, this belongs in the STEP 2 operations
* below.
*/
if (lineno == 1 && (line[n] != '/' || line[n + 1] != '*'))
{
ERROR("Missing file header comment block", lineno, 1);
}
/* Check for a blank line following a right brace */
if (bfunctions && lineno == rbrace_lineno + 1)
{
/* Check if this line contains a right brace. A right brace
* must be followed by 'else', 'while', 'break', a blank line,
* another right brace, or a pre-processor directive like #endif
*/
if (strchr(line, '}') == NULL && line[n] != '#' &&
strncmp(&line[n], "else", 4) != 0 &&
strncmp(&line[n], "while", 5) != 0 &&
strncmp(&line[n], "break", 5) != 0)
{
ERROR("Right brace must be followed by a blank line",
rbrace_lineno, n + 1);
}
/* If the right brace is followed by a pre-processor command
* like #endif (but not #else or #elif), then set the right
* brace line number to the line number of the pre-processor
* command (it then must be followed by a blank line)
*/
if (line[n] == '#')
{
int ii;
for (ii = n + 1; line[ii] != '\0' && isspace(line[ii]); ii++)
{
}
if (strncmp(&line[ii], "else", 4) != 0 &&
strncmp(&line[ii], "elif", 4) != 0)
{
rbrace_lineno = lineno;
}
}
}
}
/* STEP 1: Find the indentation level and the start of real stuff on
* the line.
*/
for (n = 0; line[n] != '\n' && isspace((int)line[n]); n++)
{
switch (line[n])
{
case ' ':
{
indent++;
}
break;
case '\t':
{
if (!btabs)
{
ERROR("TABs found. First detected", lineno, n);
btabs = true;
}
indent = (indent + 4) & ~3;
}
break;
case '\r':
{
if (!bcrs)
{
ERROR("Carriage returns found. "
"First detected", lineno, n);
bcrs = true;
}
}
break;
default:
{
snprintf(buffer, sizeof(buffer),
"Unexpected white space character %02x found",
line[n]);
ERROR(buffer, lineno, n);
}
break;
}
}
/* STEP 2: Detect some certain start of line conditions */
/* Skip over pre-processor lines (or continuations of pre-processor
* lines as indicated by ppline)
*/
if (line[indent] == '#' || ppline)
{
int len;
int ii;
/* Suppress error for comment following conditional compilation */
noblank_lineno = lineno;
/* Check pre-processor commands if this is not a continuation
* line.
*/
if (!ppline)
{
/* Skip to the pre-processor command following the '#' */
for (ii = indent + 1;
line[ii] != '\0' && isspace(line[ii]);
ii++)
{
}
if (line[ii] != '\0')
{
/* Make sure that pre-processor definitions are all in
* the pre-processor definitions section.
*/
if (strncmp(&line[ii], "define", 6) == 0)
{
if (g_section != PRE_PROCESSOR_DEFINITIONS)
{
/* A complication is the header files always have
* the idempotence guard definitions before the
* "Pre-processor Definitions section".
*/
if (g_section == NO_SECTION &&
g_file_type != C_HEADER)
{
/* Only a warning because there is some usage
* of define outside the Pre-processor
* Definitions section which is justifiable.
* Should be manually checked.
*/
WARN("#define outside of 'Pre-processor "
"Definitions' section",
lineno, ii);
}
}
}
/* Make sure that files are included only in the Included
* Files section.
*/
else if (strncmp(&line[ii], "include", 7) == 0)
{
if (g_section != INCLUDED_FILES)
{
/* Only a warning because there is some usage of
* include outside the Included Files section
* which may be is justifiable. Should be
* manually checked.
*/
WARN("#include outside of 'Included Files' "
"section",
lineno, ii);
}
}
}
}
/* Check if the next line will be a continuation of the pre-
* processor command.
*/
len = strlen(&line[indent]) + indent - 1;
if (line[len] == '\n')
{
len--;
}
ppline = (line[len] == '\\');
continue;
}
/* Check for a single line comment */
linelen = strlen(line);
if (linelen >= 5) /* Minimum is slash, star, star, slash, newline */
{
lptr = strstr(line, "*/");
if (line[indent] == '/' && line[indent + 1] == '*' &&
lptr - line == linelen - 3)
{
/* If preceding comments were to the right of code, then we can
* assume that there is a columnar alignment of columns that do
* no follow the usual alignment. So the brhcomment flag
* should propagate.
*/
brhcomment = prevbrhcmt;
/* Check if there should be a blank line before the comment */
if (lineno > 1 &&
comment_lineno != lineno - 1 &&
blank_lineno != lineno - 1 &&
noblank_lineno != lineno - 1 &&
!brhcomment)
{
/* TODO: This generates a false alarm if preceded by a label. */
ERROR("Missing blank line before comment found", lineno, 1);
}
/* 'comment_lineno 'holds the line number of the last closing
* comment. It is used only to verify that the comment is
* followed by a blank line.
*/
comment_lineno = lineno;
}
}
/* Check for the comment block indicating the beginning of a new file
* section.
*/
if (check_section_header(line, lineno))
{
if (g_section == PRIVATE_FUNCTIONS || g_section == PUBLIC_FUNCTIONS)
{
bfunctions = true; /* Latched */
}
}
/* Check for some kind of declaration.
* REVISIT: The following logic fails for any non-standard types.
* REVISIT: Terminator after keyword might not be a space. Might be
* a newline, for example. struct and unions are often unnamed, for
* example.
*/
else if (strncmp(&line[indent], "auto ", 5) == 0 ||
strncmp(&line[indent], "bool ", 5) == 0 ||
strncmp(&line[indent], "char ", 5) == 0 ||
strncmp(&line[indent], "CODE ", 5) == 0 ||
strncmp(&line[indent], "const ", 6) == 0 ||
strncmp(&line[indent], "double ", 7) == 0 ||
strncmp(&line[indent], "struct ", 7) == 0 ||
strncmp(&line[indent], "struct\n", 7) == 0 || /* May be unnamed */
strncmp(&line[indent], "enum ", 5) == 0 ||
strncmp(&line[indent], "extern ", 7) == 0 ||
strncmp(&line[indent], "EXTERN ", 7) == 0 ||
strncmp(&line[indent], "FAR ", 4) == 0 ||
strncmp(&line[indent], "float ", 6) == 0 ||
strncmp(&line[indent], "int ", 4) == 0 ||
strncmp(&line[indent], "int16_t ", 8) == 0 ||
strncmp(&line[indent], "int32_t ", 8) == 0 ||
strncmp(&line[indent], "long ", 5) == 0 ||
strncmp(&line[indent], "off_t ", 6) == 0 ||
strncmp(&line[indent], "register ", 9) == 0 ||
strncmp(&line[indent], "short ", 6) == 0 ||
strncmp(&line[indent], "signed ", 7) == 0 ||
strncmp(&line[indent], "size_t ", 7) == 0 ||
strncmp(&line[indent], "ssize_t ", 8) == 0 ||
strncmp(&line[indent], "static ", 7) == 0 ||
strncmp(&line[indent], "time_t ", 7) == 0 ||
strncmp(&line[indent], "typedef ", 8) == 0 ||
strncmp(&line[indent], "uint8_t ", 8) == 0 ||
strncmp(&line[indent], "uint16_t ", 9) == 0 ||
strncmp(&line[indent], "uint32_t ", 9) == 0 ||
strncmp(&line[indent], "union ", 6) == 0 ||
strncmp(&line[indent], "union\n", 6) == 0 || /* May be unnamed */
strncmp(&line[indent], "unsigned ", 9) == 0 ||
strncmp(&line[indent], "void ", 5) == 0 ||
strncmp(&line[indent], "volatile ", 9) == 0)
{
/* Check if this is extern "C"; We don't typically indent following
* this.
*/
if (strncmp(&line[indent], "extern \"C\"", 10) == 0)
{
externc_lineno = lineno;
}
/* bfunctions: True: Processing private or public functions.
* bnest: Brace nesting level on this line
* dnest: Data declaration nesting level on this line
*/
/* REVISIT: Also picks up function return types */
/* REVISIT: Logic problem for nested data/function declarations */
if ((!bfunctions || bnest > 0) && dnest == 0)
{
dnest = 1;
}
/* Check for multiple definitions of variables on the line.
* Ignores declarations within parentheses which are probably
* formal parameters.
*/
if (pnest == 0)
{
int tmppnest;
/* Note, we have not yet parsed each character on the line so
* a comma have have been be preceded by '(' on the same line.
* We will have parse up to any comma to see if that is the
* case.
*/
for (i = indent, tmppnest = 0;
line[i] != '\n' && line[i] != '\0';
i++)
{
if (tmppnest == 0 && line[i] == ',')
{
ERROR("Multiple data definitions", lineno, i + 1);
break;
}
else if (line[i] == '(')
{
tmppnest++;
}
else if (line[i] == ')')
{
if (tmppnest < 1)
{
/* We should catch this later */
break;
}
tmppnest--;
}
else if (line[i] == ';')
{
/* Break out if the semicolon terminates the
* declaration is found. Avoids processing any
* righthand comments in most cases.
*/
break;
}
}
}
}
/* Check for a keyword indicating the beginning of a statement.
* REVISIT: This, obviously, will not detect statements that do not
* begin with a C keyword (such as assignment statements).
*/
else if (strncmp(&line[indent], "break ", 6) == 0 ||
strncmp(&line[indent], "case ", 5) == 0 ||
#if 0 /* Part of switch */
strncmp(&line[indent], "case ", 5) == 0 ||
#endif
strncmp(&line[indent], "continue ", 9) == 0 ||
#if 0 /* Part of switch */
strncmp(&line[indent], "default ", 8) == 0 ||
#endif
strncmp(&line[indent], "do ", 3) == 0 ||
strncmp(&line[indent], "else ", 5) == 0 ||
strncmp(&line[indent], "goto ", 5) == 0 ||
strncmp(&line[indent], "if ", 3) == 0 ||
strncmp(&line[indent], "return ", 7) == 0 ||
#if 0 /* Doesn't follow pattern */
strncmp(&line[indent], "switch ", 7) == 0 ||
#endif
strncmp(&line[indent], "while ", 6) == 0)
{
bstatm = true;
}
/* Spacing works a little differently for and switch statements */
else if (strncmp(&line[indent], "for ", 4) == 0)
{
bfor = true;
bstatm = true;
}
else if (strncmp(&line[indent], "switch ", 7) == 0)
{
bswitch = true;
}
/* Also check for C keywords with missing white space */
else if (strncmp(&line[indent], "do(", 3) == 0 ||
strncmp(&line[indent], "if(", 3) == 0 ||
strncmp(&line[indent], "while(", 6) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bstatm = true;
}
else if (strncmp(&line[indent], "for(", 4) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bfor = true;
bstatm = true;
}
else if (strncmp(&line[indent], "switch(", 7) == 0)
{
ERROR("Missing whitespace after keyword", lineno, n);
bswitch = true;
}
/* STEP 3: Parse each character on the line */
bquote = false; /* True: Backslash quoted character next */
bblank = true; /* Used to verify block comment terminator */
for (; line[n] != '\n' && line[n] != '\0'; n++)
{
/* Report any use of non-standard white space characters */
if (isspace(line[n]))
{
if (line[n] == '\t')
{
if (!btabs)
{
ERROR("TABs found. First detected", lineno, n);
btabs = true;
}
}
else if (line[n] == '\r')
{
if (!bcrs)
{
ERROR("Carriage returns found. "
"First detected", lineno, n);
bcrs = true;
}
}
else if (line[n] != ' ')
{
snprintf(buffer, sizeof(buffer),
"Unexpected white space character %02x found",
line[n]);
ERROR(buffer, lineno, n);
}
}
/* Skip over identifiers */
if (ncomment == 0 && !bstring && (line[n] == '_' || isalpha(line[n])))
{
bool have_upper = false;
bool have_lower = false;
int ident_index = n;
/* Parse over the identifier. Check if it contains mixed upper-
* and lower-case characters.
*/
do
{
have_upper |= isupper(line[n]);
/* The coding standard provides for some exceptions of lower
* case characters in pre-processor strings:
*
* IPv[4|6] as an IP version number
* ICMPv6 as an ICMP version number
* IGMPv2 as an IGMP version number
* [0-9]p[0-9] as a decimal point
* d[0-9] as a divisor
*/
if (!have_lower && islower(line[n]))
{
switch (line[n])
{
/* A sequence containing 'v' may occur at the
* beginning of the identifier.
*/
case 'v':
if (n > 1 &&
line[n - 2] == 'I' &&
line[n - 1] == 'P' &&
(line[n + 1] == '4' ||
line[n + 1] == '6'))
{
}
else if (n > 3 &&
line[n - 4] == 'I' &&
line[n - 3] == 'C' &&
line[n - 2] == 'M' &&
line[n - 1] == 'P' &&
line[n + 1] == '6')
{
}
else if (n > 3 &&
line[n - 4] == 'I' &&
line[n - 3] == 'G' &&
line[n - 2] == 'M' &&
line[n - 1] == 'P' &&
line[n + 1] == '2')
{
}
else
{
have_lower = true;
}
break;
/* Sequences containing 'p' or 'd' must have been
* preceded by upper case characters.
*/
case 'p':
if (!have_upper || n < 1 ||
!isdigit(line[n - 1]) ||
!isdigit(line[n + 1]))
{
have_lower = true;
}
break;
case 'd':
if (!have_upper || !isdigit(line[n + 1]))
{
have_lower = true;
}
break;
default:
have_lower = true;
break;
}
}
n++;
}
while (line[n] == '_' || isalnum(line[n]));
/* Check for mixed upper and lower case */
if (have_upper && have_lower)
{
/* Special case hex constants. These will look like
* identifiers starting with 'x' or 'X' but preceded
* with '0'
*/
if (ident_index < 1 ||
(line[ident_index] != 'x' && line[ident_index] != 'X') ||
line[ident_index - 1] != '0')
{
/* REVISIT: Although pre-processor definitions are
* supposed to be all upper-case, there are exceptions
* such as using 'p' for a decimal point or 'MHz'.
* Those will be reported here, but probably should be
* considered false alarms.
*/
ERROR("Mixed case identifier found", lineno, ident_index);
}
else if (have_upper)
{
ERROR("Upper case hex constant found", lineno, ident_index);
}
}
/* Check if the identifier is the last thing on the line */
if (line[n] == '\n' || line[n] == '\0')
{
break;
}
}
/* Handle comments */
if (line[n] == '/' && !bstring)
{
/* Check for start of a C comment */
if (line[n + 1] == '*')
{
if (line[n + 2] == '\n')
{
ERROR("C comment opening on separate line", lineno, n);
}
else if (!isspace((int)line[n + 2]) && line[n + 2] != '*')
{
ERROR("Missing space after opening C comment", lineno, n);
}
/* Increment the count of nested comments */
ncomment++;
/* If there is anything to the left of the left brace, then
* this must be a comment to the right of code.
* Also if preceding comments were to the right of code, then
* we can assume that there is a columnar alignment of columns
* that do no follow the usual alignment. So the brhcomment
* flag should propagate.
*/
brhcomment = ((n != indent) || prevbrhcmt);
n++;
continue;
}
/* Check for end of a C comment */
else if (n > 0 && line[n - 1] == '*')
{
if (n < 2)
{
ERROR("Closing C comment not indented", lineno, n);
}
else if (!isspace((int)line[n + 1]) && line[n - 2] != '*')
{
ERROR("Missing space before closing C comment", lineno,
n);
}
/* Check for block comments that are not on a separate line.
* This would be the case if we are we are within a comment
* that did not start on this line and the current line is
* not blank up to the point where the comment was closed.
*/
if (prevncomment > 0 && !bblank && !brhcomment)
{
ERROR("Block comment terminator must be on a "
"separate line", lineno, n);
}
#if 0
/* REVISIT: Generates false alarms when portions of an
* expression are commented out within the expression.
*/
if (line[n + 1] != '\n')
{
ERROR("Garbage on line after C comment", lineno, n);
}
#endif
/* Handle nested comments */
if (ncomment > 0)
{
/* Remember the line number of the line containing the
* closing of the outermost comment.
*/
if (--ncomment == 0)
{
/* 'comment_lineno 'holds the line number of the
* last closing comment. It is used only to
* verify that the comment is followed by a blank
* line.
*/
comment_lineno = lineno;
/* Note that brhcomment must persist to support a
* later test for comment alignment. We will fix
* that at the top of the loop when ncomment == 0.
*/
}
}
else
{
/* Note that brhcomment must persist to support a later
* test for comment alignment. We will will fix that
* at the top of the loop when ncomment == 0.
*/
ncomment = 0;
ERROR("Closing without opening comment", lineno, n);
}
n++;
continue;
}
/* Check for C++ style comments */
else if (line[n + 1] == '/')
{
/* Check for "http://" or "https://" */
if ((n < 5 || strncmp(&line[n - 5], "http://", 7) != 0) &&
(n < 6 || strncmp(&line[n - 6], "https://", 8) != 0))
{
ERROR("C++ style comment", lineno, n);
n++;
continue;
}
}
}
/* Check if the line is blank so far. This is only used to
* to verify the the closing of a block comment is on a separate
* line. So we also need to treat '*' as a 'blank'.
*/
if (!isblank(line[n]) && line[n] != '*')
{
bblank = false;
}
/* Check for a string... ignore if we are in the middle of a
* comment.
*/
if (ncomment == 0)
{
/* Backslash quoted character */
if (line[n] == '\\')
{
bquote = true;
n++;
}
/* Check for quoted characters: \" in string */
if (line[n] == '"' && !bquote)
{
bstring = !bstring;
}
bquote = false;
}
/* The reset of the line is only examined of we are not in a comment
* or a string.
*
* REVISIT: Should still check for whitespace at the end of the
* line.
*/
if (ncomment == 0 && !bstring)
{
switch (line[n])
{
/* Handle logic nested with curly braces */
case '{':
{
if (n > indent)
{
/* REVISIT: dnest is always > 0 here if bfunctions == false */
if (dnest == 0 || !bfunctions)
{
ERROR("Left bracket not on separate line", lineno,
n);
}
}
else if (line[n + 1] != '\n')
{
if (dnest == 0)
{
ERROR("Garbage follows left bracket", lineno, n);
}
}
bnest++;
if (dnest > 0)
{
dnest++;
}
/* Check if we are within 'extern "C"', we don't
* normally indent in that case because the 'extern "C"'
* is conditioned on __cplusplus.
*/
if (lineno == externc_lineno ||
lineno - 1 == externc_lineno)
{
bexternc = true;
}
/* Suppress error for comment following a left brace */
noblank_lineno = lineno;
lbrace_lineno = lineno;
}
break;
case '}':
{
/* Decrement the brace nesting level */
if (bnest < 1)
{
ERROR("Unmatched right brace", lineno, n);
}
else
{
bnest--;
if (bnest < 1)
{
bnest = 0;
bswitch = false;
}
}
/* Decrement the declaration nesting level */
if (dnest < 3)
{
dnest = 0;
bexternc = false;
}
else
{
dnest--;
}
/* The right brace should be on a separate line */
if (n > indent)
{
if (dnest == 0)
{
ERROR("Right bracket not on separate line",
lineno, n);
}
}
/* Check for garbage following the left brace */
if (line[n + 1] != '\n' &&
line[n + 1] != ',' &&
line[n + 1] != ';')
{
int sndx = n + 1;
bool whitespace = false;
/* Skip over spaces */
while (line[sndx] == ' ')
{
sndx++;
}
/* One possibility is that the right bracket is
* followed by an identifier then a semi-colon.
* Comma is possible to but would be a case of
* multiple declaration of multiple instances.
*/
if (line[sndx] == '_' || isalpha(line[sndx]))
{
int endx = sndx;
/* Skip to the end of the identifier. Checking
* for mixed case identifiers will be done
* elsewhere.
*/
while (line[endx] == '_' ||
isalnum(line[endx]))
{
endx++;
}
/* Skip over spaces */
while (line[endx] == ' ')
{
whitespace = true;
endx++;
}
/* Handle according to what comes after the
* identifier.
*/
if (strncmp(&line[sndx], "while", 5) == 0)
{
ERROR("'while' must be on a separate line",
lineno, sndx);
}
else if (line[endx] == ',')
{
ERROR("Multiple data definitions on line",
lineno, endx);
}
else if (line[endx] == ';')
{
if (whitespace)
{
ERROR("Space precedes semi-colon",
lineno, endx);
}
}
else
{
ERROR("Garbage follows right bracket",
lineno, n);
}
}
else
{
ERROR("Garbage follows right bracket", lineno, n);
}
}
/* The right brace should not be preceded with a a blank line */
if (lineno == blank_lineno + 1)
{
ERROR("Blank line precedes right brace at line",
lineno, 1);
}
rbrace_lineno = lineno;
}
break;
/* Handle logic with parentheses */
case '(':
{
/* Increase the parenthetical nesting level */
pnest++;
/* Check for inappropriate space around parentheses */
if (line[n + 1] == ' ') /* && !bfor */
{
ERROR("Space follows left parenthesis", lineno, n);
}
}
break;
case ')':
{
/* Decrease the parenthetical nesting level */
if (pnest < 1)
{
ERROR("Unmatched right parentheses", lineno, n);
pnest = 0;
}
else
{
pnest--;
}
/* Allow ')' as first thing on the line (n == indent)
* Allow "for (xx; xx; )" (bfor == true)
*/
if (n > 0 && n != indent && line[n - 1] == ' ' && !bfor)
{
ERROR("Space precedes right parenthesis", lineno, n);
}
}
break;
/* Check for inappropriate space around square brackets */
case '[':
{
if (line[n + 1] == ' ')
{
ERROR("Space follows left bracket", lineno, n);
}
}
break;
case ']':
{
if (n > 0 && line[n - 1] == ' ')
{
ERROR("Space precedes right bracket", lineno, n);
}
}
break;
/* Semi-colon may terminate a declaration */
case ';':
{
if (!isspace((int)line[n + 1]))
{
ERROR("Missing whitespace after semicolon", lineno, n);
}
/* Semicolon terminates a declaration/definition if there
* was no left curly brace (i.e., dnest is only 1).
*/
if (dnest == 1)
{
dnest = 0;
}
}
break;
/* Semi-colon may terminate a declaration */
case ',':
{
if (!isspace((int)line[n + 1]))
{
ERROR("Missing whitespace after comma", lineno, n);
}
}
break;
/* Skip over character constants */
case '\'':
{
int endndx = n + 2;
if (line[n + 1] != '\n' && line[n + 1] != '\0')
{
if (line[n + 1] == '\\')
{
for (;
line[endndx] != '\n' &&
line[endndx] != '\0' &&
line[endndx] != '\'';
endndx++);
}
n = endndx + 1;
}
}
break;
/* Check for space around various operators */
case '-':
/* ->, -- */
if (line[n + 1] == '>' || line[n + 1] == '-')
{
n++;
}
/* -= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
/* '-' may function as a unary operator and snuggle
* on the left.
*/
check_spaces_left(line, lineno, n);
}
break;
case '+':
/* ++ */
if (line[n + 1] == '+')
{
n++;
}
/* += */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
/* '+' may function as a unary operator and snuggle
* on the left.
*/
check_spaces_left(line, lineno, n);
}
break;
case '&':
/* &<variable> OR &(<expression>) */
if (isalpha((int)line[n + 1]) || line[n + 1] == '_' ||
line[n + 1] == '(')
{
}
/* &&, &= */
else if (line[n + 1] == '=' || line[n + 1] == '&')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '/':
/* C comment terminator*/
if (line[n - 1] == '*')
{
n++;
}
/* C++-style comment */
else if (line[n + 1] == '/')
{
/* Check for "http://" or "https://" */
if ((n < 5 || strncmp(&line[n - 5], "http://", 7) != 0) &&
(n < 6 || strncmp(&line[n - 6], "https://", 8) != 0))
{
ERROR("C++ style comment on at %d:%d\n",
lineno, n);
}
n++;
}
/* /= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
/* Division operator */
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '*':
/* *\/, ** */
if (line[n] == '*' &&
(line[n + 1] == '/' ||
line[n + 1] == '*'))
{
n++;
break;
}
/* *<variable>, *(<expression>) */
else if (isalpha((int)line[n + 1]) ||
line[n + 1] == '_' ||
line[n + 1] == '(')
{
break;
}
/* (<type> *) */
else if (line[n + 1] == ')')
{
/* REVISIT: This gives false alarms on syntax like *--ptr */
if (line[n - 1] != ' ')
{
ERROR("Operator/assignment must be preceded "
"with whitespace", lineno, n);
}
break;
}
/* *= */
else if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
/* A single '*' may be an binary operator, but
* it could also be a unary operator when used to deference
* a pointer.
*/
check_spaces_left(line, lineno, n);
}
break;
case '%':
/* %= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '<':
/* <=, <<, <<= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '<')
{
if (line[n + 2] == '=')
{
check_spaces_leftright(line, lineno, n, n + 2);
n += 2;
}
else
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '>':
/* >=, >>, >>= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '>')
{
if (line[n + 2] == '=')
{
check_spaces_leftright(line, lineno, n, n + 2);
n += 2;
}
else
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '|':
/* |=, || */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else if (line[n + 1] == '|')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '^':
/* ^= */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '=':
/* == */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
else
{
check_spaces_leftright(line, lineno, n, n);
}
break;
case '~':
check_spaces_left(line, lineno, n);
break;
case '!':
/* != */
if (line[n + 1] == '=')
{
check_spaces_leftright(line, lineno, n, n + 1);
n++;
}
/* !! */
else if (line[n + 1] == '!')
{
check_spaces_left(line, lineno, n);
n++;
}
else
{
check_spaces_left(line, lineno, n);
}
break;
default:
break;
}
}
}
/* Loop terminates when NUL or newline character found */
if (line[n] == '\n')
{
/* Check for space at the end of the line. Except for carriage
* returns which we have already reported (one time) above.
*/
if (n > 1 && isspace((int)line[n - 1]) && line[n - 1] != '\r')
{
ERROR("Dangling whitespace at the end of line", lineno, n);
}
/* Check for long lines */
if (n > g_maxline)
{
if (g_file_type == C_SOURCE)
{
ERROR("Long line found", lineno, n);
}
else if (g_file_type == C_HEADER)
{
WARN("Long line found", lineno, n);
}
}
}
/* STEP 4: Check alignment */
/* Within a comment block, we need only check on the alignment of the
* comment.
*/
if ((ncomment > 0 || prevncomment > 0) && !bstring)
{
/* Nothing should begin in comment zero */
if (indent == 0 && line[0] != '/' && !bexternc)
{
/* NOTE: if this line contains a comment to the right of the
* code, then ncomment will be misleading because it was
* already incremented above.
*/
if (ncomment > 1 || !brhcomment)
{
ERROR("No indentation line", lineno, indent);
}
}
else if (indent == 1 && line[0] == ' ' && line[1] == '*')
{
/* Good indentation */
}
else if (indent > 0 && line[indent] == '\n')
{
ERROR("Whitespace on blank line", lineno, indent);
}
else if (indent > 0 && indent < 2)
{
if (bnest > 0)
{
ERROR("Insufficient indentation", lineno, indent);
}
else
{
ERROR("Expected indentation line", lineno, indent);
}
}
else if (indent > 0 && !bswitch)
{
if (line[indent] == '/')
{
/* Comments should like at offsets 2, 6, 10, ...
* This rule is not followed, however, if the comments are
* aligned to the right of the code.
*/
if ((indent & 3) != 2 && !brhcomment)
{
ERROR("Bad comment alignment", lineno, indent);
}
/* REVISIT: This screws up in cases where there is C code,
* followed by a comment that continues on the next line.
*/
else if (line[indent + 1] != '*')
{
ERROR("Missing asterisk in comment", lineno, indent);
}
}
else if (line[indent] == '*')
{
/* REVISIT: Generates false alarms on comments at the end of
* the line if there is nothing preceding (such as the aligned
* comments with a structure field definition). So disabled for
* comments before beginning of function definitions.
*
* Suppress this error if this is a comment to the right of code.
* Those may be unaligned.
*/
if ((indent & 3) != 3 && bfunctions && dnest == 0 &&
!brhcomment)
{
ERROR("Bad comment block alignment", lineno, indent);
}
if (line[indent + 1] != ' ' &&
line[indent + 1] != '*' &&
line[indent + 1] != '\n' &&
line[indent + 1] != '/')
{
ERROR("Invalid character after asterisk "
"in comment block", lineno, indent);
}
}
/* If this is not the line containing the comment start, then this
* line should begin with '*'
*/
else if (prevncomment > 0)
{
ERROR("Missing asterisk in comment block", lineno, indent);
}
}
}
/* Check for various alignment outside of the comment block */
else if ((ncomment == 0 && prevncomment == 0) && !bstring)
{
if (indent == 0 && strchr("\n#{}", line[0]) == NULL)
{
/* Ignore if we are at global scope */
if (prevbnest > 0)
{
bool blabel = false;
if (isalpha((int)line[indent]))
{
for (i = indent + 1; isalnum((int)line[i]) ||
line[i] == '_'; i++);
blabel = (line[i] == ':');
}
if (!blabel && !bexternc)
{
ERROR("No indentation line", lineno, indent);
}
}
}
else if (indent == 1 && line[0] == ' ' && line[1] == '*')
{
/* Good indentation */
}
else if (indent > 0 && line[indent] == '\n')
{
ERROR("Whitespace on blank line", lineno, indent);
}
else if (indent > 0 && indent < 2)
{
ERROR("Insufficient indentation line", lineno, indent);
}
else if (line[indent] == '{')
{
/* REVISIT: Possible false alarms in compound statements
* without a preceding conditional. That usage often violates
* the coding standard.
*/
if (!bfunctions && (indent & 1) != 0)
{
ERROR("Bad left brace alignment", lineno, indent);
}
else if ((indent & 3) != 0 && !bswitch && dnest == 0)
{
ERROR("Bad left brace alignment", lineno, indent);
}
}
else if (line[indent] == '}')
{
/* REVISIT: Possible false alarms in compound statements
* without a preceding conditional. That usage often violates
* the coding standard.
*/
if (!bfunctions && (indent & 1) != 0)
{
ERROR("right left brace alignment", lineno, indent);
}
else if ((indent & 3) != 0 && !bswitch && prevdnest == 0)
{
ERROR("Bad right brace alignment", lineno, indent);
}
}
else if (indent > 0)
{
/* REVISIT: Generates false alarms when a statement continues on
* the next line. The bstatm check limits to lines beginning
* with C keywords.
* REVISIT: The bstatm check will not detect statements that
* do not begin with a C keyword (such as assignment statements).
* REVISIT: Generates false alarms on comments at the end of
* the line if there is nothing preceding (such as the aligned
* comments with a structure field definition). So disabled for
* comments before beginning of function definitions.
*/
if ((bstatm || /* Begins with C keyword */
(line[indent] == '/' && bfunctions)) && /* Comment in functions */
!bswitch && /* Not in a switch */
dnest == 0) /* Not a data definition */
{
if ((indent & 3) != 2)
{
ERROR("Bad alignment", lineno, indent);
}
}
/* Crazy cases. There should be no small odd alignments
* outside of comment/string. Odd alignments are possible
* on continued lines, but not if they are small.
*/
else if (indent == 1 || indent == 3)
{
ERROR("Small odd alignment", lineno, indent);
}
}
}
}
if (!bfunctions && g_file_type == C_SOURCE)
{
ERROR("\"Private/Public Functions\" not found!"
" File was not be checked", lineno, 1);
}
if (ncomment > 0 || bstring)
{
ERROR("Comment or string found at end of file", lineno, 1);
}
fclose(instream);
if (g_verbose == 1)
{
fprintf(stderr, "%s: %s nxstyle check\n", g_file_name,
g_status == 0 ? "PASSED" : "FAILED");
}
return g_status;
}
|
the_stack_data/159515294.c | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int *p;
printf("1");
p = NULL;
printf("2");
*p = 1;
printf("3");
return 0;
}
|
the_stack_data/1165319.c | /* { dg-do compile { target { powerpc*-*-linux* && lp64 } } } */
/* { dg-options "-Wall" } */
/* Testcase to check for ABI compliance of parameter passing
for the PowerPC64 ABI. */
typedef int __attribute__((vector_size(16))) v4si;
typedef int __attribute__((vector_size(8))) v2si;
v4si
f(v4si v)
{ /* { dg-error "altivec instructions are disabled" "PR18631" { xfail *-*-* } } */
return v;
}
v2si
g(v2si v)
{
return v;
}
int
main()
{
v4si v = { 1, 2, 3, 4 };
v2si w = { 5, 6 };
v = f (v); /* { dg-error "altivec instructions are disabled" "PR18631" { xfail *-*-* } } */
w = g (w);
return 0;
}
|
the_stack_data/104184.c | #include<stdio.h>
int RectPerimeter (int num1,int num2)
{
return (num1 + num2) * 2;
}
int main (void)
{
// var declration
int num1,num2;
// user interface
printf("\nEnter Length: ");
scanf("%d",&num1);
printf("\nEnter Width: ");
scanf("%d",&num2);
// print the result
if ((num1 > 0) && (num2>0))
{
printf("\nThe perimeter of this rectangle is: %d \n \n",RectPerimeter(num1,num2));
}
else{;
printf("\nPlease enter valid length or width.\n \n");
}
return 0;
} |
the_stack_data/231393394.c | #include<stdio.h>
int main()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=24-a+b;
if(c>24)
printf("O JOGO DUROU %d HORA(S)\n",c-24);
else
printf("O JOGO DUROU %d HORA(S)\n",c);
return 0;
}
|
the_stack_data/878892.c | #include<stdio.h>
#include<stdlib.h>
int main() {
// posicoes de 0 a 9
char letra = 'l';
char palavra[10];
// for (int indice = 0; indice < 10; indice++){
// if (palavra[indice]=='\0')
// break;
// printf("palavra[%d] : ", indice);
// printf("%c\n", palavra[indice]);
// }
int indice = 0;
while(palavra[indice]!='\0'){
printf("palavra[%d] : ", indice);
printf("%s\n", palavra[indice]);
indice++;
}
printf("\na palavra eh: %s", palavra);
} |
the_stack_data/90765054.c | /*-
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Computer Consoles Inc.
*
* %sccs.include.proprietary.c%
*/
#ifndef lint
static char sccsid[] = "@(#)mclock_.c 5.2 (Berkeley) 04/12/91";
#endif /* not lint */
long int mclock_()
{
int buf[6];
times(buf);
return(buf[0]+buf[2]+buf[3]);
}
|
the_stack_data/48575357.c | #include <stdlib.h>
#define STEP 8
struct Interval {
int start;
int end;
};
static struct Interval *ans;
static int p, maxp;
static void do_init(void)
{
ans = 0;
p = maxp = 0;
}
static struct Interval *add_ans(const struct Interval *v)
{
if (!ans) {
maxp = STEP;
p = 0;
ans = malloc(maxp * sizeof(struct Interval));
}
if (p >= maxp) {
maxp += STEP;
ans = realloc(ans, maxp * sizeof(struct Interval));
}
ans[p].start = v->start;
ans[p].end = v->end;
return(&ans[p++]);
}
struct Interval *insert(struct Interval *intervals, int intervalsSize,
struct Interval newInterval, int *returnSize)
{
int i, j, flag;
struct Interval *ptr;
do_init();
if (!intervalsSize) {
add_ans(&newInterval);
*returnSize = 1;
return(ans);
}
if (newInterval.start < intervals[0].start) {
ptr = add_ans(&newInterval);
flag = 0;
i = 0;
} else {
ptr = add_ans(&intervals[0]);
flag = 1;
i = 1;
}
for (; i < intervalsSize; i++) {
if (flag && intervals[i].start >= newInterval.start) {
if (ptr->end >= newInterval.start) {
if (newInterval.end > ptr->end)
ptr->end = newInterval.end;
} else {
ptr = add_ans(&newInterval);
}
flag = 0;
}
if (ptr->end >= intervals[i].start) {
if (intervals[i].end > ptr->end)
ptr->end = intervals[i].end;
} else {
ptr = add_ans(&intervals[i]);
}
}
if (flag) {
if (ptr->end >= newInterval.start) {
if (newInterval.end > ptr->end) {
ptr->end = newInterval.end;
}
} else {
ptr = add_ans(&newInterval);
}
flag = 0;
}
*returnSize = p;
return(ans);
}
int main(void)
{
struct Interval x[] = { {1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};
struct Interval *res;
struct Interval newInterval = {4,9};
int i;
res = insert(x, 5, newInterval, &i);
return(0);
}
|
the_stack_data/43931.c | /*
*******************************************************************************
*
* Copyright (C) 2003, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: ucdstrip.c
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2003feb20
* created by: Markus W. Scherer
*
* Simple tool for Unicode Character Database files with semicolon-delimited fields.
* Removes comments behind data lines but not in others.
*
* To compile, just call a C compiler/linker with this source file.
* On Windows: cl ucdstrip.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* return the first character position after the end of the data */
static char *
endOfData(const char *l) {
char *end;
char c;
end=strchr(l, '#');
if(end!=NULL) {
/* ignore whitespace before the comment */
while(l!=end && ((c=*(end-1))==' ' || c=='\t')) {
--end;
}
} else {
end=strchr(l, 0);
}
return end;
}
extern int
main(int argc, const char *argv[]) {
static char line[2000];
char *end;
while(gets(line)!=NULL) {
if(strtol(line, &end, 16)>=0 && end!=line) {
/* code point or range followed by semicolon and data, remove comment */
*endOfData(line)=0;
}
puts(line);
}
return 0;
}
|
the_stack_data/57949919.c | /* ln - link a file Author: Andy Tanenbaum */
#include <sys/types.h>
#include <sys/stat.h>
char name[256];
struct stat stb;
main(argc, argv)
int argc;
char **argv;
{
char *file1, *file2;
char *last_comp();
if (argc < 2 || argc > 3) usage();
if (access(argv[1], 0) < 0) {
std_err("ln: cannot access ");
std_err(argv[1]);
std_err("\n");
exit(1);
}
if (stat(argv[1], &stb) >= 0 && (stb.st_mode & S_IFMT) == S_IFDIR) usage();
file1 = argv[1];
/* "ln file" means "ln file ." */
if (argc == 2)
file2 = ".";
else
file2 = argv[2];
/* Check to see if target is a directory. */
if (stat(file2, &stb) >= 0 && (stb.st_mode & S_IFMT) == S_IFDIR) {
strcpy(name, file2);
strcat(name, "/");
strcat(name, last_comp(file1));
file2 = name;
}
if (link(file1, file2)) {
std_err("ln: Can't link\n");
exit(1);
}
exit(0);
}
char *last_comp(s)
char *s;
{
/* Return pointer to last component of string. */
int n;
n = strlen(s);
while (n--)
if (*(s + n) == '/') return(s + n + 1);
return(s);
}
usage()
{
std_err("Usage: ln file1 [file2]\n");
exit(1);
}
|
the_stack_data/1233072.c | #define C 3
int foo(int x) { return ~(x + C) == (~C - x); }
/*
* check-name: simplify-not-add-cte
* check-command: test-linearize -Wno-decl $file
*
* check-output-ignore
* check-output-contains: ret\\..*\\$1
*/
|
the_stack_data/377123.c | /*
* Islamic prayer time for Asia/Srinagar
* I used https://www.salahtimes.com/india/srinagar
* to get data & then formatted it using standard
* tools like sed, cut & awk.
* asia_srinagar.c also differs with europe_copenhagen
* in that the former uses 12hr-time, while latter
* uses 24hr-time, mainly because thats the data I got
* and also because thats the prevalent system in Srinagar.
* I couldn't add am/pm to time, as that reports error.
*
* The Timezone Database (tz or zonebase).
* https://www.iana.org/time-zones
*
*/
/*
* The first element in the array contains the numbers of strings in the array.
* So "01-01" is the first string, "07:02", is the second and so on.
* The second element in the array contains the number of characters in each
* string, i.e. the dates and times.
*
* For each day there are 7 strings of each 6 characters (including the nul
* terminator). That's 7 strings * 366 days = 2562. 366 days due to the
* possibility of a leap day in February.
*/
#define CALENDAR_SIZE 2562
#define TIME_STR_SIZE 6
const char asia_srinagar[CALENDAR_SIZE][TIME_STR_SIZE] = {
"01-01", "07:02", "05:32", "03:14", "12:34", "07:37", "06:07",
"01-02", "07:02", "05:33", "03:15", "12:35", "07:37", "06:07",
"01-03", "07:03", "05:34", "03:16", "12:35", "07:37", "06:08",
"01-04", "07:04", "05:35", "03:16", "12:36", "07:37", "06:08",
"01-05", "07:05", "05:36", "03:17", "12:36", "07:37", "06:08",
"01-06", "07:05", "05:36", "03:18", "12:37", "07:37", "06:08",
"01-07", "07:06", "05:37", "03:19", "12:37", "07:37", "06:08",
"01-08", "07:07", "05:38", "03:19", "12:38", "07:37", "06:08",
"01-09", "07:08", "05:39", "03:20", "12:38", "07:37", "06:08",
"01-10", "07:08", "05:40", "03:21", "12:38", "07:37", "06:08",
"01-11", "07:09", "05:41", "03:22", "12:39", "07:37", "06:09",
"01-12", "07:10", "05:42", "03:23", "12:39", "07:37", "06:08",
"01-13", "07:11", "05:43", "03:24", "12:40", "07:37", "06:08",
"01-14", "07:12", "05:44", "03:24", "12:40", "07:37", "06:08",
"01-15", "07:12", "05:45", "03:25", "12:40", "07:36", "06:08",
"01-16", "07:13", "05:45", "03:26", "12:41", "07:36", "06:08",
"01-17", "07:14", "05:46", "03:27", "12:41", "07:36", "06:08",
"01-18", "07:15", "05:47", "03:28", "12:41", "07:35", "06:08",
"01-19", "07:16", "05:48", "03:29", "12:42", "07:35", "06:08",
"01-20", "07:17", "05:49", "03:29", "12:42", "07:35", "06:07",
"01-21", "07:17", "05:50", "03:30", "12:42", "07:34", "06:07",
"01-22", "07:18", "05:51", "03:31", "12:42", "07:34", "06:07",
"01-23", "07:19", "05:52", "03:32", "12:43", "07:33", "06:07",
"01-24", "07:20", "05:53", "03:33", "12:43", "07:33", "06:06",
"01-25", "07:21", "05:54", "03:34", "12:43", "07:32", "06:06",
"01-26", "07:22", "05:55", "03:35", "12:43", "07:32", "06:05",
"01-27", "07:23", "05:56", "03:35", "12:44", "07:31", "06:05",
"01-28", "07:23", "05:57", "03:36", "12:44", "07:31", "06:04",
"01-29", "07:24", "05:58", "03:37", "12:44", "07:30", "06:04",
"01-30", "07:25", "05:59", "03:38", "12:44", "07:29", "06:03",
"01-31", "07:26", "06:00", "03:39", "12:44", "07:29", "06:03",
"02-01", "07:27", "06:01", "03:40", "12:44", "07:28", "06:02",
"02-02", "07:28", "06:02", "03:40", "12:45", "07:27", "06:02",
"02-03", "07:29", "06:03", "03:41", "12:45", "07:27", "06:01",
"02-04", "07:29", "06:04", "03:42", "12:45", "07:26", "06:01",
"02-05", "07:30", "06:05", "03:43", "12:45", "07:25", "06:00",
"02-06", "07:31", "06:06", "03:44", "12:45", "07:24", "05:59",
"02-07", "07:32", "06:07", "03:44", "12:45", "07:23", "05:58",
"02-08", "07:33", "06:08", "03:45", "12:45", "07:22", "05:58",
"02-09", "07:34", "06:09", "03:46", "12:45", "07:22", "05:57",
"02-10", "07:34", "06:10", "03:47", "12:45", "07:21", "05:56",
"02-11", "07:35", "06:11", "03:47", "12:45", "07:20", "05:55",
"02-12", "07:36", "06:12", "03:48", "12:45", "07:19", "05:54",
"02-13", "07:37", "06:13", "03:49", "12:45", "07:18", "05:54",
"02-14", "07:38", "06:14", "03:49", "12:45", "07:17", "05:53",
"02-15", "07:39", "06:15", "03:50", "12:45", "07:16", "05:52",
"02-16", "07:39", "06:16", "03:51", "12:45", "07:15", "05:51",
"02-17", "07:40", "06:16", "03:51", "12:45", "07:14", "05:50",
"02-18", "07:41", "06:17", "03:52", "12:45", "07:13", "05:49",
"02-19", "07:42", "06:18", "03:53", "12:45", "07:12", "05:48",
"02-20", "07:43", "06:19", "03:53", "12:45", "07:10", "05:47",
"02-21", "07:44", "06:20", "03:54", "12:44", "07:09", "05:46",
"02-22", "07:44", "06:21", "03:54", "12:44", "07:08", "05:45",
"02-23", "07:45", "06:22", "03:55", "12:44", "07:07", "05:44",
"02-24", "07:46", "06:23", "03:56", "12:44", "07:06", "05:42",
"02-25", "07:47", "06:24", "03:56", "12:44", "07:05", "05:41",
"02-26", "07:48", "06:24", "03:57", "12:44", "07:03", "05:40",
"02-27", "07:49", "06:25", "03:57", "12:44", "07:02", "05:39",
"02-28", "07:49", "06:26", "03:58", "12:43", "07:01", "05:38",
"03-01", "07:50", "06:27", "03:58", "12:43", "07:00", "05:37",
"03-02", "07:51", "06:28", "03:59", "12:43", "06:59", "05:35",
"03-03", "07:52", "06:29", "03:59", "12:43", "06:57", "05:34",
"03-04", "07:53", "06:30", "04:00", "12:43", "06:56", "05:33",
"03-05", "07:53", "06:30", "04:00", "12:42", "06:55", "05:32",
"03-06", "07:54", "06:31", "04:01", "12:42", "06:53", "05:30",
"03-07", "07:55", "06:32", "04:01", "12:42", "06:52", "05:29",
"03-08", "07:56", "06:33", "04:01", "12:42", "06:51", "05:28",
"03-09", "07:57", "06:34", "04:02", "12:41", "06:50", "05:27",
"03-10", "07:58", "06:35", "04:02", "12:41", "06:48", "05:25",
"03-11", "07:58", "06:35", "04:03", "12:41", "06:47", "05:24",
"03-12", "07:59", "06:36", "04:03", "12:41", "06:46", "05:22",
"03-13", "08:00", "06:37", "04:03", "12:40", "06:44", "05:21",
"03-14", "08:01", "06:38", "04:04", "12:40", "06:43", "05:20",
"03-15", "08:02", "06:39", "04:04", "12:40", "06:42", "05:18",
"03-16", "08:03", "06:39", "04:04", "12:39", "06:40", "05:17",
"03-17", "08:03", "06:40", "04:05", "12:39", "06:39", "05:16",
"03-18", "08:04", "06:41", "04:05", "12:39", "06:37", "05:14",
"03-19", "08:05", "06:42", "04:05", "12:39", "06:36", "05:13",
"03-20", "08:06", "06:42", "04:05", "12:38", "06:35", "05:11",
"03-21", "08:07", "06:43", "04:06", "12:38", "06:33", "05:10",
"03-22", "08:08", "06:44", "04:06", "12:38", "06:32", "05:08",
"03-23", "08:09", "06:45", "04:06", "12:37", "06:31", "05:07",
"03-24", "08:09", "06:45", "04:06", "12:37", "06:29", "05:05",
"03-25", "08:10", "06:46", "04:07", "12:37", "06:28", "05:04",
"03-26", "08:11", "06:47", "04:07", "12:37", "06:27", "05:02",
"03-27", "08:12", "06:48", "04:07", "12:36", "06:25", "05:01",
"03-28", "08:13", "06:49", "04:07", "12:36", "06:24", "04:59",
"03-29", "08:14", "06:49", "04:07", "12:36", "06:22", "04:58",
"03-30", "08:15", "06:50", "04:08", "12:35", "06:21", "04:56",
"03-31", "08:16", "06:51", "04:08", "12:35", "06:20", "04:55",
"04-01", "08:17", "06:52", "04:08", "12:35", "06:18", "04:53",
"04-02", "08:18", "06:52", "04:08", "12:34", "06:17", "04:52",
"04-03", "08:19", "06:53", "04:08", "12:34", "06:16", "04:50",
"04-04", "08:19", "06:54", "04:08", "12:34", "06:14", "04:49",
"04-05", "08:20", "06:55", "04:09", "12:34", "06:13", "04:47",
"04-06", "08:21", "06:55", "04:09", "12:33", "06:12", "04:46",
"04-07", "08:22", "06:56", "04:09", "12:33", "06:10", "04:44",
"04-08", "08:23", "06:57", "04:09", "12:33", "06:09", "04:43",
"04-09", "08:24", "06:58", "04:09", "12:32", "06:08", "04:41",
"04-10", "08:25", "06:58", "04:09", "12:32", "06:06", "04:40",
"04-11", "08:26", "06:59", "04:09", "12:32", "06:05", "04:38",
"04-12", "08:27", "07:00", "04:09", "12:32", "06:04", "04:37",
"04-13", "08:28", "07:01", "04:09", "12:31", "06:03", "04:35",
"04-14", "08:29", "07:01", "04:10", "12:31", "06:01", "04:34",
"04-15", "08:30", "07:02", "04:10", "12:31", "06:00", "04:32",
"04-16", "08:31", "07:03", "04:10", "12:31", "05:59", "04:31",
"04-17", "08:32", "07:04", "04:10", "12:30", "05:58", "04:29",
"04-18", "08:33", "07:05", "04:10", "12:30", "05:56", "04:28",
"04-19", "08:34", "07:05", "04:10", "12:30", "05:55", "04:26",
"04-20", "08:35", "07:06", "04:10", "12:30", "05:54", "04:25",
"04-21", "08:36", "07:07", "04:10", "12:30", "05:53", "04:23",
"04-22", "08:37", "07:08", "04:10", "12:29", "05:52", "04:22",
"04-23", "08:39", "07:08", "04:10", "12:29", "05:50", "04:20",
"04-24", "08:40", "07:09", "04:10", "12:29", "05:49", "04:19",
"04-25", "08:41", "07:10", "04:10", "12:29", "05:48", "04:18",
"04-26", "08:42", "07:11", "04:10", "12:29", "05:47", "04:16",
"04-27", "08:42", "07:12", "04:10", "12:28", "05:46", "04:15",
"04-28", "08:43", "07:12", "04:10", "12:28", "05:45", "04:14",
"04-29", "08:43", "07:13", "04:11", "12:28", "05:44", "04:14",
"04-30", "08:44", "07:14", "04:11", "12:28", "05:43", "04:13",
"05-01", "08:44", "07:15", "04:11", "12:28", "05:42", "04:12",
"05-02", "08:45", "07:15", "04:11", "12:28", "05:41", "04:11",
"05-03", "08:45", "07:16", "04:11", "12:28", "05:40", "04:11",
"05-04", "08:46", "07:17", "04:11", "12:28", "05:39", "04:10",
"05-05", "08:46", "07:18", "04:11", "12:28", "05:38", "04:09",
"05-06", "08:47", "07:19", "04:11", "12:27", "05:37", "04:08",
"05-07", "08:47", "07:19", "04:11", "12:27", "05:36", "04:08",
"05-08", "08:48", "07:20", "04:11", "12:27", "05:35", "04:07",
"05-09", "08:49", "07:21", "04:11", "12:27", "05:34", "04:06",
"05-10", "08:49", "07:22", "04:11", "12:27", "05:33", "04:06",
"05-11", "08:50", "07:22", "04:11", "12:27", "05:32", "04:05",
"05-12", "08:50", "07:23", "04:11", "12:27", "05:32", "04:05",
"05-13", "08:51", "07:24", "04:12", "12:27", "05:31", "04:04",
"05-14", "08:51", "07:25", "04:12", "12:27", "05:30", "04:04",
"05-15", "08:52", "07:25", "04:12", "12:27", "05:29", "04:03",
"05-16", "08:52", "07:26", "04:12", "12:27", "05:29", "04:03",
"05-17", "08:53", "07:27", "04:12", "12:27", "05:28", "04:02",
"05-18", "08:53", "07:28", "04:12", "12:27", "05:27", "04:02",
"05-19", "08:54", "07:28", "04:12", "12:27", "05:27", "04:01",
"05-20", "08:54", "07:29", "04:12", "12:27", "05:26", "04:01",
"05-21", "08:55", "07:30", "04:12", "12:27", "05:25", "04:00",
"05-22", "08:55", "07:31", "04:13", "12:28", "05:25", "04:00",
"05-23", "08:56", "07:31", "04:13", "12:28", "05:24", "04:00",
"05-24", "08:57", "07:32", "04:13", "12:28", "05:24", "03:59",
"05-25", "08:57", "07:33", "04:13", "12:28", "05:23", "03:59",
"05-26", "08:58", "07:33", "04:13", "12:28", "05:23", "03:59",
"05-27", "08:58", "07:34", "04:13", "12:28", "05:22", "03:58",
"05-28", "08:59", "07:35", "04:13", "12:28", "05:22", "03:58",
"05-29", "08:59", "07:35", "04:14", "12:28", "05:21", "03:58",
"05-30", "09:00", "07:36", "04:14", "12:28", "05:21", "03:58",
"05-31", "09:00", "07:37", "04:14", "12:29", "05:21", "03:57",
"06-01", "09:00", "07:37", "04:14", "12:29", "05:20", "03:57",
"06-02", "09:01", "07:38", "04:14", "12:29", "05:20", "03:57",
"06-03", "09:01", "07:38", "04:14", "12:29", "05:20", "03:57",
"06-04", "09:02", "07:39", "04:15", "12:29", "05:20", "03:57",
"06-05", "09:02", "07:39", "04:15", "12:29", "05:19", "03:57",
"06-06", "09:03", "07:40", "04:15", "12:30", "05:19", "03:57",
"06-07", "09:03", "07:40", "04:15", "12:30", "05:19", "03:56",
"06-08", "09:04", "07:41", "04:15", "12:30", "05:19", "03:56",
"06-09", "09:04", "07:41", "04:16", "12:30", "05:19", "03:56",
"06-10", "09:04", "07:42", "04:16", "12:30", "05:19", "03:56",
"06-11", "09:05", "07:42", "04:16", "12:31", "05:19", "03:56",
"06-12", "09:05", "07:43", "04:16", "12:31", "05:19", "03:57",
"06-13", "09:05", "07:43", "04:16", "12:31", "05:19", "03:57",
"06-14", "09:06", "07:44", "04:17", "12:31", "05:19", "03:57",
"06-15", "09:06", "07:44", "04:17", "12:31", "05:19", "03:57",
"06-16", "09:06", "07:44", "04:17", "12:32", "05:19", "03:57",
"06-17", "09:07", "07:45", "04:17", "12:32", "05:19", "03:57",
"06-18", "09:07", "07:45", "04:17", "12:32", "05:19", "03:57",
"06-19", "09:07", "07:45", "04:18", "12:32", "05:19", "03:57",
"06-20", "09:07", "07:45", "04:18", "12:32", "05:20", "03:58",
"06-21", "09:08", "07:46", "04:18", "12:33", "05:20", "03:58",
"06-22", "09:08", "07:46", "04:18", "12:33", "05:20", "03:58",
"06-23", "09:08", "07:46", "04:19", "12:33", "05:20", "03:58",
"06-24", "09:08", "07:46", "04:19", "12:33", "05:21", "03:58",
"06-25", "09:08", "07:46", "04:19", "12:34", "05:21", "03:59",
"06-26", "09:08", "07:46", "04:19", "12:34", "05:21", "03:59",
"06-27", "09:09", "07:46", "04:19", "12:34", "05:21", "03:59",
"06-28", "09:09", "07:46", "04:20", "12:34", "05:22", "04:00",
"06-29", "09:09", "07:46", "04:20", "12:34", "05:22", "04:00",
"06-30", "09:09", "07:46", "04:20", "12:35", "05:23", "04:00",
"07-01", "09:09", "07:46", "04:20", "12:35", "05:23", "04:01",
"07-02", "09:09", "07:46", "04:20", "12:35", "05:23", "04:01",
"07-03", "09:09", "07:46", "04:21", "12:35", "05:24", "04:01",
"07-04", "09:09", "07:46", "04:21", "12:35", "05:24", "04:02",
"07-05", "09:09", "07:46", "04:21", "12:35", "05:25", "04:02",
"07-06", "09:09", "07:46", "04:21", "12:36", "05:25", "04:03",
"07-07", "09:08", "07:46", "04:21", "12:36", "05:26", "04:03",
"07-08", "09:08", "07:45", "04:21", "12:36", "05:26", "04:03",
"07-09", "09:08", "07:45", "04:21", "12:36", "05:27", "04:04",
"07-10", "09:08", "07:45", "04:22", "12:36", "05:27", "04:04",
"07-11", "09:08", "07:45", "04:22", "12:36", "05:28", "04:05",
"07-12", "09:08", "07:44", "04:22", "12:37", "05:29", "04:05",
"07-13", "09:07", "07:44", "04:22", "12:37", "05:29", "04:06",
"07-14", "09:07", "07:43", "04:22", "12:37", "05:30", "04:06",
"07-15", "09:07", "07:43", "04:22", "12:37", "05:30", "04:07",
"07-16", "09:07", "07:43", "04:22", "12:37", "05:31", "04:07",
"07-17", "09:06", "07:42", "04:22", "12:37", "05:32", "04:07",
"07-18", "09:06", "07:42", "04:22", "12:37", "05:32", "04:08",
"07-19", "09:06", "07:41", "04:22", "12:37", "05:33", "04:08",
"07-20", "09:05", "07:40", "04:22", "12:37", "05:34", "04:09",
"07-21", "09:05", "07:40", "04:22", "12:37", "05:34", "04:09",
"07-22", "09:04", "07:39", "04:22", "12:37", "05:35", "04:10",
"07-23", "09:04", "07:39", "04:22", "12:37", "05:36", "04:10",
"07-24", "09:04", "07:38", "04:22", "12:37", "05:36", "04:11",
"07-25", "09:03", "07:37", "04:22", "12:37", "05:37", "04:11",
"07-26", "09:03", "07:37", "04:22", "12:37", "05:38", "04:12",
"07-27", "09:02", "07:36", "04:22", "12:37", "05:38", "04:12",
"07-28", "09:01", "07:35", "04:22", "12:37", "05:39", "04:13",
"07-29", "09:01", "07:34", "04:22", "12:37", "05:40", "04:13",
"07-30", "09:00", "07:34", "04:22", "12:37", "05:41", "04:14",
"07-31", "09:00", "07:33", "04:21", "12:37", "05:41", "04:14",
"08-01", "08:59", "07:32", "04:21", "12:37", "05:42", "04:15",
"08-02", "08:58", "07:31", "04:21", "12:37", "05:43", "04:15",
"08-03", "08:58", "07:30", "04:21", "12:37", "05:43", "04:16",
"08-04", "08:57", "07:29", "04:21", "12:37", "05:44", "04:16",
"08-05", "08:56", "07:28", "04:21", "12:37", "05:45", "04:17",
"08-06", "08:56", "07:27", "04:20", "12:37", "05:46", "04:17",
"08-07", "08:55", "07:26", "04:20", "12:37", "05:46", "04:18",
"08-08", "08:54", "07:25", "04:20", "12:36", "05:47", "04:18",
"08-09", "08:53", "07:24", "04:19", "12:36", "05:48", "04:19",
"08-10", "08:53", "07:23", "04:19", "12:36", "05:49", "04:19",
"08-11", "08:52", "07:22", "04:19", "12:36", "05:49", "04:20",
"08-12", "08:51", "07:21", "04:18", "12:36", "05:50", "04:20",
"08-13", "08:50", "07:20", "04:18", "12:36", "05:51", "04:21",
"08-14", "08:49", "07:19", "04:18", "12:36", "05:51", "04:21",
"08-15", "08:49", "07:18", "04:17", "12:35", "05:52", "04:22",
"08-16", "08:48", "07:17", "04:17", "12:35", "05:53", "04:22",
"08-17", "08:46", "07:16", "04:16", "12:35", "05:54", "04:23",
"08-18", "08:45", "07:15", "04:16", "12:35", "05:54", "04:24",
"08-19", "08:43", "07:13", "04:15", "12:34", "05:55", "04:25",
"08-20", "08:42", "07:12", "04:15", "12:34", "05:56", "04:26",
"08-21", "08:40", "07:11", "04:14", "12:34", "05:57", "04:27",
"08-22", "08:39", "07:10", "04:14", "12:34", "05:57", "04:28",
"08-23", "08:37", "07:08", "04:13", "12:33", "05:58", "04:29",
"08-24", "08:36", "07:07", "04:13", "12:33", "05:59", "04:30",
"08-25", "08:34", "07:06", "04:12", "12:33", "05:59", "04:31",
"08-26", "08:33", "07:05", "04:12", "12:33", "06:00", "04:32",
"08-27", "08:31", "07:03", "04:11", "12:32", "06:01", "04:33",
"08-28", "08:30", "07:02", "04:11", "12:32", "06:01", "04:34",
"08-29", "08:28", "07:01", "04:10", "12:32", "06:02", "04:35",
"08-30", "08:27", "07:00", "04:09", "12:31", "06:03", "04:36",
"08-31", "08:25", "06:58", "04:09", "12:31", "06:04", "04:36",
"09-01", "08:24", "06:57", "04:08", "12:31", "06:04", "04:37",
"09-02", "08:22", "06:56", "04:07", "12:31", "06:05", "04:38",
"09-03", "08:21", "06:54", "04:07", "12:30", "06:06", "04:39",
"09-04", "08:19", "06:53", "04:06", "12:30", "06:06", "04:40",
"09-05", "08:17", "06:51", "04:05", "12:30", "06:07", "04:41",
"09-06", "08:16", "06:50", "04:04", "12:29", "06:08", "04:42",
"09-07", "08:14", "06:49", "04:04", "12:29", "06:08", "04:43",
"09-08", "08:13", "06:47", "04:03", "12:29", "06:09", "04:44",
"09-09", "08:11", "06:46", "04:02", "12:28", "06:10", "04:44",
"09-10", "08:10", "06:45", "04:01", "12:28", "06:10", "04:45",
"09-11", "08:08", "06:43", "04:00", "12:27", "06:11", "04:46",
"09-12", "08:07", "06:42", "04:00", "12:27", "06:12", "04:47",
"09-13", "08:05", "06:40", "03:59", "12:27", "06:13", "04:48",
"09-14", "08:04", "06:39", "03:58", "12:26", "06:13", "04:49",
"09-15", "08:02", "06:38", "03:57", "12:26", "06:14", "04:49",
"09-16", "08:00", "06:36", "03:56", "12:26", "06:15", "04:50",
"09-17", "07:59", "06:35", "03:55", "12:25", "06:15", "04:51",
"09-18", "07:57", "06:33", "03:55", "12:25", "06:16", "04:52",
"09-19", "07:56", "06:32", "03:54", "12:25", "06:17", "04:53",
"09-20", "07:54", "06:31", "03:53", "12:24", "06:17", "04:54",
"09-21", "07:53", "06:29", "03:52", "12:24", "06:18", "04:54",
"09-22", "07:51", "06:28", "03:51", "12:24", "06:19", "04:55",
"09-23", "07:50", "06:26", "03:50", "12:23", "06:20", "04:56",
"09-24", "07:48", "06:25", "03:49", "12:23", "06:20", "04:57",
"09-25", "07:47", "06:24", "03:48", "12:22", "06:21", "04:57",
"09-26", "07:45", "06:22", "03:47", "12:22", "06:22", "04:58",
"09-27", "07:44", "06:21", "03:46", "12:22", "06:22", "04:59",
"09-28", "07:43", "06:19", "03:45", "12:21", "06:23", "05:00",
"09-29", "07:41", "06:18", "03:45", "12:21", "06:24", "05:01",
"09-30", "07:40", "06:17", "03:44", "12:21", "06:24", "05:01",
"10-01", "07:38", "06:15", "03:43", "12:20", "06:25", "05:02",
"10-02", "07:37", "06:14", "03:42", "12:20", "06:26", "05:03",
"10-03", "07:36", "06:12", "03:41", "12:20", "06:27", "05:04",
"10-04", "07:34", "06:11", "03:40", "12:20", "06:27", "05:04",
"10-05", "07:33", "06:10", "03:39", "12:19", "06:28", "05:05",
"10-06", "07:32", "06:08", "03:38", "12:19", "06:29", "05:06",
"10-07", "07:30", "06:07", "03:37", "12:19", "06:30", "05:07",
"10-08", "07:29", "06:06", "03:36", "12:18", "06:30", "05:07",
"10-09", "07:28", "06:04", "03:35", "12:18", "06:31", "05:08",
"10-10", "07:26", "06:03", "03:34", "12:18", "06:32", "05:09",
"10-11", "07:25", "06:02", "03:33", "12:18", "06:33", "05:10",
"10-12", "07:24", "06:01", "03:32", "12:17", "06:34", "05:10",
"10-13", "07:23", "05:59", "03:31", "12:17", "06:34", "05:11",
"10-14", "07:21", "05:58", "03:30", "12:17", "06:35", "05:12",
"10-15", "07:20", "05:57", "03:30", "12:17", "06:36", "05:13",
"10-16", "07:19", "05:56", "03:29", "12:16", "06:37", "05:13",
"10-17", "07:18", "05:54", "03:28", "12:16", "06:37", "05:14",
"10-18", "07:17", "05:53", "03:27", "12:16", "06:38", "05:15",
"10-19", "07:15", "05:52", "03:26", "12:16", "06:39", "05:16",
"10-20", "07:14", "05:51", "03:25", "12:16", "06:40", "05:16",
"10-21", "07:13", "05:50", "03:24", "12:15", "06:41", "05:17",
"10-22", "07:12", "05:48", "03:23", "12:15", "06:42", "05:18",
"10-23", "07:11", "05:47", "03:22", "12:15", "06:42", "05:19",
"10-24", "07:10", "05:46", "03:22", "12:15", "06:43", "05:19",
"10-25", "07:09", "05:45", "03:21", "12:15", "06:44", "05:20",
"10-26", "07:08", "05:44", "03:20", "12:15", "06:45", "05:21",
"10-27", "07:07", "05:43", "03:19", "12:15", "06:46", "05:22",
"10-28", "07:06", "05:42", "03:18", "12:15", "06:47", "05:23",
"10-29", "07:05", "05:41", "03:18", "12:15", "06:48", "05:23",
"10-30", "07:04", "05:40", "03:17", "12:14", "06:49", "05:24",
"10-31", "07:04", "05:39", "03:16", "12:14", "06:49", "05:25",
"11-01", "07:03", "05:38", "03:15", "12:14", "06:50", "05:26",
"11-02", "07:02", "05:37", "03:15", "12:14", "06:51", "05:26",
"11-03", "07:01", "05:36", "03:14", "12:14", "06:52", "05:27",
"11-04", "07:00", "05:35", "03:13", "12:14", "06:53", "05:28",
"11-05", "07:00", "05:34", "03:12", "12:14", "06:54", "05:29",
"11-06", "06:59", "05:34", "03:12", "12:14", "06:55", "05:30",
"11-07", "06:58", "05:33", "03:11", "12:15", "06:56", "05:30",
"11-08", "06:58", "05:32", "03:11", "12:15", "06:57", "05:31",
"11-09", "06:57", "05:31", "03:10", "12:15", "06:58", "05:32",
"11-10", "06:56", "05:30", "03:09", "12:15", "06:59", "05:33",
"11-11", "06:56", "05:30", "03:09", "12:15", "07:00", "05:34",
"11-12", "06:55", "05:29", "03:08", "12:15", "07:01", "05:34",
"11-13", "06:55", "05:28", "03:08", "12:15", "07:01", "05:35",
"11-14", "06:54", "05:28", "03:07", "12:15", "07:02", "05:36",
"11-15", "06:54", "05:27", "03:07", "12:15", "07:03", "05:37",
"11-16", "06:53", "05:27", "03:06", "12:16", "07:04", "05:38",
"11-17", "06:53", "05:26", "03:06", "12:16", "07:05", "05:38",
"11-18", "06:52", "05:25", "03:06", "12:16", "07:06", "05:39",
"11-19", "06:52", "05:25", "03:05", "12:16", "07:07", "05:40",
"11-20", "06:52", "05:24", "03:05", "12:16", "07:08", "05:41",
"11-21", "06:51", "05:24", "03:04", "12:17", "07:09", "05:42",
"11-22", "06:51", "05:24", "03:04", "12:17", "07:10", "05:43",
"11-23", "06:51", "05:23", "03:04", "12:17", "07:11", "05:43",
"11-24", "06:51", "05:23", "03:04", "12:18", "07:12", "05:44",
"11-25", "06:50", "05:23", "03:03", "12:18", "07:13", "05:45",
"11-26", "06:50", "05:22", "03:03", "12:18", "07:14", "05:46",
"11-27", "06:50", "05:22", "03:03", "12:18", "07:15", "05:46",
"11-28", "06:50", "05:22", "03:03", "12:19", "07:15", "05:47",
"11-29", "06:50", "05:22", "03:03", "12:19", "07:16", "05:48",
"11-30", "06:50", "05:21", "03:03", "12:19", "07:17", "05:49",
"12-01", "06:50", "05:21", "03:03", "12:20", "07:18", "05:50",
"12-02", "06:50", "05:21", "03:03", "12:20", "07:19", "05:50",
"12-03", "06:50", "05:21", "03:03", "12:21", "07:20", "05:51",
"12-04", "06:50", "05:21", "03:03", "12:21", "07:21", "05:52",
"12-05", "06:50", "05:21", "03:03", "12:21", "07:22", "05:53",
"12-06", "06:50", "05:21", "03:03", "12:22", "07:22", "05:53",
"12-07", "06:50", "05:21", "03:03", "12:22", "07:23", "05:54",
"12-08", "06:51", "05:21", "03:03", "12:23", "07:24", "05:55",
"12-09", "06:51", "05:21", "03:03", "12:23", "07:25", "05:55",
"12-10", "06:51", "05:22", "03:03", "12:24", "07:25", "05:56",
"12-11", "06:51", "05:22", "03:04", "12:24", "07:26", "05:57",
"12-12", "06:52", "05:22", "03:04", "12:25", "07:27", "05:57",
"12-13", "06:52", "05:22", "03:04", "12:25", "07:28", "05:58",
"12-14", "06:52", "05:23", "03:05", "12:25", "07:28", "05:59",
"12-15", "06:52", "05:23", "03:05", "12:26", "07:29", "05:59",
"12-16", "06:53", "05:23", "03:05", "12:26", "07:30", "06:00",
"12-17", "06:53", "05:24", "03:06", "12:27", "07:30", "06:01",
"12-18", "06:54", "05:24", "03:06", "12:27", "07:31", "06:01",
"12-19", "06:54", "05:24", "03:06", "12:28", "07:31", "06:02",
"12-20", "06:55", "05:25", "03:07", "12:28", "07:32", "06:02",
"12-21", "06:55", "05:25", "03:07", "12:29", "07:32", "06:03",
"12-22", "06:56", "05:26", "03:08", "12:29", "07:33", "06:03",
"12-23", "06:56", "05:26", "03:08", "12:30", "07:33", "06:04",
"12-24", "06:57", "05:27", "03:09", "12:30", "07:34", "06:04",
"12-25", "06:57", "05:28", "03:10", "12:31", "07:34", "06:05",
"12-26", "06:58", "05:28", "03:10", "12:31", "07:35", "06:05",
"12-27", "06:58", "05:29", "03:11", "12:32", "07:35", "06:05",
"12-28", "06:59", "05:29", "03:11", "12:32", "07:35", "06:06",
"12-29", "07:00", "05:30", "03:12", "12:33", "07:36", "06:06",
"12-30", "07:00", "05:31", "03:13", "12:33", "07:36", "06:07",
"12-31", "07:01", "05:32", "03:13", "12:34", "07:36", "06:07"
};
|
the_stack_data/103264453.c | #include <stdint.h>
//
// Your typical RPG foo
//
typedef struct {
uint8_t pv;
uint8_t attack;
} Monster;
static void monster_init(Monster* monster) {
monster->pv = 10;
monster->attack = 2;
}
static void monster_take_hit(Monster* monster, uint8_t attack) {
if (monster->pv > attack) {
monster->pv -= attack;
}else {
monster->pv = 0;
}
}
//
// A hero wielding his weapon
//
typedef struct {
uint8_t attack;
uint8_t durability;
} Weapon;
typedef struct {
uint8_t pv;
uint8_t mana;
Weapon weapon;
} Hero;
static void hero_init(Hero* hero);
static void hero_change_weapon(Hero* hero, Weapon new_weapon);
static void hero_hit_monster(Hero* hero, Monster* monster);
static const Weapon fist = {.attack = 1, .durability = 255};
static const Weapon sword = {.attack = 3, .durability = 10};
static void hero_init(Hero* hero) {
hero->pv = 10;
hero->mana = 10;
hero_change_weapon(hero, fist);
}
static void hero_change_weapon(Hero* hero, Weapon new_weapon) {
hero->weapon = new_weapon;
}
static void hero_hit_monster(Hero* hero, Monster* monster) {
monster_take_hit(monster, hero->weapon.attack);
--hero->weapon.durability;
if (hero->weapon.durability == 0) {
hero_change_weapon(hero, fist);
}
}
//
// Benched routine: initialize things and begin a fight!
//
Hero hero;
Monster monsters[3];
int main(void) {
const uint8_t NB_MONSTERS = 3;
// Initialize gamestate
hero_init(&hero);
hero_change_weapon(&hero, sword);
for (uint8_t monster_num = 0; monster_num < NB_MONSTERS; ++monster_num) {
monster_init(&monsters[monster_num]);
}
// Fight!
hero_hit_monster(&hero, monsters + 1);
return 0;
}
|
the_stack_data/100139933.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char dado[1024];
printf("Programa de Registro de Dados Universal\n");
for (;;) {
printf("Entre com o dado a ser registrador:\n");
gets(dado);
if (strcmp(dado,"fim")==0)
break;
}
}
|
the_stack_data/110437.c | /**
TP3 - SGM (groupe SR 1.1)
ANDRIAMILANTO Tompoariniaina
IHSINE Azzeddine
*/
// Includes
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// Constants
#define LOOP 5
#define MQ_RIGHTS 0666|IPC_CREAT
#define MQ_KEY 42
#define BUFFER_SIZE 1024
#define MSG_TYPE 35
#define MSG_END_TYPE 37
struct message {
long type;
char msg[BUFFER_SIZE-sizeof(long)];
};
/**
* The main function to be thrown
*
* Return:
* - int => The result of the execution
*/
int main() {
// Create the message queue
int mq_id = msgget(MQ_KEY, MQ_RIGHTS);
if (mq_id == -1) fprintf(stderr, "Error creating the message queue with key %d\n", MQ_KEY);
// If really created
else {
// Here, send continuously messages
int count = 0;
struct message mess;
mess.type = MSG_TYPE;
while (count < LOOP) {
// Put the message into the buffer
snprintf(mess.msg, sizeof(mess.msg), "Je suis le message numéro %d", count);
fprintf(stderr, "%s\n", mess.msg);
// Increment the counter
++count;
// If the last message
if (count == LOOP) {
mess.type = MSG_END_TYPE;
strcpy(mess.msg, "Fin de la transmission");
}
// Send it
if (msgsnd(mq_id, &mess, BUFFER_SIZE, 0) == -1) fprintf(stderr, "Error during sending the message n°%d with key %d and id %d\n", count, MQ_KEY, mq_id);
// Wait a little before sending another message to the receiver
sleep(5);
}
// Delete the message queue
//if (msgctl(mq_id, IPC_RMID, 0) == -1) fprintf(stderr, "Error deleting the message queue with key %d and id %d\n", MQ_KEY, mq_id);
// We let the receiver delete the queue
}
return 0;
}
|
the_stack_data/137371.c | /* v1.0 - 20.Mar.94
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
asc2bin.c
Description:
~~~~~~~~~~~~
Program for converting samples in ascii format to its binary
representation.
Usage:
~~~~~~
$ asc2bin [-options] ascfile binfile
Where:
ascfile is the name of the input file in ascii format;
if ommited or if equal to "-", uses stdin
binfile is the name of the output, binary file;
if ommited or if equal to "-", uses stdout
Options:
-h data is in hex format
-d data is in decimal format (int) [default]
-short data is short int
-long data is long int
-float data is float
-double data is long double
Original Author:
~~~~~~~~~~~~~~~~
Simao Ferraz de Campos Neto -- CPqD/Telebras
<[email protected]>
History:
~~~~~~~~
20.Mar.94 v.1.0 Created.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* OS definition */
#ifdef __MSDOS__
#define MSDOS
#endif
/* includes in general */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* includes for DOS specific directives */
#if defined(MSDOS)
#include <fcntl.h>
#include <io.h>
#include <sys\stat.h>
/* includes for VMS specific directives */
#elif defined(VMS)
#include <perror.h>
#include <file.h>
/* includes for other OS (Unix) specific directives */
#else
#include <sys/stat.h>
#endif
/* ---------------------------- Display Usage ---------------------------- */
#define P(x) printf x
void display_usage()
{
P((" asc2bin: version 1.0 of 20.Mar.94 - <[email protected]>\n\n"));
P((" Program for converting samples in ascii format to its binary\n"));
P((" representation.\n"));
P(("\n"));
P((" Usage:\n"));
P((" $ asc2bin [-options] ascfile binfile\n"));
P((" Where:\n"));
P((" ascfile is the name of the input file in ascii format;\n"));
P((" if ommited or if equal to \"-\", uses stdin\n"));
P((" binfile is the name of the output, binary file;\n"));
P((" if ommited or if equal to \"-\", uses stdout\n"));
P(("\n"));
P((" Options:\n"));
P((" -h data is in hex format\n"));
P((" -d data is in decimal format (int) [default]\n"));
P((" -short data is short int\n"));
P((" -long data is long int\n"));
P((" -float data is float\n"));
P((" -double data is long double\n"));
/* Quit program */
exit(-128);
}
#undef P
/* .................. end of display_usage() .......................... */
/* ---------------------------- Main Routine ---------------------------- */
int main(argc, argv)
int argc;
char *argv[];
{
int d;
short hd;
unsigned short X;
long ld;
float f;
double lf;
long data_size = sizeof(hd);
long count = 0;
char NumberFormat = 'd';
char DataType = 'h';
void *data = &hd;
char fmt[10]; /* scanf format string */
FILE *fi, *fo;
static char *cvt_type_str[] = {"hexadecimal", "decimal", "float", "double",
"short", "long"};
enum conv {HEX, DEC, FLOAT, DOUBLE, SHORT, LONG};
int cvt_type=DEC; /* Default is decimal format */
/* Check options */
if (argc < 2)
display_usage();
else
{
while (argc > 1 && argv[1][0] == '-')
if (strcmp(argv[1], "-") == 0)
{
/* Stop processing options */
break;
}
else if (strcmp(argv[1], "-h") == 0)
{
/* Set dump as hex type */
NumberFormat = 'X';
DataType = 'h';
data = &X;
data_size = sizeof(X);
cvt_type = HEX;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else if (strcmp(argv[1], "-d") == 0)
{
/* Set dump in decimal format */
NumberFormat = 'd';
DataType = 0;
data = &d;
data_size = sizeof(d);
cvt_type = DEC;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else if (strcmp(argv[1], "-float") == 0)
{
/* Set data type as real */
NumberFormat = 'f';
DataType = 0;
data = &f;
data_size = sizeof(f);
cvt_type = FLOAT;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else if (strcmp(argv[1], "-double") == 0)
{
/* Set data type as double real */
NumberFormat = 'f';
DataType = 'l';
data = &lf;
data_size = sizeof(lf);
cvt_type = DOUBLE;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else if (strcmp(argv[1], "-short") == 0)
{
/* Set data type as short */
NumberFormat = 'd';
DataType = 'h';
data = &hd;
data_size = sizeof(hd);
cvt_type = SHORT;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else if (strcmp(argv[1], "-long") == 0)
{
/* Set data type as long */
NumberFormat = 'd';
DataType = 'l';
data = &ld;
data_size = sizeof(ld);
cvt_type = LONG;
/* Move arg{c,v} over the option to the next argument */
argc--;
argv++;
}
else
{
fprintf(stderr, "ERROR! Invalid option \"%s\" in command line\n\n",
argv[1]);
display_usage();
}
}
/* Parse file names */
switch(argc)
{
case 3:
fi = strcmp(argv[1],"-")==0 ? stdin : fopen(argv[1],"rt");
fo = strcmp(argv[2],"-")==0 ? stdout : fopen(argv[2],"wb");
break;
case 2:
fi = fopen(argv[1],"rt");
fo = stdout;
break;
case 1:
fi = stdin;
fo = stdout;
break;
}
/* Check for file opening errors */
if (fi==NULL)
return(perror(argv[1]),2);
if (fo==NULL)
return(perror(argv[2]),3);
/* Setup string conversion rules */
if (DataType)
sprintf(fmt, "%%%c%c", DataType, NumberFormat);
else
sprintf(fmt, "%%%c", NumberFormat);
/* Print info */
fprintf(stderr, "Data format is %s, each sample having %ld bytes\n",
cvt_type_str[cvt_type], data_size);
/* Convert ascii input to binary output */
while(fscanf(fi, fmt, data)==1)
{
fwrite(data, data_size, 1L, fo);
count++;
}
/* Closing program */
fprintf(stderr, "Converted %ld samples\n", count);
fclose(fi);
fclose(fo);
#ifndef VMS
return(0);
#endif
}
|
the_stack_data/18186.c | # 1 "lnautlib.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "lnautlib.c"
|
the_stack_data/716349.c | #include <stdlib.h>
#include <stdio.h>
#define MAX_NODE 100
typedef struct node{
int value;
struct node *next;
}Qnode;
typedef struct q{
Qnode *head;
Qnode *end;
}Q;
typedef struct s{
Qnode *top;
}S;
typedef struct g{
int value[MAX_NODE][MAX_NODE];
int length;
}G;
void initG (G *g){
for(int i=0; i<MAX_NODE;i++){
for(int j=0;j<MAX_NODE;j++){
g->value[i][j] = 0;
}
}
g->length = 0;
}
void connect(G *g, int x, int y){
if(x >= MAX_NODE || y >= MAX_NODE){
return;
}
g->value[x][y] = 1;
g->value[y][x] = 1;
g->length = g->length>x?g->length:(x+1);
g->length = g->length>y?g->length:(y+1);
}
void printG (const G *g){
for(int i=0; i<g->length;i++){
for(int j=0;j<g->length;j++){
printf("%d ",g->value[i][j]);
}
printf("\n");
}
}
void printQ (const Q *q){
Qnode *n = q->head;
while(n->next!=NULL){
printf("%d ", n->value);
n = n->next;
}
printf("\n");
}
void printS (const S *s){
Qnode *n = s->top;
while (n->next!=NULL){
printf("%d ", n->value);
n = n->next;
}
printf("\n");
}
void initQ (Q *q){
Qnode *n = malloc(sizeof(Qnode));
n->next = NULL;
q->head = n;
q->end = n;
}
void pushQ (Q *q, int value){
Qnode *n = malloc(sizeof(Qnode));
n->next = NULL;
n->value = 0;
q->end->value = value;
q->end->next = n;
q->end = n;
}
int popQ (Q *q){
int value = q->head->value;
Qnode *n = q->head;
q->head = q->head->next;
free(n);
return value;
}
int isInQueue(Q *q, int v){
Qnode *n = q->head;
while (n->next != NULL){
if(n->value == v) return 1;
n = n->next;
}
return 0;
}
void initS(S *s){
Qnode *n = malloc(sizeof(Qnode));
n->next = NULL;
s->top = n;
}
void pushS(S *s, int v){
Qnode *n = malloc(sizeof(Qnode));
n->next = s->top;
n->value = v;
s->top = n;
}
int popS(S *s){
int value = s->top->value;
Qnode *n = s->top;
s->top = s->top->next;
free(n);
return value;
}
int isInStack(S *s, int v){
Qnode *n = s->top;
while (n->next!=NULL){
if(n->value == v) return 1;
n = n->next;
}
return 0;
}
void breadIter(G *g, Q *q, int source){
int count = 0;
for(int i=0; i<g->length; ++i){
int v = g->value[source][i];
if(v && !isInQueue(q, i)){
pushQ(q, i);
count ++;
}
}
if(!count) return;
Qnode *n = q->head;
while (n->next != NULL){
breadIter(g, q, n->value);
n = n->next;
}
}
void deepIter(G *g, Q *q, int source){
for(int i=0; i<g->length; ++i){
int v = g->value[source][i];
if(v && !isInStack(q, i)){
pushQ(q, i);
deepIter(g, q, i);
}
}
}
void BFS(G *g, int source){
Q q;
initQ(&q);
pushQ(&q, source);
breadIter(g, &q, source);
printQ(&q);
}
void DFS(G *g, int source){
Q q;
initQ(&q);
pushQ(&q, source);
deepIter(g, &q, source);
printQ(&q);
}
int main(){
G graph;
Q queue;
S stack;
initG(&graph);
initQ(&queue);
initS(&stack);
connect(&graph, 0, 1);
connect(&graph, 0, 2);
connect(&graph, 1, 3);
connect(&graph, 1, 4);
connect(&graph, 2, 5);
connect(&graph, 2, 6);
connect(&graph, 3, 7);
connect(&graph, 4, 7);
connect(&graph, 5, 6);
printG(&graph);
pushQ(&queue, 1);
pushQ(&queue, 2);
pushQ(&queue, 3);
pushQ(&queue, 4);
printQ(&queue);
popQ(&queue);
printQ(&queue);
pushS(&stack, 1);
pushS(&stack, 2);
pushS(&stack, 3);
pushS(&stack, 4);
printS(&stack);
popS(&stack);
printS(&stack);
BFS(&graph, 0);
DFS(&graph, 0);
}
|
the_stack_data/590093.c | #include <stdio.h>
int main()
{
int n = 5, mid = n/2 + 1;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(j == 1 || j == n || i == mid)
printf("H ");
else
printf(" ");
}
printf("\n");
}
return 0;
} |
the_stack_data/1226649.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
* gcc-4.8 -m32 -O0 -S sample15.c -o sample15.s
*
* $Id: sample15.c $
* $Lastupdate: 2020/06/10 18:44:07 $
*/
/*
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
*--------+---------+---------+---------+---------X---------+---------+---------+---------+---------X
*/
int fun(void)
{
return 16;
}
int main(void)
{
int a;
a = fun();
return 0;
}
|
the_stack_data/248579771.c | #include<stdio.h>
void inputProduction(int array[], int size);
int minimumProduction(int array[], int size);
int maximumProduction(int array[], int size);
void averageProduction(int array1[], int array2[], float array3[], int size);
void printProduction(int array[], int size);
void displayDay(int array[], int size, int production);
int main()
{
int machine_A[7], machine_B[7];
float machine_Total[7];
printf("Machine A\n");
inputProduction(machine_A, 7);
printf("\nMachine B\n");
inputProduction(machine_B, 7);
printf("\n\nHighest production day of Machine A: ");
displayDay(machine_A, 7, maximumProduction(machine_A, 7));
printf("\nHighest production day of Machine B: ");
displayDay(machine_B, 7, maximumProduction(machine_B, 7));
printf("\nLowest production day of Machine A: ");
displayDay(machine_A, 7, minimumProduction(machine_A, 7));
printf("\nLowest production day of Machine B: ");
displayDay(machine_B, 7, minimumProduction(machine_B, 7));
printf("\n\nAverage Production for each day: \n");
averageProduction(machine_A, machine_B, machine_Total, 7);
printf("\nProduction of Machine A\n");
printProduction(machine_A, 7);
printf("\nProduction of Machine B\n");
printProduction(machine_B, 7);
return 0;
}
void inputProduction(int array[], int size)
{
int i;
for (i = 0; i < size; ++i) {
printf("Input productoin of day %d: ", i+1);
scanf("%d", &array[i]);
}
}
int minimumProduction(int array[], int size)
{
int i, min;
min = array[0];
for (i = 1; i < size; ++i) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
int maximumProduction(int array[], int size)
{
int i, max;
max = array[0];
for (i = 1; i < size; ++i) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
void averageProduction(int array1[], int array2[], float array3[], int size)
{
int i;
for (i = 0; i < size; ++i) {
array3[i] = (array1[i] + array2[i]) / 2.0;
printf("%d\t%.2f\n", i+1, array3[i]);
}
}
void printProduction(int array[], int size)
{
int i, j, asterisk;
for (i = 0; i < size; ++i) {
if (array[i] % 10 < 5)
asterisk = array[i] / 10;
else if (array[i] % 10 >= 5)
asterisk = array[i] / 10 + 1;
for (j = 1; j <= asterisk; ++j) {
printf("*");
}
printf("\n");
}
}
void displayDay(int array[], int size, int production)
{
int i, day;
for (i = 0; i < size; ++i) {
if (array[i] == production) {
day = i;
break;
}
}
switch (day) {
case 0: printf("Monday");
break;
case 1: printf("Tuesday");
break;
case 2: printf("Wednesday");
break;
case 3: printf("Thursday");
break;
case 4: printf("Friday");
break;
case 5: printf("Saturday");
break;
case 6: printf("Sunday");
break;
default: ;
}
}
|
the_stack_data/14201560.c | #include <stdio.h>
#include <string.h>
#define MAXLINE 1000
int mygetline(char *line, int max);
int main(int argc, char *argv[]){
char line[MAXLINE];
long lineno = 0;
int c, except = 0, number = 0, found = 0;
while (--argc > 0 && (*++argv)[0] == '-')
while ((c = *++argv[0]))
switch(c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find: illegal option %c\n", c);
argc = 0;
found = -1;
break;
}
if(argc != 1)
printf("Usage: find -x -n pattern\n");
else
while (mygetline(line, MAXLINE) > 0) {
lineno++;
if ((strstr(line, *argv) != NULL) != except) {
if (number)
printf("%ld: ", lineno);
printf("%s", line);
found++;
}
}
return found;
}
/* getline: get line into s, return length */
int mygetline(char *s, int lim) {
int c;
char *t = s;
while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
*s++ = c;
if (c == '\n')
*s++ = c;
*s = '\0';
return s -t;
}
|
the_stack_data/98574683.c |
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void insertBefore(struct Node** head_ref,
struct Node* next_node, int new_data)
{
if (next_node == NULL) {
printf("the given next node cannot be NULL");
return;
}
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = next_node->prev;
next_node->prev = new_node;
new_node->next = next_node;
if (new_node->prev != NULL)
new_node->prev->next = new_node;
else
(*head_ref) = new_node;
}
void printList(struct Node* node)
{
struct Node* last;
printf("\nTraversal in forward direction \n");
while (node != NULL) {
printf(" %d ", node->data);
last = node;
node = node->next;
}
printf("\nTraversal in reverse direction \n");
while (last != NULL) {
printf(" %d ", last->data);
last = last->prev;
}
}
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 4);
// Insert 8, before 1. So linked list becomes
// 4->8->1->7->NULL
insertBefore(&head, head->next, 8);
printf("Created DLL is: ");
printList(head);
getchar();
return 0;
}
|
the_stack_data/20448936.c | /*exerxixio_10_vetores*/
#include <stdio.h>
int main()
{
int i;
float notas[15], media;
for(i=0;i<15;i++)
{
printf("\n");
printf(" Digite a nota do %d aluno: ", i+1);
scanf("%f", ¬as[i]);
media += notas[i];
}
printf("\n A media geral é: %.1f", media/15.0);
return 0;
} |
the_stack_data/7951371.c | #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}
|
the_stack_data/151704443.c | // Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
* Copyright (C) 2009-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : testplug.c
*
* Date Name Description
* 10/29/2009 srl New.
******************************************************************************
*
*
* This file implements a number of example ICU plugins.
*
*/
#include "unicode/icuplug.h"
#if UCONFIG_ENABLE_PLUGINS
/* This file isn't usually compiled except on Windows. Guard it. */
#include <stdio.h> /* for fprintf */
#include <stdlib.h> /* for malloc */
#include "udbgutil.h"
#include "unicode/uclean.h"
#include "cmemory.h"
/**
* Prototypes
*/
#define DECLARE_PLUGIN(x) U_CAPI UPlugTokenReturn U_EXPORT2 x (UPlugData *data, UPlugReason reason, UErrorCode *status)
DECLARE_PLUGIN(myPlugin);
DECLARE_PLUGIN(myPluginLow);
DECLARE_PLUGIN(myPluginFailQuery);
DECLARE_PLUGIN(myPluginFailToken);
DECLARE_PLUGIN(myPluginBad);
DECLARE_PLUGIN(myPluginHigh);
DECLARE_PLUGIN(debugMemoryPlugin);
/**
* A simple, trivial plugin.
*/
U_CAPI
UPlugTokenReturn U_EXPORT2 myPlugin (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
/* Just print this for debugging */
fprintf(stderr,"MyPlugin: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugName(data, "Just a Test High-Level Plugin"); /* This call is optional in response to UPLUG_REASON_QUERY, but is a good idea. */
uplug_setPlugLevel(data, UPLUG_LEVEL_HIGH); /* This call is Mandatory in response to UPLUG_REASON_QUERY */
}
return UPLUG_TOKEN; /* This must always be returned, to indicate that the entrypoint was actually a plugin. */
}
U_CAPI
UPlugTokenReturn U_EXPORT2 myPluginLow (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"MyPluginLow: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugName(data, "Low Plugin");
uplug_setPlugLevel(data, UPLUG_LEVEL_LOW);
}
return UPLUG_TOKEN;
}
/**
* Doesn't respond to QUERY properly.
*/
U_CAPI
UPlugTokenReturn U_EXPORT2 myPluginFailQuery (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"MyPluginFailQuery: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
/* Should respond to UPLUG_REASON_QUERY here. */
return UPLUG_TOKEN;
}
/**
* Doesn't return the proper token.
*/
U_CAPI
UPlugTokenReturn U_EXPORT2 myPluginFailToken (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"MyPluginFailToken: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugName(data, "myPluginFailToken Plugin");
uplug_setPlugLevel(data, UPLUG_LEVEL_LOW);
}
return 0; /* Wrong. */
}
/**
* Says it's low, but isn't.
*/
U_CAPI
UPlugTokenReturn U_EXPORT2 myPluginBad (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"MyPluginLow: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugName(data, "Bad Plugin");
uplug_setPlugLevel(data, UPLUG_LEVEL_LOW);
} else if(reason == UPLUG_REASON_LOAD) {
void *ctx = uprv_malloc(12345);
uplug_setContext(data, ctx);
fprintf(stderr,"I'm %p and I did a bad thing and malloced %p\n", (void*)data, (void*)ctx);
} else if(reason == UPLUG_REASON_UNLOAD) {
void * ctx = uplug_getContext(data);
uprv_free(ctx);
}
return UPLUG_TOKEN;
}
U_CAPI
UPlugTokenReturn U_EXPORT2 myPluginHigh (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"MyPluginHigh: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugName(data, "High Plugin");
uplug_setPlugLevel(data, UPLUG_LEVEL_HIGH);
}
return UPLUG_TOKEN;
}
/* Debug Memory Plugin (see hpmufn.c) */
static void * U_CALLCONV myMemAlloc(const void *context, size_t size) {
void *retPtr = (void *)malloc(size);
(void)context; /* unused */
fprintf(stderr, "MEM: malloc(%d) = %p\n", (int32_t)size, retPtr);
return retPtr;
}
static void U_CALLCONV myMemFree(const void *context, void *mem) {
(void)context; /* unused */
free(mem);
fprintf(stderr, "MEM: free(%p)\n", mem);
}
static void * U_CALLCONV myMemRealloc(const void *context, void *mem, size_t size) {
void *retPtr;
(void)context; /* unused */
if(mem==NULL) {
retPtr = NULL;
} else {
retPtr = realloc(mem, size);
}
fprintf(stderr, "MEM: realloc(%p, %d) = %p\n", mem, (int32_t)size, retPtr);
return retPtr;
}
U_CAPI
UPlugTokenReturn U_EXPORT2 debugMemoryPlugin (
UPlugData *data,
UPlugReason reason,
UErrorCode *status) {
fprintf(stderr,"debugMemoryPlugin: data=%p, reason=%s, status=%s\n", (void*)data, udbg_enumName(UDBG_UPlugReason,(int32_t)reason), u_errorName(*status));
if(reason==UPLUG_REASON_QUERY) {
uplug_setPlugLevel(data, UPLUG_LEVEL_LOW);
uplug_setPlugName(data, "Memory Plugin");
} else if(reason==UPLUG_REASON_LOAD) {
u_setMemoryFunctions(uplug_getContext(data), &myMemAlloc, &myMemRealloc, &myMemFree, status);
fprintf(stderr, "MEM: status now %s\n", u_errorName(*status));
} else if(reason==UPLUG_REASON_UNLOAD) {
fprintf(stderr, "MEM: not possible to unload this plugin (no way to reset memory functions)...\n");
uplug_setPlugNoUnload(data, TRUE);
}
return UPLUG_TOKEN;
}
#endif
|
the_stack_data/600270.c | #include <stdio.h>
#include <stdlib.h>
extern char **environ;
int
main(int argc, char *argv[])
{
char **p;
for (p = environ; *p; p++) {
printf("%s\n", *p);
}
exit(0);
}
|
the_stack_data/15761924.c | #include <stdio.h>
//1.先定义枚举类型,再定义枚举变量
enum Season {spring, summer, autumn, winter};
enum Season s;
//2.定义枚举类型的同时定义枚举变量
enum Season2 {spring2, summer2, autumn2, winter2} s2;
//3.省略枚举名称,直接定义枚举变量
enum {spring3, summer3, autumn3, winter3} s3;
int main() {
// enum Season {spring, summer, autumn, winter} s;
// 遍历枚举元素
for (s = spring; s <= winter; s++) {
printf("枚举元素:%d \n", s);
}
return 0;
}
|
the_stack_data/198582043.c | #include <string.h>
#if defined (STACK_SIZE)
#define MEMCPY_SIZE (STACK_SIZE / 3)
#else
#define MEMCPY_SIZE (1 << 17)
#endif
void *copy (void *o, const void *i, unsigned l)
{
return memcpy (o, i, l);
}
main ()
{
unsigned i;
unsigned char src[MEMCPY_SIZE];
unsigned char dst[MEMCPY_SIZE];
for (i = 0; i < MEMCPY_SIZE; i++)
src[i] = (unsigned char) i, dst[i] = 0;
(void) memcpy (dst, src, MEMCPY_SIZE / 128);
for (i = 0; i < MEMCPY_SIZE / 128; i++)
if (dst[i] != (unsigned char) i)
abort ();
(void) memset (dst, 1, MEMCPY_SIZE / 128);
for (i = 0; i < MEMCPY_SIZE / 128; i++)
if (dst[i] != 1)
abort ();
(void) memcpy (dst, src, MEMCPY_SIZE);
for (i = 0; i < MEMCPY_SIZE; i++)
if (dst[i] != (unsigned char) i)
abort ();
(void) memset (dst, 0, MEMCPY_SIZE);
for (i = 0; i < MEMCPY_SIZE; i++)
if (dst[i] != 0)
abort ();
(void) copy (dst, src, MEMCPY_SIZE / 128);
for (i = 0; i < MEMCPY_SIZE / 128; i++)
if (dst[i] != (unsigned char) i)
abort ();
(void) memset (dst, 0, MEMCPY_SIZE);
(void) copy (dst, src, MEMCPY_SIZE);
for (i = 0; i < MEMCPY_SIZE; i++)
if (dst[i] != (unsigned char) i)
abort ();
exit (0);
}
|
the_stack_data/190767661.c | #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define MYPORT 3490 /*定义用户连接端口*/
#define BACKLOG 10 /*多少等待连接控制*/
int main(void)
{
int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(my_addr.sin_zero, sizeof(my_addr.sin_zero)); /* zero the rest of the struct */
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
while(1) { /* main accept() loop */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s\n", \
inet_ntoa(their_addr.sin_addr));
if (!fork()) { /* this is the child process */
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); /* parent doesn't need this */
while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */
}
return 0;
}
|
the_stack_data/148577562.c | #include <string.h>
size_t
strxfrm_l(char *restrict s1, const char *restrict s2, size_t n, locale_t locale)
{
return 0; /* TODO */
}
|
the_stack_data/21404.c | #include <stdio.h>
#define KEY_LENGTH 7 // Can be anything from 1 to 13
main(){
unsigned char ch;
FILE *fpIn, *fpOut;
int i;
unsigned char key[KEY_LENGTH] = {0xAB,0x56,0xC2,0xB2,0x53,0x9E,0x3E};
/* of course, I did not use the all-0s key to encrypt */
fpIn = fopen("ptext.txt", "r");
fpOut = fopen("ctext.txt", "w");
i=0;
while (fscanf(fpIn, "%c", &ch) != EOF) {
/* avoid encrypting newline characters */
/* In a "real-world" implementation of the Vigenere cipher,
every ASCII character in the plaintext would be encrypted.
However, I want to avoid encrypting newlines here because
it makes recovering the plaintext slightly more difficult... */
/* ...and my goal is not to create "production-quality" code =) */
if (ch!='\n') {
fprintf(fpOut, "%02X", ch ^ key[i % KEY_LENGTH]); // ^ is logical XOR
i++;
}
}
fclose(fpIn);
fclose(fpOut);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.