file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/76507.c | /*Program to display the pattern
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
.............
upto given number of rows
*/
void main()
{
unsigned int i,j,n; //i and j are the loop controllers
clrscr();
printf("Enter the number of rows : ");
scanf("%u",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf(" %u",j);
}
for(j=(i-1);j>0;j--)
{
printf(" %u",j);
}
printf("\n");
}
printf("\nPress any key..... ");
getch();
} |
the_stack_data/206394207.c | /*
This is a version (aka dlmalloc) of malloc/free/realloc written by
Doug Lea and released to the public domain, as explained at
http://creativecommons.org/publicdomain/zero/1.0/ Send questions,
comments, complaints, performance data, etc to [email protected]
* This is modified by to be the code used for WA1 malloc. It's a
reference.
* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea
Note: There may be an updated version of this malloc obtainable at
ftp://gee.cs.oswego.edu/pub/misc/malloc.c
Check before installing!
* Quickstart
This library is all in one file to simplify the most common usage:
ftp it, compile it (-O3), and link it into another program. All of
the compile-time options default to reasonable values for use on
most platforms. You might later want to step through various
compile-time and dynamic tuning options.
For convenience, an include file for code using this malloc is at:
ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h
You don't really need this .h file unless you call functions not
defined in your system include files. The .h file contains only the
excerpts from this file needed for using this malloc on ANSI C/C++
systems, so long as you haven't changed compile-time options about
naming and tuning parameters. If you do, then you can create your
own malloc.h that does include all settings by cutting at the point
indicated below. Note that you may already by default be using a C
library containing a malloc that is based on some version of this
malloc (for example in linux). You might still want to use the one
in this file to customize settings or to avoid overheads associated
with library versions.
* Vital statistics:
Supported pointer/size_t representation: 4 or 8 bytes
size_t MUST be an unsigned type of the same width as
pointers. (If you are using an ancient system that declares
size_t as a signed type, or need it to be a different width
than pointers, you can use a previous release of this malloc
(e.g. 2.7.2) supporting these.)
Alignment: 8 bytes (minimum)
This suffices for nearly all current machines and C compilers.
However, you can define MALLOC_ALIGNMENT to be wider than this
if necessary (up to 128bytes), at the expense of using more space.
Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
8 or 16 bytes (if 8byte sizes)
Each malloced chunk has a hidden word of overhead holding size
and status information, and additional cross-check word
if FOOTERS is defined.
Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
8-byte ptrs: 32 bytes (including overhead)
Even a request for zero bytes (i.e., malloc(0)) returns a
pointer to something of the minimum allocatable size.
The maximum overhead wastage (i.e., number of extra bytes
allocated than were requested in malloc) is less than or equal
to the minimum size, except for requests >= mmap_threshold that
are serviced via mmap(), where the worst case wastage is about
32 bytes plus the remainder from a system page (the minimal
mmap unit); typically 4096 or 8192 bytes.
Security: static-safe; optionally more or less
The "security" of malloc refers to the ability of malicious
code to accentuate the effects of errors (for example, freeing
space that is not currently malloc'ed or overwriting past the
ends of chunks) in code that calls malloc. This malloc
guarantees not to modify any memory locations below the base of
heap, i.e., static variables, even in the presence of usage
errors. The routines additionally detect most improper frees
and reallocs. All this holds as long as the static bookkeeping
for malloc itself is not corrupted by some other means. This
is only one aspect of security -- these checks do not, and
cannot, detect all possible programming errors.
If FOOTERS is defined nonzero, then each allocated chunk
carries an additional check word to verify that it was malloced
from its space. These check words are the same within each
execution of a program using malloc, but differ across
executions, so externally crafted fake chunks cannot be
freed. This improves security by rejecting frees/reallocs that
could corrupt heap memory, in addition to the checks preventing
writes to statics that are always on. This may further improve
security at the expense of time and space overhead. (Note that
FOOTERS may also be worth using with MSPACES.)
By default detected errors cause the program to abort (calling
"abort()"). You can override this to instead proceed past
errors by defining PROCEED_ON_ERROR. In this case, a bad free
has no effect, and a malloc that encounters a bad address
caused by user overwrites will ignore the bad address by
dropping pointers and indices to all known memory. This may
be appropriate for programs that should continue if at all
possible in the face of programming errors, although they may
run out of memory because dropped memory is never reclaimed.
If you don't like either of these options, you can define
CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
else. And if if you are sure that your program using malloc has
no errors or vulnerabilities, you can define INSECURE to 1,
which might (or might not) provide a small performance improvement.
It is also possible to limit the maximum total allocatable
space, using malloc_set_footprint_limit. This is not
designed as a security feature in itself (calls to set limits
are not screened or privileged), but may be useful as one
aspect of a secure implementation.
Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero
When USE_LOCKS is defined, each public call to malloc, free,
etc is surrounded with a lock. By default, this uses a plain
pthread mutex, win32 critical section, or a spin-lock if if
available for the platform and not disabled by setting
USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined,
recursive versions are used instead (which are not required for
base functionality but may be needed in layered extensions).
Using a global lock is not especially fast, and can be a major
bottleneck. It is designed only to provide minimal protection
in concurrent environments, and to provide a basis for
extensions. If you are using malloc in a concurrent program,
consider instead using nedmalloc
(http://www.nedprod.com/programs/portable/nedmalloc/) or
ptmalloc (See http://www.malloc.de), which are derived from
versions of this malloc.
System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
This malloc can use unix sbrk or any emulation (invoked using
the CALL_MORECORE macro) and/or mmap/munmap or any emulation
(invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
memory. On most unix systems, it tends to work best if both
MORECORE and MMAP are enabled. On Win32, it uses emulations
based on VirtualAlloc. It also uses common C library functions
like memset.
Compliance: I believe it is compliant with the Single Unix Specification
(See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
others as well.
* Overview of algorithms
This is not the fastest, most space-conserving, most portable, or
most tunable malloc ever written. However it is among the fastest
while also being among the most space-conserving, portable and
tunable. Consistent balance across these factors results in a good
general-purpose allocator for malloc-intensive programs.
In most ways, this malloc is a best-fit allocator. Generally, it
chooses the best-fitting existing chunk for a request, with ties
broken in approximately least-recently-used order. (This strategy
normally maintains low fragmentation.) However, for requests less
than 256bytes, it deviates from best-fit when there is not an
exactly fitting available chunk by preferring to use space adjacent
to that used for the previous small request, as well as by breaking
ties in approximately most-recently-used order. (These enhance
locality of series of small allocations.) And for very large requests
(>= 256Kb by default), it relies on system memory mapping
facilities, if supported. (This helps avoid carrying around and
possibly fragmenting memory used only for large chunks.)
All operations (except malloc_stats and mallinfo) have execution
times that are bounded by a constant factor of the number of bits in
a size_t, not counting any clearing in calloc or copying in realloc,
or actions surrounding MORECORE and MMAP that have times
proportional to the number of non-contiguous regions returned by
system allocation routines, which is often just 1. In real-time
applications, you can optionally suppress segment traversals using
NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
system allocators return non-contiguous spaces, at the typical
expense of carrying around more memory and increased fragmentation.
The implementation is not very modular and seriously overuses
macros. Perhaps someday all C compilers will do as good a job
inlining modular code as can now be done by brute-force expansion,
but now, enough of them seem not to.
Some compilers issue a lot of warnings about code that is
dead/unreachable only on some platforms, and also about intentional
uses of negation on unsigned types. All known cases of each can be
ignored.
For a longer but out of date high-level description, see
http://gee.cs.oswego.edu/dl/html/malloc.html
* MSPACES
If MSPACES is defined, then in addition to malloc, free, etc.,
this file also defines mspace_malloc, mspace_free, etc. These
are versions of malloc routines that take an "mspace" argument
obtained using create_mspace, to control all internal bookkeeping.
If ONLY_MSPACES is defined, only these versions are compiled.
So if you would like to use this allocator for only some allocations,
and your system malloc for others, you can compile with
ONLY_MSPACES and then do something like...
static mspace mymspace = create_mspace(0,0); // for example
#define mymalloc(bytes) mspace_malloc(mymspace, bytes)
(Note: If you only need one instance of an mspace, you can instead
use "USE_DL_PREFIX" to relabel the global malloc.)
You can similarly create thread-local allocators by storing
mspaces as thread-locals. For example:
static __thread mspace tlms = 0;
void* tlmalloc(size_t bytes) {
if (tlms == 0) tlms = create_mspace(0, 0);
return mspace_malloc(tlms, bytes);
}
void tlfree(void* mem) { mspace_free(tlms, mem); }
Unless FOOTERS is defined, each mspace is completely independent.
You cannot allocate from one and free to another (although
conformance is only weakly checked, so usage errors are not always
caught). If FOOTERS is defined, then each chunk carries around a tag
indicating its originating mspace, and frees are directed to their
originating spaces. Normally, this requires use of locks.
------------------------- Compile-time options ---------------------------
Be careful in setting #define values for numerical constants of type
size_t. On some systems, literal values are not automatically extended
to size_t precision unless they are explicitly casted. You can also
use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
WIN32 default: defined if _WIN32 defined
Defining WIN32 sets up defaults for MS environment and compilers.
Otherwise defaults are for unix. Beware that there seem to be some
cases where this malloc might not be a pure drop-in replacement for
Win32 malloc: Random-looking failures from Win32 GDI API's (eg;
SetDIBits()) may be due to bugs in some video driver implementations
when pixel buffers are malloc()ed, and the region spans more than
one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)
default granularity, pixel buffers may straddle virtual allocation
regions more often than when using the Microsoft allocator. You can
avoid this by using VirtualAlloc() and VirtualFree() for all pixel
buffers rather than using malloc(). If this is not possible,
recompile this malloc with a larger DEFAULT_GRANULARITY. Note:
in cases where MSC and gcc (cygwin) are known to differ on WIN32,
conditions use _MSC_VER to distinguish them.
DLMALLOC_EXPORT default: extern
Defines how public APIs are declared. If you want to export via a
Windows DLL, you might define this as
#define DLMALLOC_EXPORT extern __declspec(dllexport)
If you want a POSIX ELF shared object, you might use
#define DLMALLOC_EXPORT extern __attribute__((visibility("default")))
MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *))
Controls the minimum alignment for malloc'ed chunks. It must be a
power of two and at least 8, even on machines for which smaller
alignments would suffice. It may be defined as larger than this
though. Note however that code and data structures are optimized for
the case of 8-byte alignment.
MSPACES default: 0 (false)
If true, compile in support for independent allocation spaces.
This is only supported if HAVE_MMAP is true.
ONLY_MSPACES default: 0 (false)
If true, only compile in mspace versions, not regular versions.
USE_LOCKS default: 0 (false)
Causes each call to each public routine to be surrounded with
pthread or WIN32 mutex lock/unlock. (If set true, this can be
overridden on a per-mspace basis for mspace versions.) If set to a
non-zero value other than 1, locks are used, but their
implementation is left out, so lock functions must be supplied manually,
as described below.
USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available
If true, uses custom spin locks for locking. This is currently
supported only gcc >= 4.1, older gccs on x86 platforms, and recent
MS compilers. Otherwise, posix locks or win32 critical sections are
used.
USE_RECURSIVE_LOCKS default: not defined
If defined nonzero, uses recursive (aka reentrant) locks, otherwise
uses plain mutexes. This is not required for malloc proper, but may
be needed for layered allocators such as nedmalloc.
LOCK_AT_FORK default: not defined
If defined nonzero, performs pthread_atfork upon initialization
to initialize child lock while holding parent lock. The implementation
assumes that pthread locks (not custom locks) are being used. In other
cases, you may need to customize the implementation.
FOOTERS default: 0
If true, provide extra checking and dispatching by placing
information in the footers of allocated chunks. This adds
space and time overhead.
INSECURE default: 0
If true, omit checks for usage errors and heap space overwrites.
USE_DL_PREFIX default: NOT defined
Causes compiler to prefix all public routines with the string 'dl'.
This can be useful when you only want to use this malloc in one part
of a program, using your regular system malloc elsewhere.
MALLOC_INSPECT_ALL default: NOT defined
If defined, compiles malloc_inspect_all and mspace_inspect_all, that
perform traversal of all heap space. Unless access to these
functions is otherwise restricted, you probably do not want to
include them in secure implementations.
ABORT default: defined as abort()
Defines how to abort on failed checks. On most systems, a failed
check cannot die with an "assert" or even print an informative
message, because the underlying print routines in turn call malloc,
which will fail again. Generally, the best policy is to simply call
abort(). It's not very useful to do more than this because many
errors due to overwriting will show up as address faults (null, odd
addresses etc) rather than malloc-triggered checks, so will also
abort. Also, most compilers know that abort() does not return, so
can better optimize code conditionally calling it.
PROCEED_ON_ERROR default: defined as 0 (false)
Controls whether detected bad addresses cause them to bypassed
rather than aborting. If set, detected bad arguments to free and
realloc are ignored. And all bookkeeping information is zeroed out
upon a detected overwrite of freed heap space, thus losing the
ability to ever return it from malloc again, but enabling the
application to proceed. If PROCEED_ON_ERROR is defined, the
static variable malloc_corruption_error_count is compiled in
and can be examined to see if errors have occurred. This option
generates slower code than the default abort policy.
DEBUG default: NOT defined
The DEBUG setting is mainly intended for people trying to modify
this code or diagnose problems when porting to new platforms.
However, it may also be able to better isolate user errors than just
using runtime checks. The assertions in the check routines spell
out in more detail the assumptions and invariants underlying the
algorithms. The checking is fairly extensive, and will slow down
execution noticeably. Calling malloc_stats or mallinfo with DEBUG
set will attempt to check every non-mmapped allocated and free chunk
in the course of computing the summaries.
ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
Debugging assertion failures can be nearly impossible if your
version of the assert macro causes malloc to be called, which will
lead to a cascade of further failures, blowing the runtime stack.
ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
which will usually make debugging easier.
MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
The action to take before "return 0" when malloc fails to be able to
return memory because there is none available.
HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
True if this system supports sbrk or an emulation of it.
MORECORE default: sbrk
The name of the sbrk-style system routine to call to obtain more
memory. See below for guidance on writing custom MORECORE
functions. The type of the argument to sbrk/MORECORE varies across
systems. It cannot be size_t, because it supports negative
arguments, so it is normally the signed type of the same width as
size_t (sometimes declared as "intptr_t"). It doesn't much matter
though. Internally, we only call it with arguments less than half
the max value of a size_t, which should work across all reasonable
possibilities, although sometimes generating compiler warnings.
MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE
If true, take advantage of fact that consecutive calls to MORECORE
with positive arguments always return contiguous increasing
addresses. This is true of unix sbrk. It does not hurt too much to
set it true anyway, since malloc copes with non-contiguities.
Setting it false when definitely non-contiguous saves time
and possibly wasted space it would take to discover this though.
MORECORE_CANNOT_TRIM default: NOT defined
True if MORECORE cannot release space back to the system when given
negative arguments. This is generally necessary only if you are
using a hand-crafted MORECORE function that cannot handle negative
arguments.
NO_SEGMENT_TRAVERSAL default: 0
If non-zero, suppresses traversals of memory segments
returned by either MORECORE or CALL_MMAP. This disables
merging of segments that are contiguous, and selectively
releasing them to the OS if unused, but bounds execution times.
HAVE_MMAP default: 1 (true)
True if this system supports mmap or an emulation of it. If so, and
HAVE_MORECORE is not true, MMAP is used for all system
allocation. If set and HAVE_MORECORE is true as well, MMAP is
primarily used to directly allocate very large blocks. It is also
used as a backup strategy in cases where MORECORE fails to provide
space from system. Note: A single call to MUNMAP is assumed to be
able to unmap memory that may have be allocated using multiple calls
to MMAP, so long as they are adjacent.
HAVE_MREMAP default: 1 on linux, else 0
If true realloc() uses mremap() to re-allocate large blocks and
extend or shrink allocation spaces.
MMAP_CLEARS default: 1 except on WINCE.
True if mmap clears memory so calloc doesn't need to. This is true
for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
USE_BUILTIN_FFS default: 0 (i.e., not used)
Causes malloc to use the builtin ffs() function to compute indices.
Some compilers may recognize and intrinsify ffs to be faster than the
supplied C version. Also, the case of x86 using gcc is special-cased
to an asm instruction, so is already as fast as it can be, and so
this setting has no effect. Similarly for Win32 under recent MS compilers.
(On most x86s, the asm version is only slightly faster than the C version.)
malloc_getpagesize default: derive from system includes, or 4096.
The system page size. To the extent possible, this malloc manages
memory from the system in page-size units. This may be (and
usually is) a function rather than a constant. This is ignored
if WIN32, where page size is determined using getSystemInfo during
initialization.
USE_DEV_RANDOM default: 0 (i.e., not used)
Causes malloc to use /dev/random to initialize secure magic seed for
stamping footers. Otherwise, the current time is used.
NO_MALLINFO default: 0
If defined, don't compile "mallinfo". This can be a simple way
of dealing with mismatches between system declarations and
those in this file.
MALLINFO_FIELD_TYPE default: size_t
The type of the fields in the mallinfo struct. This was originally
defined as "int" in SVID etc, but is more usefully defined as
size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
NO_MALLOC_STATS default: 0
If defined, don't compile "malloc_stats". This avoids calls to
fprintf and bringing in stdio dependencies you might not want.
REALLOC_ZERO_BYTES_FREES default: not defined
This should be set if a call to realloc with zero bytes should
be the same as a call to free. Some people think it should. Otherwise,
since this malloc returns a unique pointer for malloc(0), so does
realloc(p, 0).
LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32
Define these if your system does not have these header files.
You might need to manually insert some of the declarations they provide.
DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
system_info.dwAllocationGranularity in WIN32,
otherwise 64K.
Also settable using mallopt(M_GRANULARITY, x)
The unit for allocating and deallocating memory from the system. On
most systems with contiguous MORECORE, there is no reason to
make this more than a page. However, systems with MMAP tend to
either require or encourage larger granularities. You can increase
this value to prevent system allocation functions to be called so
often, especially if they are slow. The value must be at least one
page and must be a power of two. Setting to 0 causes initialization
to either page size or win32 region size. (Note: In previous
versions of malloc, the equivalent of this option was called
"TOP_PAD")
DEFAULT_TRIM_THRESHOLD default: 2MB
Also settable using mallopt(M_TRIM_THRESHOLD, x)
The maximum amount of unused top-most memory to keep before
releasing via malloc_trim in free(). Automatic trimming is mainly
useful in long-lived programs using contiguous MORECORE. Because
trimming via sbrk can be slow on some systems, and can sometimes be
wasteful (in cases where programs immediately afterward allocate
more large chunks) the value should be high enough so that your
overall system performance would improve by releasing this much
memory. As a rough guide, you might set to a value close to the
average size of a process (program) running on your system.
Releasing this much memory would allow such a process to run in
memory. Generally, it is worth tuning trim thresholds when a
program undergoes phases where several large chunks are allocated
and released in ways that can reuse each other's storage, perhaps
mixed with phases where there are no such chunks at all. The trim
value must be greater than page size to have any useful effect. To
disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
some people use of mallocing a huge space and then freeing it at
program startup, in an attempt to reserve system memory, doesn't
have the intended effect under automatic trimming, since that memory
will immediately be returned to the system.
DEFAULT_MMAP_THRESHOLD default: 256K
Also settable using mallopt(M_MMAP_THRESHOLD, x)
The request size threshold for using MMAP to directly service a
request. Requests of at least this size that cannot be allocated
using already-existing space will be serviced via mmap. (If enough
normal freed space already exists it is used instead.) Using mmap
segregates relatively large chunks of memory so that they can be
individually obtained and released from the host system. A request
serviced through mmap is never reused by any other request (at least
not directly; the system may just so happen to remap successive
requests to the same locations). Segregating space in this way has
the benefits that: Mmapped space can always be individually released
back to the system, which helps keep the system level memory demands
of a long-lived program low. Also, mapped memory doesn't become
`locked' between other chunks, as can happen with normally allocated
chunks, which means that even trimming via malloc_trim would not
release them. However, it has the disadvantage that the space
cannot be reclaimed, consolidated, and then used to service later
requests, as happens with normal chunks. The advantages of mmap
nearly always outweigh disadvantages for "large" chunks, but the
value of "large" may vary across systems. The default is an
empirically derived value that works well in most systems. You can
disable mmap by setting to MAX_SIZE_T.
MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP
The number of consolidated frees between checks to release
unused segments when freeing. When using non-contiguous segments,
especially with multiple mspaces, checking only for topmost space
doesn't always suffice to trigger trimming. To compensate for this,
free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
current number of segments, if greater) try to release unused
segments to the OS when freeing chunks that result in
consolidation. The best value for this parameter is a compromise
between slowing down frees with relatively costly checks that
rarely trigger versus holding on to unused memory. To effectively
disable, set to MAX_SIZE_T. This may lead to a very slight speed
improvement at the expense of carrying around more memory.
*/
/* Version identifier to allow people to support multiple versions */
#ifndef DLMALLOC_VERSION
#define DLMALLOC_VERSION 20806
#endif /* DLMALLOC_VERSION */
#ifndef DLMALLOC_EXPORT
#define DLMALLOC_EXPORT extern
#endif
#ifndef WIN32
#ifdef _WIN32
#define WIN32 1
#endif /* _WIN32 */
#ifdef _WIN32_WCE
#define LACKS_FCNTL_H
#define WIN32 1
#endif /* _WIN32_WCE */
#endif /* WIN32 */
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#define HAVE_MMAP 1
#define HAVE_MORECORE 0
#define LACKS_UNISTD_H
#define LACKS_SYS_PARAM_H
#define LACKS_SYS_MMAN_H
#define LACKS_STRING_H
#define LACKS_STRINGS_H
#define LACKS_SYS_TYPES_H
#define LACKS_ERRNO_H
#define LACKS_SCHED_H
#ifndef MALLOC_FAILURE_ACTION
#define MALLOC_FAILURE_ACTION
#endif /* MALLOC_FAILURE_ACTION */
#ifndef MMAP_CLEARS
#ifdef _WIN32_WCE /* WINCE reportedly does not clear */
#define MMAP_CLEARS 0
#else
#define MMAP_CLEARS 1
#endif /* _WIN32_WCE */
#endif /*MMAP_CLEARS */
#endif /* WIN32 */
#if defined(DARWIN) || defined(_DARWIN)
/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
#ifndef HAVE_MORECORE
#define HAVE_MORECORE 0
#define HAVE_MMAP 1
/* OSX allocators provide 16 byte alignment */
#ifndef MALLOC_ALIGNMENT
#define MALLOC_ALIGNMENT ((size_t)16U)
#endif
#endif /* HAVE_MORECORE */
#endif /* DARWIN */
#ifndef LACKS_SYS_TYPES_H
#include <sys/types.h> /* For size_t */
#endif /* LACKS_SYS_TYPES_H */
/* The maximum possible size_t value has all bits set */
#define MAX_SIZE_T (~(size_t)0)
#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */
#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \
(defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0))
#endif /* USE_LOCKS */
#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */
#if ((defined(__GNUC__) && \
((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
defined(__i386__) || defined(__x86_64__))) || \
(defined(_MSC_VER) && _MSC_VER>=1310))
#ifndef USE_SPIN_LOCKS
#define USE_SPIN_LOCKS 1
#endif /* USE_SPIN_LOCKS */
#elif USE_SPIN_LOCKS
#error "USE_SPIN_LOCKS defined without implementation"
#endif /* ... locks available... */
#elif !defined(USE_SPIN_LOCKS)
#define USE_SPIN_LOCKS 0
#endif /* USE_LOCKS */
#ifndef ONLY_MSPACES
#define ONLY_MSPACES 0
#endif /* ONLY_MSPACES */
#ifndef MSPACES
#if ONLY_MSPACES
#define MSPACES 1
#else /* ONLY_MSPACES */
#define MSPACES 0
#endif /* ONLY_MSPACES */
#endif /* MSPACES */
#ifndef MALLOC_ALIGNMENT
//#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *)))
#define MALLOC_ALIGNMENT (8) //*_*
#endif /* MALLOC_ALIGNMENT */
#ifndef FOOTERS
#define FOOTERS 0
#endif /* FOOTERS */
#ifndef ABORT
#define ABORT abort()
#endif /* ABORT */
#ifndef ABORT_ON_ASSERT_FAILURE
#define ABORT_ON_ASSERT_FAILURE 1
#endif /* ABORT_ON_ASSERT_FAILURE */
#ifndef PROCEED_ON_ERROR
#define PROCEED_ON_ERROR 0
#endif /* PROCEED_ON_ERROR */
#ifndef INSECURE
#define INSECURE 0
#endif /* INSECURE */
#ifndef MALLOC_INSPECT_ALL
#define MALLOC_INSPECT_ALL 0
#endif /* MALLOC_INSPECT_ALL */
#ifndef HAVE_MMAP
#define HAVE_MMAP 0 // *_*
#endif /* HAVE_MMAP */
#ifndef MMAP_CLEARS
#define MMAP_CLEARS 0 // *_*
#endif /* MMAP_CLEARS */
#ifndef HAVE_MREMAP
#ifdef linux
#define HAVE_MREMAP 1
#define _GNU_SOURCE /* Turns on mremap() definition */
#else /* linux */
#define HAVE_MREMAP 0
#endif /* linux */
#endif /* HAVE_MREMAP */
#ifndef MALLOC_FAILURE_ACTION
#define MALLOC_FAILURE_ACTION (0) //*_* was errno = ENOMEM;
#endif /* MALLOC_FAILURE_ACTION */
#ifndef HAVE_MORECORE
#if ONLY_MSPACES
#define HAVE_MORECORE 0
#else /* ONLY_MSPACES */
#define HAVE_MORECORE 1
#endif /* ONLY_MSPACES */
#endif /* HAVE_MORECORE */
#if !HAVE_MORECORE
#define MORECORE_CONTIGUOUS 0
#else /* !HAVE_MORECORE */
#define MORECORE_DEFAULT sbrk
#ifndef MORECORE_CONTIGUOUS
#define MORECORE_CONTIGUOUS 1
#endif /* MORECORE_CONTIGUOUS */
#endif /* HAVE_MORECORE */
#ifndef DEFAULT_GRANULARITY
#if (MORECORE_CONTIGUOUS || defined(WIN32))
//#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) //*_*
#else /* MORECORE_CONTIGUOUS */
#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
#endif /* MORECORE_CONTIGUOUS */
#endif /* DEFAULT_GRANULARITY */
#ifndef DEFAULT_TRIM_THRESHOLD
#ifndef MORECORE_CANNOT_TRIM
#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
#else /* MORECORE_CANNOT_TRIM */
#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
#endif /* MORECORE_CANNOT_TRIM */
#endif /* DEFAULT_TRIM_THRESHOLD */
#ifndef DEFAULT_MMAP_THRESHOLD
#if HAVE_MMAP
#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
#else /* HAVE_MMAP */
#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
#endif /* HAVE_MMAP */
#endif /* DEFAULT_MMAP_THRESHOLD */
#ifndef MAX_RELEASE_CHECK_RATE
#if HAVE_MMAP
#define MAX_RELEASE_CHECK_RATE 4095
#else
#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
#endif /* HAVE_MMAP */
#endif /* MAX_RELEASE_CHECK_RATE */
#ifndef USE_BUILTIN_FFS
#define USE_BUILTIN_FFS 1 //*_*
#endif /* USE_BUILTIN_FFS */
#ifndef USE_DEV_RANDOM
#define USE_DEV_RANDOM 0
#endif /* USE_DEV_RANDOM */
#ifndef NO_MALLINFO
#define NO_MALLINFO 0
#endif /* NO_MALLINFO */
#ifndef MALLINFO_FIELD_TYPE
#define MALLINFO_FIELD_TYPE size_t
#endif /* MALLINFO_FIELD_TYPE */
#ifndef NO_MALLOC_STATS
#define NO_MALLOC_STATS 0
#endif /* NO_MALLOC_STATS */
#ifndef NO_SEGMENT_TRAVERSAL
#define NO_SEGMENT_TRAVERSAL 0
#endif /* NO_SEGMENT_TRAVERSAL */
/*
mallopt tuning options. SVID/XPG defines four standard parameter
numbers for mallopt, normally defined in malloc.h. None of these
are used in this malloc, so setting them has no effect. But this
malloc does support the following options.
*/
#define M_TRIM_THRESHOLD (-1)
#define M_GRANULARITY (-2)
#define M_MMAP_THRESHOLD (-3)
/* ------------------------ Mallinfo declarations ------------------------ */
#if !NO_MALLINFO
/*
This version of malloc supports the standard SVID/XPG mallinfo
routine that returns a struct containing usage properties and
statistics. It should work on any system that has a
/usr/include/malloc.h defining struct mallinfo. The main
declaration needed is the mallinfo struct that is returned (by-copy)
by mallinfo(). The malloinfo struct contains a bunch of fields that
are not even meaningful in this version of malloc. These fields are
are instead filled by mallinfo() with other numbers that might be of
interest.
HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
/usr/include/malloc.h file that includes a declaration of struct
mallinfo. If so, it is included; else a compliant version is
declared below. These must be precisely the same for mallinfo() to
work. The original SVID version of this struct, defined on most
systems with mallinfo, declares all fields as ints. But some others
define as unsigned long. If your system defines the fields using a
type of different width than listed here, you MUST #include your
system version and #define HAVE_USR_INCLUDE_MALLOC_H.
*/
/* #define HAVE_USR_INCLUDE_MALLOC_H */
#ifdef HAVE_USR_INCLUDE_MALLOC_H
#include "/usr/include/malloc.h"
#else /* HAVE_USR_INCLUDE_MALLOC_H */
#ifndef STRUCT_MALLINFO_DECLARED
/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */
#define _STRUCT_MALLINFO
#define STRUCT_MALLINFO_DECLARED 1
struct mallinfo {
MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
MALLINFO_FIELD_TYPE smblks; /* always 0 */
MALLINFO_FIELD_TYPE hblks; /* always 0 */
MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
MALLINFO_FIELD_TYPE fordblks; /* total free space */
MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
};
#endif /* STRUCT_MALLINFO_DECLARED */
#endif /* HAVE_USR_INCLUDE_MALLOC_H */
#endif /* NO_MALLINFO */
/*
Try to persuade compilers to inline. The most critical functions for
inlining are defined as macros, so these aren't used for them.
*/
#ifndef FORCEINLINE
#if defined(__GNUC__)
#define FORCEINLINE __inline __attribute__ ((always_inline))
#elif defined(_MSC_VER)
#define FORCEINLINE __forceinline
#endif
#endif
#ifndef NOINLINE
#if defined(__GNUC__)
#define NOINLINE __attribute__ ((noinline))
#elif defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#endif
#ifdef __cplusplus
extern "C" {
#ifndef FORCEINLINE
#define FORCEINLINE inline
#endif
#endif /* __cplusplus */
#ifndef FORCEINLINE
#define FORCEINLINE
#endif
#if !ONLY_MSPACES
/* ------------------- Declarations of public routines ------------------- */
#ifndef USE_DL_PREFIX
#define dlcalloc calloc
#define dlfree free
#define dlmalloc malloc
#define dlmemalign memalign
#define dlposix_memalign posix_memalign
#define dlrealloc realloc
#define dlrealloc_in_place realloc_in_place
#define dlvalloc valloc
#define dlpvalloc pvalloc
#define dlmallinfo mallinfo
#define dlmallopt mallopt
#define dlmalloc_trim malloc_trim
#define dlmalloc_stats malloc_stats
#define dlmalloc_usable_size malloc_usable_size
#define dlmalloc_footprint malloc_footprint
#define dlmalloc_max_footprint malloc_max_footprint
#define dlmalloc_footprint_limit malloc_footprint_limit
#define dlmalloc_set_footprint_limit malloc_set_footprint_limit
#define dlmalloc_inspect_all malloc_inspect_all
#define dlindependent_calloc independent_calloc
#define dlindependent_comalloc independent_comalloc
#define dlbulk_free bulk_free
#endif /* USE_DL_PREFIX */
/*
malloc(size_t n)
Returns a pointer to a newly allocated chunk of at least n bytes, or
null if no space is available, in which case errno is set to ENOMEM
on ANSI C systems.
If n is zero, malloc returns a minimum-sized chunk. (The minimum
size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
systems.) Note that size_t is an unsigned type, so calls with
arguments that would be negative if signed are interpreted as
requests for huge amounts of space, which will often fail. The
maximum supported value of n differs across systems, but is in all
cases less than the maximum representable value of a size_t.
*/
DLMALLOC_EXPORT void* dlmalloc(size_t);
/*
free(void* p)
Releases the chunk of memory pointed to by p, that had been previously
allocated using malloc or a related routine such as realloc.
It has no effect if p is null. If p was not malloced or already
freed, free(p) will by default cause the current program to abort.
*/
DLMALLOC_EXPORT void dlfree(void*);
/*
calloc(size_t n_elements, size_t element_size);
Returns a pointer to n_elements * element_size bytes, with all locations
set to zero.
*/
DLMALLOC_EXPORT void* dlcalloc(size_t, size_t);
/*
realloc(void* p, size_t n)
Returns a pointer to a chunk of size n that contains the same data
as does chunk p up to the minimum of (n, p's size) bytes, or null
if no space is available.
The returned pointer may or may not be the same as p. The algorithm
prefers extending p in most cases when possible, otherwise it
employs the equivalent of a malloc-copy-free sequence.
If p is null, realloc is equivalent to malloc.
If space is not available, realloc returns null, errno is set (if on
ANSI) and p is NOT freed.
if n is for fewer bytes than already held by p, the newly unused
space is lopped off and freed if possible. realloc with a size
argument of zero (re)allocates a minimum-sized chunk.
The old unix realloc convention of allowing the last-free'd chunk
to be used as an argument to realloc is not supported.
*/
DLMALLOC_EXPORT void* dlrealloc(void*, size_t);
/*
realloc_in_place(void* p, size_t n)
Resizes the space allocated for p to size n, only if this can be
done without moving p (i.e., only if there is adjacent space
available if n is greater than p's current allocated size, or n is
less than or equal to p's size). This may be used instead of plain
realloc if an alternative allocation strategy is needed upon failure
to expand space; for example, reallocation of a buffer that must be
memory-aligned or cleared. You can use realloc_in_place to trigger
these alternatives only when needed.
Returns p if successful; otherwise null.
*/
DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t);
/*
memalign(size_t alignment, size_t n);
Returns a pointer to a newly allocated chunk of n bytes, aligned
in accord with the alignment argument.
The alignment argument should be a power of two. If the argument is
not a power of two, the nearest greater power is used.
8-byte alignment is guaranteed by normal malloc calls, so don't
bother calling memalign with an argument of 8 or less.
Overreliance on memalign is a sure way to fragment space.
*/
DLMALLOC_EXPORT void* dlmemalign(size_t, size_t);
/*
int posix_memalign(void** pp, size_t alignment, size_t n);
Allocates a chunk of n bytes, aligned in accord with the alignment
argument. Differs from memalign only in that it (1) assigns the
allocated memory to *pp rather than returning it, (2) fails and
returns EINVAL if the alignment is not a power of two (3) fails and
returns ENOMEM if memory cannot be allocated.
*/
DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t);
/*
valloc(size_t n);
Equivalent to memalign(pagesize, n), where pagesize is the page
size of the system. If the pagesize is unknown, 4096 is used.
*/
DLMALLOC_EXPORT void* dlvalloc(size_t);
/*
mallopt(int parameter_number, int parameter_value)
Sets tunable parameters The format is to provide a
(parameter-number, parameter-value) pair. mallopt then sets the
corresponding parameter to the argument value if it can (i.e., so
long as the value is meaningful), and returns 1 if successful else
0. To workaround the fact that mallopt is specified to use int,
not size_t parameters, the value -1 is specially treated as the
maximum unsigned size_t value.
SVID/XPG/ANSI defines four standard param numbers for mallopt,
normally defined in malloc.h. None of these are use in this malloc,
so setting them has no effect. But this malloc also supports other
options in mallopt. See below for details. Briefly, supported
parameters are as follows (listed defaults are for "typical"
configurations).
Symbol param # default allowed param values
M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables)
M_GRANULARITY -2 page size any power of 2 >= page size
M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
*/
DLMALLOC_EXPORT int dlmallopt(int, int);
/*
malloc_footprint();
Returns the number of bytes obtained from the system. The total
number of bytes allocated by malloc, realloc etc., is less than this
value. Unlike mallinfo, this function returns only a precomputed
result, so can be called frequently to monitor memory consumption.
Even if locks are otherwise defined, this function does not use them,
so results might not be up to date.
*/
DLMALLOC_EXPORT size_t dlmalloc_footprint(void);
/*
malloc_max_footprint();
Returns the maximum number of bytes obtained from the system. This
value will be greater than current footprint if deallocated space
has been reclaimed by the system. The peak number of bytes allocated
by malloc, realloc etc., is less than this value. Unlike mallinfo,
this function returns only a precomputed result, so can be called
frequently to monitor memory consumption. Even if locks are
otherwise defined, this function does not use them, so results might
not be up to date.
*/
DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void);
/*
malloc_footprint_limit();
Returns the number of bytes that the heap is allowed to obtain from
the system, returning the last value returned by
malloc_set_footprint_limit, or the maximum size_t value if
never set. The returned value reflects a permission. There is no
guarantee that this number of bytes can actually be obtained from
the system.
*/
DLMALLOC_EXPORT size_t dlmalloc_footprint_limit();
/*
malloc_set_footprint_limit();
Sets the maximum number of bytes to obtain from the system, causing
failure returns from malloc and related functions upon attempts to
exceed this value. The argument value may be subject to page
rounding to an enforceable limit; this actual value is returned.
Using an argument of the maximum possible size_t effectively
disables checks. If the argument is less than or equal to the
current malloc_footprint, then all future allocations that require
additional system memory will fail. However, invocation cannot
retroactively deallocate existing used memory.
*/
DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes);
#if MALLOC_INSPECT_ALL
/*
malloc_inspect_all(void(*handler)(void *start,
void *end,
size_t used_bytes,
void* callback_arg),
void* arg);
Traverses the heap and calls the given handler for each managed
region, skipping all bytes that are (or may be) used for bookkeeping
purposes. Traversal does not include include chunks that have been
directly memory mapped. Each reported region begins at the start
address, and continues up to but not including the end address. The
first used_bytes of the region contain allocated data. If
used_bytes is zero, the region is unallocated. The handler is
invoked with the given callback argument. If locks are defined, they
are held during the entire traversal. It is a bad idea to invoke
other malloc functions from within the handler.
For example, to count the number of in-use chunks with size greater
than 1000, you could write:
static int count = 0;
void count_chunks(void* start, void* end, size_t used, void* arg) {
if (used >= 1000) ++count;
}
then:
malloc_inspect_all(count_chunks, NULL);
malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined.
*/
DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*),
void* arg);
#endif /* MALLOC_INSPECT_ALL */
#if !NO_MALLINFO
/*
mallinfo()
Returns (by copy) a struct containing various summary statistics:
arena: current total non-mmapped bytes allocated from system
ordblks: the number of free chunks
smblks: always zero.
hblks: current number of mmapped regions
hblkhd: total bytes held in mmapped regions
usmblks: the maximum total allocated space. This will be greater
than current total if trimming has occurred.
fsmblks: always zero
uordblks: current total allocated space (normal or mmapped)
fordblks: total free space
keepcost: the maximum number of bytes that could ideally be released
back to system via malloc_trim. ("ideally" means that
it ignores page restrictions etc.)
Because these fields are ints, but internal bookkeeping may
be kept as longs, the reported values may wrap around zero and
thus be inaccurate.
*/
DLMALLOC_EXPORT struct mallinfo dlmallinfo(void);
#endif /* NO_MALLINFO */
/*
independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
independent_calloc is similar to calloc, but instead of returning a
single cleared space, it returns an array of pointers to n_elements
independent elements that can hold contents of size elem_size, each
of which starts out cleared, and can be independently freed,
realloc'ed etc. The elements are guaranteed to be adjacently
allocated (this is not guaranteed to occur with multiple callocs or
mallocs), which may also improve cache locality in some
applications.
The "chunks" argument is optional (i.e., may be null, which is
probably the most typical usage). If it is null, the returned array
is itself dynamically allocated and should also be freed when it is
no longer needed. Otherwise, the chunks array must be of at least
n_elements in length. It is filled in with the pointers to the
chunks.
In either case, independent_calloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and "chunks"
is null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be freed when it is no longer needed. This can be
done all at once using bulk_free.
independent_calloc simplifies and speeds up implementations of many
kinds of pools. It may also be useful when constructing large data
structures that initially have a fixed number of fixed-sized nodes,
but the number is not known at compile time, and some of the nodes
may later need to be freed. For example:
struct Node { int item; struct Node* next; };
struct Node* build_list() {
struct Node** pool;
int n = read_number_of_nodes_needed();
if (n <= 0) return 0;
pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
if (pool == 0) die();
// organize into a linked list...
struct Node* first = pool[0];
for (i = 0; i < n-1; ++i)
pool[i]->next = pool[i+1];
free(pool); // Can now free the array (or not, if it is needed later)
return first;
}
*/
DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**);
/*
independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
independent_comalloc allocates, all at once, a set of n_elements
chunks with sizes indicated in the "sizes" array. It returns
an array of pointers to these elements, each of which can be
independently freed, realloc'ed etc. The elements are guaranteed to
be adjacently allocated (this is not guaranteed to occur with
multiple callocs or mallocs), which may also improve cache locality
in some applications.
The "chunks" argument is optional (i.e., may be null). If it is null
the returned array is itself dynamically allocated and should also
be freed when it is no longer needed. Otherwise, the chunks array
must be of at least n_elements in length. It is filled in with the
pointers to the chunks.
In either case, independent_comalloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and chunks is
null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be freed when it is no longer needed. This can be
done all at once using bulk_free.
independent_comallac differs from independent_calloc in that each
element may have a different size, and also that it does not
automatically clear elements.
independent_comalloc can be used to speed up allocation in cases
where several structs or objects must always be allocated at the
same time. For example:
struct Head { ... }
struct Foot { ... }
void send_message(char* msg) {
int msglen = strlen(msg);
size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
void* chunks[3];
if (independent_comalloc(3, sizes, chunks) == 0)
die();
struct Head* head = (struct Head*)(chunks[0]);
char* body = (char*)(chunks[1]);
struct Foot* foot = (struct Foot*)(chunks[2]);
// ...
}
In general though, independent_comalloc is worth using only for
larger values of n_elements. For small values, you probably won't
detect enough difference from series of malloc calls to bother.
Overuse of independent_comalloc can increase overall memory usage,
since it cannot reuse existing noncontiguous small chunks that
might be available for some of the elements.
*/
DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**);
/*
bulk_free(void* array[], size_t n_elements)
Frees and clears (sets to null) each non-null pointer in the given
array. This is likely to be faster than freeing them one-by-one.
If footers are used, pointers that have been allocated in different
mspaces are not freed or cleared, and the count of all such pointers
is returned. For large arrays of pointers with poor locality, it
may be worthwhile to sort this array before calling bulk_free.
*/
DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements);
/*
pvalloc(size_t n);
Equivalent to valloc(minimum-page-that-holds(n)), that is,
round up n to nearest pagesize.
*/
DLMALLOC_EXPORT void* dlpvalloc(size_t);
/*
malloc_trim(size_t pad);
If possible, gives memory back to the system (via negative arguments
to sbrk) if there is unused memory at the `high' end of the malloc
pool or in unused MMAP segments. You can call this after freeing
large blocks of memory to potentially reduce the system-level memory
requirements of a program. However, it cannot guarantee to reduce
memory. Under some allocation patterns, some large free blocks of
memory will be locked between two used chunks, so they cannot be
given back to the system.
The `pad' argument to malloc_trim represents the amount of free
trailing space to leave untrimmed. If this argument is zero, only
the minimum amount of memory to maintain internal data structures
will be left. Non-zero arguments can be supplied to maintain enough
trailing space to service future expected allocations without having
to re-obtain memory from the system.
Malloc_trim returns 1 if it actually released any memory, else 0.
*/
DLMALLOC_EXPORT int dlmalloc_trim(size_t);
/*
malloc_stats();
Prints on stderr the amount of space obtained from the system (both
via sbrk and mmap), the maximum amount (which may be more than
current if malloc_trim and/or munmap got called), and the current
number of bytes allocated via malloc (or realloc, etc) but not yet
freed. Note that this is the number of bytes allocated, not the
number requested. It will be larger than the number requested
because of alignment and bookkeeping overhead. Because it includes
alignment wastage as being in use, this figure may be greater than
zero even when no user-level chunks are allocated.
The reported current and maximum system memory can be inaccurate if
a program makes other calls to system memory allocation functions
(normally sbrk) outside of malloc.
malloc_stats prints only the most commonly interesting statistics.
More information can be obtained by calling mallinfo.
*/
DLMALLOC_EXPORT void dlmalloc_stats(void);
/*
malloc_usable_size(void* p);
Returns the number of bytes you can actually use in
an allocated chunk, which may be more than you requested (although
often not) due to alignment and minimum size constraints.
You can use this many bytes without worrying about
overwriting other allocated objects. This is not a particularly great
programming practice. malloc_usable_size can be more useful in
debugging and assertions, for example:
p = malloc(n);
assert(malloc_usable_size(p) >= 256);
*/
size_t dlmalloc_usable_size(void*);
#endif /* ONLY_MSPACES */
#if MSPACES
/*
mspace is an opaque type representing an independent
region of space that supports mspace_malloc, etc.
*/
typedef void* mspace;
/*
create_mspace creates and returns a new independent space with the
given initial capacity, or, if 0, the default granularity size. It
returns null if there is no system memory available to create the
space. If argument locked is non-zero, the space uses a separate
lock to control access. The capacity of the space will grow
dynamically as needed to service mspace_malloc requests. You can
control the sizes of incremental increases of this space by
compiling with a different DEFAULT_GRANULARITY or dynamically
setting with mallopt(M_GRANULARITY, value).
*/
DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked);
/*
destroy_mspace destroys the given space, and attempts to return all
of its memory back to the system, returning the total number of
bytes freed. After destruction, the results of access to all memory
used by the space become undefined.
*/
DLMALLOC_EXPORT size_t destroy_mspace(mspace msp);
/*
create_mspace_with_base uses the memory supplied as the initial base
of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
space is used for bookkeeping, so the capacity must be at least this
large. (Otherwise 0 is returned.) When this initial space is
exhausted, additional memory will be obtained from the system.
Destroying this space will deallocate all additionally allocated
space (if possible) but not the initial base.
*/
DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked);
/*
mspace_track_large_chunks controls whether requests for large chunks
are allocated in their own untracked mmapped regions, separate from
others in this mspace. By default large chunks are not tracked,
which reduces fragmentation. However, such chunks are not
necessarily released to the system upon destroy_mspace. Enabling
tracking by setting to true may increase fragmentation, but avoids
leakage when relying on destroy_mspace to release all memory
allocated using this space. The function returns the previous
setting.
*/
DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable);
/*
mspace_malloc behaves as malloc, but operates within
the given space.
*/
DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes);
/*
mspace_free behaves as free, but operates within
the given space.
If compiled with FOOTERS==1, mspace_free is not actually needed.
free may be called instead of mspace_free because freed chunks from
any space are handled by their originating spaces.
*/
DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem);
/*
mspace_realloc behaves as realloc, but operates within
the given space.
If compiled with FOOTERS==1, mspace_realloc is not actually
needed. realloc may be called instead of mspace_realloc because
realloced chunks from any space are handled by their originating
spaces.
*/
DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize);
/*
mspace_calloc behaves as calloc, but operates within
the given space.
*/
DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
/*
mspace_memalign behaves as memalign, but operates within
the given space.
*/
DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
/*
mspace_independent_calloc behaves as independent_calloc, but
operates within the given space.
*/
DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]);
/*
mspace_independent_comalloc behaves as independent_comalloc, but
operates within the given space.
*/
DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]);
/*
mspace_footprint() returns the number of bytes obtained from the
system for this space.
*/
DLMALLOC_EXPORT size_t mspace_footprint(mspace msp);
/*
mspace_max_footprint() returns the peak number of bytes obtained from the
system for this space.
*/
DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp);
#if !NO_MALLINFO
/*
mspace_mallinfo behaves as mallinfo, but reports properties of
the given space.
*/
DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp);
#endif /* NO_MALLINFO */
/*
malloc_usable_size(void* p) behaves the same as malloc_usable_size;
*/
DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem);
/*
mspace_malloc_stats behaves as malloc_stats, but reports
properties of the given space.
*/
DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp);
/*
mspace_trim behaves as malloc_trim, but
operates within the given space.
*/
DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad);
/*
An alias for mallopt.
*/
DLMALLOC_EXPORT int mspace_mallopt(int, int);
#endif /* MSPACES */
#ifdef __cplusplus
} /* end of extern "C" */
#endif /* __cplusplus */
/*
========================================================================
To make a fully customizable malloc.h header file, cut everything
above this line, put into file malloc.h, edit to suit, and #include it
on the next line, as well as in programs that use this malloc.
========================================================================
*/
/* #include "malloc.h" */
/*------------------------------ internal #includes ---------------------- */
#ifdef _MSC_VER
#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
#endif /* _MSC_VER */
#if !NO_MALLOC_STATS
#include <stdio.h> /* for printing in malloc_stats */
#endif /* NO_MALLOC_STATS */
#ifndef LACKS_ERRNO_H
#include <errno.h> /* for MALLOC_FAILURE_ACTION */
#endif /* LACKS_ERRNO_H */
#ifdef DEBUG
#if ABORT_ON_ASSERT_FAILURE
#undef assert
#define assert(x) if(!(x)) ABORT
#else /* ABORT_ON_ASSERT_FAILURE */
#include <assert.h>
#endif /* ABORT_ON_ASSERT_FAILURE */
#else /* DEBUG */
#ifndef assert
#define assert(x)
#endif
#define DEBUG 0
#endif /* DEBUG */
#if !defined(WIN32) && !defined(LACKS_TIME_H)
#include <time.h> /* for magic initialization */
#endif /* WIN32 */
#ifndef LACKS_STDLIB_H
#include <stdlib.h> /* for abort() */
#endif /* LACKS_STDLIB_H */
#ifndef LACKS_STRING_H
#include <string.h> /* for memset etc */
#endif /* LACKS_STRING_H */
#if USE_BUILTIN_FFS
#ifndef LACKS_STRINGS_H
#include <strings.h> /* for ffs */
#endif /* LACKS_STRINGS_H */
#endif /* USE_BUILTIN_FFS */
#if HAVE_MMAP
#ifndef LACKS_SYS_MMAN_H
/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */
#if (defined(linux) && !defined(__USE_GNU))
#define __USE_GNU 1
#include <sys/mman.h> /* for mmap */
#undef __USE_GNU
#else
#include <sys/mman.h> /* for mmap */
#endif /* linux */
#endif /* LACKS_SYS_MMAN_H */
#ifndef LACKS_FCNTL_H
#include <fcntl.h>
#endif /* LACKS_FCNTL_H */
#endif /* HAVE_MMAP */
#ifndef LACKS_UNISTD_H
#include <unistd.h> /* for sbrk, sysconf */
#else /* LACKS_UNISTD_H */
#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
extern void* sbrk(ptrdiff_t);
#endif /* FreeBSD etc */
#endif /* LACKS_UNISTD_H */
/* Declarations for locking */
#if USE_LOCKS
#ifndef WIN32
#if defined (__SVR4) && defined (__sun) /* solaris */
#include <thread.h>
#elif !defined(LACKS_SCHED_H)
#include <sched.h>
#endif /* solaris or LACKS_SCHED_H */
#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS
#include <pthread.h>
#endif /* USE_RECURSIVE_LOCKS ... */
#elif defined(_MSC_VER)
#ifndef _M_AMD64
/* These are already defined on AMD64 builds */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);
LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _M_AMD64 */
#pragma intrinsic (_InterlockedCompareExchange)
#pragma intrinsic (_InterlockedExchange)
#define interlockedcompareexchange _InterlockedCompareExchange
#define interlockedexchange _InterlockedExchange
#elif defined(WIN32) && defined(__GNUC__)
#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b)
#define interlockedexchange __sync_lock_test_and_set
#endif /* Win32 */
#else /* USE_LOCKS */
#endif /* USE_LOCKS */
#ifndef LOCK_AT_FORK
#define LOCK_AT_FORK 0
#endif
/* Declarations for bit scanning on win32 */
#if defined(_MSC_VER) && _MSC_VER>=1300
#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#define BitScanForward _BitScanForward
#define BitScanReverse _BitScanReverse
#pragma intrinsic(_BitScanForward)
#pragma intrinsic(_BitScanReverse)
#endif /* BitScanForward */
#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */
#ifndef WIN32
#ifndef malloc_getpagesize
# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
# ifndef _SC_PAGE_SIZE
# define _SC_PAGE_SIZE _SC_PAGESIZE
# endif
# endif
# ifdef _SC_PAGE_SIZE
# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
# else
# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
extern size_t getpagesize();
# define malloc_getpagesize getpagesize()
# else
# ifdef WIN32 /* use supplied emulation of getpagesize */
# define malloc_getpagesize getpagesize()
# else
# ifndef LACKS_SYS_PARAM_H
# include <sys/param.h>
# endif
# ifdef EXEC_PAGESIZE
# define malloc_getpagesize EXEC_PAGESIZE
# else
# ifdef NBPG
# ifndef CLSIZE
# define malloc_getpagesize NBPG
# else
# define malloc_getpagesize (NBPG * CLSIZE)
# endif
# else
# ifdef NBPC
# define malloc_getpagesize NBPC
# else
# ifdef PAGESIZE
# define malloc_getpagesize PAGESIZE
# else /* just guess */
# define malloc_getpagesize ((size_t)4096U)
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
#endif
/* ------------------- size_t and alignment properties -------------------- */
/* The byte and bit size of a size_t */
#define SIZE_T_SIZE (sizeof(size_t))
#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
/* Some constants coerced to size_t */
/* Annoying but necessary to avoid errors on some platforms */
#define SIZE_T_ZERO ((size_t)0)
#define SIZE_T_ONE ((size_t)1)
#define SIZE_T_TWO ((size_t)2)
#define SIZE_T_FOUR ((size_t)4)
#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
/* The bit mask value corresponding to MALLOC_ALIGNMENT */
#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
/* True if address a has acceptable alignment */
#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
/* the number of bytes to offset an address to align it */
#define align_offset(A)\
((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
/* -------------------------- MMAP preliminaries ------------------------- */
/*
If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
checks to fail so compiler optimizer can delete code rather than
using so many "#if"s.
*/
/* MORECORE and MMAP must return MFAIL on failure */
#define MFAIL ((void*)(MAX_SIZE_T))
#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
#if HAVE_MMAP
#ifndef WIN32
#define MUNMAP_DEFAULT(a, s) munmap((a), (s))
#define MMAP_PROT (PROT_READ|PROT_WRITE)
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif /* MAP_ANON */
#ifdef MAP_ANONYMOUS
#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
#else /* MAP_ANONYMOUS */
/*
Nearly all versions of mmap support MAP_ANONYMOUS, so the following
is unlikely to be needed, but is supplied just in case.
*/
#define MMAP_FLAGS (MAP_PRIVATE)
static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \
(dev_zero_fd = open("/dev/zero", O_RDWR), \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
#endif /* MAP_ANONYMOUS */
#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)
#else /* WIN32 */
/* Win32 MMAP via VirtualAlloc */
static FORCEINLINE void* win32mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
static FORCEINLINE void* win32direct_mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* This function supports releasing coalesed segments */
static FORCEINLINE int win32munmap(void* ptr, size_t size) {
MEMORY_BASIC_INFORMATION minfo;
char* cptr = (char*)ptr;
while (size) {
if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
return -1;
if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
minfo.State != MEM_COMMIT || minfo.RegionSize > size)
return -1;
if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
return -1;
cptr += minfo.RegionSize;
size -= minfo.RegionSize;
}
return 0;
}
#define MMAP_DEFAULT(s) win32mmap(s)
#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s))
#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s)
#endif /* WIN32 */
#endif /* HAVE_MMAP */
#if HAVE_MREMAP
#ifndef WIN32
#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
#endif /* WIN32 */
#endif /* HAVE_MREMAP */
/**
* Define CALL_MORECORE
*/
#if HAVE_MORECORE
#ifdef MORECORE
#define CALL_MORECORE(S) MORECORE(S)
#else /* MORECORE */
#define CALL_MORECORE(S) MORECORE_DEFAULT(S)
#endif /* MORECORE */
#else /* HAVE_MORECORE */
#define CALL_MORECORE(S) MFAIL
#endif /* HAVE_MORECORE */
/**
* Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP
*/
#if HAVE_MMAP
#define USE_MMAP_BIT (SIZE_T_ONE)
#ifdef MMAP
#define CALL_MMAP(s) MMAP(s)
#else /* MMAP */
#define CALL_MMAP(s) MMAP_DEFAULT(s)
#endif /* MMAP */
#ifdef MUNMAP
#define CALL_MUNMAP(a, s) MUNMAP((a), (s))
#else /* MUNMAP */
#define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s))
#endif /* MUNMAP */
#ifdef DIRECT_MMAP
#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
#else /* DIRECT_MMAP */
#define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)
#endif /* DIRECT_MMAP */
#else /* HAVE_MMAP */
#define USE_MMAP_BIT (SIZE_T_ZERO)
#define MMAP(s) MFAIL
#define MUNMAP(a, s) (-1)
#define DIRECT_MMAP(s) MFAIL
#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
#define CALL_MMAP(s) MMAP(s)
#define CALL_MUNMAP(a, s) MUNMAP((a), (s))
#endif /* HAVE_MMAP */
/**
* Define CALL_MREMAP
*/
#if HAVE_MMAP && HAVE_MREMAP
#ifdef MREMAP
#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))
#else /* MREMAP */
#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))
#endif /* MREMAP */
#else /* HAVE_MMAP && HAVE_MREMAP */
#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
#endif /* HAVE_MMAP && HAVE_MREMAP */
/* mstate bit set if continguous morecore disabled or failed */
#define USE_NONCONTIGUOUS_BIT (4U)
/* segment bit set in create_mspace_with_base */
#define EXTERN_BIT (8U)
/* --------------------------- Lock preliminaries ------------------------ */
/*
When locks are defined, there is one global lock, plus
one per-mspace lock.
The global lock_ensures that mparams.magic and other unique
mparams values are initialized only once. It also protects
sequences of calls to MORECORE. In many cases sys_alloc requires
two calls, that should not be interleaved with calls by other
threads. This does not protect against direct calls to MORECORE
by other threads not using this lock, so there is still code to
cope the best we can on interference.
Per-mspace locks surround calls to malloc, free, etc.
By default, locks are simple non-reentrant mutexes.
Because lock-protected regions generally have bounded times, it is
OK to use the supplied simple spinlocks. Spinlocks are likely to
improve performance for lightly contended applications, but worsen
performance under heavy contention.
If USE_LOCKS is > 1, the definitions of lock routines here are
bypassed, in which case you will need to define the type MLOCK_T,
and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK
and TRY_LOCK. You must also declare a
static MLOCK_T malloc_global_mutex = { initialization values };.
*/
#if !USE_LOCKS
#define USE_LOCK_BIT (0U)
#define INITIAL_LOCK(l) (0)
#define DESTROY_LOCK(l) (0)
#define ACQUIRE_MALLOC_GLOBAL_LOCK()
#define RELEASE_MALLOC_GLOBAL_LOCK()
#else
#if USE_LOCKS > 1
/* ----------------------- User-defined locks ------------------------ */
/* Define your own lock implementation here */
/* #define INITIAL_LOCK(lk) ... */
/* #define DESTROY_LOCK(lk) ... */
/* #define ACQUIRE_LOCK(lk) ... */
/* #define RELEASE_LOCK(lk) ... */
/* #define TRY_LOCK(lk) ... */
/* static MLOCK_T malloc_global_mutex = ... */
#elif USE_SPIN_LOCKS
/* First, define CAS_LOCK and CLEAR_LOCK on ints */
/* Note CAS_LOCK defined to return 0 on success */
#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))
#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1)
#define CLEAR_LOCK(sl) __sync_lock_release(sl)
#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
/* Custom spin locks for older gcc on x86 */
static FORCEINLINE int x86_cas_lock(int *sl) {
int ret;
int val = 1;
int cmp = 0;
__asm__ __volatile__ ("lock; cmpxchgl %1, %2"
: "=a" (ret)
: "r" (val), "m" (*(sl)), "0"(cmp)
: "memory", "cc");
return ret;
}
static FORCEINLINE void x86_clear_lock(int* sl) {
assert(*sl != 0);
int prev = 0;
int ret;
__asm__ __volatile__ ("lock; xchgl %0, %1"
: "=r" (ret)
: "m" (*(sl)), "0"(prev)
: "memory");
}
#define CAS_LOCK(sl) x86_cas_lock(sl)
#define CLEAR_LOCK(sl) x86_clear_lock(sl)
#else /* Win32 MSC */
#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1)
#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0)
#endif /* ... gcc spins locks ... */
/* How to yield for a spin lock */
#define SPINS_PER_YIELD 63
#if defined(_MSC_VER)
#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */
#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE)
#elif defined (__SVR4) && defined (__sun) /* solaris */
#define SPIN_LOCK_YIELD thr_yield();
#elif !defined(LACKS_SCHED_H)
#define SPIN_LOCK_YIELD sched_yield();
#else
#define SPIN_LOCK_YIELD
#endif /* ... yield ... */
#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0
/* Plain spin locks use single word (embedded in malloc_states) */
static int spin_acquire_lock(int *sl) {
int spins = 0;
while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) {
if ((++spins & SPINS_PER_YIELD) == 0) {
SPIN_LOCK_YIELD;
}
}
return 0;
}
#define MLOCK_T int
#define TRY_LOCK(sl) !CAS_LOCK(sl)
#define RELEASE_LOCK(sl) CLEAR_LOCK(sl)
#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0)
#define INITIAL_LOCK(sl) (*sl = 0)
#define DESTROY_LOCK(sl) (0)
static MLOCK_T malloc_global_mutex = 0;
#else /* USE_RECURSIVE_LOCKS */
/* types for lock owners */
#ifdef WIN32
#define THREAD_ID_T DWORD
#define CURRENT_THREAD GetCurrentThreadId()
#define EQ_OWNER(X,Y) ((X) == (Y))
#else
/*
Note: the following assume that pthread_t is a type that can be
initialized to (casted) zero. If this is not the case, you will need to
somehow redefine these or not use spin locks.
*/
#define THREAD_ID_T pthread_t
#define CURRENT_THREAD pthread_self()
#define EQ_OWNER(X,Y) pthread_equal(X, Y)
#endif
struct malloc_recursive_lock {
int sl;
unsigned int c;
THREAD_ID_T threadid;
};
#define MLOCK_T struct malloc_recursive_lock
static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0};
static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) {
assert(lk->sl != 0);
if (--lk->c == 0) {
CLEAR_LOCK(&lk->sl);
}
}
static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) {
THREAD_ID_T mythreadid = CURRENT_THREAD;
int spins = 0;
for (;;) {
if (*((volatile int *)(&lk->sl)) == 0) {
if (!CAS_LOCK(&lk->sl)) {
lk->threadid = mythreadid;
lk->c = 1;
return 0;
}
}
else if (EQ_OWNER(lk->threadid, mythreadid)) {
++lk->c;
return 0;
}
if ((++spins & SPINS_PER_YIELD) == 0) {
SPIN_LOCK_YIELD;
}
}
}
static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) {
THREAD_ID_T mythreadid = CURRENT_THREAD;
if (*((volatile int *)(&lk->sl)) == 0) {
if (!CAS_LOCK(&lk->sl)) {
lk->threadid = mythreadid;
lk->c = 1;
return 1;
}
}
else if (EQ_OWNER(lk->threadid, mythreadid)) {
++lk->c;
return 1;
}
return 0;
}
#define RELEASE_LOCK(lk) recursive_release_lock(lk)
#define TRY_LOCK(lk) recursive_try_lock(lk)
#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk)
#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0)
#define DESTROY_LOCK(lk) (0)
#endif /* USE_RECURSIVE_LOCKS */
#elif defined(WIN32) /* Win32 critical sections */
#define MLOCK_T CRITICAL_SECTION
#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0)
#define RELEASE_LOCK(lk) LeaveCriticalSection(lk)
#define TRY_LOCK(lk) TryEnterCriticalSection(lk)
#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000))
#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0)
#define NEED_GLOBAL_LOCK_INIT
static MLOCK_T malloc_global_mutex;
static volatile LONG malloc_global_mutex_status;
/* Use spin loop to initialize global lock */
static void init_malloc_global_mutex() {
for (;;) {
long stat = malloc_global_mutex_status;
if (stat > 0)
return;
/* transition to < 0 while initializing, then to > 0) */
if (stat == 0 &&
interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) {
InitializeCriticalSection(&malloc_global_mutex);
interlockedexchange(&malloc_global_mutex_status, (LONG)1);
return;
}
SleepEx(0, FALSE);
}
}
#else /* pthreads-based locks */
#define MLOCK_T pthread_mutex_t
#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk)
#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk)
#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk))
#define INITIAL_LOCK(lk) pthread_init_lock(lk)
#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk)
#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE)
/* Cope with old-style linux recursive lock initialization by adding */
/* skipped internal declaration from pthread.h */
extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,
int __kind));
#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP
#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)
#endif /* USE_RECURSIVE_LOCKS ... */
static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;
static int pthread_init_lock (MLOCK_T *lk) {
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr)) return 1;
#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
#endif
if (pthread_mutex_init(lk, &attr)) return 1;
if (pthread_mutexattr_destroy(&attr)) return 1;
return 0;
}
#endif /* ... lock types ... */
/* Common code for all lock types */
#define USE_LOCK_BIT (2U)
#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK
#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex);
#endif
#ifndef RELEASE_MALLOC_GLOBAL_LOCK
#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex);
#endif
#endif /* USE_LOCKS */
/* ----------------------- Chunk representations ------------------------ */
/*
(The following includes lightly edited explanations by Colin Plumb.)
The malloc_chunk declaration below is misleading (but accurate and
necessary). It declares a "view" into memory allowing access to
necessary fields at known offsets from a given base.
Chunks of memory are maintained using a `boundary tag' method as
originally described by Knuth. (See the paper by Paul Wilson
ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
techniques.) Sizes of free chunks are stored both in the front of
each chunk and at the end. This makes consolidating fragmented
chunks into bigger chunks fast. The head fields also hold bits
representing whether chunks are free or in use.
Here are some pictures to make it clearer. They are "exploded" to
show that the state of a chunk can be thought of as extending from
the high 31 bits of the head field of its header through the
prev_foot and PINUSE_BIT bit of the following chunk header.
A chunk that's in use looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk (if P = 0) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 1| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- -+
| :
+- size - sizeof(size_t) available payload bytes -+
: |
chunk-> +- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
| Size of next chunk (may or may not be in use) | +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
And if it's free, it looks like this:
chunk-> +- -+
| User payload (must be in use, or we would have merged!) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 0| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Prev pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- size - sizeof(struct chunk) unused bytes -+
: |
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
| Size of next chunk (must be in use, or we would have merged)| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- User payload -+
: |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|
+-+
Note that since we always merge adjacent free chunks, the chunks
adjacent to a free chunk must be in use.
Given a pointer to a chunk (which can be derived trivially from the
payload pointer) we can, in O(1) time, find out whether the adjacent
chunks are free, and if so, unlink them from the lists that they
are on and merge them with the current chunk.
Chunks always begin on even word boundaries, so the mem portion
(which is returned to the user) is also on an even word boundary, and
thus at least double-word aligned.
The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
chunk size (which is always a multiple of two words), is an in-use
bit for the *previous* chunk. If that bit is *clear*, then the
word before the current chunk size contains the previous chunk
size, and can be used to find the front of the previous chunk.
The very first chunk allocated always has this bit set, preventing
access to non-existent (or non-owned) memory. If pinuse is set for
any given chunk, then you CANNOT determine the size of the
previous chunk, and might even get a memory addressing fault when
trying to do so.
The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
the chunk size redundantly records whether the current chunk is
inuse (unless the chunk is mmapped). This redundancy enables usage
checks within free and realloc, and reduces indirection when freeing
and consolidating chunks.
Each freshly allocated chunk must have both cinuse and pinuse set.
That is, each allocated chunk borders either a previously allocated
and still in-use chunk, or the base of its memory arena. This is
ensured by making all allocations from the `lowest' part of any
found chunk. Further, no free chunk physically borders another one,
so each free chunk is known to be preceded and followed by either
inuse chunks or the ends of memory.
Note that the `foot' of the current chunk is actually represented
as the prev_foot of the NEXT chunk. This makes it easier to
deal with alignments etc but can be very confusing when trying
to extend or adapt this code.
The exceptions to all this are
1. The special chunk `top' is the top-most available chunk (i.e.,
the one bordering the end of available memory). It is treated
specially. Top is never included in any bin, is used only if
no other chunk is available, and is released back to the
system if it is very large (see M_TRIM_THRESHOLD). In effect,
the top chunk is treated as larger (and thus less well
fitting) than any other available chunk. The top chunk
doesn't update its trailing size field since there is no next
contiguous chunk that would have to index off it. However,
space is still allocated for it (TOP_FOOT_SIZE) to enable
separation or merging when space is extended.
3. Chunks allocated via mmap, have both cinuse and pinuse bits
cleared in their head fields. Because they are allocated
one-by-one, each must carry its own prev_foot field, which is
also used to hold the offset this chunk has within its mmapped
region, which is needed to preserve alignment. Each mmapped
chunk is trailed by the first two fields of a fake next-chunk
for sake of usage checks.
*/
struct malloc_chunk {
size_t prev_foot; /* Size of previous chunk (if free). */
size_t head; /* Size and inuse bits. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
};
typedef struct malloc_chunk mchunk;
typedef struct malloc_chunk* mchunkptr;
typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
typedef unsigned int bindex_t; /* Described below */
typedef unsigned int binmap_t; /* Described below */
typedef unsigned int flag_t; /* The type of various bit flag sets */
/* ------------------- Chunks sizes and alignments ----------------------- */
#define MCHUNK_SIZE (sizeof(mchunk))
#if FOOTERS
#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
#else /* FOOTERS */
#define CHUNK_OVERHEAD (SIZE_T_SIZE)
#endif /* FOOTERS */
/* MMapped chunks need a second word of overhead ... */
#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
/* ... and additional padding for fake next-chunk at foot */
#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
/* The smallest size we can malloc is an aligned minimal chunk */
#define MIN_CHUNK_SIZE\
((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
/* chunk associated with aligned address A */
#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
/* Bounds on request (not chunk) sizes. */
#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
/* pad request bytes into a usable size */
#define pad_request(req) \
(((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* pad request, checking for minimum (but not maximum) */
#define request2size(req) \
(((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
/* ------------------ Operations on head and foot fields ----------------- */
/*
The head field of a chunk is or'ed with PINUSE_BIT when previous
adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
use, unless mmapped, in which case both bits are cleared.
FLAG4_BIT is not used by this malloc, but might be useful in extensions.
*/
#define PINUSE_BIT (SIZE_T_ONE)
#define CINUSE_BIT (SIZE_T_TWO)
#define FLAG4_BIT (SIZE_T_FOUR)
#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)
/* Head value for fenceposts */
#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
/* extraction of fields from head words */
#define cinuse(p) ((p)->head & CINUSE_BIT)
#define pinuse(p) ((p)->head & PINUSE_BIT)
#define flag4inuse(p) ((p)->head & FLAG4_BIT)
#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT)
#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0)
#define chunksize(p) ((p)->head & ~(FLAG_BITS))
#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
#define set_flag4(p) ((p)->head |= FLAG4_BIT)
#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT)
/* Treat space at ptr +/- offset as a chunk */
#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
/* Ptr to next or previous physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))
#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
/* extract next chunk's pinuse bit */
#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
/* Get/set size at footer */
#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
/* Set size, pinuse bit, and foot */
#define set_size_and_pinuse_of_free_chunk(p, s)\
((p)->head = (s|PINUSE_BIT), set_foot(p, s))
/* Set size, pinuse bit, foot, and clear next pinuse */
#define set_free_with_pinuse(p, s, n)\
(clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
/* Get the internal overhead associated with chunk p */
#define overhead_for(p)\
(is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
/* Return true if malloced space is not necessarily cleared */
#if MMAP_CLEARS
#define calloc_must_clear(p) (!is_mmapped(p))
#else /* MMAP_CLEARS */
#define calloc_must_clear(p) (1)
#endif /* MMAP_CLEARS */
/* ---------------------- Overlaid data structures ----------------------- */
/*
When chunks are not in use, they are treated as nodes of either
lists or trees.
"Small" chunks are stored in circular doubly-linked lists, and look
like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Larger chunks are kept in a form of bitwise digital trees (aka
tries) keyed on chunksizes. Because malloc_tree_chunks are only for
free chunks greater than 256 bytes, their size doesn't impose any
constraints on user chunk sizes. Each node looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to left child (child[0]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to right child (child[1]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to parent |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| bin index of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Each tree holding treenodes is a tree of unique chunk sizes. Chunks
of the same size are arranged in a circularly-linked list, with only
the oldest chunk (the next to be used, in our FIFO ordering)
actually in the tree. (Tree members are distinguished by a non-null
parent pointer.) If a chunk with the same size an an existing node
is inserted, it is linked off the existing node using pointers that
work in the same way as fd/bk pointers of small chunks.
Each tree contains a power of 2 sized range of chunk sizes (the
smallest is 0x100 <= x < 0x180), which is is divided in half at each
tree level, with the chunks in the smaller half of the range (0x100
<= x < 0x140 for the top nose) in the left subtree and the larger
half (0x140 <= x < 0x180) in the right subtree. This is, of course,
done by inspecting individual bits.
Using these rules, each node's left subtree contains all smaller
sizes than its right subtree. However, the node at the root of each
subtree has no particular ordering relationship to either. (The
dividing line between the subtree sizes is based on trie relation.)
If we remove the last chunk of a given size from the interior of the
tree, we need to replace it with a leaf node. The tree ordering
rules permit a node to be replaced by any leaf below it.
The smallest chunk in a tree (a common operation in a best-fit
allocator) can be found by walking a path to the leftmost leaf in
the tree. Unlike a usual binary tree, where we follow left child
pointers until we reach a null, here we follow the right child
pointer any time the left one is null, until we reach a leaf with
both child pointers null. The smallest chunk in the tree will be
somewhere along that path.
The worst case number of steps to add, find, or remove a node is
bounded by the number of bits differentiating chunks within
bins. Under current bin calculations, this ranges from 6 up to 21
(for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
is of course much better.
*/
struct malloc_tree_chunk {
/* The first four fields must be compatible with malloc_chunk */
size_t prev_foot;
size_t head;
struct malloc_tree_chunk* fd;
struct malloc_tree_chunk* bk;
struct malloc_tree_chunk* child[2];
struct malloc_tree_chunk* parent;
bindex_t index;
};
typedef struct malloc_tree_chunk tchunk;
typedef struct malloc_tree_chunk* tchunkptr;
typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
/* A little helper macro for trees */
#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
/* ----------------------------- Segments -------------------------------- */
/*
Each malloc space may include non-contiguous segments, held in a
list headed by an embedded malloc_segment record representing the
top-most space. Segments also include flags holding properties of
the space. Large chunks that are directly allocated by mmap are not
included in this list. They are instead independently created and
destroyed without otherwise keeping track of them.
Segment management mainly comes into play for spaces allocated by
MMAP. Any call to MMAP might or might not return memory that is
adjacent to an existing segment. MORECORE normally contiguously
extends the current space, so this space is almost always adjacent,
which is simpler and faster to deal with. (This is why MORECORE is
used preferentially to MMAP when both are available -- see
sys_alloc.) When allocating using MMAP, we don't use any of the
hinting mechanisms (inconsistently) supported in various
implementations of unix mmap, or distinguish reserving from
committing memory. Instead, we just ask for space, and exploit
contiguity when we get it. It is probably possible to do
better than this on some systems, but no general scheme seems
to be significantly better.
Management entails a simpler variant of the consolidation scheme
used for chunks to reduce fragmentation -- new adjacent memory is
normally prepended or appended to an existing segment. However,
there are limitations compared to chunk consolidation that mostly
reflect the fact that segment processing is relatively infrequent
(occurring only when getting memory from system) and that we
don't expect to have huge numbers of segments:
* Segments are not indexed, so traversal requires linear scans. (It
would be possible to index these, but is not worth the extra
overhead and complexity for most programs on most platforms.)
* New segments are only appended to old ones when holding top-most
memory; if they cannot be prepended to others, they are held in
different segments.
Except for the top-most segment of an mstate, each segment record
is kept at the tail of its segment. Segments are added by pushing
segment records onto the list headed by &mstate.seg for the
containing mstate.
Segment flags control allocation/merge/deallocation policies:
* If EXTERN_BIT set, then we did not allocate this segment,
and so should not try to deallocate or merge with others.
(This currently holds only for the initial segment passed
into create_mspace_with_base.)
* If USE_MMAP_BIT set, the segment may be merged with
other surrounding mmapped segments and trimmed/de-allocated
using munmap.
* If neither bit is set, then the segment was obtained using
MORECORE so can be merged with surrounding MORECORE'd segments
and deallocated/trimmed using MORECORE with negative arguments.
*/
struct malloc_segment {
char* base; /* base address */
size_t size; /* allocated size */
struct malloc_segment* next; /* ptr to next segment */
flag_t sflags; /* mmap and extern flag */
};
#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT)
#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
typedef struct malloc_segment msegment;
typedef struct malloc_segment* msegmentptr;
/* ---------------------------- malloc_state ----------------------------- */
/*
A malloc_state holds all of the bookkeeping for a space.
The main fields are:
Top
The topmost chunk of the currently active segment. Its size is
cached in topsize. The actual size of topmost space is
topsize+TOP_FOOT_SIZE, which includes space reserved for adding
fenceposts and segment records if necessary when getting more
space from the system. The size at which to autotrim top is
cached from mparams in trim_check, except that it is disabled if
an autotrim fails.
Designated victim (dv)
This is the preferred chunk for servicing small requests that
don't have exact fits. It is normally the chunk split off most
recently to service another small request. Its size is cached in
dvsize. The link fields of this chunk are not maintained since it
is not kept in a bin.
SmallBins
An array of bin headers for free chunks. These bins hold chunks
with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
chunks of all the same size, spaced 8 bytes apart. To simplify
use in double-linked lists, each bin header acts as a malloc_chunk
pointing to the real first node, if it exists (else pointing to
itself). This avoids special-casing for headers. But to avoid
waste, we allocate only the fd/bk pointers of bins, and then use
repositioning tricks to treat these as the fields of a chunk.
TreeBins
Treebins are pointers to the roots of trees holding a range of
sizes. There are 2 equally spaced treebins for each power of two
from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
larger.
Bin maps
There is one bit map for small bins ("smallmap") and one for
treebins ("treemap). Each bin sets its bit when non-empty, and
clears the bit when empty. Bit operations are then used to avoid
bin-by-bin searching -- nearly all "search" is done without ever
looking at bins that won't be selected. The bit maps
conservatively use 32 bits per map word, even if on 64bit system.
For a good description of some of the bit-based techniques used
here, see Henry S. Warren Jr's book "Hacker's Delight" (and
supplement at http://hackersdelight.org/). Many of these are
intended to reduce the branchiness of paths through malloc etc, as
well as to reduce the number of memory locations read or written.
Segments
A list of segments headed by an embedded malloc_segment record
representing the initial space.
Address check support
The least_addr field is the least address ever obtained from
MORECORE or MMAP. Attempted frees and reallocs of any address less
than this are trapped (unless INSECURE is defined).
Magic tag
A cross-check field that should always hold same value as mparams.magic.
Max allowed footprint
The maximum allowed bytes to allocate from system (zero means no limit)
Flags
Bits recording whether to use MMAP, locks, or contiguous MORECORE
Statistics
Each space keeps track of current and maximum system memory
obtained via MORECORE or MMAP.
Trim support
Fields holding the amount of unused topmost memory that should trigger
trimming, and a counter to force periodic scanning to release unused
non-topmost segments.
Locking
If USE_LOCKS is defined, the "mutex" lock is acquired and released
around every public call using this mspace.
Extension support
A void* pointer and a size_t field that can be used to help implement
extensions to this malloc.
*/
/* Bin types, widths and sizes */
#define NSMALLBINS (32U)
#define NTREEBINS (32U)
#define SMALLBIN_SHIFT (3U)
#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
#define TREEBIN_SHIFT (8U)
#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
struct malloc_state {
binmap_t smallmap;
binmap_t treemap;
size_t dvsize;
size_t topsize;
char* least_addr;
mchunkptr dv;
mchunkptr top;
size_t trim_check;
size_t release_checks;
size_t magic;
mchunkptr smallbins[(NSMALLBINS+1)*2];
tbinptr treebins[NTREEBINS];
size_t footprint;
size_t max_footprint;
size_t footprint_limit; /* zero means no limit */
flag_t mflags;
#if USE_LOCKS
MLOCK_T mutex; /* locate lock among fields that rarely change */
#endif /* USE_LOCKS */
msegment seg;
void* extp; /* Unused but available for extensions */
size_t exts;
};
typedef struct malloc_state* mstate;
/* ------------- Global malloc_state and malloc_params ------------------- */
/*
malloc_params holds global properties, including those that can be
dynamically set using mallopt. There is a single instance, mparams,
initialized in init_mparams. Note that the non-zeroness of "magic"
also serves as an initialization flag.
*/
struct malloc_params {
size_t magic;
size_t page_size;
size_t granularity;
size_t mmap_threshold;
size_t trim_threshold;
flag_t default_mflags;
};
static struct malloc_params mparams;
/* Ensure mparams initialized */
#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())
#if !ONLY_MSPACES
/* The global malloc_state used for all non-"mspace" calls */
static struct malloc_state _gm_;
#define gm (&_gm_)
#define is_global(M) ((M) == &_gm_)
#endif /* !ONLY_MSPACES */
#define is_initialized(M) ((M)->top != 0)
/* -------------------------- system alloc setup ------------------------- */
/* Operations on mflags */
#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
#if USE_LOCKS
#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
#else
#define disable_lock(M)
#endif
#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
#if HAVE_MMAP
#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
#else
#define disable_mmap(M)
#endif
#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
#define set_lock(M,L)\
((M)->mflags = (L)?\
((M)->mflags | USE_LOCK_BIT) :\
((M)->mflags & ~USE_LOCK_BIT))
/* page-align a size */
#define page_align(S)\
(((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))
/* granularity-align a size */
#define granularity_align(S)\
(((S) + (mparams.granularity - SIZE_T_ONE))\
& ~(mparams.granularity - SIZE_T_ONE))
/* For mmap, use granularity alignment on windows, else page-align */
#ifdef WIN32
#define mmap_align(S) granularity_align(S)
#else
#define mmap_align(S) page_align(S)
#endif
/* For sys_alloc, enough padding to ensure can malloc request on success */
#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)
#define is_page_aligned(S)\
(((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
#define is_granularity_aligned(S)\
(((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
/* True if segment S holds address A */
#define segment_holds(S, A)\
((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
/* Return segment holding given address */
static msegmentptr segment_holding(mstate m, char* addr) {
msegmentptr sp = &m->seg;
for (;;) {
if (addr >= sp->base && addr < sp->base + sp->size)
return sp;
if ((sp = sp->next) == 0)
return 0;
}
}
/* Return true if segment contains a segment link */
static int has_segment_link(mstate m, msegmentptr ss) {
msegmentptr sp = &m->seg;
for (;;) {
if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
return 1;
if ((sp = sp->next) == 0)
return 0;
}
}
#ifndef MORECORE_CANNOT_TRIM
#define should_trim(M,s) ((s) > (M)->trim_check)
#else /* MORECORE_CANNOT_TRIM */
#define should_trim(M,s) (0)
#endif /* MORECORE_CANNOT_TRIM */
/*
TOP_FOOT_SIZE is padding at the end of a segment, including space
that may be needed to place segment records and fenceposts when new
noncontiguous segments are added.
*/
#define TOP_FOOT_SIZE\
(align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
/* ------------------------------- Hooks -------------------------------- */
/*
PREACTION should be defined to return 0 on success, and nonzero on
failure. If you are not using locking, you can redefine these to do
anything you like.
*/
#if USE_LOCKS
#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
#else /* USE_LOCKS */
#ifndef PREACTION
#define PREACTION(M) (0)
#endif /* PREACTION */
#ifndef POSTACTION
#define POSTACTION(M)
#endif /* POSTACTION */
#endif /* USE_LOCKS */
/*
CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
USAGE_ERROR_ACTION is triggered on detected bad frees and
reallocs. The argument p is an address that might have triggered the
fault. It is ignored by the two predefined actions, but might be
useful in custom actions that try to help diagnose errors.
*/
#if PROCEED_ON_ERROR
/* A count of the number of corruption errors causing resets */
int malloc_corruption_error_count;
/* default corruption action */
static void reset_on_error(mstate m);
#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
#define USAGE_ERROR_ACTION(m, p)
#else /* PROCEED_ON_ERROR */
#ifndef CORRUPTION_ERROR_ACTION
#define CORRUPTION_ERROR_ACTION(m) ABORT
#endif /* CORRUPTION_ERROR_ACTION */
#ifndef USAGE_ERROR_ACTION
#define USAGE_ERROR_ACTION(m,p) ABORT
#endif /* USAGE_ERROR_ACTION */
#endif /* PROCEED_ON_ERROR */
/* -------------------------- Debugging setup ---------------------------- */
#if ! DEBUG
#define check_free_chunk(M,P)
#define check_inuse_chunk(M,P)
#define check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P)
#define check_malloc_state(M)
#define check_top_chunk(M,P)
#else /* DEBUG */
#define check_free_chunk(M,P) do_check_free_chunk(M,P)
#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
#define check_top_chunk(M,P) do_check_top_chunk(M,P)
#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
#define check_malloc_state(M) do_check_malloc_state(M)
static void do_check_any_chunk(mstate m, mchunkptr p);
static void do_check_top_chunk(mstate m, mchunkptr p);
static void do_check_mmapped_chunk(mstate m, mchunkptr p);
static void do_check_inuse_chunk(mstate m, mchunkptr p);
static void do_check_free_chunk(mstate m, mchunkptr p);
static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
static void do_check_tree(mstate m, tchunkptr t);
static void do_check_treebin(mstate m, bindex_t i);
static void do_check_smallbin(mstate m, bindex_t i);
static void do_check_malloc_state(mstate m);
static int bin_find(mstate m, mchunkptr x);
static size_t traverse_and_check(mstate m);
#endif /* DEBUG */
/* ---------------------------- Indexing Bins ---------------------------- */
#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT)
#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
/* addressing by index. See above about smallbin repositioning */
#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
#define treebin_at(M,i) (&((M)->treebins[i]))
/* assign tree index for size S to variable I. Use x86 asm if possible */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define compute_tree_index(S, I)\
{\
unsigned int X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#elif defined (__INTEL_COMPILER)
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K = _bit_scan_reverse (X); \
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#elif defined(_MSC_VER) && _MSC_VER>=1300
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K;\
_BitScanReverse((DWORD *) &K, (DWORD) X);\
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#else /* GNUC */
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int Y = (unsigned int)X;\
unsigned int N = ((Y - 0x100) >> 16) & 8;\
unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
N += K;\
N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
K = 14 - N + ((Y <<= K) >> 15);\
I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
}\
}
#endif /* GNUC */
/* Bit representing maximum resolved size in a treebin at i */
#define bit_for_tree_index(i) \
(i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
/* Shift placing maximum resolved bit in a treebin at i as sign bit */
#define leftshift_for_tree_index(i) \
((i == NTREEBINS-1)? 0 : \
((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
/* The size of the smallest chunk held in bin with index i */
#define minsize_for_tree_index(i) \
((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
(((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
/* ------------------------ Operations on bin maps ----------------------- */
/* bit corresponding to given index */
#define idx2bit(i) ((binmap_t)(1) << (i))
/* Mark/Clear bits with given index */
#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
/* isolate the least set bit of a bitmap */
#define least_bit(x) ((x) & -(x))
/* mask with all bits to left of least bit of x on */
#define left_bits(x) ((x<<1) | -(x<<1))
/* mask with all bits to left of or equal to least bit of x on */
#define same_or_left_bits(x) ((x) | -(x))
/* index corresponding to given bit. Use x86 asm if possible */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
J = __builtin_ctz(X); \
I = (bindex_t)J;\
}
#elif defined (__INTEL_COMPILER)
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
J = _bit_scan_forward (X); \
I = (bindex_t)J;\
}
#elif defined(_MSC_VER) && _MSC_VER>=1300
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
_BitScanForward((DWORD *) &J, X);\
I = (bindex_t)J;\
}
#elif USE_BUILTIN_FFS
#define compute_bit2idx(X, I) I = ffs(X)-1
#else
#define compute_bit2idx(X, I)\
{\
unsigned int Y = X - 1;\
unsigned int K = Y >> (16-4) & 16;\
unsigned int N = K; Y >>= K;\
N += K = Y >> (8-3) & 8; Y >>= K;\
N += K = Y >> (4-2) & 4; Y >>= K;\
N += K = Y >> (2-1) & 2; Y >>= K;\
N += K = Y >> (1-0) & 1; Y >>= K;\
I = (bindex_t)(N + Y);\
}
#endif /* GNUC */
/* ----------------------- Runtime Check Support ------------------------- */
/*
For security, the main invariant is that malloc/free/etc never
writes to a static address other than malloc_state, unless static
malloc_state itself has been corrupted, which cannot occur via
malloc (because of these checks). In essence this means that we
believe all pointers, sizes, maps etc held in malloc_state, but
check all of those linked or offsetted from other embedded data
structures. These checks are interspersed with main code in a way
that tends to minimize their run-time cost.
When FOOTERS is defined, in addition to range checking, we also
verify footer fields of inuse chunks, which can be used guarantee
that the mstate controlling malloc/free is intact. This is a
streamlined version of the approach described by William Robertson
et al in "Run-time Detection of Heap-based Overflows" LISA'03
http://www.usenix.org/events/lisa03/tech/robertson.html The footer
of an inuse chunk holds the xor of its mstate and a random seed,
that is checked upon calls to free() and realloc(). This is
(probabalistically) unguessable from outside the program, but can be
computed by any code successfully malloc'ing any chunk, so does not
itself provide protection against code that has already broken
security through some other means. Unlike Robertson et al, we
always dynamically check addresses of all offset chunks (previous,
next, etc). This turns out to be cheaper than relying on hashes.
*/
#if !INSECURE
/* Check if address a is at least as high as any from MORECORE or MMAP */
#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
/* Check if address of next chunk n is higher than base chunk p */
#define ok_next(p, n) ((char*)(p) < (char*)(n))
/* Check if p has inuse status */
#define ok_inuse(p) is_inuse(p)
/* Check if p has its pinuse bit on */
#define ok_pinuse(p) pinuse(p)
#else /* !INSECURE */
#define ok_address(M, a) (1)
#define ok_next(b, n) (1)
#define ok_inuse(p) (1)
#define ok_pinuse(p) (1)
#endif /* !INSECURE */
#if (FOOTERS && !INSECURE)
/* Check if (alleged) mstate m has expected magic field */
#define ok_magic(M) ((M)->magic == mparams.magic)
#else /* (FOOTERS && !INSECURE) */
#define ok_magic(M) (1)
#endif /* (FOOTERS && !INSECURE) */
/* In gcc, use __builtin_expect to minimize impact of checks */
#if !INSECURE
#if defined(__GNUC__) && __GNUC__ >= 3
#define RTCHECK(e) __builtin_expect(e, 1)
#else /* GNUC */
#define RTCHECK(e) (e)
#endif /* GNUC */
#else /* !INSECURE */
#define RTCHECK(e) (1)
#endif /* !INSECURE */
/* macros to set up inuse chunks with or without footers */
#if !FOOTERS
#define mark_inuse_foot(M,p,s)
/* Macros for setting head/foot of non-mmapped chunks */
/* Set cinuse bit and pinuse bit of next chunk */
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set size, cinuse and pinuse bit of this chunk */
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
#else /* FOOTERS */
/* Set foot of inuse chunk to be xor of mstate and seed */
#define mark_inuse_foot(M,p,s)\
(((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
#define get_mstate_for(p)\
((mstate)(((mchunkptr)((char*)(p) +\
(chunksize(p))))->prev_foot ^ mparams.magic))
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
mark_inuse_foot(M,p,s))
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
mark_inuse_foot(M,p,s))
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
mark_inuse_foot(M, p, s))
#endif /* !FOOTERS */
/* ---------------------------- setting mparams -------------------------- */
#if LOCK_AT_FORK
static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); }
static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); }
static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); }
#endif /* LOCK_AT_FORK */
/* Initialize mparams */
static int init_mparams(void) {
#ifdef NEED_GLOBAL_LOCK_INIT
if (malloc_global_mutex_status <= 0)
init_malloc_global_mutex();
#endif
ACQUIRE_MALLOC_GLOBAL_LOCK();
if (mparams.magic == 0) {
size_t magic;
size_t psize;
size_t gsize;
#ifndef WIN32
psize = malloc_getpagesize;
gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);
#else /* WIN32 */
{
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
psize = system_info.dwPageSize;
gsize = ((DEFAULT_GRANULARITY != 0)?
DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);
}
#endif /* WIN32 */
/* Sanity-check configuration:
size_t must be unsigned and as wide as pointer type.
ints must be at least 4 bytes.
alignment must be at least 8.
Alignment, min chunk size, and page size must all be powers of 2.
*/
if ((sizeof(size_t) != sizeof(char*)) ||
(MAX_SIZE_T < MIN_CHUNK_SIZE) ||
(sizeof(int) < 4) ||
(MALLOC_ALIGNMENT < (size_t)8U) ||
((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
((gsize & (gsize-SIZE_T_ONE)) != 0) ||
((psize & (psize-SIZE_T_ONE)) != 0))
ABORT;
mparams.granularity = gsize;
mparams.page_size = psize;
mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
#if MORECORE_CONTIGUOUS
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
#else /* MORECORE_CONTIGUOUS */
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
#endif /* MORECORE_CONTIGUOUS */
#if !ONLY_MSPACES
/* Set up lock for main malloc area */
gm->mflags = mparams.default_mflags;
(void)INITIAL_LOCK(&gm->mutex);
#endif
#if LOCK_AT_FORK
pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child);
#endif
{
#if USE_DEV_RANDOM
int fd;
unsigned char buf[sizeof(size_t)];
/* Try to use /dev/urandom, else fall back on using time */
if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
read(fd, buf, sizeof(buf)) == sizeof(buf)) {
magic = *((size_t *) buf);
close(fd);
}
else
#endif /* USE_DEV_RANDOM */
#ifdef WIN32
magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);
#elif defined(LACKS_TIME_H)
magic = (size_t)&magic ^ (size_t)0x55555555U;
#else
magic = (size_t)(time(0) ^ (size_t)0x55555555U);
#endif
magic |= (size_t)8U; /* ensure nonzero */
magic &= ~(size_t)7U; /* improve chances of fault for bad values */
/* Until memory modes commonly available, use volatile-write */
(*(volatile size_t *)(&(mparams.magic))) = magic;
}
}
RELEASE_MALLOC_GLOBAL_LOCK();
return 1;
}
/* support for mallopt */
static int change_mparam(int param_number, int value) {
size_t val;
ensure_initialization();
val = (value == -1)? MAX_SIZE_T : (size_t)value;
switch(param_number) {
case M_TRIM_THRESHOLD:
mparams.trim_threshold = val;
return 1;
case M_GRANULARITY:
if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
mparams.granularity = val;
return 1;
}
else
return 0;
case M_MMAP_THRESHOLD:
mparams.mmap_threshold = val;
return 1;
default:
return 0;
}
}
#if DEBUG
/* ------------------------- Debugging Support --------------------------- */
/* Check properties of any chunk, whether free, inuse, mmapped etc */
static void do_check_any_chunk(mstate m, mchunkptr p) {
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
}
/* Check properties of top chunk */
static void do_check_top_chunk(mstate m, mchunkptr p) {
msegmentptr sp = segment_holding(m, (char*)p);
size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */
assert(sp != 0);
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(sz == m->topsize);
assert(sz > 0);
assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
assert(pinuse(p));
assert(!pinuse(chunk_plus_offset(p, sz)));
}
/* Check properties of (inuse) mmapped chunks */
static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
size_t sz = chunksize(p);
size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);
assert(is_mmapped(p));
assert(use_mmap(m));
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(!is_small(sz));
assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
}
/* Check properties of inuse chunks */
static void do_check_inuse_chunk(mstate m, mchunkptr p) {
do_check_any_chunk(m, p);
assert(is_inuse(p));
assert(next_pinuse(p));
/* If not pinuse and not mmapped, previous chunk has OK offset */
assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
if (is_mmapped(p))
do_check_mmapped_chunk(m, p);
}
/* Check properties of free chunks */
static void do_check_free_chunk(mstate m, mchunkptr p) {
size_t sz = chunksize(p);
mchunkptr next = chunk_plus_offset(p, sz);
do_check_any_chunk(m, p);
assert(!is_inuse(p));
assert(!next_pinuse(p));
assert (!is_mmapped(p));
if (p != m->dv && p != m->top) {
if (sz >= MIN_CHUNK_SIZE) {
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(is_aligned(chunk2mem(p)));
assert(next->prev_foot == sz);
assert(pinuse(p));
assert (next == m->top || is_inuse(next));
assert(p->fd->bk == p);
assert(p->bk->fd == p);
}
else /* markers are always of size SIZE_T_SIZE */
assert(sz == SIZE_T_SIZE);
}
}
/* Check properties of malloced chunks at the point they are malloced */
static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
size_t sz = p->head & ~INUSE_BITS;
do_check_inuse_chunk(m, p);
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(sz >= MIN_CHUNK_SIZE);
assert(sz >= s);
/* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
}
}
/* Check a tree and its subtrees. */
static void do_check_tree(mstate m, tchunkptr t) {
tchunkptr head = 0;
tchunkptr u = t;
bindex_t tindex = t->index;
size_t tsize = chunksize(t);
bindex_t idx;
compute_tree_index(tsize, idx);
assert(tindex == idx);
assert(tsize >= MIN_LARGE_SIZE);
assert(tsize >= minsize_for_tree_index(idx));
assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
do { /* traverse through chain of same-sized nodes */
do_check_any_chunk(m, ((mchunkptr)u));
assert(u->index == tindex);
assert(chunksize(u) == tsize);
assert(!is_inuse(u));
assert(!next_pinuse(u));
assert(u->fd->bk == u);
assert(u->bk->fd == u);
if (u->parent == 0) {
assert(u->child[0] == 0);
assert(u->child[1] == 0);
}
else {
assert(head == 0); /* only one node on chain has parent */
head = u;
assert(u->parent != u);
assert (u->parent->child[0] == u ||
u->parent->child[1] == u ||
*((tbinptr*)(u->parent)) == u);
if (u->child[0] != 0) {
assert(u->child[0]->parent == u);
assert(u->child[0] != u);
do_check_tree(m, u->child[0]);
}
if (u->child[1] != 0) {
assert(u->child[1]->parent == u);
assert(u->child[1] != u);
do_check_tree(m, u->child[1]);
}
if (u->child[0] != 0 && u->child[1] != 0) {
assert(chunksize(u->child[0]) < chunksize(u->child[1]));
}
}
u = u->fd;
} while (u != t);
assert(head != 0);
}
/* Check all the chunks in a treebin. */
static void do_check_treebin(mstate m, bindex_t i) {
tbinptr* tb = treebin_at(m, i);
tchunkptr t = *tb;
int empty = (m->treemap & (1U << i)) == 0;
if (t == 0)
assert(empty);
if (!empty)
do_check_tree(m, t);
}
/* Check all the chunks in a smallbin. */
static void do_check_smallbin(mstate m, bindex_t i) {
sbinptr b = smallbin_at(m, i);
mchunkptr p = b->bk;
unsigned int empty = (m->smallmap & (1U << i)) == 0;
if (p == b)
assert(empty);
if (!empty) {
for (; p != b; p = p->bk) {
size_t size = chunksize(p);
mchunkptr q;
/* each chunk claims to be free */
do_check_free_chunk(m, p);
/* chunk belongs in bin */
assert(small_index(size) == i);
assert(p->bk == b || chunksize(p->bk) == chunksize(p));
/* chunk is followed by an inuse chunk */
q = next_chunk(p);
if (q->head != FENCEPOST_HEAD)
do_check_inuse_chunk(m, q);
}
}
}
/* Find x in a bin. Used in other check functions. */
static int bin_find(mstate m, mchunkptr x) {
size_t size = chunksize(x);
if (is_small(size)) {
bindex_t sidx = small_index(size);
sbinptr b = smallbin_at(m, sidx);
if (smallmap_is_marked(m, sidx)) {
mchunkptr p = b;
do {
if (p == x)
return 1;
} while ((p = p->fd) != b);
}
}
else {
bindex_t tidx;
compute_tree_index(size, tidx);
if (treemap_is_marked(m, tidx)) {
tchunkptr t = *treebin_at(m, tidx);
size_t sizebits = size << leftshift_for_tree_index(tidx);
while (t != 0 && chunksize(t) != size) {
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
sizebits <<= 1;
}
if (t != 0) {
tchunkptr u = t;
do {
if (u == (tchunkptr)x)
return 1;
} while ((u = u->fd) != t);
}
}
}
return 0;
}
/* Traverse each chunk and check it; return total */
static size_t traverse_and_check(mstate m) {
size_t sum = 0;
if (is_initialized(m)) {
msegmentptr s = &m->seg;
sum += m->topsize + TOP_FOOT_SIZE;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
mchunkptr lastq = 0;
assert(pinuse(q));
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
sum += chunksize(q);
if (is_inuse(q)) {
assert(!bin_find(m, q));
do_check_inuse_chunk(m, q);
}
else {
assert(q == m->dv || bin_find(m, q));
assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */
do_check_free_chunk(m, q);
}
lastq = q;
q = next_chunk(q);
}
s = s->next;
}
}
return sum;
}
/* Check all properties of malloc_state. */
static void do_check_malloc_state(mstate m) {
bindex_t i;
size_t total;
/* check bins */
for (i = 0; i < NSMALLBINS; ++i)
do_check_smallbin(m, i);
for (i = 0; i < NTREEBINS; ++i)
do_check_treebin(m, i);
if (m->dvsize != 0) { /* check dv chunk */
do_check_any_chunk(m, m->dv);
assert(m->dvsize == chunksize(m->dv));
assert(m->dvsize >= MIN_CHUNK_SIZE);
assert(bin_find(m, m->dv) == 0);
}
if (m->top != 0) { /* check top chunk */
do_check_top_chunk(m, m->top);
/*assert(m->topsize == chunksize(m->top)); redundant */
assert(m->topsize > 0);
assert(bin_find(m, m->top) == 0);
}
total = traverse_and_check(m);
assert(total <= m->footprint);
assert(m->footprint <= m->max_footprint);
}
#endif /* DEBUG */
/* ----------------------------- statistics ------------------------------ */
#if !NO_MALLINFO
static struct mallinfo internal_mallinfo(mstate m) {
struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ensure_initialization();
if (!PREACTION(m)) {
check_malloc_state(m);
if (is_initialized(m)) {
size_t nfree = SIZE_T_ONE; /* top always free */
size_t mfree = m->topsize + TOP_FOOT_SIZE;
size_t sum = mfree;
msegmentptr s = &m->seg;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
size_t sz = chunksize(q);
sum += sz;
if (!is_inuse(q)) {
mfree += sz;
++nfree;
}
q = next_chunk(q);
}
s = s->next;
}
nm.arena = sum;
nm.ordblks = nfree;
nm.hblkhd = m->footprint - sum;
nm.usmblks = m->max_footprint;
nm.uordblks = m->footprint - mfree;
nm.fordblks = mfree;
nm.keepcost = m->topsize;
}
POSTACTION(m);
}
return nm;
}
#endif /* !NO_MALLINFO */
#if !NO_MALLOC_STATS
static void internal_malloc_stats(mstate m) {
ensure_initialization();
if (!PREACTION(m)) {
size_t maxfp = 0;
size_t fp = 0;
size_t used = 0;
check_malloc_state(m);
if (is_initialized(m)) {
msegmentptr s = &m->seg;
maxfp = m->max_footprint;
fp = m->footprint;
used = fp - (m->topsize + TOP_FOOT_SIZE);
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
if (!is_inuse(q))
used -= chunksize(q);
q = next_chunk(q);
}
s = s->next;
}
}
POSTACTION(m); /* drop lock */
fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));
fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));
}
}
#endif /* NO_MALLOC_STATS */
/* ----------------------- Operations on smallbins ----------------------- */
/*
Various forms of linking and unlinking are defined as macros. Even
the ones for trees, which are very long but have very short typical
paths. This is ugly but reduces reliance on inlining support of
compilers.
*/
/* Link a free chunk into a smallbin */
#define insert_small_chunk(M, P, S) {\
bindex_t I = small_index(S);\
mchunkptr B = smallbin_at(M, I);\
mchunkptr F = B;\
assert(S >= MIN_CHUNK_SIZE);\
if (!smallmap_is_marked(M, I))\
mark_smallmap(M, I);\
else if (RTCHECK(ok_address(M, B->fd)))\
F = B->fd;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
B->fd = P;\
F->bk = P;\
P->fd = F;\
P->bk = B;\
}
/* Unlink a chunk from a smallbin */
#define unlink_small_chunk(M, P, S) {\
mchunkptr F = P->fd;\
mchunkptr B = P->bk;\
bindex_t I = small_index(S);\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \
if (B == F) {\
clear_smallmap(M, I);\
}\
else if (RTCHECK(B == smallbin_at(M,I) ||\
(ok_address(M, B) && B->fd == P))) {\
F->bk = B;\
B->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Unlink the first chunk from a smallbin */
#define unlink_first_small_chunk(M, B, P, I) {\
mchunkptr F = P->fd;\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (B == F) {\
clear_smallmap(M, I);\
}\
else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\
F->bk = B;\
B->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Replace dv node, binning the old one */
/* Used only when dvsize known to be small */
#define replace_dv(M, P, S) {\
size_t DVS = M->dvsize;\
assert(is_small(DVS));\
if (DVS != 0) {\
mchunkptr DV = M->dv;\
insert_small_chunk(M, DV, DVS);\
}\
M->dvsize = S;\
M->dv = P;\
}
/* ------------------------- Operations on trees ------------------------- */
/* Insert chunk into tree */
#define insert_large_chunk(M, X, S) {\
tbinptr* H;\
bindex_t I;\
compute_tree_index(S, I);\
H = treebin_at(M, I);\
X->index = I;\
X->child[0] = X->child[1] = 0;\
if (!treemap_is_marked(M, I)) {\
mark_treemap(M, I);\
*H = X;\
X->parent = (tchunkptr)H;\
X->fd = X->bk = X;\
}\
else {\
tchunkptr T = *H;\
size_t K = S << leftshift_for_tree_index(I);\
for (;;) {\
if (chunksize(T) != S) {\
tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
K <<= 1;\
if (*C != 0)\
T = *C;\
else if (RTCHECK(ok_address(M, C))) {\
*C = X;\
X->parent = T;\
X->fd = X->bk = X;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
else {\
tchunkptr F = T->fd;\
if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
T->fd = F->bk = X;\
X->fd = F;\
X->bk = T;\
X->parent = 0;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
}\
}\
}
/*
Unlink steps:
1. If x is a chained node, unlink it from its same-sized fd/bk links
and choose its bk node as its replacement.
2. If x was the last node of its size, but not a leaf node, it must
be replaced with a leaf node (not merely one with an open left or
right), to make sure that lefts and rights of descendents
correspond properly to bit masks. We use the rightmost descendent
of x. We could use any other leaf, but this is easy to locate and
tends to counteract removal of leftmosts elsewhere, and so keeps
paths shorter than minimally guaranteed. This doesn't loop much
because on average a node in a tree is near the bottom.
3. If x is the base of a chain (i.e., has parent links) relink
x's parent and children to x's replacement (or null if none).
*/
#define unlink_large_chunk(M, X) {\
tchunkptr XP = X->parent;\
tchunkptr R;\
if (X->bk != X) {\
tchunkptr F = X->fd;\
R = X->bk;\
if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\
F->bk = R;\
R->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else {\
tchunkptr* RP;\
if (((R = *(RP = &(X->child[1]))) != 0) ||\
((R = *(RP = &(X->child[0]))) != 0)) {\
tchunkptr* CP;\
while ((*(CP = &(R->child[1])) != 0) ||\
(*(CP = &(R->child[0])) != 0)) {\
R = *(RP = CP);\
}\
if (RTCHECK(ok_address(M, RP)))\
*RP = 0;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}\
if (XP != 0) {\
tbinptr* H = treebin_at(M, X->index);\
if (X == *H) {\
if ((*H = R) == 0) \
clear_treemap(M, X->index);\
}\
else if (RTCHECK(ok_address(M, XP))) {\
if (XP->child[0] == X) \
XP->child[0] = R;\
else \
XP->child[1] = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
if (R != 0) {\
if (RTCHECK(ok_address(M, R))) {\
tchunkptr C0, C1;\
R->parent = XP;\
if ((C0 = X->child[0]) != 0) {\
if (RTCHECK(ok_address(M, C0))) {\
R->child[0] = C0;\
C0->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
if ((C1 = X->child[1]) != 0) {\
if (RTCHECK(ok_address(M, C1))) {\
R->child[1] = C1;\
C1->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}
/* Relays to large vs small bin operations */
#define insert_chunk(M, P, S)\
if (is_small(S)) insert_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
#define unlink_chunk(M, P, S)\
if (is_small(S)) unlink_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
/* Relays to internal calls to malloc/free from realloc, memalign etc */
#if ONLY_MSPACES
#define internal_malloc(m, b) mspace_malloc(m, b)
#define internal_free(m, mem) mspace_free(m,mem);
#else /* ONLY_MSPACES */
#if MSPACES
#define internal_malloc(m, b)\
((m == gm)? dlmalloc(b) : mspace_malloc(m, b))
#define internal_free(m, mem)\
if (m == gm) dlfree(mem); else mspace_free(m,mem);
#else /* MSPACES */
#define internal_malloc(m, b) dlmalloc(b)
#define internal_free(m, mem) dlfree(mem)
#endif /* MSPACES */
#endif /* ONLY_MSPACES */
/* ----------------------- Direct-mmapping chunks ----------------------- */
/*
Directly mmapped chunks are set up with an offset to the start of
the mmapped region stored in the prev_foot field of the chunk. This
allows reconstruction of the required argument to MUNMAP when freed,
and also allows adjustment of the returned chunk to meet alignment
requirements (especially in memalign).
*/
/* Malloc using mmap */
static void* mmap_alloc(mstate m, size_t nb) {
size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
if (m->footprint_limit != 0) {
size_t fp = m->footprint + mmsize;
if (fp <= m->footprint || fp > m->footprint_limit)
return 0;
}
if (mmsize > nb) { /* Check for wrap around 0 */
char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));
if (mm != CMFAIL) {
size_t offset = align_offset(chunk2mem(mm));
size_t psize = mmsize - offset - MMAP_FOOT_PAD;
mchunkptr p = (mchunkptr)(mm + offset);
p->prev_foot = offset;
p->head = psize;
mark_inuse_foot(m, p, psize);
chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
if (m->least_addr == 0 || mm < m->least_addr)
m->least_addr = mm;
if ((m->footprint += mmsize) > m->max_footprint)
m->max_footprint = m->footprint;
assert(is_aligned(chunk2mem(p)));
check_mmapped_chunk(m, p);
return chunk2mem(p);
}
}
return 0;
}
/* Realloc using mmap */
static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) {
size_t oldsize = chunksize(oldp);
(void)flags; /* placate people compiling -Wunused */
if (is_small(nb)) /* Can't shrink mmap regions below small size */
return 0;
/* Keep old chunk if big enough but not too big */
if (oldsize >= nb + SIZE_T_SIZE &&
(oldsize - nb) <= (mparams.granularity << 1))
return oldp;
else {
size_t offset = oldp->prev_foot;
size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
oldmmsize, newmmsize, flags);
if (cp != CMFAIL) {
mchunkptr newp = (mchunkptr)(cp + offset);
size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
newp->head = psize;
mark_inuse_foot(m, newp, psize);
chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
if (cp < m->least_addr)
m->least_addr = cp;
if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
m->max_footprint = m->footprint;
check_mmapped_chunk(m, newp);
return newp;
}
}
return 0;
}
/* -------------------------- mspace management -------------------------- */
/* Initialize top chunk and its size */
static void init_top(mstate m, mchunkptr p, size_t psize) {
/* Ensure alignment */
size_t offset = align_offset(chunk2mem(p));
p = (mchunkptr)((char*)p + offset);
psize -= offset;
m->top = p;
m->topsize = psize;
p->head = psize | PINUSE_BIT;
/* set size of fake trailing chunk holding overhead space only once */
chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
m->trim_check = mparams.trim_threshold; /* reset on each update */
}
/* Initialize bins for a new mstate that is otherwise zeroed out */
static void init_bins(mstate m) {
/* Establish circular links for smallbins */
bindex_t i;
for (i = 0; i < NSMALLBINS; ++i) {
sbinptr bin = smallbin_at(m,i);
bin->fd = bin->bk = bin;
}
}
#if PROCEED_ON_ERROR
/* default corruption action */
static void reset_on_error(mstate m) {
int i;
++malloc_corruption_error_count;
/* Reinitialize fields to forget about all memory */
m->smallmap = m->treemap = 0;
m->dvsize = m->topsize = 0;
m->seg.base = 0;
m->seg.size = 0;
m->seg.next = 0;
m->top = m->dv = 0;
for (i = 0; i < NTREEBINS; ++i)
*treebin_at(m, i) = 0;
init_bins(m);
}
#endif /* PROCEED_ON_ERROR */
/* Allocate chunk and prepend remainder with chunk in successor base. */
static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
size_t nb) {
mchunkptr p = align_as_chunk(newbase);
mchunkptr oldfirst = align_as_chunk(oldbase);
size_t psize = (char*)oldfirst - (char*)p;
mchunkptr q = chunk_plus_offset(p, nb);
size_t qsize = psize - nb;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
assert((char*)oldfirst > (char*)q);
assert(pinuse(oldfirst));
assert(qsize >= MIN_CHUNK_SIZE);
/* consolidate remainder with first chunk of old base */
if (oldfirst == m->top) {
size_t tsize = m->topsize += qsize;
m->top = q;
q->head = tsize | PINUSE_BIT;
check_top_chunk(m, q);
}
else if (oldfirst == m->dv) {
size_t dsize = m->dvsize += qsize;
m->dv = q;
set_size_and_pinuse_of_free_chunk(q, dsize);
}
else {
if (!is_inuse(oldfirst)) {
size_t nsize = chunksize(oldfirst);
unlink_chunk(m, oldfirst, nsize);
oldfirst = chunk_plus_offset(oldfirst, nsize);
qsize += nsize;
}
set_free_with_pinuse(q, qsize, oldfirst);
insert_chunk(m, q, qsize);
check_free_chunk(m, q);
}
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
/* Add a segment to hold a new noncontiguous region */
static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
/* Determine locations and sizes of segment, fenceposts, old top */
char* old_top = (char*)m->top;
msegmentptr oldsp = segment_holding(m, old_top);
char* old_end = oldsp->base + oldsp->size;
size_t ssize = pad_request(sizeof(struct malloc_segment));
char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
size_t offset = align_offset(chunk2mem(rawsp));
char* asp = rawsp + offset;
char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
mchunkptr sp = (mchunkptr)csp;
msegmentptr ss = (msegmentptr)(chunk2mem(sp));
mchunkptr tnext = chunk_plus_offset(sp, ssize);
mchunkptr p = tnext;
int nfences = 0;
/* reset top to new space */
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
/* Set up segment record */
assert(is_aligned(ss));
set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
*ss = m->seg; /* Push current record */
m->seg.base = tbase;
m->seg.size = tsize;
m->seg.sflags = mmapped;
m->seg.next = ss;
/* Insert trailing fenceposts */
for (;;) {
mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
p->head = FENCEPOST_HEAD;
++nfences;
if ((char*)(&(nextp->head)) < old_end)
p = nextp;
else
break;
}
assert(nfences >= 2);
/* Insert the rest of old top into a bin as an ordinary free chunk */
if (csp != old_top) {
mchunkptr q = (mchunkptr)old_top;
size_t psize = csp - old_top;
mchunkptr tn = chunk_plus_offset(q, psize);
set_free_with_pinuse(q, psize, tn);
insert_chunk(m, q, psize);
}
check_top_chunk(m, m->top);
}
/* -------------------------- System allocation -------------------------- */
/* Get memory from system using MORECORE or MMAP */
static void* sys_alloc(mstate m, size_t nb) {
char* tbase = CMFAIL;
size_t tsize = 0;
flag_t mmap_flag = 0;
size_t asize; /* allocation size */
ensure_initialization();
/* Directly map large chunks, but only if already initialized */
if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {
void* mem = mmap_alloc(m, nb);
if (mem != 0)
return mem;
}
asize = granularity_align(nb + SYS_ALLOC_PADDING);
if (asize <= nb)
return 0; /* wraparound */
if (m->footprint_limit != 0) {
size_t fp = m->footprint + asize;
if (fp <= m->footprint || fp > m->footprint_limit)
return 0;
}
/*
Try getting memory in any of three ways (in most-preferred to
least-preferred order):
1. A call to MORECORE that can normally contiguously extend memory.
(disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
or main space is mmapped or a previous contiguous call failed)
2. A call to MMAP new space (disabled if not HAVE_MMAP).
Note that under the default settings, if MORECORE is unable to
fulfill a request, and HAVE_MMAP is true, then mmap is
used as a noncontiguous system allocator. This is a useful backup
strategy for systems with holes in address spaces -- in this case
sbrk cannot contiguously expand the heap, but mmap may be able to
find space.
3. A call to MORECORE that cannot usually contiguously extend memory.
(disabled if not HAVE_MORECORE)
In all cases, we need to request enough bytes from system to ensure
we can malloc nb bytes upon success, so pad with enough space for
top_foot, plus alignment-pad to make sure we don't lose bytes if
not on boundary, and round this up to a granularity unit.
*/
if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
char* br = CMFAIL;
size_t ssize = asize; /* sbrk call size */
msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
ACQUIRE_MALLOC_GLOBAL_LOCK();
if (ss == 0) { /* First time through or recovery */
char* base = (char*)CALL_MORECORE(0);
if (base != CMFAIL) {
size_t fp;
/* Adjust to end on a page boundary */
if (!is_page_aligned(base))
ssize += (page_align((size_t)base) - (size_t)base);
fp = m->footprint + ssize; /* recheck limits */
if (ssize > nb && ssize < HALF_MAX_SIZE_T &&
(m->footprint_limit == 0 ||
(fp > m->footprint && fp <= m->footprint_limit)) &&
(br = (char*)(CALL_MORECORE(ssize))) == base) {
tbase = base;
tsize = ssize;
}
}
}
else {
/* Subtract out existing available top space from MORECORE request. */
ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);
/* Use mem here only if it did continuously extend old space */
if (ssize < HALF_MAX_SIZE_T &&
(br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) {
tbase = br;
tsize = ssize;
}
}
if (tbase == CMFAIL) { /* Cope with partial failure */
if (br != CMFAIL) { /* Try to use/extend the space we did get */
if (ssize < HALF_MAX_SIZE_T &&
ssize < nb + SYS_ALLOC_PADDING) {
size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize);
if (esize < HALF_MAX_SIZE_T) {
char* end = (char*)CALL_MORECORE(esize);
if (end != CMFAIL)
ssize += esize;
else { /* Can't use; try to release */
(void) CALL_MORECORE(-ssize);
br = CMFAIL;
}
}
}
}
if (br != CMFAIL) { /* Use the space we did get */
tbase = br;
tsize = ssize;
}
else
disable_contiguous(m); /* Don't try contiguous path in the future */
}
RELEASE_MALLOC_GLOBAL_LOCK();
}
if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
char* mp = (char*)(CALL_MMAP(asize));
if (mp != CMFAIL) {
tbase = mp;
tsize = asize;
mmap_flag = USE_MMAP_BIT;
}
}
if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
if (asize < HALF_MAX_SIZE_T) {
char* br = CMFAIL;
char* end = CMFAIL;
ACQUIRE_MALLOC_GLOBAL_LOCK();
br = (char*)(CALL_MORECORE(asize));
end = (char*)(CALL_MORECORE(0));
RELEASE_MALLOC_GLOBAL_LOCK();
if (br != CMFAIL && end != CMFAIL && br < end) {
size_t ssize = end - br;
if (ssize > nb + TOP_FOOT_SIZE) {
tbase = br;
tsize = ssize;
}
}
}
}
if (tbase != CMFAIL) {
if ((m->footprint += tsize) > m->max_footprint)
m->max_footprint = m->footprint;
if (!is_initialized(m)) { /* first-time initialization */
if (m->least_addr == 0 || tbase < m->least_addr)
m->least_addr = tbase;
m->seg.base = tbase;
m->seg.size = tsize;
m->seg.sflags = mmap_flag;
m->magic = mparams.magic;
m->release_checks = MAX_RELEASE_CHECK_RATE;
init_bins(m);
#if !ONLY_MSPACES
if (is_global(m))
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
else
#endif
{
/* Offset top by embedded malloc_state */
mchunkptr mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
}
}
else {
/* Try to merge with an existing segment */
msegmentptr sp = &m->seg;
/* Only consider most recent segment if traversal suppressed */
while (sp != 0 && tbase != sp->base + sp->size)
sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & USE_MMAP_BIT) == mmap_flag &&
segment_holds(sp, m->top)) { /* append */
sp->size += tsize;
init_top(m, m->top, m->topsize + tsize);
}
else {
if (tbase < m->least_addr)
m->least_addr = tbase;
sp = &m->seg;
while (sp != 0 && sp->base != tbase + tsize)
sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & USE_MMAP_BIT) == mmap_flag) {
char* oldbase = sp->base;
sp->base = tbase;
sp->size += tsize;
return prepend_alloc(m, tbase, oldbase, nb);
}
else
add_segment(m, tbase, tsize, mmap_flag);
}
}
if (nb < m->topsize) { /* Allocate from new or extended top space */
size_t rsize = m->topsize -= nb;
mchunkptr p = m->top;
mchunkptr r = m->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
check_top_chunk(m, m->top);
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
}
MALLOC_FAILURE_ACTION;
return 0;
}
/* ----------------------- system deallocation -------------------------- */
/* Unmap and unlink any mmapped segments that don't contain used chunks */
static size_t release_unused_segments(mstate m) {
size_t released = 0;
int nsegs = 0;
msegmentptr pred = &m->seg;
msegmentptr sp = pred->next;
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
msegmentptr next = sp->next;
++nsegs;
if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
mchunkptr p = align_as_chunk(base);
size_t psize = chunksize(p);
/* Can unmap if first chunk holds entire segment and not pinned */
if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
tchunkptr tp = (tchunkptr)p;
assert(segment_holds(sp, (char*)sp));
if (p == m->dv) {
m->dv = 0;
m->dvsize = 0;
}
else {
unlink_large_chunk(m, tp);
}
if (CALL_MUNMAP(base, size) == 0) {
released += size;
m->footprint -= size;
/* unlink obsoleted record */
sp = pred;
sp->next = next;
}
else { /* back out if cannot unmap */
insert_large_chunk(m, tp, psize);
}
}
}
if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
break;
pred = sp;
sp = next;
}
/* Reset check counter */
m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)?
(size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE);
return released;
}
static int sys_trim(mstate m, size_t pad) {
size_t released = 0;
ensure_initialization();
if (pad < MAX_REQUEST && is_initialized(m)) {
pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
if (m->topsize > pad) {
/* Shrink top space in granularity-size units, keeping at least one */
size_t unit = mparams.granularity;
size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
SIZE_T_ONE) * unit;
msegmentptr sp = segment_holding(m, (char*)m->top);
if (!is_extern_segment(sp)) {
if (is_mmapped_segment(sp)) {
if (HAVE_MMAP &&
sp->size >= extra &&
!has_segment_link(m, sp)) { /* can't shrink if pinned */
size_t newsize = sp->size - extra;
(void)newsize; /* placate people compiling -Wunused-variable */
/* Prefer mremap, fall back to munmap */
if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
(CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
released = extra;
}
}
}
else if (HAVE_MORECORE) {
if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
ACQUIRE_MALLOC_GLOBAL_LOCK();
{
/* Make sure end of memory is where we last set it. */
char* old_br = (char*)(CALL_MORECORE(0));
if (old_br == sp->base + sp->size) {
char* rel_br = (char*)(CALL_MORECORE(-extra));
char* new_br = (char*)(CALL_MORECORE(0));
if (rel_br != CMFAIL && new_br < old_br)
released = old_br - new_br;
}
}
RELEASE_MALLOC_GLOBAL_LOCK();
}
}
if (released != 0) {
sp->size -= released;
m->footprint -= released;
init_top(m, m->top, m->topsize - released);
check_top_chunk(m, m->top);
}
}
/* Unmap any unused mmapped segments */
if (HAVE_MMAP)
released += release_unused_segments(m);
/* On failure, disable autotrim to avoid repeated failed future calls */
if (released == 0 && m->topsize > m->trim_check)
m->trim_check = MAX_SIZE_T;
}
return (released != 0)? 1 : 0;
}
/* Consolidate and bin a chunk. Differs from exported versions
of free mainly in that the chunk need not be marked as inuse.
*/
static void dispose_chunk(mstate m, mchunkptr p, size_t psize) {
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
mchunkptr prev;
size_t prevsize = p->prev_foot;
if (is_mmapped(p)) {
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
m->footprint -= psize;
return;
}
prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */
if (p != m->dv) {
unlink_chunk(m, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
m->dvsize = psize;
set_free_with_pinuse(p, psize, next);
return;
}
}
else {
CORRUPTION_ERROR_ACTION(m);
return;
}
}
if (RTCHECK(ok_address(m, next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == m->top) {
size_t tsize = m->topsize += psize;
m->top = p;
p->head = tsize | PINUSE_BIT;
if (p == m->dv) {
m->dv = 0;
m->dvsize = 0;
}
return;
}
else if (next == m->dv) {
size_t dsize = m->dvsize += psize;
m->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
return;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(m, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == m->dv) {
m->dvsize = psize;
return;
}
}
}
else {
set_free_with_pinuse(p, psize, next);
}
insert_chunk(m, p, psize);
}
else {
CORRUPTION_ERROR_ACTION(m);
}
}
/* ---------------------------- malloc --------------------------- */
/* allocate a large request from the best fitting chunk in a treebin */
static void* tmalloc_large(mstate m, size_t nb) {
tchunkptr v = 0;
size_t rsize = -nb; /* Unsigned negation */
tchunkptr t;
bindex_t idx;
compute_tree_index(nb, idx);
if ((t = *treebin_at(m, idx)) != 0) {
/* Traverse tree for this bin looking for node with size == nb */
size_t sizebits = nb << leftshift_for_tree_index(idx);
tchunkptr rst = 0; /* The deepest untaken right subtree */
for (;;) {
tchunkptr rt;
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
v = t;
if ((rsize = trem) == 0)
break;
}
rt = t->child[1];
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
if (rt != 0 && rt != t)
rst = rt;
if (t == 0) {
t = rst; /* set t to least subtree holding sizes > nb */
break;
}
sizebits <<= 1;
}
}
if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
if (leftbits != 0) {
bindex_t i;
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
t = *treebin_at(m, i);
}
}
while (t != 0) { /* find smallest of tree or subtree */
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
t = leftmost_child(t);
}
/* If dv is a better fit, return 0 so malloc will use it */
if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
if (RTCHECK(ok_address(m, v))) { /* split */
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
insert_chunk(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
}
return 0;
}
/* allocate a small request from the best fitting chunk in a treebin */
static void* tmalloc_small(mstate m, size_t nb) {
tchunkptr t, v;
size_t rsize;
bindex_t i;
binmap_t leastbit = least_bit(m->treemap);
compute_bit2idx(leastbit, i);
v = t = *treebin_at(m, i);
rsize = chunksize(t) - nb;
while ((t = leftmost_child(t)) != 0) {
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
}
if (RTCHECK(ok_address(m, v))) {
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
return 0;
}
#if !ONLY_MSPACES
void* dlmalloc(size_t bytes) {
/*
Basic algorithm:
If a small request (< 256 bytes minus per-chunk overhead):
1. If one exists, use a remainderless chunk in associated smallbin.
(Remainderless means that there are too few excess bytes to
represent as a chunk.)
2. If it is big enough, use the dv chunk, which is normally the
chunk adjacent to the one used for the most recent small request.
3. If one exists, split the smallest available chunk in a bin,
saving remainder in dv.
4. If it is big enough, use the top chunk.
5. If available, get memory from system and use it
Otherwise, for a large request:
1. Find the smallest available binned chunk that fits, and use it
if it is better fitting than dv chunk, splitting if necessary.
2. If better fitting than any binned chunk, use the dv chunk.
3. If it is big enough, use the top chunk.
4. If request size >= mmap threshold, try to directly mmap this chunk.
5. If available, get memory from system and use it
The ugly goto's here ensure that postaction occurs along all paths.
*/
#if USE_LOCKS
ensure_initialization(); /* initialize in sys_alloc if not using locks */
#endif
if (!PREACTION(gm)) {
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = gm->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(gm, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(gm, b, p, idx);
set_inuse_and_pinuse(gm, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb > gm->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(gm, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(gm, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(gm, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(gm, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
if (nb <= gm->dvsize) {
size_t rsize = gm->dvsize - nb;
mchunkptr p = gm->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
gm->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
}
else { /* exhaust dv */
size_t dvs = gm->dvsize;
gm->dvsize = 0;
gm->dv = 0;
set_inuse_and_pinuse(gm, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb < gm->topsize) { /* Split top */
size_t rsize = gm->topsize -= nb;
mchunkptr p = gm->top;
mchunkptr r = gm->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
mem = chunk2mem(p);
check_top_chunk(gm, gm->top);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
mem = sys_alloc(gm, nb);
postaction:
POSTACTION(gm);
return mem;
}
return 0;
}
/* ---------------------------- free --------------------------- */
void dlfree(void* mem) {
/*
Consolidate freed chunks with preceeding or succeeding bordering
free chunks, if they exist, and then place in a bin. Intermixed
with special cases for top, dv, mmapped chunks, and usage errors.
*/
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
#if FOOTERS
mstate fm = get_mstate_for(p);
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
#else /* FOOTERS */
#define fm gm
#endif /* FOOTERS */
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if (is_mmapped(p)) {
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
if (is_small(psize)) {
insert_small_chunk(fm, p, psize);
check_free_chunk(fm, p);
}
else {
tchunkptr tp = (tchunkptr)p;
insert_large_chunk(fm, tp, psize);
check_free_chunk(fm, p);
if (--fm->release_checks == 0)
release_unused_segments(fm);
}
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
#if !FOOTERS
#undef fm
#endif /* FOOTERS */
}
void* dlcalloc(size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = dlmalloc(req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
#endif /* !ONLY_MSPACES */
/* ------------ Internal support for realloc, memalign, etc -------------- */
/* Try to realloc; only in-place unless can_move true */
static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb,
int can_move) {
mchunkptr newp = 0;
size_t oldsize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, oldsize);
if (RTCHECK(ok_address(m, p) && ok_inuse(p) &&
ok_next(p, next) && ok_pinuse(next))) {
if (is_mmapped(p)) {
newp = mmap_resize(m, p, nb, can_move);
}
else if (oldsize >= nb) { /* already big enough */
size_t rsize = oldsize - nb;
if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */
mchunkptr r = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
set_inuse(m, r, rsize);
dispose_chunk(m, r, rsize);
}
newp = p;
}
else if (next == m->top) { /* extend into top */
if (oldsize + m->topsize > nb) {
size_t newsize = oldsize + m->topsize;
size_t newtopsize = newsize - nb;
mchunkptr newtop = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
newtop->head = newtopsize |PINUSE_BIT;
m->top = newtop;
m->topsize = newtopsize;
newp = p;
}
}
else if (next == m->dv) { /* extend into dv */
size_t dvs = m->dvsize;
if (oldsize + dvs >= nb) {
size_t dsize = oldsize + dvs - nb;
if (dsize >= MIN_CHUNK_SIZE) {
mchunkptr r = chunk_plus_offset(p, nb);
mchunkptr n = chunk_plus_offset(r, dsize);
set_inuse(m, p, nb);
set_size_and_pinuse_of_free_chunk(r, dsize);
clear_pinuse(n);
m->dvsize = dsize;
m->dv = r;
}
else { /* exhaust dv */
size_t newsize = oldsize + dvs;
set_inuse(m, p, newsize);
m->dvsize = 0;
m->dv = 0;
}
newp = p;
}
}
else if (!cinuse(next)) { /* extend into next free chunk */
size_t nextsize = chunksize(next);
if (oldsize + nextsize >= nb) {
size_t rsize = oldsize + nextsize - nb;
unlink_chunk(m, next, nextsize);
if (rsize < MIN_CHUNK_SIZE) {
size_t newsize = oldsize + nextsize;
set_inuse(m, p, newsize);
}
else {
mchunkptr r = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
set_inuse(m, r, rsize);
dispose_chunk(m, r, rsize);
}
newp = p;
}
}
}
else {
USAGE_ERROR_ACTION(m, chunk2mem(p));
}
return newp;
}
static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
void* mem = 0;
if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
alignment = MIN_CHUNK_SIZE;
if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
size_t a = MALLOC_ALIGNMENT << 1;
while (a < alignment) a <<= 1;
alignment = a;
}
if (bytes >= MAX_REQUEST - alignment) {
if (m != 0) { /* Test isn't needed but avoids compiler warning */
MALLOC_FAILURE_ACTION;
}
}
else {
size_t nb = request2size(bytes);
size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
mem = internal_malloc(m, req);
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (PREACTION(m))
return 0;
if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */
/*
Find an aligned spot inside chunk. Since we need to give
back leading space in a chunk of at least MIN_CHUNK_SIZE, if
the first calculation places us at a spot with less than
MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
We've allocated enough total room so that this is always
possible.
*/
char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment -
SIZE_T_ONE)) &
-alignment));
char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
br : br+alignment;
mchunkptr newp = (mchunkptr)pos;
size_t leadsize = pos - (char*)(p);
size_t newsize = chunksize(p) - leadsize;
if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
newp->prev_foot = p->prev_foot + leadsize;
newp->head = newsize;
}
else { /* Otherwise, give back leader, use the rest */
set_inuse(m, newp, newsize);
set_inuse(m, p, leadsize);
dispose_chunk(m, p, leadsize);
}
p = newp;
}
/* Give back spare room at the end */
if (!is_mmapped(p)) {
size_t size = chunksize(p);
if (size > nb + MIN_CHUNK_SIZE) {
size_t remainder_size = size - nb;
mchunkptr remainder = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
set_inuse(m, remainder, remainder_size);
dispose_chunk(m, remainder, remainder_size);
}
}
mem = chunk2mem(p);
assert (chunksize(p) >= nb);
assert(((size_t)mem & (alignment - 1)) == 0);
check_inuse_chunk(m, p);
POSTACTION(m);
}
}
return mem;
}
/*
Common support for independent_X routines, handling
all of the combinations that can result.
The opts arg has:
bit 0 set if all elements are same size (using sizes[0])
bit 1 set if elements should be zeroed
*/
static void** ialloc(mstate m,
size_t n_elements,
size_t* sizes,
int opts,
void* chunks[]) {
size_t element_size; /* chunksize of each element, if all same */
size_t contents_size; /* total size of elements */
size_t array_size; /* request size of pointer array */
void* mem; /* malloced aggregate space */
mchunkptr p; /* corresponding chunk */
size_t remainder_size; /* remaining bytes while splitting */
void** marray; /* either "chunks" or malloced ptr array */
mchunkptr array_chunk; /* chunk for malloced ptr array */
flag_t was_enabled; /* to disable mmap */
size_t size;
size_t i;
ensure_initialization();
/* compute array length, if needed */
if (chunks != 0) {
if (n_elements == 0)
return chunks; /* nothing to do */
marray = chunks;
array_size = 0;
}
else {
/* if empty req, must still return chunk representing empty array */
if (n_elements == 0)
return (void**)internal_malloc(m, 0);
marray = 0;
array_size = request2size(n_elements * (sizeof(void*)));
}
/* compute total element size */
if (opts & 0x1) { /* all-same-size */
element_size = request2size(*sizes);
contents_size = n_elements * element_size;
}
else { /* add up all the sizes */
element_size = 0;
contents_size = 0;
for (i = 0; i != n_elements; ++i)
contents_size += request2size(sizes[i]);
}
size = contents_size + array_size;
/*
Allocate the aggregate chunk. First disable direct-mmapping so
malloc won't use it, since we would not be able to later
free/realloc space internal to a segregated mmap region.
*/
was_enabled = use_mmap(m);
disable_mmap(m);
mem = internal_malloc(m, size - CHUNK_OVERHEAD);
if (was_enabled)
enable_mmap(m);
if (mem == 0)
return 0;
if (PREACTION(m)) return 0;
p = mem2chunk(mem);
remainder_size = chunksize(p);
assert(!is_mmapped(p));
if (opts & 0x2) { /* optionally clear the elements */
memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
}
/* If not provided, allocate the pointer array as final part of chunk */
if (marray == 0) {
size_t array_chunk_size;
array_chunk = chunk_plus_offset(p, contents_size);
array_chunk_size = remainder_size - contents_size;
marray = (void**) (chunk2mem(array_chunk));
set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
remainder_size = contents_size;
}
/* split out elements */
for (i = 0; ; ++i) {
marray[i] = chunk2mem(p);
if (i != n_elements-1) {
if (element_size != 0)
size = element_size;
else
size = request2size(sizes[i]);
remainder_size -= size;
set_size_and_pinuse_of_inuse_chunk(m, p, size);
p = chunk_plus_offset(p, size);
}
else { /* the final element absorbs any overallocation slop */
set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
break;
}
}
#if DEBUG
if (marray != chunks) {
/* final element must have exactly exhausted chunk */
if (element_size != 0) {
assert(remainder_size == element_size);
}
else {
assert(remainder_size == request2size(sizes[i]));
}
check_inuse_chunk(m, mem2chunk(marray));
}
for (i = 0; i != n_elements; ++i)
check_inuse_chunk(m, mem2chunk(marray[i]));
#endif /* DEBUG */
POSTACTION(m);
return marray;
}
/* Try to free all pointers in the given array.
Note: this could be made faster, by delaying consolidation,
at the price of disabling some user integrity checks, We
still optimize some consolidations by combining adjacent
chunks before freeing, which will occur often if allocated
with ialloc or the array is sorted.
*/
static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) {
size_t unfreed = 0;
if (!PREACTION(m)) {
void** a;
void** fence = &(array[nelem]);
for (a = array; a != fence; ++a) {
void* mem = *a;
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
size_t psize = chunksize(p);
#if FOOTERS
if (get_mstate_for(p) != m) {
++unfreed;
continue;
}
#endif
check_inuse_chunk(m, p);
*a = 0;
if (RTCHECK(ok_address(m, p) && ok_inuse(p))) {
void ** b = a + 1; /* try to merge with next chunk */
mchunkptr next = next_chunk(p);
if (b != fence && *b == chunk2mem(next)) {
size_t newsize = chunksize(next) + psize;
set_inuse(m, p, newsize);
*b = chunk2mem(p);
}
else
dispose_chunk(m, p, psize);
}
else {
CORRUPTION_ERROR_ACTION(m);
break;
}
}
}
if (should_trim(m, m->topsize))
sys_trim(m, 0);
POSTACTION(m);
}
return unfreed;
}
/* Traversal */
#if MALLOC_INSPECT_ALL
static void internal_inspect_all(mstate m,
void(*handler)(void *start,
void *end,
size_t used_bytes,
void* callback_arg),
void* arg) {
if (is_initialized(m)) {
mchunkptr top = m->top;
msegmentptr s;
for (s = &m->seg; s != 0; s = s->next) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) {
mchunkptr next = next_chunk(q);
size_t sz = chunksize(q);
size_t used;
void* start;
if (is_inuse(q)) {
used = sz - CHUNK_OVERHEAD; /* must not be mmapped */
start = chunk2mem(q);
}
else {
used = 0;
if (is_small(sz)) { /* offset by possible bookkeeping */
start = (void*)((char*)q + sizeof(struct malloc_chunk));
}
else {
start = (void*)((char*)q + sizeof(struct malloc_tree_chunk));
}
}
if (start < (void*)next) /* skip if all space is bookkeeping */
handler(start, next, used, arg);
if (q == top)
break;
q = next;
}
}
}
}
#endif /* MALLOC_INSPECT_ALL */
/* ------------------ Exported realloc, memalign, etc -------------------- */
#if !ONLY_MSPACES
void* dlrealloc(void* oldmem, size_t bytes) {
void* mem = 0;
if (oldmem == 0) {
mem = dlmalloc(bytes);
}
else if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
}
#ifdef REALLOC_ZERO_BYTES_FREES
else if (bytes == 0) {
dlfree(oldmem);
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
size_t nb = request2size(bytes);
mchunkptr oldp = mem2chunk(oldmem);
#if ! FOOTERS
mstate m = gm;
#else /* FOOTERS */
mstate m = get_mstate_for(oldp);
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
if (!PREACTION(m)) {
mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);
POSTACTION(m);
if (newp != 0) {
check_inuse_chunk(m, newp);
mem = chunk2mem(newp);
}
else {
mem = internal_malloc(m, bytes);
if (mem != 0) {
size_t oc = chunksize(oldp) - overhead_for(oldp);
memcpy(mem, oldmem, (oc < bytes)? oc : bytes);
internal_free(m, oldmem);
}
}
}
}
return mem;
}
void* dlrealloc_in_place(void* oldmem, size_t bytes) {
void* mem = 0;
if (oldmem != 0) {
if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
}
else {
size_t nb = request2size(bytes);
mchunkptr oldp = mem2chunk(oldmem);
#if ! FOOTERS
mstate m = gm;
#else /* FOOTERS */
mstate m = get_mstate_for(oldp);
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
if (!PREACTION(m)) {
mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);
POSTACTION(m);
if (newp == oldp) {
check_inuse_chunk(m, newp);
mem = oldmem;
}
}
}
}
return mem;
}
void* dlmemalign(size_t alignment, size_t bytes) {
if (alignment <= MALLOC_ALIGNMENT) {
return dlmalloc(bytes);
}
return internal_memalign(gm, alignment, bytes);
}
int dlposix_memalign(void** pp, size_t alignment, size_t bytes) {
void* mem = 0;
if (alignment == MALLOC_ALIGNMENT)
mem = dlmalloc(bytes);
else {
size_t d = alignment / sizeof(void*);
size_t r = alignment % sizeof(void*);
if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0)
return 22;//EINVAL;
else if (bytes <= MAX_REQUEST - alignment) {
if (alignment < MIN_CHUNK_SIZE)
alignment = MIN_CHUNK_SIZE;
mem = internal_memalign(gm, alignment, bytes);
}
}
if (mem == 0)
return 12;//ENOMEM;
else {
*pp = mem;
return 0;
}
}
void* dlvalloc(size_t bytes) {
size_t pagesz;
ensure_initialization();
pagesz = mparams.page_size;
return dlmemalign(pagesz, bytes);
}
void* dlpvalloc(size_t bytes) {
size_t pagesz;
ensure_initialization();
pagesz = mparams.page_size;
return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
}
void** dlindependent_calloc(size_t n_elements, size_t elem_size,
void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
return ialloc(gm, n_elements, &sz, 3, chunks);
}
void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
void* chunks[]) {
return ialloc(gm, n_elements, sizes, 0, chunks);
}
size_t dlbulk_free(void* array[], size_t nelem) {
return internal_bulk_free(gm, array, nelem);
}
#if MALLOC_INSPECT_ALL
void dlmalloc_inspect_all(void(*handler)(void *start,
void *end,
size_t used_bytes,
void* callback_arg),
void* arg) {
ensure_initialization();
if (!PREACTION(gm)) {
internal_inspect_all(gm, handler, arg);
POSTACTION(gm);
}
}
#endif /* MALLOC_INSPECT_ALL */
int dlmalloc_trim(size_t pad) {
int result = 0;
ensure_initialization();
if (!PREACTION(gm)) {
result = sys_trim(gm, pad);
POSTACTION(gm);
}
return result;
}
size_t dlmalloc_footprint(void) {
return gm->footprint;
}
size_t dlmalloc_max_footprint(void) {
return gm->max_footprint;
}
size_t dlmalloc_footprint_limit(void) {
size_t maf = gm->footprint_limit;
return maf == 0 ? MAX_SIZE_T : maf;
}
size_t dlmalloc_set_footprint_limit(size_t bytes) {
size_t result; /* invert sense of 0 */
if (bytes == 0)
result = granularity_align(1); /* Use minimal size */
if (bytes == MAX_SIZE_T)
result = 0; /* disable */
else
result = granularity_align(bytes);
return gm->footprint_limit = result;
}
#if !NO_MALLINFO
struct mallinfo dlmallinfo(void) {
return internal_mallinfo(gm);
}
#endif /* NO_MALLINFO */
#if !NO_MALLOC_STATS
void dlmalloc_stats() {
internal_malloc_stats(gm);
}
#endif /* NO_MALLOC_STATS */
int dlmallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
size_t dlmalloc_usable_size(void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (is_inuse(p))
return chunksize(p) - overhead_for(p);
}
return 0;
}
#endif /* !ONLY_MSPACES */
/* ----------------------------- user mspaces ---------------------------- */
#if MSPACES
static mstate init_user_mstate(char* tbase, size_t tsize) {
size_t msize = pad_request(sizeof(struct malloc_state));
mchunkptr mn;
mchunkptr msp = align_as_chunk(tbase);
mstate m = (mstate)(chunk2mem(msp));
memset(m, 0, msize);
(void)INITIAL_LOCK(&m->mutex);
msp->head = (msize|INUSE_BITS);
m->seg.base = m->least_addr = tbase;
m->seg.size = m->footprint = m->max_footprint = tsize;
m->magic = mparams.magic;
m->release_checks = MAX_RELEASE_CHECK_RATE;
m->mflags = mparams.default_mflags;
m->extp = 0;
m->exts = 0;
disable_contiguous(m);
init_bins(m);
mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
check_top_chunk(m, m->top);
return m;
}
mspace create_mspace(size_t capacity, int locked) {
mstate m = 0;
size_t msize;
ensure_initialization();
msize = pad_request(sizeof(struct malloc_state));
if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
size_t rs = ((capacity == 0)? mparams.granularity :
(capacity + TOP_FOOT_SIZE + msize));
size_t tsize = granularity_align(rs);
char* tbase = (char*)(CALL_MMAP(tsize));
if (tbase != CMFAIL) {
m = init_user_mstate(tbase, tsize);
m->seg.sflags = USE_MMAP_BIT;
set_lock(m, locked);
}
}
return (mspace)m;
}
mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
mstate m = 0;
size_t msize;
ensure_initialization();
msize = pad_request(sizeof(struct malloc_state));
if (capacity > msize + TOP_FOOT_SIZE &&
capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
m = init_user_mstate((char*)base, capacity);
m->seg.sflags = EXTERN_BIT;
set_lock(m, locked);
}
return (mspace)m;
}
int mspace_track_large_chunks(mspace msp, int enable) {
int ret = 0;
mstate ms = (mstate)msp;
if (!PREACTION(ms)) {
if (!use_mmap(ms)) {
ret = 1;
}
if (!enable) {
enable_mmap(ms);
} else {
disable_mmap(ms);
}
POSTACTION(ms);
}
return ret;
}
size_t destroy_mspace(mspace msp) {
size_t freed = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
msegmentptr sp = &ms->seg;
(void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
flag_t flag = sp->sflags;
(void)base; /* placate people compiling -Wunused-variable */
sp = sp->next;
if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&
CALL_MUNMAP(base, size) == 0)
freed += size;
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return freed;
}
/*
mspace versions of routines are near-clones of the global
versions. This is not so nice but better than the alternatives.
*/
void* mspace_malloc(mspace msp, size_t bytes) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (!PREACTION(ms)) {
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = ms->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(ms, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(ms, b, p, idx);
set_inuse_and_pinuse(ms, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb > ms->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(ms, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(ms, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(ms, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(ms, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
if (nb <= ms->dvsize) {
size_t rsize = ms->dvsize - nb;
mchunkptr p = ms->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
ms->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
}
else { /* exhaust dv */
size_t dvs = ms->dvsize;
ms->dvsize = 0;
ms->dv = 0;
set_inuse_and_pinuse(ms, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb < ms->topsize) { /* Split top */
size_t rsize = ms->topsize -= nb;
mchunkptr p = ms->top;
mchunkptr r = ms->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
mem = chunk2mem(p);
check_top_chunk(ms, ms->top);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
mem = sys_alloc(ms, nb);
postaction:
POSTACTION(ms);
return mem;
}
return 0;
}
void mspace_free(mspace msp, void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
#if FOOTERS
mstate fm = get_mstate_for(p);
(void)msp; /* placate people compiling -Wunused */
#else /* FOOTERS */
mstate fm = (mstate)msp;
#endif /* FOOTERS */
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if (is_mmapped(p)) {
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
if (is_small(psize)) {
insert_small_chunk(fm, p, psize);
check_free_chunk(fm, p);
}
else {
tchunkptr tp = (tchunkptr)p;
insert_large_chunk(fm, tp, psize);
check_free_chunk(fm, p);
if (--fm->release_checks == 0)
release_unused_segments(fm);
}
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
}
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = internal_malloc(ms, req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
void* mem = 0;
if (oldmem == 0) {
mem = mspace_malloc(msp, bytes);
}
else if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
}
#ifdef REALLOC_ZERO_BYTES_FREES
else if (bytes == 0) {
mspace_free(msp, oldmem);
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
size_t nb = request2size(bytes);
mchunkptr oldp = mem2chunk(oldmem);
#if ! FOOTERS
mstate m = (mstate)msp;
#else /* FOOTERS */
mstate m = get_mstate_for(oldp);
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
if (!PREACTION(m)) {
mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);
POSTACTION(m);
if (newp != 0) {
check_inuse_chunk(m, newp);
mem = chunk2mem(newp);
}
else {
mem = mspace_malloc(m, bytes);
if (mem != 0) {
size_t oc = chunksize(oldp) - overhead_for(oldp);
memcpy(mem, oldmem, (oc < bytes)? oc : bytes);
mspace_free(m, oldmem);
}
}
}
}
return mem;
}
void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) {
void* mem = 0;
if (oldmem != 0) {
if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
}
else {
size_t nb = request2size(bytes);
mchunkptr oldp = mem2chunk(oldmem);
#if ! FOOTERS
mstate m = (mstate)msp;
#else /* FOOTERS */
mstate m = get_mstate_for(oldp);
(void)msp; /* placate people compiling -Wunused */
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
if (!PREACTION(m)) {
mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);
POSTACTION(m);
if (newp == oldp) {
check_inuse_chunk(m, newp);
mem = oldmem;
}
}
}
}
return mem;
}
void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (alignment <= MALLOC_ALIGNMENT)
return mspace_malloc(msp, bytes);
return internal_memalign(ms, alignment, bytes);
}
void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, &sz, 3, chunks);
}
void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, sizes, 0, chunks);
}
size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) {
return internal_bulk_free((mstate)msp, array, nelem);
}
#if MALLOC_INSPECT_ALL
void mspace_inspect_all(mspace msp,
void(*handler)(void *start,
void *end,
size_t used_bytes,
void* callback_arg),
void* arg) {
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
if (!PREACTION(ms)) {
internal_inspect_all(ms, handler, arg);
POSTACTION(ms);
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
}
#endif /* MALLOC_INSPECT_ALL */
int mspace_trim(mspace msp, size_t pad) {
int result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
if (!PREACTION(ms)) {
result = sys_trim(ms, pad);
POSTACTION(ms);
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
#if !NO_MALLOC_STATS
void mspace_malloc_stats(mspace msp) {
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
internal_malloc_stats(ms);
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
}
#endif /* NO_MALLOC_STATS */
size_t mspace_footprint(mspace msp) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->footprint;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
size_t mspace_max_footprint(mspace msp) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->max_footprint;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
size_t mspace_footprint_limit(mspace msp) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
size_t maf = ms->footprint_limit;
result = (maf == 0) ? MAX_SIZE_T : maf;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
size_t mspace_set_footprint_limit(mspace msp, size_t bytes) {
size_t result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
if (bytes == 0)
result = granularity_align(1); /* Use minimal size */
if (bytes == MAX_SIZE_T)
result = 0; /* disable */
else
result = granularity_align(bytes);
ms->footprint_limit = result;
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
#if !NO_MALLINFO
struct mallinfo mspace_mallinfo(mspace msp) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
}
return internal_mallinfo(ms);
}
#endif /* NO_MALLINFO */
size_t mspace_usable_size(const void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (is_inuse(p))
return chunksize(p) - overhead_for(p);
}
return 0;
}
int mspace_mallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
#endif /* MSPACES */
/* -------------------- Alternative MORECORE functions ------------------- */
/*
Guidelines for creating a custom version of MORECORE:
* For best performance, MORECORE should allocate in multiples of pagesize.
* MORECORE may allocate more memory than requested. (Or even less,
but this will usually result in a malloc failure.)
* MORECORE must not allocate memory when given argument zero, but
instead return one past the end address of memory from previous
nonzero call.
* For best performance, consecutive calls to MORECORE with positive
arguments should return increasing addresses, indicating that
space has been contiguously extended.
* Even though consecutive calls to MORECORE need not return contiguous
addresses, it must be OK for malloc'ed chunks to span multiple
regions in those cases where they do happen to be contiguous.
* MORECORE need not handle negative arguments -- it may instead
just return MFAIL when given negative arguments.
Negative arguments are always multiples of pagesize. MORECORE
must not misinterpret negative args as large positive unsigned
args. You can suppress all such calls from even occurring by defining
MORECORE_CANNOT_TRIM,
As an example alternative MORECORE, here is a custom allocator
kindly contributed for pre-OSX macOS. It uses virtually but not
necessarily physically contiguous non-paged memory (locked in,
present and won't get swapped out). You can use it by uncommenting
this section, adding some #includes, and setting up the appropriate
defines above:
#define MORECORE osMoreCore
There is also a shutdown routine that should somehow be called for
cleanup upon program exit.
#define MAX_POOL_ENTRIES 100
#define MINIMUM_MORECORE_SIZE (64 * 1024U)
static int next_os_pool;
void *our_os_pools[MAX_POOL_ENTRIES];
void *osMoreCore(int size)
{
void *ptr = 0;
static void *sbrk_top = 0;
if (size > 0)
{
if (size < MINIMUM_MORECORE_SIZE)
size = MINIMUM_MORECORE_SIZE;
if (CurrentExecutionLevel() == kTaskLevel)
ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
if (ptr == 0)
{
return (void *) MFAIL;
}
// save ptrs so they can be freed during cleanup
our_os_pools[next_os_pool] = ptr;
next_os_pool++;
ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
sbrk_top = (char *) ptr + size;
return ptr;
}
else if (size < 0)
{
// we don't currently support shrink behavior
return (void *) MFAIL;
}
else
{
return sbrk_top;
}
}
// cleanup any allocated memory pools
// called as last thing before shutting down driver
void osCleanupMem(void)
{
void **ptr;
for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
if (*ptr)
{
PoolDeallocate(*ptr);
*ptr = 0;
}
}
*/
/* -----------------------------------------------------------------------
History:
v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea
* fix bad comparison in dlposix_memalign
* don't reuse adjusted asize in sys_alloc
* add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion
* reduce compiler warnings -- thanks to all who reported/suggested these
v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee)
* Always perform unlink checks unless INSECURE
* Add posix_memalign.
* Improve realloc to expand in more cases; expose realloc_in_place.
Thanks to Peter Buhr for the suggestion.
* Add footprint_limit, inspect_all, bulk_free. Thanks
to Barry Hayes and others for the suggestions.
* Internal refactorings to avoid calls while holding locks
* Use non-reentrant locks by default. Thanks to Roland McGrath
for the suggestion.
* Small fixes to mspace_destroy, reset_on_error.
* Various configuration extensions/changes. Thanks
to all who contributed these.
V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu)
* Update Creative Commons URL
V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)
* Use zeros instead of prev foot for is_mmapped
* Add mspace_track_large_chunks; thanks to Jean Brouwers
* Fix set_inuse in internal_realloc; thanks to Jean Brouwers
* Fix insufficient sys_alloc padding when using 16byte alignment
* Fix bad error check in mspace_footprint
* Adaptations for ptmalloc; thanks to Wolfram Gloger.
* Reentrant spin locks; thanks to Earl Chew and others
* Win32 improvements; thanks to Niall Douglas and Earl Chew
* Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options
* Extension hook in malloc_state
* Various small adjustments to reduce warnings on some compilers
* Various configuration extensions/changes for more platforms. Thanks
to all who contributed these.
V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
* Add max_footprint functions
* Ensure all appropriate literals are size_t
* Fix conditional compilation problem for some #define settings
* Avoid concatenating segments with the one provided
in create_mspace_with_base
* Rename some variables to avoid compiler shadowing warnings
* Use explicit lock initialization.
* Better handling of sbrk interference.
* Simplify and fix segment insertion, trimming and mspace_destroy
* Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
* Thanks especially to Dennis Flanagan for help on these.
V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
* Fix memalign brace error.
V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
* Fix improper #endif nesting in C++
* Add explicit casts needed for C++
V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
* Use trees for large bins
* Support mspaces
* Use segments to unify sbrk-based and mmap-based system allocation,
removing need for emulation on most platforms without sbrk.
* Default safety checks
* Optional footer checks. Thanks to William Robertson for the idea.
* Internal code refactoring
* Incorporate suggestions and platform-specific changes.
Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
Aaron Bachmann, Emery Berger, and others.
* Speed up non-fastbin processing enough to remove fastbins.
* Remove useless cfree() to avoid conflicts with other apps.
* Remove internal memcpy, memset. Compilers handle builtins better.
* Remove some options that no one ever used and rename others.
V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
* Fix malloc_state bitmap array misdeclaration
V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
* Allow tuning of FIRST_SORTED_BIN_SIZE
* Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
* Better detection and support for non-contiguousness of MORECORE.
Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
* Bypass most of malloc if no frees. Thanks To Emery Berger.
* Fix freeing of old top non-contiguous chunk im sysmalloc.
* Raised default trim and map thresholds to 256K.
* Fix mmap-related #defines. Thanks to Lubos Lunak.
* Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
* Branch-free bin calculation
* Default trim and mmap thresholds now 256K.
V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
* Introduce independent_comalloc and independent_calloc.
Thanks to Michael Pachos for motivation and help.
* Make optional .h file available
* Allow > 2GB requests on 32bit systems.
* new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.
Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
and Anonymous.
* Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
helping test this.)
* memalign: check alignment arg
* realloc: don't try to shift chunks backwards, since this
leads to more fragmentation in some programs and doesn't
seem to help in any others.
* Collect all cases in malloc requiring system memory into sysmalloc
* Use mmap as backup to sbrk
* Place all internal state in malloc_state
* Introduce fastbins (although similar to 2.5.1)
* Many minor tunings and cosmetic improvements
* Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
* Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
Thanks to Tony E. Bennett <[email protected]> and others.
* Include errno.h to support default failure action.
V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
* return null for negative arguments
* Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
(e.g. WIN32 platforms)
* Cleanup header file inclusion for WIN32 platforms
* Cleanup code to avoid Microsoft Visual C++ compiler complaints
* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
memory allocation routines
* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
usage of 'assert' in non-WIN32 code
* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
avoid infinite loop
* Always call 'fREe()' rather than 'free()'
V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
* Fixed ordering problem with boundary-stamping
V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
* Added pvalloc, as recommended by H.J. Liu
* Added 64bit pointer support mainly from Wolfram Gloger
* Added anonymously donated WIN32 sbrk emulation
* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
* malloc_extend_top: fix mask error that caused wastage after
foreign sbrks
* Add linux mremap support code from HJ Liu
V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
* Integrated most documentation with the code.
* Add support for mmap, with help from
Wolfram Gloger ([email protected]).
* Use last_remainder in more cases.
* Pack bins using idea from [email protected]
* Use ordered bins instead of best-fit threshhold
* Eliminate block-local decls to simplify tracing and debugging.
* Support another case of realloc via move into top
* Fix error occuring when initial sbrk_base not word-aligned.
* Rely on page size for units instead of SBRK_UNIT to
avoid surprises about sbrk alignment conventions.
* Add mallinfo, mallopt. Thanks to Raymond Nijssen
([email protected]) for the suggestion.
* Add `pad' argument to malloc_trim and top_pad mallopt parameter.
* More precautions for cases where other routines call sbrk,
courtesy of Wolfram Gloger ([email protected]).
* Added macros etc., allowing use in linux libc from
H.J. Lu ([email protected])
* Inverted this history list
V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
* Re-tuned and fixed to behave more nicely with V2.6.0 changes.
* Removed all preallocation code since under current scheme
the work required to undo bad preallocations exceeds
the work saved in good cases for most test programs.
* No longer use return list or unconsolidated bins since
no scheme using them consistently outperforms those that don't
given above changes.
* Use best fit for very large chunks to prevent some worst-cases.
* Added some support for debugging
V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
* Removed footers when chunks are in use. Thanks to
Paul Wilson ([email protected]) for the suggestion.
V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
* Added malloc_trim, with help from Wolfram Gloger
([email protected]).
V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
* realloc: try to expand in both directions
* malloc: swap order of clean-bin strategy;
* realloc: only conditionally expand backwards
* Try not to scavenge used bins
* Use bin counts as a guide to preallocation
* Occasionally bin return list chunks in first scan
* Add a few optimizations from [email protected]
V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
* faster bin computation & slightly different binning
* merged all consolidations to one part of malloc proper
(eliminating old malloc_find_space & malloc_clean_bin)
* Scan 2 returns chunks (not just 1)
* Propagate failure in realloc if malloc returns 0
* Add stuff to allow compilation on non-ANSI compilers
from [email protected]
V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
* removed potential for odd address access in prev_chunk
* removed dependency on getpagesize.h
* misc cosmetics and a bit more internal documentation
* anticosmetics: mangled names in macros to evade debugger strangeness
* tested on sparc, hp-700, dec-mips, rs6000
with gcc & native cc (hp, dec only) allowing
Detlefs & Zorn comparison study (in SIGPLAN Notices.)
Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
* Based loosely on libg++-1.2X malloc. (It retains some of the overall
structure of old version, but most details differ.)
*/
|
the_stack_data/167331156.c | #include <stdlib.h>
#include <stdio.h>
int main() {
puts("Hello, I am a sample program.");
}
|
the_stack_data/220456660.c | #include <stdio.h>
int main()
{
int a = 10;
printf("%d \n", a);
printf("%u \n", a);
printf("%f \n", (float)a);
printf("%e \n", (float)a);
char c = 'A';
printf("%c \n", c);
printf("%d \n", c);
char str[] = "Hello world.";
printf("%s \n", str);
return 0;
} |
the_stack_data/96041.c | #include<stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b){
return *(int *)a-*(int *)b;
}
int main(void)
{
int n, k;
scanf("%d",&n);
int a[n], x, i, j, t, m;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&k);
qsort(a,n,sizeof(a[0]),cmp);
for(i=n-1;i>n-k;i--){
if(a[i]==a[i-1]){
k++;
}
}
for(i=n-k,j=1;i>0;i--){
if(a[i]==a[i-1]){
j++;
}
else{
break;
}
}
printf("%d %d", a[n-k], j);
return 0;
} |
the_stack_data/39803.c | /*-
* Copyright (c) 1990 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(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)ffs.c 5.4 (Berkeley) 5/17/90";
#endif /* LIBC_SCCS and not lint */
#include <string.h>
/*
* ffs -- vax ffs instruction
*/
int ffs(mask)
register int mask;
{
register int bit;
if (mask == 0)
return(0);
for (bit = 1; !(mask & 1); bit++)
mask >>= 1;
return(bit);
}
|
the_stack_data/74854.c | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char const *argv[]) {
for (size_t i = 0; i < 2; i++) {
pid_t pid = fork();
if (pid > 0) {
wait(0);
}
else {
printf("Processo %i filho de %i\n", getpid(), getppid());
for (size_t i = 0; i < 2; i++) {
pid_t pid0 = fork();
if (pid0 == 0) {
printf("Processo %i filho de %i\n", getpid(), getppid());
break;
}
}
break;
}
}
return 0;
}
|
the_stack_data/179830911.c | #include<stdio.h>
void main ()
{
int x,y;
scanf("%d",&x);
if(x<1)
printf("x=%3d,y=x=%3d\n",x,x);
else if(x<10)
printf("x=%3d,y=2*x-1=%3d\n",x,y);
} |
the_stack_data/132369.c | /*
* System call names.
*
* DO NOT EDIT-- this file is automatically generated.
* created from NetBSD: syscalls.master,v 1.12 1997/10/18 16:30:34 christos Exp
*/
char *freebsd_syscallnames[] = {
"syscall", /* 0 = syscall */
"exit", /* 1 = exit */
"fork", /* 2 = fork */
"read", /* 3 = read */
"write", /* 4 = write */
"open", /* 5 = open */
"close", /* 6 = close */
"wait4", /* 7 = wait4 */
"ocreat", /* 8 = ocreat */
"link", /* 9 = link */
"unlink", /* 10 = unlink */
"#11 (obsolete execv)", /* 11 = obsolete execv */
"chdir", /* 12 = chdir */
"fchdir", /* 13 = fchdir */
"mknod", /* 14 = mknod */
"chmod", /* 15 = chmod */
"chown", /* 16 = chown */
"break", /* 17 = break */
"getfsstat", /* 18 = getfsstat */
"olseek", /* 19 = olseek */
"getpid", /* 20 = getpid */
"mount", /* 21 = mount */
"unmount", /* 22 = unmount */
"setuid", /* 23 = setuid */
"getuid", /* 24 = getuid */
"geteuid", /* 25 = geteuid */
"ptrace", /* 26 = ptrace */
"recvmsg", /* 27 = recvmsg */
"sendmsg", /* 28 = sendmsg */
"recvfrom", /* 29 = recvfrom */
"accept", /* 30 = accept */
"getpeername", /* 31 = getpeername */
"getsockname", /* 32 = getsockname */
"access", /* 33 = access */
"chflags", /* 34 = chflags */
"fchflags", /* 35 = fchflags */
"sync", /* 36 = sync */
"kill", /* 37 = kill */
"stat43", /* 38 = stat43 */
"getppid", /* 39 = getppid */
"lstat43", /* 40 = lstat43 */
"dup", /* 41 = dup */
"pipe", /* 42 = pipe */
"getegid", /* 43 = getegid */
"profil", /* 44 = profil */
#ifdef KTRACE
"ktrace", /* 45 = ktrace */
#else
"#45 (unimplemented ktrace)", /* 45 = unimplemented ktrace */
#endif
"sigaction", /* 46 = sigaction */
"getgid", /* 47 = getgid */
"sigprocmask", /* 48 = sigprocmask */
"__getlogin", /* 49 = __getlogin */
"setlogin", /* 50 = setlogin */
"acct", /* 51 = acct */
"sigpending", /* 52 = sigpending */
"sigaltstack", /* 53 = sigaltstack */
"ioctl", /* 54 = ioctl */
"reboot", /* 55 = reboot */
"revoke", /* 56 = revoke */
"symlink", /* 57 = symlink */
"readlink", /* 58 = readlink */
"execve", /* 59 = execve */
"umask", /* 60 = umask */
"chroot", /* 61 = chroot */
"fstat43", /* 62 = fstat43 */
"ogetkerninfo", /* 63 = ogetkerninfo */
"ogetpagesize", /* 64 = ogetpagesize */
"msync", /* 65 = msync */
"vfork", /* 66 = vfork */
"#67 (obsolete vread)", /* 67 = obsolete vread */
"#68 (obsolete vwrite)", /* 68 = obsolete vwrite */
"sbrk", /* 69 = sbrk */
"sstk", /* 70 = sstk */
"ommap", /* 71 = ommap */
"vadvise", /* 72 = vadvise */
"munmap", /* 73 = munmap */
"mprotect", /* 74 = mprotect */
"madvise", /* 75 = madvise */
"#76 (obsolete vhangup)", /* 76 = obsolete vhangup */
"#77 (obsolete vlimit)", /* 77 = obsolete vlimit */
"mincore", /* 78 = mincore */
"getgroups", /* 79 = getgroups */
"setgroups", /* 80 = setgroups */
"getpgrp", /* 81 = getpgrp */
"setpgid", /* 82 = setpgid */
"setitimer", /* 83 = setitimer */
"owait", /* 84 = owait */
"swapon", /* 85 = swapon */
"getitimer", /* 86 = getitimer */
"ogethostname", /* 87 = ogethostname */
"osethostname", /* 88 = osethostname */
"ogetdtablesize", /* 89 = ogetdtablesize */
"dup2", /* 90 = dup2 */
"#91 (unimplemented getdopt)", /* 91 = unimplemented getdopt */
"fcntl", /* 92 = fcntl */
"select", /* 93 = select */
"#94 (unimplemented setdopt)", /* 94 = unimplemented setdopt */
"fsync", /* 95 = fsync */
"setpriority", /* 96 = setpriority */
"socket", /* 97 = socket */
"connect", /* 98 = connect */
"oaccept", /* 99 = oaccept */
"getpriority", /* 100 = getpriority */
"osend", /* 101 = osend */
"orecv", /* 102 = orecv */
"sigreturn", /* 103 = sigreturn */
"bind", /* 104 = bind */
"setsockopt", /* 105 = setsockopt */
"listen", /* 106 = listen */
"#107 (obsolete vtimes)", /* 107 = obsolete vtimes */
"osigvec", /* 108 = osigvec */
"osigblock", /* 109 = osigblock */
"osigsetmask", /* 110 = osigsetmask */
"sigsuspend", /* 111 = sigsuspend */
"osigstack", /* 112 = osigstack */
"orecvmsg", /* 113 = orecvmsg */
"osendmsg", /* 114 = osendmsg */
#ifdef TRACE
"vtrace", /* 115 = vtrace */
#else
"#115 (obsolete vtrace)", /* 115 = obsolete vtrace */
#endif
"gettimeofday", /* 116 = gettimeofday */
"getrusage", /* 117 = getrusage */
"getsockopt", /* 118 = getsockopt */
"#119 (obsolete resuba)", /* 119 = obsolete resuba */
"readv", /* 120 = readv */
"writev", /* 121 = writev */
"settimeofday", /* 122 = settimeofday */
"fchown", /* 123 = fchown */
"fchmod", /* 124 = fchmod */
"orecvfrom", /* 125 = orecvfrom */
"setreuid", /* 126 = setreuid */
"setregid", /* 127 = setregid */
"rename", /* 128 = rename */
"otruncate", /* 129 = otruncate */
"oftruncate", /* 130 = oftruncate */
"flock", /* 131 = flock */
"mkfifo", /* 132 = mkfifo */
"sendto", /* 133 = sendto */
"shutdown", /* 134 = shutdown */
"socketpair", /* 135 = socketpair */
"mkdir", /* 136 = mkdir */
"rmdir", /* 137 = rmdir */
"utimes", /* 138 = utimes */
"#139 (obsolete 4.2 sigreturn)", /* 139 = obsolete 4.2 sigreturn */
"adjtime", /* 140 = adjtime */
"ogetpeername", /* 141 = ogetpeername */
"ogethostid", /* 142 = ogethostid */
"osethostid", /* 143 = osethostid */
"ogetrlimit", /* 144 = ogetrlimit */
"osetrlimit", /* 145 = osetrlimit */
"okillpg", /* 146 = okillpg */
"setsid", /* 147 = setsid */
"quotactl", /* 148 = quotactl */
"oquota", /* 149 = oquota */
"ogetsockname", /* 150 = ogetsockname */
"#151 (unimplemented)", /* 151 = unimplemented */
"#152 (unimplemented)", /* 152 = unimplemented */
"#153 (unimplemented)", /* 153 = unimplemented */
"#154 (unimplemented)", /* 154 = unimplemented */
#if defined(NFS) || defined(NFSSERVER)
"nfssvc", /* 155 = nfssvc */
#else
"#155 (unimplemented)", /* 155 = unimplemented */
#endif
"ogetdirentries", /* 156 = ogetdirentries */
"statfs", /* 157 = statfs */
"fstatfs", /* 158 = fstatfs */
"#159 (unimplemented)", /* 159 = unimplemented */
"#160 (unimplemented)", /* 160 = unimplemented */
#ifdef NFS
"getfh", /* 161 = getfh */
#else
"#161 (unimplemented getfh)", /* 161 = unimplemented getfh */
#endif
"getdomainname", /* 162 = getdomainname */
"setdomainname", /* 163 = setdomainname */
"uname", /* 164 = uname */
"sysarch", /* 165 = sysarch */
"rtprio", /* 166 = rtprio */
"#167 (unimplemented)", /* 167 = unimplemented */
"#168 (unimplemented)", /* 168 = unimplemented */
#if defined(SYSVSEM) && !defined(alpha)
"semsys", /* 169 = semsys */
#else
"#169 (unimplemented 1.0 semsys)", /* 169 = unimplemented 1.0 semsys */
#endif
#if defined(SYSVMSG) && !defined(alpha)
"msgsys", /* 170 = msgsys */
#else
"#170 (unimplemented 1.0 msgsys)", /* 170 = unimplemented 1.0 msgsys */
#endif
#if defined(SYSVSHM) && !defined(alpha)
"shmsys", /* 171 = shmsys */
#else
"#171 (unimplemented 1.0 shmsys)", /* 171 = unimplemented 1.0 shmsys */
#endif
"#172 (unimplemented)", /* 172 = unimplemented */
"#173 (unimplemented)", /* 173 = unimplemented */
"#174 (unimplemented)", /* 174 = unimplemented */
"#175 (unimplemented)", /* 175 = unimplemented */
"freebsd_ntp_adjtime", /* 176 = freebsd_ntp_adjtime */
"#177 (unimplemented)", /* 177 = unimplemented */
"#178 (unimplemented)", /* 178 = unimplemented */
"#179 (unimplemented)", /* 179 = unimplemented */
"#180 (unimplemented)", /* 180 = unimplemented */
"setgid", /* 181 = setgid */
"setegid", /* 182 = setegid */
"seteuid", /* 183 = seteuid */
#ifdef LFS
"lfs_bmapv", /* 184 = lfs_bmapv */
"lfs_markv", /* 185 = lfs_markv */
"lfs_segclean", /* 186 = lfs_segclean */
"lfs_segwait", /* 187 = lfs_segwait */
#else
"#184 (unimplemented)", /* 184 = unimplemented */
"#185 (unimplemented)", /* 185 = unimplemented */
"#186 (unimplemented)", /* 186 = unimplemented */
"#187 (unimplemented)", /* 187 = unimplemented */
#endif
"stat", /* 188 = stat */
"fstat", /* 189 = fstat */
"lstat", /* 190 = lstat */
"pathconf", /* 191 = pathconf */
"fpathconf", /* 192 = fpathconf */
"#193 (unimplemented)", /* 193 = unimplemented */
"getrlimit", /* 194 = getrlimit */
"setrlimit", /* 195 = setrlimit */
"getdirentries", /* 196 = getdirentries */
"mmap", /* 197 = mmap */
"__syscall", /* 198 = __syscall */
"lseek", /* 199 = lseek */
"truncate", /* 200 = truncate */
"ftruncate", /* 201 = ftruncate */
"__sysctl", /* 202 = __sysctl */
"mlock", /* 203 = mlock */
"munlock", /* 204 = munlock */
#ifdef FREEBSD_BASED_ON_44LITE_R2
"undelete", /* 205 = undelete */
#else
"#205 (unimplemented)", /* 205 = unimplemented */
#endif
"#206 (unimplemented)", /* 206 = unimplemented */
"#207 (unimplemented)", /* 207 = unimplemented */
"#208 (unimplemented)", /* 208 = unimplemented */
"#209 (unimplemented)", /* 209 = unimplemented */
"#210 (unimplemented)", /* 210 = unimplemented */
"#211 (unimplemented)", /* 211 = unimplemented */
"#212 (unimplemented)", /* 212 = unimplemented */
"#213 (unimplemented)", /* 213 = unimplemented */
"#214 (unimplemented)", /* 214 = unimplemented */
"#215 (unimplemented)", /* 215 = unimplemented */
"#216 (unimplemented)", /* 216 = unimplemented */
"#217 (unimplemented)", /* 217 = unimplemented */
"#218 (unimplemented)", /* 218 = unimplemented */
"#219 (unimplemented)", /* 219 = unimplemented */
"#220 (unimplemented)", /* 220 = unimplemented */
"#221 (unimplemented)", /* 221 = unimplemented */
"#222 (unimplemented)", /* 222 = unimplemented */
"#223 (unimplemented)", /* 223 = unimplemented */
"#224 (unimplemented)", /* 224 = unimplemented */
"#225 (unimplemented)", /* 225 = unimplemented */
"#226 (unimplemented)", /* 226 = unimplemented */
"#227 (unimplemented)", /* 227 = unimplemented */
"#228 (unimplemented)", /* 228 = unimplemented */
"#229 (unimplemented)", /* 229 = unimplemented */
"#230 (unimplemented)", /* 230 = unimplemented */
"#231 (unimplemented)", /* 231 = unimplemented */
"#232 (unimplemented)", /* 232 = unimplemented */
"#233 (unimplemented)", /* 233 = unimplemented */
"#234 (unimplemented)", /* 234 = unimplemented */
"#235 (unimplemented)", /* 235 = unimplemented */
"#236 (unimplemented)", /* 236 = unimplemented */
"#237 (unimplemented)", /* 237 = unimplemented */
"#238 (unimplemented)", /* 238 = unimplemented */
"#239 (unimplemented)", /* 239 = unimplemented */
"#240 (unimplemented)", /* 240 = unimplemented */
"#241 (unimplemented)", /* 241 = unimplemented */
"#242 (unimplemented)", /* 242 = unimplemented */
"#243 (unimplemented)", /* 243 = unimplemented */
"#244 (unimplemented)", /* 244 = unimplemented */
"#245 (unimplemented)", /* 245 = unimplemented */
"#246 (unimplemented)", /* 246 = unimplemented */
"#247 (unimplemented)", /* 247 = unimplemented */
"#248 (unimplemented)", /* 248 = unimplemented */
"#249 (unimplemented)", /* 249 = unimplemented */
"#250 (unimplemented)", /* 250 = unimplemented */
"#251 (unimplemented)", /* 251 = unimplemented */
"#252 (unimplemented)", /* 252 = unimplemented */
"#253 (unimplemented)", /* 253 = unimplemented */
"lchown", /* 254 = lchown */
};
|
the_stack_data/574645.c | #include <aio.h>
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int fd;
static struct aiocb aiocbp;
struct input_event event;
static void aio_complete_handler(__sigval_t sigval);
static void read_from_event(void)
{
/* read from /dev/input/event0 of the specific input_event data*/
bzero((char *) &aiocbp, sizeof(struct aiocb));
aiocbp.aio_fildes = fd;
aiocbp.aio_buf = &event;
aiocbp.aio_offset = 0;
aiocbp.aio_nbytes = sizeof(struct input_event);
/* create a new thread to execute the callback function */
aiocbp.aio_sigevent.sigev_notify = SIGEV_THREAD;
aiocbp.aio_sigevent.sigev_notify_function = aio_complete_handler;
aiocbp.aio_sigevent.sigev_notify_attributes = NULL;
aiocbp.aio_sigevent.sigev_value.sival_ptr = &aiocbp;
aio_read(&aiocbp);
}
static void aio_complete_handler(__sigval_t sigval)
{
struct aiocb *req;
int ret;
struct input_event *event;
int index;
req = (struct aiocb *) sigval.sival_ptr;
if (aio_error(req) == 0) {
ret = aio_return(req);
event = (struct input_event *) req->aio_buf;
printf("get event: type = 0x%x, code = 0x%x, value = 0x%x\n", event->type, event->code, event->value);
/* read from next */
read_from_event();
} else {
printf("failed to read data\n");
}
}
int main(int argc, char **argv)
{
struct input_event event;
if (argc != 2) {
printf("Usage: %s <dev>\n", argv[0]);
return -1;
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
printf("failed to open file\n");
}
read_from_event();
while (1) { /* go and do something in this thread */
}
return 0;
} |
the_stack_data/132952450.c | #include <stdio.h>
int main()
{
int numero = 13051;
printf("Decimal usando 'i': %i\n", numero);
printf("Decimal usando 'd': %d\n", numero);
printf("Heximal: %x\n", numero);
printf("Octal: %o\n", numero);
signed int x = 10;
printf("El valor inicial de x es %i\n", x);
x = 50;
printf("Ahora el valor es %i\n", x);
printf("El tipo int ocupa %lu bytes = %lu bits\n", sizeof(int), sizeof(int)*8);
printf("El tipo int puede almacenar %lu\n", 2 ^ (sizeof(int) * 8));
return 0;
}
|
the_stack_data/64201533.c | /*
* 这是中M2019年春季班(第8期)的C语言入门和进阶两门课的练习题目集。
* 普通编程题,标号7-27, 兔子繁衍问题 (15 分)
* PTA,程序设计类实验辅助教学平台,https://pintia.cn
* 作者:hitmanl
* 日期:2019-04-12
* 体会:
* (1)第一次接触兔子繁衍问题,在草稿纸上推导了半天,本来想利用基本数据类型计算的,
* (2)后来还是觉得使用结构体比较容易。
* (3)第一次提交的时候,自动判题系统给出的结果是3个测试点通过,2个测试点未通过,
* (4)经过检查没有逻辑问题之后,直接把兔子的变量数组的长度扩大到超出题目要求,
* (5)然后就全部通过了。
* (6)也许不是空间、时间复杂度上的好算法,重在理解推演过程和实现过程吧。
* 收获:
* (1)结构体是个好东西。
*/
#include <stdio.h>
#define N 20000
typedef struct rabbit {
int num;
int months;
} Rabbit;
int main(int argc, char const *argv[])
{
int dest;
scanf("%d", &dest);
Rabbit a[N];
for (int i = 0; i < N; i++) {
a[i].num = 0;
a[i].months = 0;
}
a[0].num = 1;
a[0].months = 1;
int mon;
int sum = 0;
for (mon = 1;; mon++) {
for (int i = 0; i < N; i++) {
if (a[i].num == 0) {
break;
}
if (a[i].months > 2) {
//a[i].num++;
for (int j = i + 1; j < N; j++) {
if (a[j].num == 0) {
a[j].num++;
a[j].months++;
break;
}
}
}
a[i].months++;
}
for (int k = 0;; k++) {
if (a[k].num) {
sum += a[k].num;
} else {
break;
}
}
//printf("month = %d, sum = %d\n", mon, sum);
if (sum >= dest) {
printf("%d", mon);
return 0;
} else {
sum = 0;
}
}
return 0;
}
/*
一对兔子,从出生后第3个月起每个月都生一对兔子。
小兔子长到第3个月后每个月又生一对兔子。
假如兔子都不死,请问第1个月出生的一对兔子,
至少需要繁衍到第几个月时兔子总数才可以达到N对?
输入格式:
输入在一行中给出一个不超过10000的正整数N。
输出格式:
在一行中输出兔子总数达到N最少需要的月数。
输入样例:
30
输出样例:
9
*/
|
the_stack_data/161081950.c | #include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
int sockfd, newsockfd;
uint16_t portno;
unsigned int clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
ssize_t n;
if (argc < 2) {
fprintf(stderr, "usage %s port\n", argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
portno = (uint16_t) atoi(argv[1]);
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
exit(1);
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
perror("ERROR on accept");
exit(1);
}
bzero(buffer, 256);
n = read(newsockfd, buffer, 255); // recv on Windows
if (n < 0) {
perror("ERROR reading from socket");
exit(1);
}
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "I got your message", 18); // send on Windows
if (n < 0) {
perror("ERROR writing to socket");
exit(1);
}
return 0;
}
|
the_stack_data/59513731.c | /*
* Write a program that declares a 3x5 array of int and initializes it to
* some values of your choice. Have the pgraom print the values, double all
* the values, and then display the new values. Write a function to do the
* displaying and a second function to do the doubling. Have the functions take
* the array name and the number of rows as arguments
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 3
#define COLS 5
void print_array(int arr[][COLS], int rows)
{
printf("[\n");
for (int i = 0; i < rows; i++)
{
printf(" [");
for (int j = 0; j < COLS; j++)
{
printf("%d, ", *(*(arr+i) + j));
}
printf("],\n");
}
printf("]\n");
return;
}
void scale_array_by_2(int arr[][COLS], int rows)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < COLS; j++)
arr[i][j] = arr[i][j] * 2;
return;
}
int main(void)
{
int test[ROWS][COLS] = {
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
};
print_array(test, ROWS);
scale_array_by_2(test, ROWS);
print_array(test, ROWS);
return 0;
}
|
the_stack_data/40761598.c | /*
* $Id$
* Copyright (C) 2004-2007, Parrot Foundation.
*/
/*
=head1 NAME
config/gen/platform/generic/math.c
=head1 DESCRIPTION
math stuff
=head2 Functions
=over 4
=cut
*/
/*
=item C<extern int Parrot_signbit(double x)>
return true if the Numval has a negative sign.
This is mostly for handling the -0.0 case.
=cut
*/
/*
*/
#if DOUBLE_SIZE == 2 * INT_SIZE
extern int
Parrot_signbit(double x)
{
union {
double d;
int i[2];
} u;
u.d = x;
# if PARROT_BIGENDIAN
return u.i[0] < 0;
# else
return u.i[1] < 0;
# endif
}
#endif
/*
=item C<int Parrot_signbit_l(long double x)>
=cut
*/
#if NUMVAL_SIZE == 12 && DOUBLE_SIZE == 3 * INT_SIZE && PARROT_LITTLE_ENDIAN
int
Parrot_signbit_l(long double x)
{
union {
long double d;
int i[3];
} u;
u.d = x;
return u.i[2] < 0;
}
#endif
/*
=back
=cut
*/
/*
* Local variables:
* c-file-style: "parrot"
* End:
* vim: expandtab shiftwidth=4:
*/
|
the_stack_data/26700871.c | // RUN: jlang-cc -fsyntax-only -verify -pedantic %s
// The preprocessor shouldn't warn about extensions within macro bodies that
// aren't expanded.
#define TY typeof
#define TY1 typeof(1)
// But we should warn here
TY1 x; // expected-warning {{extension}}
TY(1) x; // FIXME: And we should warn here
// Note: this warning intentionally doesn't trigger on keywords like
// __attribute; the standard allows implementation-defined extensions
// prefixed with "__".
// Current list of keywords this can trigger on:
// inline, restrict, asm, typeof, _asm
void whatever() {}
|
the_stack_data/178265639.c | #include <stdio.h>
int main()
{
int N,count=1,a,b,c,d,e,f,g,h,i,j;
scanf("%d",&N);
if(N<=0 || N>=20)
return 0;
while(scanf("%d %d %d %d %d %d %d %d %d %d",&a,&b,&c,&d,&e,&f,&g,&h,&i,&j) !=EOF)
{
if(count == 1)
printf("Lumberjacks:\n");
if((a>=0 && a<100) && (b>=0 && b<100) && (c>=0 && c<100) && (d>=0 && d<100) && (e>=0 && e<100) && (f>=0 && f<100) && (g>=0 && g<100) && (h>=0 && h<100) && (i>=0 && i<100) && (j>=0 && j<100))
{
if(a>b && b>c && c>d && d>e && e>f && f>g && g>h && h>i && i>j)
printf("Ordered\n");
else if(j>i && i>h && h>g && g>f && f>e && e>d && d>c && c>b && b>a)
printf("Ordered\n");
else
printf("Unordered\n");
count++;
if(count>N)
break;
}
}
return 0;
}
|
the_stack_data/25794.c | #if _WIN32 || _WIN64
# define F_GETFL 0
# define F_SETFL 0
# define O_NONBLOCK 0
#else
# include <fcntl.h>
#endif
#include <stdio.h>
#include <stdlib.h>
static int
msc_version_to_dll_version(int msc_version)
{
if(msc_version == 800) {
return 10; /* 1.0 is an exception */
} else {
return (msc_version / 10) - 60;
}
}
int
main(void)
{
printf("F_GETFL=%d\n", F_GETFL);
printf("F_SETFL=%d\n", F_SETFL);
printf("O_NONBLOCK=%d\n", O_NONBLOCK);
#if _WIN32 || _WIN64
# if defined(_MSC_VER) && (_MSC_VER < 1000 || _MSC_VER >= 1300)
printf("CLIB=\"msvcr%d.dll\"\n", msc_version_to_dll_version(_MSC_VER));
# else
printf("CLIB=\"msvcrt.dll\"\n");
# endif
#else
printf("CLIB=Str\n");
#endif
return 0;
}
|
the_stack_data/181394098.c | // RUN: %clang %s -### -no-canonical-prefixes --target=x86_64-unknown-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-X86_64 %s
// RUN: %clang %s -### -no-canonical-prefixes --target=aarch64-unknown-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-AARCH64 %s
// RUN: %clang %s -### -no-canonical-prefixes --target=riscv64-unknown-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-RISCV64 %s
// RUN: %clang %s -### -no-canonical-prefixes --target=x86_64-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-X86_64 %s
// RUN: %clang %s -### -no-canonical-prefixes --target=aarch64-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-AARCH64 %s
// RUN: %clang %s -### -no-canonical-prefixes --target=riscv64-fuchsia \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
// RUN: | FileCheck -check-prefixes=CHECK,CHECK-RISCV64 %s
// CHECK: {{.*}}clang{{.*}}" "-cc1"
// CHECK-X86_64: "-triple" "x86_64-unknown-fuchsia"
// CHECK-AARCH64: "-triple" "aarch64-unknown-fuchsia"
// CHECK-RISCV64: "-triple" "riscv64-unknown-fuchsia"
// CHECK: "--mrelax-relocations"
// CHECK: "-funwind-tables=2"
// CHECK: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
// CHECK: "-internal-externc-isystem" "[[SYSROOT]]{{/|\\\\}}include"
// CHECK-AARCH64: "-fsanitize=shadow-call-stack"
// CHECK-X86_64: "-fsanitize=safe-stack"
// CHECK: "-stack-protector" "2"
// CHECK-AARCH64: "-target-feature" "+outline-atomics"
// CHECK-NOT: "-fcommon"
// CHECK: {{.*}}ld.lld{{.*}}" "-z" "max-page-size=4096" "-z" "now" "-z" "rodynamic" "-z" "separate-loadable-segments" "-z" "rel" "--pack-dyn-relocs=relr"
// CHECK: "--sysroot=[[SYSROOT]]"
// CHECK: "-pie"
// CHECK: "--build-id"
// CHECK: "--hash-style=gnu"
// CHECK-AARCH64: "--fix-cortex-a53-843419"
// CHECK: "-dynamic-linker" "ld.so.1"
// CHECK: Scrt1.o
// CHECK-NOT: crti.o
// CHECK-NOT: crtbegin.o
// CHECK: "-L[[SYSROOT]]{{/|\\\\}}lib"
// CHECK-X86_64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK-RISCV64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}riscv64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK: "-lc"
// CHECK-NOT: crtend.o
// CHECK-NOT: crtn.o
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -rtlib=libgcc -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-RTLIB
// CHECK-RTLIB: error: invalid runtime library name in argument '-rtlib=libgcc'
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -static -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-STATIC
// CHECK-STATIC: "-Bstatic"
// CHECK-STATIC: "-Bdynamic"
// CHECK-STATIC: "-lc"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -shared -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-SHARED
// CHECK-SHARED-NOT: "-pie"
// CHECK-SHARED: "-shared"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -r -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-RELOCATABLE
// CHECK-RELOCATABLE-NOT: "-pie"
// CHECK-RELOCATABLE-NOT: "--build-id"
// CHECK-RELOCATABLE: "-r"
// CHECK-RELOCATABLE-NOT: "-l
// CHECK-RELOCATABLE-NOT: crt{{[^./]+}}.o
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -nodefaultlibs -fuse-ld=lld 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: | FileCheck %s -check-prefix=CHECK-NODEFAULTLIBS
// CHECK-NODEFAULTLIBS: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-NODEFAULTLIBS-NOT: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK-NODEFAULTLIBS-NOT: "-lc"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -nostdlib -fuse-ld=lld 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: | FileCheck %s -check-prefix=CHECK-NOSTDLIB
// CHECK-NOSTDLIB: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-NOSTDLIB-NOT: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK-NOSTDLIB-NOT: "-lc"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia -nolibc -fuse-ld=lld 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: | FileCheck %s -check-prefix=CHECK-NOLIBC
// CHECK-NOLIBC: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-NOLIBC: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.builtins.a"
// CHECK-NOLIBC-NOT: "-lc"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=safe-stack 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-SAFESTACK
// CHECK-SAFESTACK: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-SAFESTACK: "-fsanitize=safe-stack"
// CHECK-SAFESTACK-NOT: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.safestack.a"
// CHECK-SAFESTACK-NOT: "__safestack_init"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=address 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-ASAN-X86
// CHECK-ASAN-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-ASAN-X86: "-fsanitize=address"
// CHECK-ASAN-X86: "-fsanitize-address-globals-dead-stripping"
// CHECK-ASAN-X86: "-dynamic-linker" "asan/ld.so.1"
// CHECK-ASAN-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan.so"
// CHECK-ASAN-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan-preinit.a"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fsanitize=address 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-ASAN-AARCH64
// CHECK-ASAN-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-ASAN-AARCH64: "-fsanitize=address,shadow-call-stack"
// CHECK-ASAN-AARCH64: "-fsanitize-address-globals-dead-stripping"
// CHECK-ASAN-AARCH64: "-dynamic-linker" "asan/ld.so.1"
// CHECK-ASAN-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan.so"
// CHECK-ASAN-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan-preinit.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=address -fPIC -shared 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-ASAN-SHARED
// CHECK-ASAN-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-ASAN-SHARED: "-fsanitize=address"
// CHECK-ASAN-SHARED: "-fsanitize-address-globals-dead-stripping"
// CHECK-ASAN-SHARED: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan.so"
// CHECK-ASAN-SHARED-NOT: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.asan-preinit.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=fuzzer 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-FUZZER-X86
// CHECK-FUZZER-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-FUZZER-X86: "-fsanitize=fuzzer,fuzzer-no-link,safe-stack"
// CHECK-FUZZER-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.fuzzer.a"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fsanitize=fuzzer 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-FUZZER-AARCH64
// CHECK-FUZZER-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-FUZZER-AARCH64: "-fsanitize=fuzzer,fuzzer-no-link,shadow-call-stack"
// CHECK-FUZZER-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.fuzzer.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=scudo 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-SCUDO-X86
// CHECK-SCUDO-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-SCUDO-X86: "-fsanitize=safe-stack,scudo"
// CHECK-SCUDO-X86: "-pie"
// CHECK-SCUDO-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.scudo.so"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fsanitize=scudo 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-SCUDO-AARCH64
// CHECK-SCUDO-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-SCUDO-AARCH64: "-fsanitize=shadow-call-stack,scudo"
// CHECK-SCUDO-AARCH64: "-pie"
// CHECK-SCUDO-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.scudo.so"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=scudo -fPIC -shared 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-SCUDO-SHARED
// CHECK-SCUDO-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-SCUDO-SHARED: "-fsanitize=safe-stack,scudo"
// CHECK-SCUDO-SHARED: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.scudo.so"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fsanitize=leak 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-AARCH64
// CHECK-LSAN-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-LSAN-AARCH64: "-fsanitize=leak,shadow-call-stack"
// CHECK-LSAN-AARCH64: "-pie"
// CHECK-LSAN-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.lsan.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fsanitize=leak 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-X86
// CHECK-LSAN-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-LSAN-X86: "-fsanitize=leak,safe-stack"
// CHECK-LSAN-X86: "-pie"
// CHECK-LSAN-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.lsan.a"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fsanitize=leak -fPIC -shared 2>&1 \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-SHARED
// CHECK-LSAN-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-LSAN-SHARED: "-fsanitize=leak,shadow-call-stack"
// CHECK-LSAN-SHARED-NOT: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.lsan.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fxray-instrument -fxray-modes=xray-basic \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-XRAY-X86
// CHECK-XRAY-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-XRAY-X86: "-fxray-instrument"
// CHECK-XRAY-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.xray.a"
// CHECK-XRAY-X86: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.xray-basic.a"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fxray-instrument -fxray-modes=xray-basic \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-XRAY-AARCH64
// CHECK-XRAY-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-XRAY-AARCH64: "-fxray-instrument"
// CHECK-XRAY-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.xray.a"
// CHECK-XRAY-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.xray-basic.a"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -O3 -flto -mcpu=cortex-a53 2>&1 \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-LTO
// CHECK-LTO: "-plugin-opt=mcpu=cortex-a53"
// CHECK-LTO: "-plugin-opt=O3"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -flto=thin -flto-jobs=8 2>&1 \
// RUN: -fuse-ld=lld \
// RUN: | FileCheck %s -check-prefix=CHECK-THINLTO
// CHECK-THINLTO: "-plugin-opt=mcpu=x86-64"
// CHECK-THINLTO: "-plugin-opt=thinlto"
// CHECK-THINLTO: "-plugin-opt=jobs=8"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -gsplit-dwarf -g -c %s 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-SPLIT-DWARF
// CHECK-SPLIT-DWARF: "-split-dwarf-output" "fuchsia.dwo"
// RUN: %clang %s -### --target=aarch64-unknown-fuchsia \
// RUN: -fprofile-instr-generate -fcoverage-mapping \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-PROFRT-AARCH64
// CHECK-PROFRT-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-PROFRT-AARCH64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}aarch64-unknown-fuchsia{{/|\\\\}}libclang_rt.profile.a"
// RUN: %clang %s -### --target=x86_64-unknown-fuchsia \
// RUN: -fprofile-instr-generate -fcoverage-mapping \
// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
// RUN: -fuse-ld=lld 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-PROFRT-X86_64
// CHECK-PROFRT-X86_64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// CHECK-PROFRT-X86_64: "[[RESOURCE_DIR]]{{/|\\\\}}lib{{/|\\\\}}x86_64-unknown-fuchsia{{/|\\\\}}libclang_rt.profile.a"
|
the_stack_data/182954220.c | /*
* int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime)
*
* If successful, the pthread_mutex_timedlock() function shall return zero;
* otherwise, an error number shall be returned to indicate the error.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
int main(void)
{
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
t.tv_sec += 10;
pthread_mutex_timedlock(&lock, &t);
printf("timeout\n");
return EXIT_SUCCESS;
}
|
the_stack_data/145867.c | #include<stdio.h>
int main() {
int a, b, c;
c = 11 % 5;
printf("%d\n", c);
return 0;
} |
the_stack_data/839171.c | /*
* FreeRTOS-Cellular-Interface v1.1.0
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*/
/**
* @file bsearch.c
* @brief Creates a stub for bsearch. This stub checks if, for the input copy
* length, the destination and source are valid accessible memory.
*/
#include <stdio.h>
void * bsearch( const void * key,
const void * base,
size_t num,
size_t size,
int ( * compar )( const void *, const void * ) )
{
int offset = nondet_size_t();
char * p = ( char * ) base;
( void ) key;
( void ) base;
if( ( offset >= 0 ) && ( offset < num ) )
{
return ( void * ) ( p + ( offset * size ) );
}
return NULL;
}
|
the_stack_data/68688.c | static void main(void)
{
asm("cpuid"
::: "eax", "ebx", "ecx", "edx");
}
|
the_stack_data/26804.c | #include <stdio.h>
int main(int argc, char* argv[]){
int numbers[5];
int temp;
printf("Input the first number: \n");
scanf("%d", &numbers[0]);
printf("Input the second number: \n");
scanf("%d", &numbers[1]);
printf("Input the third number: \n");
scanf("%d", &numbers[2]);
printf("Input the fourth number: \n");
scanf("%d", &numbers[3]);
printf("Input the fifth number: \n");
scanf("%d", &numbers[4]);
for(int i = 0; i < sizeof(numbers)/sizeof(int); i++){
if(numbers[i] > temp){
temp = i;
}
}
printf("The maximum value is: %d\n", numbers[temp]);
printf("Its position is: %d\n", temp+1);
return 0;
} |
the_stack_data/111079109.c | void main()
{
int symbol_a;
int symbol_b;
int nondet;
int *nondet_pointer;
if(nondet > 0)
{
nondet_pointer = &symbol_a;
}
else
{
nondet_pointer = &symbol_b;
}
int *arr[] = {&symbol_a, &symbol_b, nondet_pointer};
// Simplify the pointer
*arr[0] = 1;
// Simplify index and the pointer
int constant1 = 1;
*arr[constant1] = 2;
// Simplify the index but not the pointer
int constant2 = 2;
*arr[constant2] = 3;
// No simplification
int nondet_index;
*arr[nondet_index] = 4;
}
|
the_stack_data/61074000.c | /* { dg-options "-O2 -fdump-tree-vrp1" } */
/* { dg-final { scan-tree-dump "case 9 ... 10:" "vrp1" } } */
/* { dg-final { scan-tree-dump "case 17 ... 18:" "vrp1" } } */
/* { dg-final { scan-tree-dump "case 27 ... 30:" "vrp1" } } */
extern void foo (void);
extern void bar (void);
void
test1 (int i)
{
if (i != 7 && i != 8)
switch (i)
{
case 1:
case 2:
foo ();
break;
case 7: /* Redundant label. */
case 8: /* Redundant label. */
case 9:
case 10:
bar ();
break;
}
}
void
test3 (int i)
{
if (i != 19 && i != 20)
switch (i)
{
case 1:
case 2:
foo ();
break;
case 17:
case 18:
case 19: /* Redundant label. */
case 20: /* Redundant label. */
bar ();
break;
}
}
void
test2 (int i)
{
if (i != 28 && i != 29)
switch (i)
{
case 1:
case 2:
foo ();
break;
/* No redundancy. */
case 27:
case 28:
case 29:
case 30:
bar ();
break;
}
}
|
the_stack_data/89046.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
//---------------------------------------FUNÇÃO DE ORDENAMETO--------------------------------------------
void change(int* v, int i, int j){
int aux = v[i];
v[i] = v[j];
v[j] = aux;
}
int partion(int *v, int p, int r){
int x;
int i, j;
int aux = (p + r)/2;
change(v, aux, r);
x = v[r];
i = p - 1;
for(j = p; j < r; j++){
if(v[j] <= x){
i++;
change(v, i, j);
}
}
change(v, i+1, r);
return i + 1;
}
void quickSort(int* v, int e, int d){
int q;
if(e < d){
q = partion(v, e, d);
quickSort(v, e, q-1);
quickSort(v, q+1, d);
}
}
//---------------------------------------OUTRAS FUNÇÕES--------------------------------------------------
int* random_vector(int n, int max, int seed){
srand(seed);
int* vetor = (int*) calloc(n, sizeof(int));
for(int i = 0; i < n; i++){
vetor[i] = rand() % max;
}
return vetor;
}
void print_vector(int* v, int tam){
for(int i = 0; i < tam; i++){
printf("%d ", v[i]);
}
printf("\n\n\n");
}
//---------------------------------------FUNÇÃO PRINCIPAL------------------------------------------------
int main(){
int n = 100;
int max = 100*n;
int seed = 42;
int* v = random_vector(n, max, seed);
print_vector(v, n);
//inicio
clock_t start = clock();
quickSort(v, 0, n-1);
clock_t end = clock();
//fim
double tempo = (double)(end - start)/CLOCKS_PER_SEC;
print_vector(v, n);
printf("Tempo do algoritmo: %f\n", tempo);
return 0;
} |
the_stack_data/184517989.c | /* Reverse 2005-Nov-21
* by Joseph Larson (c) 2008
* Inspired by a BASIC game of the same name by Peter Sessions
* as found in 'BASIC Computer Games' edited by David H. Ahl (c) 1978
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#define X 16
int main (void) {
int list[X], c, d, turns;
long mask;
char yn;
srand (time(NULL));
printf ("Reverse\n-------\n\n"
"This is the game of Reverse. To win all you have to do is arrange a list\n"
"of numbers (1 through %d) in numerical order left to right.\n"
"To move, you input how many numbers from the right you want to reverse.\n"
"You will no doubt like this game but, if you want to quit just input '0'\n"
"as your move.\n\n", X);
do {
mask = 0;
for (c = 0; c < X; c++) {
while (1 << (list[c] = rand () % X + 1) & mask);
mask |= 1 << list[c];
}
turns = 0;
puts ("Here we go...\n");
do {
putchar ('\t');
for (c = X; c > 0;) printf ("%2d ",list[--c]);
printf ("\t? ");
scanf ("%d", &d);
if (d > 1 && d <= X) {
for (c = 0; c < (d / 2); c++) {
list[c] ^= list[d - c - 1];
list[d - c - 1] ^= list[c];
list[c] ^= list[d - c - 1];
}
turns++;
} else printf ("You can not reverse %d. Try again.\n", d);
for (c = 0; c < X - 1 && list[c] > list [c + 1]; c++);
} while (d && c < X - 1);
if (d) {
putchar ('\t');
for (c = X; c > 0;) printf ("%2d ",list[--c]);
printf ("\n\nYou ordered the list in %d moves.\n", turns);
if (turns > X * 2 - 3)
printf ("But it shouldn't have taken more than %d moves.\n" , X * 2 - 3);
if (turns <= X)
puts ("Wow, you are either extremely good, or extremely lucky.");
}
printf ("\nWould you like to try another? (y/n) : ");
while (!isalpha (yn = getchar ()));
} while (yn == 'y');
puts ("\n\n\n\n\n\n\n\n\tCymon's Games\n\n\thttp://WWW.CYMONSGAMES.COM\n\n\n"
" This game and its code is a 2008 Cymon's Games game.\n"
" If you have enjoyed this game or would just like to have a new game\n"
" each week please visit:\n"
" http://WWW.CYMONSGAMES.COM for C/C++ programming resources and programs\n"
" for everyone, beginners and advanced users alike.\n\n");
printf ("\n\tPress ENTER to continue...\n\n\n\n\n\n");
getchar (); getchar();
puts ("Good bye for now then!");
exit (0);
}
|
the_stack_data/237643302.c | //Diseñar un programa que cuente el número de sus entradas que son positivas, negativas y cero.
#include <stdio.h>
int num=0, negativo=0, positivo=0, cero=0;
char resp=' ';
int main (){
printf("\n\t\t Este programa te indicara cuantos numeros que positivos, negativos o cero \n");
do{
printf("\nIngresa un numero\n");
scanf(" %d",&num);
if(num > 0)
positivo++;
else if (num==0)
cero++;
else
negativo++;
printf("\n Desea Ingresar otro numero?: s/n \n");
scanf(" %c",&resp);
} while (resp=='s');
printf("\nIngresaste %d numeros negativos, %d numeros positivos y %d numero 0 \n\n",negativo,positivo,cero);
return 0;
}
|
the_stack_data/175143305.c | /* showip.c
*
* Copyright 2021 kevinjad
*
* 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 X CONSORTIUM BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the sale,
* use or other dealings in this Software without prior written
* authorization.
*/
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
void error_n_exit(char* msg){
fprintf(stderr, "[FATAL] %s\n", msg);
exit(-1);
}
int main(int argc, char* args[]){
struct addrinfo hint, *res, *p; //p is for traversing the result
int status;
char ip[INET6_ADDRSTRLEN];
memset (&hint, 0, sizeof (hint));
hint.ai_family = AF_UNSPEC;
hint.ai_socktype = SOCK_STREAM;
if(argc < 2){
error_n_exit ("Invalid Usage: Please provide a host address.");
}
if( (status = getaddrinfo ( args[1], NULL, &hint, &res)) != 0){
error_n_exit ("getaddrinfo failed :(");
}
printf ("IP address for %s:\n", args[1]);
for(p = res; p != NULL; p = p->ai_next){
void* address;
char* ip_version;
if(p->ai_family == AF_INET){ //IPV4
struct sockaddr_in* ipv4 = (struct sockaddr_in*) p->ai_addr;
address = &(ipv4->sin_addr);
ip_version = "IPv4";
} else{ //IPv6
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) p->ai_addr;
address = &(ipv6->sin6_addr);
ip_version = "IPv6";
}
inet_ntop (p->ai_family, address, ip, sizeof (ip));
printf("%s: %s\n", ip_version, ip);
}
freeaddrinfo (res);
return 0;
}
|
the_stack_data/568899.c | #include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
// ref https://coolshell.cn/articles/11377.html
typedef struct {
void *handle;
char name[]; // same with char name[0];
} test_t1;
// x86 sizeof() = 4
// x64 sizeof() = 8
typedef struct {
void *handle;
char name[0]; // msvc c++ will have warning warning C4200: 使用了非标准扩展: 结构/联合中的零大小数组
// note: 默认构造函数或 copy/move 赋值运算符将忽略此成员
} test_t2;
// x86 sizeof() = 8
// x64 sizeof() = 16
typedef struct {
void *handle;
char name[1]; // recommended, will have redundant memory, but no warning
} test_t3;
// x86 sizeof() = 8
// x64 sizeof() = 16
typedef struct {
void *handle;
char *name;
} test_t4;
void test_flexible_array()
{
size_t test_t1_size = sizeof(test_t2) + 6;
size_t test_t2_size = sizeof(test_t3) + 6;
test_t2 *p1 = (test_t2 *)calloc(1, test_t1_size);
test_t3 *p2 = (test_t3 *)calloc(1, test_t2_size);
// x86 = 6
printf("test_t1 rest size=%zu\n", test_t1_size - ((uint8_t *)(&p1->name) - (uint8_t *)p1));
// x86 = 10
printf("test_t2 rest size=%zu\n", test_t2_size - ((uint8_t *)(&p2->name) - (uint8_t *)p2));
memcpy(p1->name, "hello", 5);
memcpy(p2->name, "hello", 5);
free(p1);
free(p2);
printf("pass %s()\n", __FUNCTION__);
}
int main()
{
test_flexible_array();
return 0;
}
|
the_stack_data/1256147.c | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
struct Event {
int x;
int y;
int t;
};
int cmp_event(const void *a, const void *b) {
struct Event *e1 = a;
struct Event *e2 = b;
return (e1->t > e2->t) - (e1->t < e2->t);
}
int cmp_int(void* a, void* b){
return (*(int*)a - *(int*)b);
}
bool in(int val, int *arr){
for (int i = 0; i < sizeof(arr); i++) {
if (arr[i] == val) return true;
}
return false;
}
int main(){
int n, m;
scanf("%d %d", &n, &m);
int infected[n];
memset(infected, 0, n);
infected[0] = 1;
int infected_idx = 1;
struct Event events[m];
memset(events, 0, sizeof(events));
for (int i = 0; i<m; i++)
scanf("%d %d %d", &events[i].x, &events[i].y, &events[i].t);
qsort(events, m, sizeof(struct Event), cmp_event);
for (int i = 0; i<m; i++){
bool inf_x = in(events[i].x, infected);
bool inf_y = in(events[i].y, infected);
if (inf_x && inf_y) continue;
if (inf_x && !inf_y){
infected[infected_idx] = events[i].y;
infected_idx++;
}
if (!inf_x && inf_y){
infected[infected_idx] = events[i].x;
infected_idx++;
}
}
qsort(infected, infected_idx, sizeof(int), cmp_int);
for (int i = 0; i<infected_idx; i++)
printf("%d ", infected[i]);
printf("\n");
return 0;
}
|
the_stack_data/31386976.c | /* $NetBSD: wmemset.c,v 1.3 2012/06/25 22:32:46 abs Exp $ */
/*-
* Copyright (c)1999 Citrus Project,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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.
*
* citrus Id: wmemset.c,v 1.2 2000/12/20 14:08:31 itojun Exp
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: wmemset.c,v 1.3 2012/06/25 22:32:46 abs Exp $");
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <wchar.h>
wchar_t *
wmemset(wchar_t *s, wchar_t c, size_t n)
{
size_t i;
wchar_t *p;
_DIAGASSERT(s != NULL);
p = (wchar_t *)s;
for (i = 0; i < n; i++) {
*p = c;
p++;
}
return s;
}
|
the_stack_data/61075388.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
long long int a;
scanf("%d",&t);
while(t--)
{
scanf("%lld",&a);
printf("%lld\n",4294967295-a);
}
return 0;
}
|
the_stack_data/111078281.c | /* 2 Faça uma função recursiva que receba um número inteiro positivo N e imprima todos os números
naturais de 0 até N em ordem decrescente. */
#include <stdio.h>
void Exer02(int valor);
int main(void)
{
int valor;
printf("Insira um numero positivo: ");
scanf("%d", &valor);
Exer02(valor);
}
void Exer02(int valor)
{
if (valor != -1)
{
printf("%d ", valor);
Exer02(valor - 1);
}
}
|
the_stack_data/69500.c | /*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* 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 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 UNIVERSITY 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 UNIVERSITY 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.
*/
/*
Test suite.
This program takes the palindrome below and checks if it's
a palindrome or not. It will hopefully exhibit an interesting
page fault pattern.
The palindrome was taken from
http://www.cs.brown.edu/people/nfp/palindrome.html
This is not large enough to really stress the VM system, but
might be useful for testing in the early stages of the VM
assignment.
*/
/*
A man, a plan, a caret, a ban, a myriad, a sum, a lac, a liar, a hoop,
a pint, a catalpa, a gas, an oil, a bird, a yell, a vat, a caw, a pax,
a wag, a tax, a nay, a ram, a cap, a yam, a gay, a tsar, a wall, a
car, a luger, a ward, a bin, a woman, a vassal, a wolf, a tuna, a nit,
a pall, a fret, a watt, a bay, a daub, a tan, a cab, a datum, a gall,
a hat, a fag, a zap, a say, a jaw, a lay, a wet, a gallop, a tug, a
trot, a trap, a tram, a torr, a caper, a top, a tonk, a toll, a ball,
a fair, a sax, a minim, a tenor, a bass, a passer, a capital, a rut,
an amen, a ted, a cabal, a tang, a sun, an ass, a maw, a sag, a jam,
a dam, a sub, a salt, an axon, a sail, an ad, a wadi, a radian, a
room, a rood, a rip, a tad, a pariah, a revel, a reel, a reed, a pool,
a plug, a pin, a peek, a parabola, a dog, a pat, a cud, a nu, a fan,
a pal, a rum, a nod, an eta, a lag, an eel, a batik, a mug, a mot, a
nap, a maxim, a mood, a leek, a grub, a gob, a gel, a drab, a citadel,
a total, a cedar, a tap, a gag, a rat, a manor, a bar, a gal, a cola,
a pap, a yaw, a tab, a raj, a gab, a nag, a pagan, a bag, a jar, a
bat, a way, a papa, a local, a gar, a baron, a mat, a rag, a gap, a
tar, a decal, a tot, a led, a tic, a bard, a leg, a bog, a burg, a
keel, a doom, a mix, a map, an atom, a gum, a kit, a baleen, a gala,
a ten, a don, a mural, a pan, a faun, a ducat, a pagoda, a lob, a rap,
a keep, a nip, a gulp, a loop, a deer, a leer, a lever, a hair, a pad,
a tapir, a door, a moor, an aid, a raid, a wad, an alias, an ox, an
atlas, a bus, a madam, a jag, a saw, a mass, an anus, a gnat, a lab,
a cadet, an em, a natural, a tip, a caress, a pass, a baronet, a
minimax, a sari, a fall, a ballot, a knot, a pot, a rep, a carrot,
a mart, a part, a tort, a gut, a poll, a gateway, a law, a jay, a sap,
a zag, a fat, a hall, a gamut, a dab, a can, a tabu, a day, a batt,
a waterfall, a patina, a nut, a flow, a lass, a van, a mow, a nib,
a draw, a regular, a call, a war, a stay, a gam, a yap, a cam, a ray,
an ax, a tag, a wax, a paw, a cat, a valley, a drib, a lion, a saga,
a plat, a catnip, a pooh, a rail, a calamus, a dairyman, a bater,
a canal - Panama!
*/
/* The palindrome below is a quadruple concatenation of the above */
#include <stdio.h>
#include <string.h>
char palindrome[8000] =
"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil"
"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla"
"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya"
"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga"
"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora"
"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga"
"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada"
"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua"
"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda"
"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara"
"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa"
"localagarabaronamataragagapataradecalatotaledaticabardalegaboga"
"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala"
"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera"
"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam"
"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa"
"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta"
"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday"
"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla"
"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona"
"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama"
"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil"
"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla"
"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya"
"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga"
"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora"
"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga"
"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada"
"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua"
"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda"
"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara"
"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa"
"localagarabaronamataragagapataradecalatotaledaticabardalegaboga"
"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala"
"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera"
"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam"
"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa"
"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta"
"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday"
"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla"
"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona"
"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama"
"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil"
"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla"
"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya"
"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga"
"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora"
"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga"
"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada"
"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua"
"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda"
"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara"
"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa"
"localagarabaronamataragagapataradecalatotaledaticabardalegaboga"
"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala"
"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera"
"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam"
"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa"
"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta"
"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday"
"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla"
"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona"
"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama"
"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil"
"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla"
"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya"
"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga"
"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora"
"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga"
"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada"
"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua"
"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda"
"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara"
"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa"
"localagarabaronamataragagapataradecalatotaledaticabardalegaboga"
"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala"
"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera"
"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam"
"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa"
"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta"
"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday"
"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla"
"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona"
"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama";
int
main()
{
char *start, *end;
printf("Welcome to the palindrome tester!\n");
printf("I will take a large palindrome and test it.\n");
printf("Here it is:\n");
printf("%s\n", palindrome);
printf("Testing...");
/* skip to end */
end = palindrome+strlen(palindrome);
end--;
for (start = palindrome; start <= end; start++, end--) {
putchar('.');
if (*start != *end) {
printf("NOT a palindrome\n");
return 0;
}
}
printf("IS a palindrome\n");
return 0;
}
|
the_stack_data/67326013.c | /* { dg-do compile } */
/* { dg-options "-msse2 -O2" } */
/* { dg-require-effective-target ia32 } */
/* Make sure we know that mysinfp returns in %xmm0. */
double __attribute__((sseregparm)) mysin(void);
double __attribute__((sseregparm)) (*mysinfp)(void) = mysin;
double bar(double x)
{
return mysinfp();
}
/* { dg-final { scan-assembler "fldl" } } */
|
the_stack_data/50082.c | #include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *prev,*head,*p;
int n,i;
printf ("number of elements:");
scanf("%d",&n);
head=NULL;
for(i=0;i<n;i++)
{
p=malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else
prev->next=p;
prev=p;
}
return 0;
}
|
the_stack_data/170453767.c | /* Copyright (C) 1996, 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <unistd.h>
/* Synchronize at least the data part of a file with the underlying
media. */
int
fdatasync (int fildes)
{
return fsync (fildes);
}
|
the_stack_data/39948.c | #include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd = open(argv[1], O_RDONLY);
char buf[8192];
size_t nbytes = sizeof(buf);
ssize_t bytes_read;
int flr = 0;
int p2 = -1;
int i = 1;
while((bytes_read = read(fd, buf, nbytes)) > 0) {
for (int j = 0; j < bytes_read; j++, i++) {
char ch = buf[j];
switch (ch) {
case '(':
flr++;
break;
case ')':
flr--;
}
if (flr == -1 && p2 == -1) {
p2 = i;
}
}
}
printf("Part1: %d\n", flr);
printf("Part2: %d\n", p2);
close(fd);
return 0;
} |
the_stack_data/8185.c | //@ #include "map.gh"
/*@
//TODO: refactor this file
//1. remove map, use list of pairs instead.
//2. current version is not total. Therefore, well-definedness conditions need to be specified.
lemma void map_contains_spec<tk,tv>(map<tk,tv> m, tk k, tv v)
requires true;
ensures map_contains(m, k, v) == (map_contains_key(m, k) && map_get(m, k) == v);
{
switch(m) {
case mnil:
case mcons(k2, v2, t): map_contains_spec(t, k, v);
}
}
lemma void map_contains_functional<tk,tv>(map<tk,tv> m, tk k1, tv v1, tk k2, tv v2)
requires map_contains(m, k1, v1) && map_contains(m, k2, v2);
ensures (k1 == k2 ? v1 == v2 : true);
{
map_contains_spec(m, k1, v1);
map_contains_spec(m, k2, v2);
}
lemma void map_put_maintains_map_contains<tk,tv>(map<tk,tv> m, tk k1, tv v1, tk k2, tv v2)
requires k1 != k2;
ensures map_contains(map_put(m, k2, v2), k1, v1) == map_contains(m, k1, v1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3 && k2 != k3) {
map_put_maintains_map_contains(t, k1, v1, k2, v2);
}
}
}
lemma void map_put_causes_map_contains<tk,tv>(map<tk,tv> m, tk k1, tv v1)
requires true;
ensures map_contains(map_put(m, k1, v1), k1, v1) == true;
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3) {
map_put_causes_map_contains(t, k1, v1);
}
}
}
lemma void map_remove_maintains_map_contains<tk,tv>(map<tk,tv> m, tk k1, tv v1, tk k2)
requires k1 != k2;
ensures map_contains(map_remove(m, k2), k1, v1) == map_contains(m, k1, v1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3) {
map_remove_maintains_map_contains(t, k1, v1, k2);
}
}
}
lemma void map_put_invariant<tk,tv>(map<tk,tv> m, tk k1, tk k2, tv v2)
requires k1 != k2;
ensures map_get(map_put(m, k2, v2), k1) == map_get(m, k1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3 && k2 != k3) {
map_put_invariant(t, k1, k2, v2);
}
}
}
lemma void map_remove_invariant<tk,tv>(map<tk,tv> m, tk k1, tk k2)
requires k1 != k2;
ensures map_get(map_remove(m, k2), k1) == map_get(m, k1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k3 != k1) {
map_remove_invariant(t, k1, k2);
}
}
}
lemma void map_contains_key_after_put<tk,tv>(map<tk,tv> m, tk k1, tk k2, tv v2)
requires k1 != k2;
ensures map_contains_key(map_put(m, k2, v2), k1) == map_contains_key(m, k1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3 && k2 != k3) {
map_contains_key_after_put(t, k1, k2, v2);
}
}
}
lemma void map_contains_key_after_remove<tk,tv>(map<tk,tv> m, tk k1, tk k2)
requires k1 != k2;
ensures map_contains_key(map_remove(m, k2), k1) == map_contains_key(m, k1);
{
switch(m) {
case mnil:
case mcons(k3, v3, t):
if(k1 != k3) {
map_contains_key_after_remove(t, k1, k2);
}
}
}
lemma void map_contains_key_mem_map_keys<tk,tv>(map<tk,tv> m, tk k)
requires true;
ensures mem(k, map_keys(m)) == map_contains_key(m, k);
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_contains_key_mem_map_keys(t, k);
}
}
lemma void map_put_map_keys<tk,tv>(map<tk,tv> m, tk k, tv v)
requires !map_contains_key(m, k);
ensures map_keys(map_put(m, k, v)) == snoc(map_keys(m), k);
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_put_map_keys(t, k, v);
}
}
lemma void map_put_map_values<tk,tv>(map<tk,tv> m, tk k, tv v)
requires !map_contains_key(m, k);
ensures map_values(map_put(m, k, v)) == snoc(map_values(m), v);
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_put_map_values(t, k, v);
}
}
lemma void map_put_map_contains_key<tk,tv>(map<tk,tv> m, tk k, tv v)
requires true;
ensures map_contains_key(map_put(m, k, v), k) == true;
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_put_map_contains_key(t, k, v);
}
}
lemma void map_put_map_get<tk,tv>(map<tk,tv> m, tk k, tv v)
requires true;
ensures map_get(map_put(m, k, v), k) == v;
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_put_map_get(t, k, v);
}
}
lemma void map_remove_map_keys<tk,tv>(map<tk,tv> m, tk k)
requires true;
ensures map_keys(map_remove(m, k)) == remove(k, map_keys(m));
{
switch(m) {
case mnil:
case mcons(k2, v2, t):
map_remove_map_keys(t, k);
}
}
lemma void map_disjoint_mnil<tk,tv>(map<tk,tv> m)
requires true;
ensures map_disjoint(m, mnil) == true;
{
switch(m) {
case mnil:
case mcons(k, v, t):
map_disjoint_mnil(t);
}
}
lemma void map_alldisjoint_mnil<tk,tv>(list<map<tk,tv> > ms)
requires true;
ensures map_alldisjoint(mnil, ms) == true;
{
switch(ms) {
case nil:
case cons(h, t):
map_alldisjoint_mnil(t);
}
}
lemma void map_disjoint_cons_r<tk,tv>(map<tk,tv> m1, tk k, tv v, map<tk,tv> m2)
requires true;
ensures map_disjoint(m1, mcons(k, v, m2)) == (!map_contains_key(m1, k) && map_disjoint(m1, m2));
{
switch(m1) {
case mnil: map_disjoint_mnil(m2);
case mcons(k2,v2,t):
map_disjoint_cons_r(t, k, v, m2);
}
}
lemma void map_disjoint_sym<tk,tv>(map<tk,tv> m1, map<tk,tv> m2)
requires true;
ensures map_disjoint(m1, m2) == map_disjoint(m2, m1);
{
switch(m1) {
case mnil: map_disjoint_mnil(m2);
case mcons(k,v,t):
map_disjoint_sym(t, m2);
map_disjoint_cons_r(m2, k, v, t);
}
}
lemma void map_alldisjoint_snoc<tk,tv>(map<tk,tv> m, list<map<tk,tv> > ms, map<tk,tv> m2)
requires true;
ensures map_alldisjoint(m, snoc(ms, m2)) == (map_alldisjoint(m, ms) && map_disjoint(m, m2));
{
switch(ms) {
case nil:
case cons(h, t):
map_alldisjoint_snoc(m, t, m2);
}
}
lemma void maps_disjoint_snoc<tk,tv>(list<map<tk,tv> > ms, map<tk,tv> m)
requires true;
ensures maps_disjoint(snoc(ms, m)) == (maps_disjoint(ms) && map_alldisjoint(m, ms));
{
switch(ms) {
case nil:
case cons(h, t):
map_alldisjoint_snoc(h, t, m);
maps_disjoint_snoc(t, m);
map_disjoint_sym(m, h);
}
}
lemma void maps_disjunion_snoc_mnil<tk,tv>(list<map<tk,tv> > ms)
requires true;
ensures maps_disjunion(snoc(ms, mnil)) == maps_disjunion(ms);
{
switch(ms) {
case nil:
case cons(h, t):
maps_disjunion_snoc_mnil(t);
}
}
@*/
|
the_stack_data/1009259.c | int main()
{
int x;
void *p;
// from integer 0 to NULL
if(x==0)
{
p=x;
assert(p==0);
}
// the other way around
if(p==0)
{
x=p;
assert(x==0);
}
}
|
the_stack_data/40763980.c | // RUN: %clang_cc1 -mspeculative-load-hardening -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s -check-prefix=SLH
// RUN: %clang -mno-speculative-load-hardening -S -emit-llvm %s -o - | FileCheck %s -check-prefix=NOSLH
//
// Check that we set the attribute on each function.
int test1() {
return 42;
}
// SLH: @{{.*}}test1{{.*}}[[SLH:#[0-9]+]]
// SLH: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
// NOSLH: @{{.*}}test1{{.*}}[[NOSLH:#[0-9]+]]
// NOSLH-NOT: attributes [[NOSLH]] = { {{.*}}speculative_load_hardening{{.*}} }
|
the_stack_data/154827498.c | long long x, y, z;
void foo (void) {}
|
the_stack_data/117837.c | /*-
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.proprietary.c%
*/
#ifndef lint
static char sccsid[] = "@(#)open.c 8.1 (Berkeley) 06/04/93";
#endif /* not lint */
openvt(){
}
openpl(){
}
|
the_stack_data/97282.c | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement the "sqlite" command line
** utility for accessing SQLite databases.
*/
#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
/* This needs to come before any includes for MSVC compiler */
#define _CRT_SECURE_NO_WARNINGS
#endif
/*
** If requested, include the SQLite compiler options file for MSVC.
*/
#if defined(INCLUDE_MSVC_H)
#include "msvc.h"
#endif
/*
** No support for loadable extensions in VxWorks.
*/
#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
# define SQLITE_OMIT_LOAD_EXTENSION 1
#endif
/*
** Enable large-file support for fopen() and friends on unix.
*/
#ifndef SQLITE_DISABLE_LFS
# define _LARGE_FILE 1
# ifndef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "sqlite3.h"
#if SQLITE_USER_AUTHENTICATION
# include "sqlite3userauth.h"
#endif
#include <ctype.h>
#include <stdarg.h>
#if !defined(_WIN32) && !defined(WIN32)
# include <signal.h>
# if !defined(__RTP__) && !defined(_WRS_KERNEL)
# include <pwd.h>
# endif
# include <unistd.h>
# include <sys/types.h>
#endif
#if HAVE_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif
#if HAVE_EDITLINE
# include <editline/readline.h>
#endif
#if HAVE_EDITLINE || HAVE_READLINE
# define shell_add_history(X) add_history(X)
# define shell_read_history(X) read_history(X)
# define shell_write_history(X) write_history(X)
# define shell_stifle_history(X) stifle_history(X)
# define shell_readline(X) readline(X)
#elif HAVE_LINENOISE
# include "linenoise.h"
# define shell_add_history(X) linenoiseHistoryAdd(X)
# define shell_read_history(X) linenoiseHistoryLoad(X)
# define shell_write_history(X) linenoiseHistorySave(X)
# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
# define shell_readline(X) linenoise(X)
#else
# define shell_read_history(X)
# define shell_write_history(X)
# define shell_stifle_history(X)
# define SHELL_USE_LOCAL_GETLINE 1
#endif
#if defined(_WIN32) || defined(WIN32)
# include <io.h>
# include <fcntl.h>
# define isatty(h) _isatty(h)
# ifndef access
# define access(f,m) _access((f),(m))
# endif
# undef popen
# define popen _popen
# undef pclose
# define pclose _pclose
#else
/* Make sure isatty() has a prototype. */
extern int isatty(int);
# if !defined(__RTP__) && !defined(_WRS_KERNEL)
/* popen and pclose are not C89 functions and so are
** sometimes omitted from the <stdio.h> header */
extern FILE *popen(const char*,const char*);
extern int pclose(FILE*);
# else
# define SQLITE_OMIT_POPEN 1
# endif
#endif
#if defined(_WIN32_WCE)
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
* thus we always assume that we have a console. That can be
* overridden with the -batch command line option.
*/
#define isatty(x) 1
#endif
/* ctype macros that work with signed characters */
#define IsSpace(X) isspace((unsigned char)X)
#define IsDigit(X) isdigit((unsigned char)X)
#define ToLower(X) (char)tolower((unsigned char)X)
#if defined(_WIN32) || defined(WIN32)
#include <windows.h>
/* string conversion routines only needed on Win32 */
extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
#endif
/* On Windows, we normally run with output mode of TEXT so that \n characters
** are automatically translated into \r\n. However, this behavior needs
** to be disabled in some cases (ex: when generating CSV output and when
** rendering quoted strings that contain \n characters). The following
** routines take care of that.
*/
#if defined(_WIN32) || defined(WIN32)
static void setBinaryMode(FILE *file, int isOutput){
if( isOutput ) fflush(file);
_setmode(_fileno(file), _O_BINARY);
}
static void setTextMode(FILE *file, int isOutput){
if( isOutput ) fflush(file);
_setmode(_fileno(file), _O_TEXT);
}
#else
# define setBinaryMode(X,Y)
# define setTextMode(X,Y)
#endif
/* True if the timer is enabled */
static int enableTimer = 0;
/* Return the current wall-clock time */
static sqlite3_int64 timeOfDay(void){
static sqlite3_vfs *clockVfs = 0;
sqlite3_int64 t;
if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
clockVfs->xCurrentTimeInt64(clockVfs, &t);
}else{
double r;
clockVfs->xCurrentTime(clockVfs, &r);
t = (sqlite3_int64)(r*86400000.0);
}
return t;
}
#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
#include <sys/time.h>
#include <sys/resource.h>
/* VxWorks does not support getrusage() as far as we can determine */
#if defined(_WRS_KERNEL) || defined(__RTP__)
struct rusage {
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
};
#define getrusage(A,B) memset(B,0,sizeof(*B))
#endif
/* Saved resource information for the beginning of an operation */
static struct rusage sBegin; /* CPU time at start */
static sqlite3_int64 iBegin; /* Wall-clock time at start */
/*
** Begin timing an operation
*/
static void beginTimer(void){
if( enableTimer ){
getrusage(RUSAGE_SELF, &sBegin);
iBegin = timeOfDay();
}
}
/* Return the difference of two time_structs in seconds */
static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
(double)(pEnd->tv_sec - pStart->tv_sec);
}
/*
** Print the timing results.
*/
static void endTimer(void){
if( enableTimer ){
sqlite3_int64 iEnd = timeOfDay();
struct rusage sEnd;
getrusage(RUSAGE_SELF, &sEnd);
printf("Run Time: real %.3f user %f sys %f\n",
(iEnd - iBegin)*0.001,
timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
}
}
#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER 1
#elif (defined(_WIN32) || defined(WIN32))
/* Saved resource information for the beginning of an operation */
static HANDLE hProcess;
static FILETIME ftKernelBegin;
static FILETIME ftUserBegin;
static sqlite3_int64 ftWallBegin;
typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
LPFILETIME, LPFILETIME);
static GETPROCTIMES getProcessTimesAddr = NULL;
/*
** Check to see if we have timer support. Return 1 if necessary
** support found (or found previously).
*/
static int hasTimer(void){
if( getProcessTimesAddr ){
return 1;
} else {
/* GetProcessTimes() isn't supported in WIN95 and some other Windows
** versions. See if the version we are running on has it, and if it
** does, save off a pointer to it and the current process handle.
*/
hProcess = GetCurrentProcess();
if( hProcess ){
HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
if( NULL != hinstLib ){
getProcessTimesAddr =
(GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
if( NULL != getProcessTimesAddr ){
return 1;
}
FreeLibrary(hinstLib);
}
}
}
return 0;
}
/*
** Begin timing an operation
*/
static void beginTimer(void){
if( enableTimer && getProcessTimesAddr ){
FILETIME ftCreation, ftExit;
getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
&ftKernelBegin,&ftUserBegin);
ftWallBegin = timeOfDay();
}
}
/* Return the difference of two FILETIME structs in seconds */
static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
return (double) ((i64End - i64Start) / 10000000.0);
}
/*
** Print the timing results.
*/
static void endTimer(void){
if( enableTimer && getProcessTimesAddr){
FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
sqlite3_int64 ftWallEnd = timeOfDay();
getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
printf("Run Time: real %.3f user %f sys %f\n",
(ftWallEnd - ftWallBegin)*0.001,
timeDiff(&ftUserBegin, &ftUserEnd),
timeDiff(&ftKernelBegin, &ftKernelEnd));
}
}
#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER hasTimer()
#else
#define BEGIN_TIMER
#define END_TIMER
#define HAS_TIMER 0
#endif
/*
** Used to prevent warnings about unused parameters
*/
#define UNUSED_PARAMETER(x) (void)(x)
/*
** If the following flag is set, then command execution stops
** at an error if we are not interactive.
*/
static int bail_on_error = 0;
/*
** Threat stdin as an interactive input if the following variable
** is true. Otherwise, assume stdin is connected to a file or pipe.
*/
static int stdin_is_interactive = 1;
/*
** On Windows systems we have to know if standard output is a console
** in order to translate UTF-8 into MBCS. The following variable is
** true if translation is required.
*/
static int stdout_is_console = 1;
/*
** The following is the open SQLite database. We make a pointer
** to this database a static variable so that it can be accessed
** by the SIGINT handler to interrupt database processing.
*/
static sqlite3 *globalDb = 0;
/*
** True if an interrupt (Control-C) has been received.
*/
static volatile int seenInterrupt = 0;
/*
** This is the name of our program. It is set in main(), used
** in a number of other places, mostly for error messages.
*/
static char *Argv0;
/*
** Prompt strings. Initialized in main. Settable with
** .prompt main continue
*/
static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
/*
** Render output like fprintf(). Except, if the output is going to the
** console and if this is running on a Windows machine, translate the
** output from UTF-8 into MBCS.
*/
#if defined(_WIN32) || defined(WIN32)
void utf8_printf(FILE *out, const char *zFormat, ...){
va_list ap;
va_start(ap, zFormat);
if( stdout_is_console && (out==stdout || out==stderr) ){
char *z1 = sqlite3_vmprintf(zFormat, ap);
char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
sqlite3_free(z1);
fputs(z2, out);
sqlite3_free(z2);
}else{
vfprintf(out, zFormat, ap);
}
va_end(ap);
}
#elif !defined(utf8_printf)
# define utf8_printf fprintf
#endif
/*
** Render output like fprintf(). This should not be used on anything that
** includes string formatting (e.g. "%s").
*/
#if !defined(raw_printf)
# define raw_printf fprintf
#endif
/*
** Write I/O traces to the following stream.
*/
#ifdef SQLITE_ENABLE_IOTRACE
static FILE *iotrace = 0;
#endif
/*
** This routine works like printf in that its first argument is a
** format string and subsequent arguments are values to be substituted
** in place of % fields. The result of formatting this string
** is written to iotrace.
*/
#ifdef SQLITE_ENABLE_IOTRACE
static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
va_list ap;
char *z;
if( iotrace==0 ) return;
va_start(ap, zFormat);
z = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
utf8_printf(iotrace, "%s", z);
sqlite3_free(z);
}
#endif
/*
** Determines if a string is a number of not.
*/
static int isNumber(const char *z, int *realnum){
if( *z=='-' || *z=='+' ) z++;
if( !IsDigit(*z) ){
return 0;
}
z++;
if( realnum ) *realnum = 0;
while( IsDigit(*z) ){ z++; }
if( *z=='.' ){
z++;
if( !IsDigit(*z) ) return 0;
while( IsDigit(*z) ){ z++; }
if( realnum ) *realnum = 1;
}
if( *z=='e' || *z=='E' ){
z++;
if( *z=='+' || *z=='-' ) z++;
if( !IsDigit(*z) ) return 0;
while( IsDigit(*z) ){ z++; }
if( realnum ) *realnum = 1;
}
return *z==0;
}
/*
** A global char* and an SQL function to access its current value
** from within an SQL statement. This program used to use the
** sqlite_exec_printf() API to substitue a string into an SQL statement.
** The correct way to do this with sqlite3 is to use the bind API, but
** since the shell is built around the callback paradigm it would be a lot
** of work. Instead just use this hack, which is quite harmless.
*/
static const char *zShellStatic = 0;
static void shellstaticFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
assert( 0==argc );
assert( zShellStatic );
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
}
/*
** Compute a string length that is limited to what can be stored in
** lower 30 bits of a 32-bit signed integer.
*/
static int strlen30(const char *z){
const char *z2 = z;
while( *z2 ){ z2++; }
return 0x3fffffff & (int)(z2 - z);
}
/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text. NULL is returned at end of file, or if malloc()
** fails.
**
** If zLine is not NULL then it is a malloced buffer returned from
** a previous call to this routine that may be reused.
*/
static char *local_getline(char *zLine, FILE *in){
int nLine = zLine==0 ? 0 : 100;
int n = 0;
while( 1 ){
if( n+100>nLine ){
nLine = nLine*2 + 100;
zLine = realloc(zLine, nLine);
if( zLine==0 ) return 0;
}
if( fgets(&zLine[n], nLine - n, in)==0 ){
if( n==0 ){
free(zLine);
return 0;
}
zLine[n] = 0;
break;
}
while( zLine[n] ) n++;
if( n>0 && zLine[n-1]=='\n' ){
n--;
if( n>0 && zLine[n-1]=='\r' ) n--;
zLine[n] = 0;
break;
}
}
#if defined(_WIN32) || defined(WIN32)
/* For interactive input on Windows systems, translate the
** multi-byte characterset characters into UTF-8. */
if( stdin_is_interactive && in==stdin ){
char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
if( zTrans ){
int nTrans = strlen30(zTrans)+1;
if( nTrans>nLine ){
zLine = realloc(zLine, nTrans);
if( zLine==0 ){
sqlite3_free(zTrans);
return 0;
}
}
memcpy(zLine, zTrans, nTrans);
sqlite3_free(zTrans);
}
}
#endif /* defined(_WIN32) || defined(WIN32) */
return zLine;
}
/*
** Retrieve a single line of input text.
**
** If in==0 then read from standard input and prompt before each line.
** If isContinuation is true, then a continuation prompt is appropriate.
** If isContinuation is zero, then the main prompt should be used.
**
** If zPrior is not NULL then it is a buffer from a prior call to this
** routine that can be reused.
**
** The result is stored in space obtained from malloc() and must either
** be freed by the caller or else passed back into this routine via the
** zPrior argument for reuse.
*/
static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
char *zPrompt;
char *zResult;
if( in!=0 ){
zResult = local_getline(zPrior, in);
}else{
zPrompt = isContinuation ? continuePrompt : mainPrompt;
#if SHELL_USE_LOCAL_GETLINE
printf("%s", zPrompt);
fflush(stdout);
zResult = local_getline(zPrior, stdin);
#else
free(zPrior);
zResult = shell_readline(zPrompt);
if( zResult && *zResult ) shell_add_history(zResult);
#endif
}
return zResult;
}
#if defined(SQLITE_ENABLE_SESSION)
/*
** State information for a single open session
*/
typedef struct OpenSession OpenSession;
struct OpenSession {
char *zName; /* Symbolic name for this session */
int nFilter; /* Number of xFilter rejection GLOB patterns */
char **azFilter; /* Array of xFilter rejection GLOB patterns */
sqlite3_session *p; /* The open session */
};
#endif
/*
** Shell output mode information from before ".explain on",
** saved so that it can be restored by ".explain off"
*/
typedef struct SavedModeInfo SavedModeInfo;
struct SavedModeInfo {
int valid; /* Is there legit data in here? */
int mode; /* Mode prior to ".explain on" */
int showHeader; /* The ".header" setting prior to ".explain on" */
int colWidth[100]; /* Column widths prior to ".explain on" */
};
/*
** State information about the database connection is contained in an
** instance of the following structure.
*/
typedef struct ShellState ShellState;
struct ShellState {
sqlite3 *db; /* The database */
int echoOn; /* True to echo input commands */
int autoExplain; /* Automatically turn on .explain mode */
int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
int statsOn; /* True to display memory stats before each finalize */
int scanstatsOn; /* True to display scan stats before each finalize */
int countChanges; /* True to display change counts */
int backslashOn; /* Resolve C-style \x escapes in SQL input text */
int outCount; /* Revert to stdout when reaching zero */
int cnt; /* Number of records displayed so far */
FILE *out; /* Write results here */
FILE *traceOut; /* Output for sqlite3_trace() */
int nErr; /* Number of errors seen */
int mode; /* An output mode setting */
int cMode; /* temporary output mode for the current query */
int normalMode; /* Output mode before ".explain on" */
int writableSchema; /* True if PRAGMA writable_schema=ON */
int showHeader; /* True to show column names in List or Column mode */
int nCheck; /* Number of ".check" commands run */
unsigned shellFlgs; /* Various flags */
char *zDestTable; /* Name of destination table when MODE_Insert */
char zTestcase[30]; /* Name of current test case */
char colSeparator[20]; /* Column separator character for several modes */
char rowSeparator[20]; /* Row separator character for MODE_Ascii */
int colWidth[100]; /* Requested width of each column when in column mode*/
int actualWidth[100]; /* Actual width of each column */
char nullValue[20]; /* The text to print when a NULL comes back from
** the database */
char outfile[FILENAME_MAX]; /* Filename for *out */
const char *zDbFilename; /* name of the database file */
char *zFreeOnClose; /* Filename to free when closing */
const char *zVfs; /* Name of VFS to use */
sqlite3_stmt *pStmt; /* Current statement if any. */
FILE *pLog; /* Write log output here */
int *aiIndent; /* Array of indents used in MODE_Explain */
int nIndent; /* Size of array aiIndent[] */
int iIndent; /* Index of current op in aiIndent[] */
#if defined(SQLITE_ENABLE_SESSION)
int nSession; /* Number of active sessions */
OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
#endif
};
/*
** These are the allowed shellFlgs values
*/
#define SHFLG_Scratch 0x00001 /* The --scratch option is used */
#define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
#define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
/*
** These are the allowed modes.
*/
#define MODE_Line 0 /* One column per line. Blank line between records */
#define MODE_Column 1 /* One record per line in neat columns */
#define MODE_List 2 /* One record per line with a separator */
#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
#define MODE_Html 4 /* Generate an XHTML table */
#define MODE_Insert 5 /* Generate SQL "insert" statements */
#define MODE_Quote 6 /* Quote values as for SQL */
#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
#define MODE_Csv 8 /* Quote strings, numbers are plain */
#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
#define MODE_Pretty 11 /* Pretty-print schemas */
static const char *modeDescr[] = {
"line",
"column",
"list",
"semi",
"html",
"insert",
"quote",
"tcl",
"csv",
"explain",
"ascii",
"prettyprint",
};
/*
** These are the column/row/line separators used by the various
** import/export modes.
*/
#define SEP_Column "|"
#define SEP_Row "\n"
#define SEP_Tab "\t"
#define SEP_Space " "
#define SEP_Comma ","
#define SEP_CrLf "\r\n"
#define SEP_Unit "\x1F"
#define SEP_Record "\x1E"
/*
** Number of elements in an array
*/
#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
/*
** A callback for the sqlite3_log() interface.
*/
static void shellLog(void *pArg, int iErrCode, const char *zMsg){
ShellState *p = (ShellState*)pArg;
if( p->pLog==0 ) return;
utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
fflush(p->pLog);
}
/*
** Output the given string as a hex-encoded blob (eg. X'1234' )
*/
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
int i;
char *zBlob = (char *)pBlob;
raw_printf(out,"X'");
for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
raw_printf(out,"'");
}
/*
** Output the given string as a quoted string using SQL quoting conventions.
*/
static void output_quoted_string(FILE *out, const char *z){
int i;
int nSingle = 0;
setBinaryMode(out, 1);
for(i=0; z[i]; i++){
if( z[i]=='\'' ) nSingle++;
}
if( nSingle==0 ){
utf8_printf(out,"'%s'",z);
}else{
raw_printf(out,"'");
while( *z ){
for(i=0; z[i] && z[i]!='\''; i++){}
if( i==0 ){
raw_printf(out,"''");
z++;
}else if( z[i]=='\'' ){
utf8_printf(out,"%.*s''",i,z);
z += i+1;
}else{
utf8_printf(out,"%s",z);
break;
}
}
raw_printf(out,"'");
}
setTextMode(out, 1);
}
/*
** Output the given string as a quoted according to C or TCL quoting rules.
*/
static void output_c_string(FILE *out, const char *z){
unsigned int c;
fputc('"', out);
while( (c = *(z++))!=0 ){
if( c=='\\' ){
fputc(c, out);
fputc(c, out);
}else if( c=='"' ){
fputc('\\', out);
fputc('"', out);
}else if( c=='\t' ){
fputc('\\', out);
fputc('t', out);
}else if( c=='\n' ){
fputc('\\', out);
fputc('n', out);
}else if( c=='\r' ){
fputc('\\', out);
fputc('r', out);
}else if( !isprint(c&0xff) ){
raw_printf(out, "\\%03o", c&0xff);
}else{
fputc(c, out);
}
}
fputc('"', out);
}
/*
** Output the given string with characters that are special to
** HTML escaped.
*/
static void output_html_string(FILE *out, const char *z){
int i;
if( z==0 ) z = "";
while( *z ){
for(i=0; z[i]
&& z[i]!='<'
&& z[i]!='&'
&& z[i]!='>'
&& z[i]!='\"'
&& z[i]!='\'';
i++){}
if( i>0 ){
utf8_printf(out,"%.*s",i,z);
}
if( z[i]=='<' ){
raw_printf(out,"<");
}else if( z[i]=='&' ){
raw_printf(out,"&");
}else if( z[i]=='>' ){
raw_printf(out,">");
}else if( z[i]=='\"' ){
raw_printf(out,""");
}else if( z[i]=='\'' ){
raw_printf(out,"'");
}else{
break;
}
z += i + 1;
}
}
/*
** If a field contains any character identified by a 1 in the following
** array, then the string must be quoted for CSV.
*/
static const char needCsvQuote[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
/*
** Output a single term of CSV. Actually, p->colSeparator is used for
** the separator, which may or may not be a comma. p->nullValue is
** the null value. Strings are quoted if necessary. The separator
** is only issued if bSep is true.
*/
static void output_csv(ShellState *p, const char *z, int bSep){
FILE *out = p->out;
if( z==0 ){
utf8_printf(out,"%s",p->nullValue);
}else{
int i;
int nSep = strlen30(p->colSeparator);
for(i=0; z[i]; i++){
if( needCsvQuote[((unsigned char*)z)[i]]
|| (z[i]==p->colSeparator[0] &&
(nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
i = 0;
break;
}
}
if( i==0 ){
putc('"', out);
for(i=0; z[i]; i++){
if( z[i]=='"' ) putc('"', out);
putc(z[i], out);
}
putc('"', out);
}else{
utf8_printf(out, "%s", z);
}
}
if( bSep ){
utf8_printf(p->out, "%s", p->colSeparator);
}
}
#ifdef SIGINT
/*
** This routine runs when the user presses Ctrl-C
*/
static void interrupt_handler(int NotUsed){
UNUSED_PARAMETER(NotUsed);
seenInterrupt++;
if( seenInterrupt>2 ) exit(1);
if( globalDb ) sqlite3_interrupt(globalDb);
}
#endif
#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** When the ".auth ON" is set, the following authorizer callback is
** invoked. It always returns SQLITE_OK.
*/
static int shellAuth(
void *pClientData,
int op,
const char *zA1,
const char *zA2,
const char *zA3,
const char *zA4
){
ShellState *p = (ShellState*)pClientData;
static const char *azAction[] = { 0,
"CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
"CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
"CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
"DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
"DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
"DROP_TRIGGER", "DROP_VIEW", "INSERT",
"PRAGMA", "READ", "SELECT",
"TRANSACTION", "UPDATE", "ATTACH",
"DETACH", "ALTER_TABLE", "REINDEX",
"ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
"FUNCTION", "SAVEPOINT", "RECURSIVE"
};
int i;
const char *az[4];
az[0] = zA1;
az[1] = zA2;
az[2] = zA3;
az[3] = zA4;
utf8_printf(p->out, "authorizer: %s", azAction[op]);
for(i=0; i<4; i++){
raw_printf(p->out, " ");
if( az[i] ){
output_c_string(p->out, az[i]);
}else{
raw_printf(p->out, "NULL");
}
}
raw_printf(p->out, "\n");
return SQLITE_OK;
}
#endif
/*
** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
**
** This routine converts some CREATE TABLE statements for shadow tables
** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
*/
static void printSchemaLine(FILE *out, const char *z, const char *zTail){
if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
}else{
utf8_printf(out, "%s%s", z, zTail);
}
}
static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
char c = z[n];
z[n] = 0;
printSchemaLine(out, z, zTail);
z[n] = c;
}
/*
** This is the callback routine that the shell
** invokes for each row of a query result.
*/
static int shell_callback(
void *pArg,
int nArg, /* Number of result columns */
char **azArg, /* Text of each result column */
char **azCol, /* Column names */
int *aiType /* Column types */
){
int i;
ShellState *p = (ShellState*)pArg;
switch( p->cMode ){
case MODE_Line: {
int w = 5;
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
int len = strlen30(azCol[i] ? azCol[i] : "");
if( len>w ) w = len;
}
if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
for(i=0; i<nArg; i++){
utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
}
break;
}
case MODE_Explain:
case MODE_Column: {
static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
const int *colWidth;
int showHdr;
char *rowSep;
if( p->cMode==MODE_Column ){
colWidth = p->colWidth;
showHdr = p->showHeader;
rowSep = p->rowSeparator;
}else{
colWidth = aExplainWidths;
showHdr = 1;
rowSep = SEP_Row;
}
if( p->cnt++==0 ){
for(i=0; i<nArg; i++){
int w, n;
if( i<ArraySize(p->colWidth) ){
w = colWidth[i];
}else{
w = 0;
}
if( w==0 ){
w = strlen30(azCol[i] ? azCol[i] : "");
if( w<10 ) w = 10;
n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
if( w<n ) w = n;
}
if( i<ArraySize(p->actualWidth) ){
p->actualWidth[i] = w;
}
if( showHdr ){
if( w<0 ){
utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
i==nArg-1 ? rowSep : " ");
}else{
utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
i==nArg-1 ? rowSep : " ");
}
}
}
if( showHdr ){
for(i=0; i<nArg; i++){
int w;
if( i<ArraySize(p->actualWidth) ){
w = p->actualWidth[i];
if( w<0 ) w = -w;
}else{
w = 10;
}
utf8_printf(p->out,"%-*.*s%s",w,w,
"----------------------------------------------------------"
"----------------------------------------------------------",
i==nArg-1 ? rowSep : " ");
}
}
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
int w;
if( i<ArraySize(p->actualWidth) ){
w = p->actualWidth[i];
}else{
w = 10;
}
if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
w = strlen30(azArg[i]);
}
if( i==1 && p->aiIndent && p->pStmt ){
if( p->iIndent<p->nIndent ){
utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
}
p->iIndent++;
}
if( w<0 ){
utf8_printf(p->out,"%*.*s%s",-w,-w,
azArg[i] ? azArg[i] : p->nullValue,
i==nArg-1 ? rowSep : " ");
}else{
utf8_printf(p->out,"%-*.*s%s",w,w,
azArg[i] ? azArg[i] : p->nullValue,
i==nArg-1 ? rowSep : " ");
}
}
break;
}
case MODE_Semi: { /* .schema and .fullschema output */
printSchemaLine(p->out, azArg[0], ";\n");
break;
}
case MODE_Pretty: { /* .schema and .fullschema with --indent */
char *z;
int j;
int nParen = 0;
char cEnd = 0;
char c;
int nLine = 0;
assert( nArg==1 );
if( azArg[0]==0 ) break;
if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
|| sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
){
utf8_printf(p->out, "%s;\n", azArg[0]);
break;
}
z = sqlite3_mprintf("%s", azArg[0]);
j = 0;
for(i=0; IsSpace(z[i]); i++){}
for(; (c = z[i])!=0; i++){
if( IsSpace(c) ){
if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
}else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
j--;
}
z[j++] = c;
}
while( j>0 && IsSpace(z[j-1]) ){ j--; }
z[j] = 0;
if( strlen30(z)>=79 ){
for(i=j=0; (c = z[i])!=0; i++){
if( c==cEnd ){
cEnd = 0;
}else if( c=='"' || c=='\'' || c=='`' ){
cEnd = c;
}else if( c=='[' ){
cEnd = ']';
}else if( c=='(' ){
nParen++;
}else if( c==')' ){
nParen--;
if( nLine>0 && nParen==0 && j>0 ){
printSchemaLineN(p->out, z, j, "\n");
j = 0;
}
}
z[j++] = c;
if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
if( c=='\n' ) j--;
printSchemaLineN(p->out, z, j, "\n ");
j = 0;
nLine++;
while( IsSpace(z[i+1]) ){ i++; }
}
}
z[j] = 0;
}
printSchemaLine(p->out, z, ";\n");
sqlite3_free(z);
break;
}
case MODE_List: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
utf8_printf(p->out,"%s%s",azCol[i],
i==nArg-1 ? p->rowSeparator : p->colSeparator);
}
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
char *z = azArg[i];
if( z==0 ) z = p->nullValue;
utf8_printf(p->out, "%s", z);
if( i<nArg-1 ){
utf8_printf(p->out, "%s", p->colSeparator);
}else{
utf8_printf(p->out, "%s", p->rowSeparator);
}
}
break;
}
case MODE_Html: {
if( p->cnt++==0 && p->showHeader ){
raw_printf(p->out,"<TR>");
for(i=0; i<nArg; i++){
raw_printf(p->out,"<TH>");
output_html_string(p->out, azCol[i]);
raw_printf(p->out,"</TH>\n");
}
raw_printf(p->out,"</TR>\n");
}
if( azArg==0 ) break;
raw_printf(p->out,"<TR>");
for(i=0; i<nArg; i++){
raw_printf(p->out,"<TD>");
output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
raw_printf(p->out,"</TD>\n");
}
raw_printf(p->out,"</TR>\n");
break;
}
case MODE_Tcl: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
output_c_string(p->out,azCol[i] ? azCol[i] : "");
if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
}
utf8_printf(p->out, "%s", p->rowSeparator);
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
}
utf8_printf(p->out, "%s", p->rowSeparator);
break;
}
case MODE_Csv: {
setBinaryMode(p->out, 1);
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
}
utf8_printf(p->out, "%s", p->rowSeparator);
}
if( nArg>0 ){
for(i=0; i<nArg; i++){
output_csv(p, azArg[i], i<nArg-1);
}
utf8_printf(p->out, "%s", p->rowSeparator);
}
setTextMode(p->out, 1);
break;
}
case MODE_Quote:
case MODE_Insert: {
if( azArg==0 ) break;
if( p->cMode==MODE_Insert ){
utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
if( p->showHeader ){
raw_printf(p->out,"(");
for(i=0; i<nArg; i++){
char *zSep = i>0 ? ",": "";
utf8_printf(p->out, "%s%s", zSep, azCol[i]);
}
raw_printf(p->out,")");
}
raw_printf(p->out," VALUES(");
}else if( p->cnt==0 && p->showHeader ){
for(i=0; i<nArg; i++){
if( i>0 ) raw_printf(p->out, ",");
output_quoted_string(p->out, azCol[i]);
}
raw_printf(p->out,"\n");
}
p->cnt++;
for(i=0; i<nArg; i++){
char *zSep = i>0 ? ",": "";
if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
utf8_printf(p->out,"%sNULL",zSep);
}else if( aiType && aiType[i]==SQLITE_TEXT ){
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
output_quoted_string(p->out, azArg[i]);
}else if( aiType && (aiType[i]==SQLITE_INTEGER
|| aiType[i]==SQLITE_FLOAT) ){
utf8_printf(p->out,"%s%s",zSep, azArg[i]);
}else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
const void *pBlob = sqlite3_column_blob(p->pStmt, i);
int nBlob = sqlite3_column_bytes(p->pStmt, i);
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
output_hex_blob(p->out, pBlob, nBlob);
}else if( isNumber(azArg[i], 0) ){
utf8_printf(p->out,"%s%s",zSep, azArg[i]);
}else{
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
output_quoted_string(p->out, azArg[i]);
}
}
raw_printf(p->out,p->cMode==MODE_Quote?"\n":");\n");
break;
}
case MODE_Ascii: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
}
utf8_printf(p->out, "%s", p->rowSeparator);
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
}
utf8_printf(p->out, "%s", p->rowSeparator);
break;
}
}
return 0;
}
/*
** This is the callback routine that the SQLite library
** invokes for each row of a query result.
*/
static int callback(void *pArg, int nArg, char **azArg, char **azCol){
/* since we don't have type info, call the shell_callback with a NULL value */
return shell_callback(pArg, nArg, azArg, azCol, NULL);
}
/*
** Set the destination table field of the ShellState structure to
** the name of the table given. Escape any quote characters in the
** table name.
*/
static void set_table_name(ShellState *p, const char *zName){
int i, n;
int needQuote;
char *z;
if( p->zDestTable ){
free(p->zDestTable);
p->zDestTable = 0;
}
if( zName==0 ) return;
needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
for(i=n=0; zName[i]; i++, n++){
if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
needQuote = 1;
if( zName[i]=='\'' ) n++;
}
}
if( needQuote ) n += 2;
z = p->zDestTable = malloc( n+1 );
if( z==0 ){
raw_printf(stderr,"Error: out of memory\n");
exit(1);
}
n = 0;
if( needQuote ) z[n++] = '\'';
for(i=0; zName[i]; i++){
z[n++] = zName[i];
if( zName[i]=='\'' ) z[n++] = '\'';
}
if( needQuote ) z[n++] = '\'';
z[n] = 0;
}
/* zIn is either a pointer to a NULL-terminated string in memory obtained
** from malloc(), or a NULL pointer. The string pointed to by zAppend is
** added to zIn, and the result returned in memory obtained from malloc().
** zIn, if it was not NULL, is freed.
**
** If the third argument, quote, is not '\0', then it is used as a
** quote character for zAppend.
*/
static char *appendText(char *zIn, char const *zAppend, char quote){
int len;
int i;
int nAppend = strlen30(zAppend);
int nIn = (zIn?strlen30(zIn):0);
len = nAppend+nIn+1;
if( quote ){
len += 2;
for(i=0; i<nAppend; i++){
if( zAppend[i]==quote ) len++;
}
}
zIn = (char *)realloc(zIn, len);
if( !zIn ){
return 0;
}
if( quote ){
char *zCsr = &zIn[nIn];
*zCsr++ = quote;
for(i=0; i<nAppend; i++){
*zCsr++ = zAppend[i];
if( zAppend[i]==quote ) *zCsr++ = quote;
}
*zCsr++ = quote;
*zCsr++ = '\0';
assert( (zCsr-zIn)==len );
}else{
memcpy(&zIn[nIn], zAppend, nAppend);
zIn[len-1] = '\0';
}
return zIn;
}
/*
** Execute a query statement that will generate SQL output. Print
** the result columns, comma-separated, on a line and then add a
** semicolon terminator to the end of that line.
**
** If the number of columns is 1 and that column contains text "--"
** then write the semicolon on a separate line. That way, if a
** "--" comment occurs at the end of the statement, the comment
** won't consume the semicolon terminator.
*/
static int run_table_dump_query(
ShellState *p, /* Query context */
const char *zSelect, /* SELECT statement to extract content */
const char *zFirstRow /* Print before first row, if not NULL */
){
sqlite3_stmt *pSelect;
int rc;
int nResult;
int i;
const char *z;
rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
if( rc!=SQLITE_OK || !pSelect ){
utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
sqlite3_errmsg(p->db));
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
return rc;
}
rc = sqlite3_step(pSelect);
nResult = sqlite3_column_count(pSelect);
while( rc==SQLITE_ROW ){
if( zFirstRow ){
utf8_printf(p->out, "%s", zFirstRow);
zFirstRow = 0;
}
z = (const char*)sqlite3_column_text(pSelect, 0);
utf8_printf(p->out, "%s", z);
for(i=1; i<nResult; i++){
utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
}
if( z==0 ) z = "";
while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
if( z[0] ){
raw_printf(p->out, "\n;\n");
}else{
raw_printf(p->out, ";\n");
}
rc = sqlite3_step(pSelect);
}
rc = sqlite3_finalize(pSelect);
if( rc!=SQLITE_OK ){
utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
sqlite3_errmsg(p->db));
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
}
return rc;
}
/*
** Allocate space and save off current error string.
*/
static char *save_err_msg(
sqlite3 *db /* Database to query */
){
int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
char *zErrMsg = sqlite3_malloc64(nErrMsg);
if( zErrMsg ){
memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
}
return zErrMsg;
}
#ifdef __linux__
/*
** Attempt to display I/O stats on Linux using /proc/PID/io
*/
static void displayLinuxIoStats(FILE *out){
FILE *in;
char z[200];
sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
in = fopen(z, "rb");
if( in==0 ) return;
while( fgets(z, sizeof(z), in)!=0 ){
static const struct {
const char *zPattern;
const char *zDesc;
} aTrans[] = {
{ "rchar: ", "Bytes received by read():" },
{ "wchar: ", "Bytes sent to write():" },
{ "syscr: ", "Read() system calls:" },
{ "syscw: ", "Write() system calls:" },
{ "read_bytes: ", "Bytes read from storage:" },
{ "write_bytes: ", "Bytes written to storage:" },
{ "cancelled_write_bytes: ", "Cancelled write bytes:" },
};
int i;
for(i=0; i<ArraySize(aTrans); i++){
int n = (int)strlen(aTrans[i].zPattern);
if( strncmp(aTrans[i].zPattern, z, n)==0 ){
utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
break;
}
}
}
fclose(in);
}
#endif
/*
** Display memory stats.
*/
static int display_stats(
sqlite3 *db, /* Database to query */
ShellState *pArg, /* Pointer to ShellState */
int bReset /* True to reset the stats */
){
int iCur;
int iHiwtr;
if( pArg && pArg->out ){
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Memory Used: %d (max %d) bytes\n",
iCur, iHiwtr);
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n",
iCur, iHiwtr);
if( pArg->shellFlgs & SHFLG_Pagecache ){
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Number of Pcache Pages Used: %d (max %d) pages\n",
iCur, iHiwtr);
}
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
iCur, iHiwtr);
if( pArg->shellFlgs & SHFLG_Scratch ){
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Number of Scratch Allocations Used: %d (max %d)\n",
iCur, iHiwtr);
}
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
iCur, iHiwtr);
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Largest Allocation: %d bytes\n",
iHiwtr);
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n",
iHiwtr);
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n",
iHiwtr);
#ifdef YYTRACKMAXSTACKDEPTH
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n",
iCur, iHiwtr);
#endif
}
if( pArg && pArg->out && db ){
if( pArg->shellFlgs & SHFLG_Lookaside ){
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
&iCur, &iHiwtr, bReset);
raw_printf(pArg->out,
"Lookaside Slots Used: %d (max %d)\n",
iCur, iHiwtr);
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
&iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
iHiwtr);
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
&iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
iHiwtr);
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
&iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
iHiwtr);
}
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
iCur);
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
iCur);
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
iCur);
}
if( pArg && pArg->out && db && pArg->pStmt ){
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
bReset);
raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
}
#ifdef __linux__
displayLinuxIoStats(pArg->out);
#endif
/* Do not remove this machine readable comment: extra-stats-output-here */
return 0;
}
/*
** Display scan stats.
*/
static void display_scanstats(
sqlite3 *db, /* Database to query */
ShellState *pArg /* Pointer to ShellState */
){
#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
UNUSED_PARAMETER(db);
UNUSED_PARAMETER(pArg);
#else
int i, k, n, mx;
raw_printf(pArg->out, "-------- scanstats --------\n");
mx = 0;
for(k=0; k<=mx; k++){
double rEstLoop = 1.0;
for(i=n=0; 1; i++){
sqlite3_stmt *p = pArg->pStmt;
sqlite3_int64 nLoop, nVisit;
double rEst;
int iSid;
const char *zExplain;
if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
break;
}
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
if( iSid>mx ) mx = iSid;
if( iSid!=k ) continue;
if( n==0 ){
rEstLoop = (double)nLoop;
if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
}
n++;
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
rEstLoop *= rEst;
raw_printf(pArg->out,
" nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
);
}
}
raw_printf(pArg->out, "---------------------------\n");
#endif
}
/*
** Parameter azArray points to a zero-terminated array of strings. zStr
** points to a single nul-terminated string. Return non-zero if zStr
** is equal, according to strcmp(), to any of the strings in the array.
** Otherwise, return zero.
*/
static int str_in_array(const char *zStr, const char **azArray){
int i;
for(i=0; azArray[i]; i++){
if( 0==strcmp(zStr, azArray[i]) ) return 1;
}
return 0;
}
/*
** If compiled statement pSql appears to be an EXPLAIN statement, allocate
** and populate the ShellState.aiIndent[] array with the number of
** spaces each opcode should be indented before it is output.
**
** The indenting rules are:
**
** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
** all opcodes that occur between the p2 jump destination and the opcode
** itself by 2 spaces.
**
** * For each "Goto", if the jump destination is earlier in the program
** and ends on one of:
** Yield SeekGt SeekLt RowSetRead Rewind
** or if the P1 parameter is one instead of zero,
** then indent all opcodes between the earlier instruction
** and "Goto" by 2 spaces.
*/
static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
const char *zSql; /* The text of the SQL statement */
const char *z; /* Used to check if this is an EXPLAIN */
int *abYield = 0; /* True if op is an OP_Yield */
int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
int iOp; /* Index of operation in p->aiIndent[] */
const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
"NextIfOpen", "PrevIfOpen", 0 };
const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
"Rewind", 0 };
const char *azGoto[] = { "Goto", 0 };
/* Try to figure out if this is really an EXPLAIN statement. If this
** cannot be verified, return early. */
if( sqlite3_column_count(pSql)!=8 ){
p->cMode = p->mode;
return;
}
zSql = sqlite3_sql(pSql);
if( zSql==0 ) return;
for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
if( sqlite3_strnicmp(z, "explain", 7) ){
p->cMode = p->mode;
return;
}
for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
int i;
int iAddr = sqlite3_column_int(pSql, 0);
const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
/* Set p2 to the P2 field of the current opcode. Then, assuming that
** p2 is an instruction address, set variable p2op to the index of that
** instruction in the aiIndent[] array. p2 and p2op may be different if
** the current instruction is part of a sub-program generated by an
** SQL trigger or foreign key. */
int p2 = sqlite3_column_int(pSql, 3);
int p2op = (p2 + (iOp-iAddr));
/* Grow the p->aiIndent array as required */
if( iOp>=nAlloc ){
if( iOp==0 ){
/* Do further verfication that this is explain output. Abort if
** it is not */
static const char *explainCols[] = {
"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
int jj;
for(jj=0; jj<ArraySize(explainCols); jj++){
if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
p->cMode = p->mode;
sqlite3_reset(pSql);
return;
}
}
}
nAlloc += 100;
p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
}
abYield[iOp] = str_in_array(zOp, azYield);
p->aiIndent[iOp] = 0;
p->nIndent = iOp+1;
if( str_in_array(zOp, azNext) ){
for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
}
if( str_in_array(zOp, azGoto) && p2op<p->nIndent
&& (abYield[p2op] || sqlite3_column_int(pSql, 2))
){
for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
}
}
p->iIndent = 0;
sqlite3_free(abYield);
sqlite3_reset(pSql);
}
/*
** Free the array allocated by explain_data_prepare().
*/
static void explain_data_delete(ShellState *p){
sqlite3_free(p->aiIndent);
p->aiIndent = 0;
p->nIndent = 0;
p->iIndent = 0;
}
/*
** Disable and restore .wheretrace and .selecttrace settings.
*/
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
extern int sqlite3SelectTrace;
static int savedSelectTrace;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
extern int sqlite3WhereTrace;
static int savedWhereTrace;
#endif
static void disable_debug_trace_modes(void){
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
savedSelectTrace = sqlite3SelectTrace;
sqlite3SelectTrace = 0;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
savedWhereTrace = sqlite3WhereTrace;
sqlite3WhereTrace = 0;
#endif
}
static void restore_debug_trace_modes(void){
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
sqlite3SelectTrace = savedSelectTrace;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
sqlite3WhereTrace = savedWhereTrace;
#endif
}
/*
** Run a prepared statement
*/
static void exec_prepared_stmt(
ShellState *pArg, /* Pointer to ShellState */
sqlite3_stmt *pStmt, /* Statment to run */
int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
){
int rc;
/* perform the first step. this will tell us if we
** have a result set or not and how wide it is.
*/
rc = sqlite3_step(pStmt);
/* if we have a result set... */
if( SQLITE_ROW == rc ){
/* if we have a callback... */
if( xCallback ){
/* allocate space for col name ptr, value ptr, and type */
int nCol = sqlite3_column_count(pStmt);
void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
if( !pData ){
rc = SQLITE_NOMEM;
}else{
char **azCols = (char **)pData; /* Names of result columns */
char **azVals = &azCols[nCol]; /* Results */
int *aiTypes = (int *)&azVals[nCol]; /* Result types */
int i, x;
assert(sizeof(int) <= sizeof(char *));
/* save off ptrs to column names */
for(i=0; i<nCol; i++){
azCols[i] = (char *)sqlite3_column_name(pStmt, i);
}
do{
/* extract the data and data types */
for(i=0; i<nCol; i++){
aiTypes[i] = x = sqlite3_column_type(pStmt, i);
if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
azVals[i] = "";
}else{
azVals[i] = (char*)sqlite3_column_text(pStmt, i);
}
if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
rc = SQLITE_NOMEM;
break; /* from for */
}
} /* end for */
/* if data and types extracted successfully... */
if( SQLITE_ROW == rc ){
/* call the supplied callback with the result row data */
if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
rc = SQLITE_ABORT;
}else{
rc = sqlite3_step(pStmt);
}
}
} while( SQLITE_ROW == rc );
sqlite3_free(pData);
}
}else{
do{
rc = sqlite3_step(pStmt);
} while( rc == SQLITE_ROW );
}
}
}
/*
** Execute a statement or set of statements. Print
** any result rows/columns depending on the current mode
** set via the supplied callback.
**
** This is very similar to SQLite's built-in sqlite3_exec()
** function except it takes a slightly different callback
** and callback data argument.
*/
static int shell_exec(
sqlite3 *db, /* An open database */
const char *zSql, /* SQL to be evaluated */
int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
/* (not the same as sqlite3_exec) */
ShellState *pArg, /* Pointer to ShellState */
char **pzErrMsg /* Error msg written here */
){
sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
int rc = SQLITE_OK; /* Return Code */
int rc2;
const char *zLeftover; /* Tail of unprocessed SQL */
if( pzErrMsg ){
*pzErrMsg = NULL;
}
while( zSql[0] && (SQLITE_OK == rc) ){
static const char *zStmtSql;
rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
if( SQLITE_OK != rc ){
if( pzErrMsg ){
*pzErrMsg = save_err_msg(db);
}
}else{
if( !pStmt ){
/* this happens for a comment or white-space */
zSql = zLeftover;
while( IsSpace(zSql[0]) ) zSql++;
continue;
}
zStmtSql = sqlite3_sql(pStmt);
if( zStmtSql==0 ) zStmtSql = "";
while( IsSpace(zStmtSql[0]) ) zStmtSql++;
/* save off the prepared statment handle and reset row count */
if( pArg ){
pArg->pStmt = pStmt;
pArg->cnt = 0;
}
/* echo the sql statement if echo on */
if( pArg && pArg->echoOn ){
utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
}
/* Show the EXPLAIN QUERY PLAN if .eqp is on */
if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
sqlite3_stmt *pExplain;
char *zEQP;
disable_debug_trace_modes();
zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
if( rc==SQLITE_OK ){
while( sqlite3_step(pExplain)==SQLITE_ROW ){
raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
}
}
sqlite3_finalize(pExplain);
sqlite3_free(zEQP);
if( pArg->autoEQP>=2 ){
/* Also do an EXPLAIN for ".eqp full" mode */
zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
if( rc==SQLITE_OK ){
pArg->cMode = MODE_Explain;
explain_data_prepare(pArg, pExplain);
exec_prepared_stmt(pArg, pExplain, xCallback);
explain_data_delete(pArg);
}
sqlite3_finalize(pExplain);
sqlite3_free(zEQP);
}
restore_debug_trace_modes();
}
if( pArg ){
pArg->cMode = pArg->mode;
if( pArg->autoExplain
&& sqlite3_column_count(pStmt)==8
&& sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
){
pArg->cMode = MODE_Explain;
}
/* If the shell is currently in ".explain" mode, gather the extra
** data required to add indents to the output.*/
if( pArg->cMode==MODE_Explain ){
explain_data_prepare(pArg, pStmt);
}
}
exec_prepared_stmt(pArg, pStmt, xCallback);
explain_data_delete(pArg);
/* print usage stats if stats on */
if( pArg && pArg->statsOn ){
display_stats(db, pArg, 0);
}
/* print loop-counters if required */
if( pArg && pArg->scanstatsOn ){
display_scanstats(db, pArg);
}
/* Finalize the statement just executed. If this fails, save a
** copy of the error message. Otherwise, set zSql to point to the
** next statement to execute. */
rc2 = sqlite3_finalize(pStmt);
if( rc!=SQLITE_NOMEM ) rc = rc2;
if( rc==SQLITE_OK ){
zSql = zLeftover;
while( IsSpace(zSql[0]) ) zSql++;
}else if( pzErrMsg ){
*pzErrMsg = save_err_msg(db);
}
/* clear saved stmt handle */
if( pArg ){
pArg->pStmt = NULL;
}
}
} /* end while */
return rc;
}
/*
** This is a different callback routine used for dumping the database.
** Each row received by this callback consists of a table name,
** the table type ("index" or "table") and SQL to create the table.
** This routine should print text sufficient to recreate the table.
*/
static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
int rc;
const char *zTable;
const char *zType;
const char *zSql;
const char *zPrepStmt = 0;
ShellState *p = (ShellState *)pArg;
UNUSED_PARAMETER(azCol);
if( nArg!=3 ) return 1;
zTable = azArg[0];
zType = azArg[1];
zSql = azArg[2];
if( strcmp(zTable, "sqlite_sequence")==0 ){
zPrepStmt = "DELETE FROM sqlite_sequence;\n";
}else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
raw_printf(p->out, "ANALYZE sqlite_master;\n");
}else if( strncmp(zTable, "sqlite_", 7)==0 ){
return 0;
}else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
char *zIns;
if( !p->writableSchema ){
raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
p->writableSchema = 1;
}
zIns = sqlite3_mprintf(
"INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
"VALUES('table','%q','%q',0,'%q');",
zTable, zTable, zSql);
utf8_printf(p->out, "%s\n", zIns);
sqlite3_free(zIns);
return 0;
}else{
printSchemaLine(p->out, zSql, ";\n");
}
if( strcmp(zType, "table")==0 ){
sqlite3_stmt *pTableInfo = 0;
char *zSelect = 0;
char *zTableInfo = 0;
char *zTmp = 0;
int nRow = 0;
zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
zTableInfo = appendText(zTableInfo, zTable, '"');
zTableInfo = appendText(zTableInfo, ");", 0);
rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
free(zTableInfo);
if( rc!=SQLITE_OK || !pTableInfo ){
return 1;
}
zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
/* Always quote the table name, even if it appears to be pure ascii,
** in case it is a keyword. Ex: INSERT INTO "table" ... */
zTmp = appendText(zTmp, zTable, '"');
if( zTmp ){
zSelect = appendText(zSelect, zTmp, '\'');
free(zTmp);
}
zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
rc = sqlite3_step(pTableInfo);
while( rc==SQLITE_ROW ){
const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
zSelect = appendText(zSelect, "quote(", 0);
zSelect = appendText(zSelect, zText, '"');
rc = sqlite3_step(pTableInfo);
if( rc==SQLITE_ROW ){
zSelect = appendText(zSelect, "), ", 0);
}else{
zSelect = appendText(zSelect, ") ", 0);
}
nRow++;
}
rc = sqlite3_finalize(pTableInfo);
if( rc!=SQLITE_OK || nRow==0 ){
free(zSelect);
return 1;
}
zSelect = appendText(zSelect, "|| ')' FROM ", 0);
zSelect = appendText(zSelect, zTable, '"');
rc = run_table_dump_query(p, zSelect, zPrepStmt);
if( rc==SQLITE_CORRUPT ){
zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
run_table_dump_query(p, zSelect, 0);
}
free(zSelect);
}
return 0;
}
/*
** Run zQuery. Use dump_callback() as the callback routine so that
** the contents of the query are output as SQL statements.
**
** If we get a SQLITE_CORRUPT error, rerun the query after appending
** "ORDER BY rowid DESC" to the end.
*/
static int run_schema_dump_query(
ShellState *p,
const char *zQuery
){
int rc;
char *zErr = 0;
rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
if( rc==SQLITE_CORRUPT ){
char *zQ2;
int len = strlen30(zQuery);
raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
if( zErr ){
utf8_printf(p->out, "/****** %s ******/\n", zErr);
sqlite3_free(zErr);
zErr = 0;
}
zQ2 = malloc( len+100 );
if( zQ2==0 ) return rc;
sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
if( rc ){
utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
}else{
rc = SQLITE_CORRUPT;
}
sqlite3_free(zErr);
free(zQ2);
}
return rc;
}
/*
** Text of a help message
*/
static char zHelp[] =
#ifndef SQLITE_OMIT_AUTHORIZATION
".auth ON|OFF Show authorizer callbacks\n"
#endif
".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
".bail on|off Stop after hitting an error. Default OFF\n"
".binary on|off Turn binary output on or off. Default OFF\n"
".changes on|off Show number of rows changed by SQL\n"
".check GLOB Fail if output since .testcase does not match\n"
".clone NEWDB Clone data into NEWDB from the existing database\n"
".databases List names and files of attached databases\n"
".dbinfo ?DB? Show status information about the database\n"
".dump ?TABLE? ... Dump the database in an SQL text format\n"
" If TABLE specified, only dump tables matching\n"
" LIKE pattern TABLE.\n"
".echo on|off Turn command echo on or off\n"
".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
".exit Exit this program\n"
".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
".headers on|off Turn display of headers on or off\n"
".help Show this message\n"
".import FILE TABLE Import data from FILE into TABLE\n"
#ifndef SQLITE_OMIT_TEST_CONTROL
".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
#endif
".indexes ?TABLE? Show names of all indexes\n"
" If TABLE specified, only show indexes for tables\n"
" matching LIKE pattern TABLE.\n"
#ifdef SQLITE_ENABLE_IOTRACE
".iotrace FILE Enable I/O diagnostic logging to FILE\n"
#endif
".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
".lint OPTIONS Report potential schema issues. Options:\n"
" fkey-indexes Find missing foreign key indexes\n"
#ifndef SQLITE_OMIT_LOAD_EXTENSION
".load FILE ?ENTRY? Load an extension library\n"
#endif
".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
" ascii Columns/rows delimited by 0x1F and 0x1E\n"
" csv Comma-separated values\n"
" column Left-aligned columns. (See .width)\n"
" html HTML <table> code\n"
" insert SQL insert statements for TABLE\n"
" line One value per line\n"
" list Values delimited by .separator strings\n"
" quote Escape answers as for SQL\n"
" tabs Tab-separated values\n"
" tcl TCL list elements\n"
".nullvalue STRING Use STRING in place of NULL values\n"
".once FILENAME Output for the next SQL command only to FILENAME\n"
".open ?--new? ?FILE? Close existing database and reopen FILE\n"
" The --new starts with an empty file\n"
".output ?FILENAME? Send output to FILENAME or stdout\n"
".print STRING... Print literal STRING\n"
".prompt MAIN CONTINUE Replace the standard prompts\n"
".quit Exit this program\n"
".read FILENAME Execute SQL in FILENAME\n"
".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
".save FILE Write in-memory database into FILE\n"
".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
" Add --indent for pretty-printing\n"
".separator COL ?ROW? Change the column separator and optionally the row\n"
" separator for both the output mode and .import\n"
#if defined(SQLITE_ENABLE_SESSION)
".session CMD ... Create or control sessions\n"
#endif
".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
".show Show the current values for various settings\n"
".stats ?on|off? Show stats or turn stats on or off\n"
".system CMD ARGS... Run CMD ARGS... in a system shell\n"
".tables ?TABLE? List names of tables\n"
" If TABLE specified, only list tables matching\n"
" LIKE pattern TABLE.\n"
".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
".timeout MS Try opening locked tables for MS milliseconds\n"
".timer on|off Turn SQL timer on or off\n"
".trace FILE|off Output each SQL statement as it is run\n"
".vfsinfo ?AUX? Information about the top-level VFS\n"
".vfslist List all available VFSes\n"
".vfsname ?AUX? Print the name of the VFS stack\n"
".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
" Negative values right-justify\n"
;
#if defined(SQLITE_ENABLE_SESSION)
/*
** Print help information for the ".sessions" command
*/
void session_help(ShellState *p){
raw_printf(p->out,
".session ?NAME? SUBCOMMAND ?ARGS...?\n"
"If ?NAME? is omitted, the first defined session is used.\n"
"Subcommands:\n"
" attach TABLE Attach TABLE\n"
" changeset FILE Write a changeset into FILE\n"
" close Close one session\n"
" enable ?BOOLEAN? Set or query the enable bit\n"
" filter GLOB... Reject tables matching GLOBs\n"
" indirect ?BOOLEAN? Mark or query the indirect status\n"
" isempty Query whether the session is empty\n"
" list List currently open session names\n"
" open DB NAME Open a new session on DB\n"
" patchset FILE Write a patchset into FILE\n"
);
}
#endif
/* Forward reference */
static int process_input(ShellState *p, FILE *in);
/*
** Read the content of file zName into memory obtained from sqlite3_malloc64()
** and return a pointer to the buffer. The caller is responsible for freeing
** the memory.
**
** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
** read.
**
** For convenience, a nul-terminator byte is always appended to the data read
** from the file before the buffer is returned. This byte is not included in
** the final value of (*pnByte), if applicable.
**
** NULL is returned if any error is encountered. The final value of *pnByte
** is undefined in this case.
*/
static char *readFile(const char *zName, int *pnByte){
FILE *in = fopen(zName, "rb");
long nIn;
size_t nRead;
char *pBuf;
if( in==0 ) return 0;
fseek(in, 0, SEEK_END);
nIn = ftell(in);
rewind(in);
pBuf = sqlite3_malloc64( nIn+1 );
if( pBuf==0 ) return 0;
nRead = fread(pBuf, nIn, 1, in);
fclose(in);
if( nRead!=1 ){
sqlite3_free(pBuf);
return 0;
}
pBuf[nIn] = 0;
if( pnByte ) *pnByte = nIn;
return pBuf;
}
/*
** Implementation of the "readfile(X)" SQL function. The entire content
** of the file named X is read and returned as a BLOB. NULL is returned
** if the file does not exist or is unreadable.
*/
static void readfileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const char *zName;
void *pBuf;
int nBuf;
UNUSED_PARAMETER(argc);
zName = (const char*)sqlite3_value_text(argv[0]);
if( zName==0 ) return;
pBuf = readFile(zName, &nBuf);
if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
}
/*
** Implementation of the "writefile(X,Y)" SQL function. The argument Y
** is written into file X. The number of bytes written is returned. Or
** NULL is returned if something goes wrong, such as being unable to open
** file X for writing.
*/
static void writefileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
FILE *out;
const char *z;
sqlite3_int64 rc;
const char *zFile;
UNUSED_PARAMETER(argc);
zFile = (const char*)sqlite3_value_text(argv[0]);
if( zFile==0 ) return;
out = fopen(zFile, "wb");
if( out==0 ) return;
z = (const char*)sqlite3_value_blob(argv[1]);
if( z==0 ){
rc = 0;
}else{
rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
}
fclose(out);
sqlite3_result_int64(context, rc);
}
#if defined(SQLITE_ENABLE_SESSION)
/*
** Close a single OpenSession object and release all of its associated
** resources.
*/
static void session_close(OpenSession *pSession){
int i;
sqlite3session_delete(pSession->p);
sqlite3_free(pSession->zName);
for(i=0; i<pSession->nFilter; i++){
sqlite3_free(pSession->azFilter[i]);
}
sqlite3_free(pSession->azFilter);
memset(pSession, 0, sizeof(OpenSession));
}
#endif
/*
** Close all OpenSession objects and release all associated resources.
*/
#if defined(SQLITE_ENABLE_SESSION)
static void session_close_all(ShellState *p){
int i;
for(i=0; i<p->nSession; i++){
session_close(&p->aSession[i]);
}
p->nSession = 0;
}
#else
# define session_close_all(X)
#endif
/*
** Implementation of the xFilter function for an open session. Omit
** any tables named by ".session filter" but let all other table through.
*/
#if defined(SQLITE_ENABLE_SESSION)
static int session_filter(void *pCtx, const char *zTab){
OpenSession *pSession = (OpenSession*)pCtx;
int i;
for(i=0; i<pSession->nFilter; i++){
if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
}
return 1;
}
#endif
/*
** Make sure the database is open. If it is not, then open it. If
** the database fails to open, print an error message and exit.
*/
static void open_db(ShellState *p, int keepAlive){
if( p->db==0 ){
sqlite3_initialize();
sqlite3_open(p->zDbFilename, &p->db);
globalDb = p->db;
if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
shellstaticFunc, 0, 0);
}
if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
p->zDbFilename, sqlite3_errmsg(p->db));
if( keepAlive ) return;
exit(1);
}
#ifndef SQLITE_OMIT_LOAD_EXTENSION
sqlite3_enable_load_extension(p->db, 1);
#endif
sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
readfileFunc, 0, 0);
sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
writefileFunc, 0, 0);
}
}
/*
** Do C-language style dequoting.
**
** \a -> alarm
** \b -> backspace
** \t -> tab
** \n -> newline
** \v -> vertical tab
** \f -> form feed
** \r -> carriage return
** \s -> space
** \" -> "
** \' -> '
** \\ -> backslash
** \NNN -> ascii character NNN in octal
*/
static void resolve_backslashes(char *z){
int i, j;
char c;
while( *z && *z!='\\' ) z++;
for(i=j=0; (c = z[i])!=0; i++, j++){
if( c=='\\' && z[i+1]!=0 ){
c = z[++i];
if( c=='a' ){
c = '\a';
}else if( c=='b' ){
c = '\b';
}else if( c=='t' ){
c = '\t';
}else if( c=='n' ){
c = '\n';
}else if( c=='v' ){
c = '\v';
}else if( c=='f' ){
c = '\f';
}else if( c=='r' ){
c = '\r';
}else if( c=='"' ){
c = '"';
}else if( c=='\'' ){
c = '\'';
}else if( c=='\\' ){
c = '\\';
}else if( c>='0' && c<='7' ){
c -= '0';
if( z[i+1]>='0' && z[i+1]<='7' ){
i++;
c = (c<<3) + z[i] - '0';
if( z[i+1]>='0' && z[i+1]<='7' ){
i++;
c = (c<<3) + z[i] - '0';
}
}
}
}
z[j] = c;
}
if( j<i ) z[j] = 0;
}
/*
** Return the value of a hexadecimal digit. Return -1 if the input
** is not a hex digit.
*/
static int hexDigitValue(char c){
if( c>='0' && c<='9' ) return c - '0';
if( c>='a' && c<='f' ) return c - 'a' + 10;
if( c>='A' && c<='F' ) return c - 'A' + 10;
return -1;
}
/*
** Interpret zArg as an integer value, possibly with suffixes.
*/
static sqlite3_int64 integerValue(const char *zArg){
sqlite3_int64 v = 0;
static const struct { char *zSuffix; int iMult; } aMult[] = {
{ "KiB", 1024 },
{ "MiB", 1024*1024 },
{ "GiB", 1024*1024*1024 },
{ "KB", 1000 },
{ "MB", 1000000 },
{ "GB", 1000000000 },
{ "K", 1000 },
{ "M", 1000000 },
{ "G", 1000000000 },
};
int i;
int isNeg = 0;
if( zArg[0]=='-' ){
isNeg = 1;
zArg++;
}else if( zArg[0]=='+' ){
zArg++;
}
if( zArg[0]=='0' && zArg[1]=='x' ){
int x;
zArg += 2;
while( (x = hexDigitValue(zArg[0]))>=0 ){
v = (v<<4) + x;
zArg++;
}
}else{
while( IsDigit(zArg[0]) ){
v = v*10 + zArg[0] - '0';
zArg++;
}
}
for(i=0; i<ArraySize(aMult); i++){
if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
v *= aMult[i].iMult;
break;
}
}
return isNeg? -v : v;
}
/*
** Interpret zArg as either an integer or a boolean value. Return 1 or 0
** for TRUE and FALSE. Return the integer value if appropriate.
*/
static int booleanValue(char *zArg){
int i;
if( zArg[0]=='0' && zArg[1]=='x' ){
for(i=2; hexDigitValue(zArg[i])>=0; i++){}
}else{
for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
}
if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
return 1;
}
if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
return 0;
}
utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
zArg);
return 0;
}
/*
** Close an output file, assuming it is not stderr or stdout
*/
static void output_file_close(FILE *f){
if( f && f!=stdout && f!=stderr ) fclose(f);
}
/*
** Try to open an output file. The names "stdout" and "stderr" are
** recognized and do the right thing. NULL is returned if the output
** filename is "off".
*/
static FILE *output_file_open(const char *zFile){
FILE *f;
if( strcmp(zFile,"stdout")==0 ){
f = stdout;
}else if( strcmp(zFile, "stderr")==0 ){
f = stderr;
}else if( strcmp(zFile, "off")==0 ){
f = 0;
}else{
f = fopen(zFile, "wb");
if( f==0 ){
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
}
}
return f;
}
#if !defined(SQLITE_UNTESTABLE)
#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
/*
** A routine for handling output from sqlite3_trace().
*/
static int sql_trace_callback(
unsigned mType,
void *pArg,
void *pP,
void *pX
){
FILE *f = (FILE*)pArg;
UNUSED_PARAMETER(mType);
UNUSED_PARAMETER(pP);
if( f ){
const char *z = (const char*)pX;
int i = (int)strlen(z);
while( i>0 && z[i-1]==';' ){ i--; }
utf8_printf(f, "%.*s;\n", i, z);
}
return 0;
}
#endif
#endif
/*
** A no-op routine that runs with the ".breakpoint" doc-command. This is
** a useful spot to set a debugger breakpoint.
*/
static void test_breakpoint(void){
static int nCall = 0;
nCall++;
}
/*
** An object used to read a CSV and other files for import.
*/
typedef struct ImportCtx ImportCtx;
struct ImportCtx {
const char *zFile; /* Name of the input file */
FILE *in; /* Read the CSV text from this input stream */
char *z; /* Accumulated text for a field */
int n; /* Number of bytes in z */
int nAlloc; /* Space allocated for z[] */
int nLine; /* Current line number */
int cTerm; /* Character that terminated the most recent field */
int cColSep; /* The column separator character. (Usually ",") */
int cRowSep; /* The row separator character. (Usually "\n") */
};
/* Append a single byte to z[] */
static void import_append_char(ImportCtx *p, int c){
if( p->n+1>=p->nAlloc ){
p->nAlloc += p->nAlloc + 100;
p->z = sqlite3_realloc64(p->z, p->nAlloc);
if( p->z==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
}
p->z[p->n++] = (char)c;
}
/* Read a single field of CSV text. Compatible with rfc4180 and extended
** with the option of having a separator other than ",".
**
** + Input comes from p->in.
** + Store results in p->z of length p->n. Space to hold p->z comes
** from sqlite3_malloc64().
** + Use p->cSep as the column separator. The default is ",".
** + Use p->rSep as the row separator. The default is "\n".
** + Keep track of the line number in p->nLine.
** + Store the character that terminates the field in p->cTerm. Store
** EOF on end-of-file.
** + Report syntax errors on stderr
*/
static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
int c;
int cSep = p->cColSep;
int rSep = p->cRowSep;
p->n = 0;
c = fgetc(p->in);
if( c==EOF || seenInterrupt ){
p->cTerm = EOF;
return 0;
}
if( c=='"' ){
int pc, ppc;
int startLine = p->nLine;
int cQuote = c;
pc = ppc = 0;
while( 1 ){
c = fgetc(p->in);
if( c==rSep ) p->nLine++;
if( c==cQuote ){
if( pc==cQuote ){
pc = 0;
continue;
}
}
if( (c==cSep && pc==cQuote)
|| (c==rSep && pc==cQuote)
|| (c==rSep && pc=='\r' && ppc==cQuote)
|| (c==EOF && pc==cQuote)
){
do{ p->n--; }while( p->z[p->n]!=cQuote );
p->cTerm = c;
break;
}
if( pc==cQuote && c!='\r' ){
utf8_printf(stderr, "%s:%d: unescaped %c character\n",
p->zFile, p->nLine, cQuote);
}
if( c==EOF ){
utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
p->zFile, startLine, cQuote);
p->cTerm = c;
break;
}
import_append_char(p, c);
ppc = pc;
pc = c;
}
}else{
while( c!=EOF && c!=cSep && c!=rSep ){
import_append_char(p, c);
c = fgetc(p->in);
}
if( c==rSep ){
p->nLine++;
if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
}
p->cTerm = c;
}
if( p->z ) p->z[p->n] = 0;
return p->z;
}
/* Read a single field of ASCII delimited text.
**
** + Input comes from p->in.
** + Store results in p->z of length p->n. Space to hold p->z comes
** from sqlite3_malloc64().
** + Use p->cSep as the column separator. The default is "\x1F".
** + Use p->rSep as the row separator. The default is "\x1E".
** + Keep track of the row number in p->nLine.
** + Store the character that terminates the field in p->cTerm. Store
** EOF on end-of-file.
** + Report syntax errors on stderr
*/
static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
int c;
int cSep = p->cColSep;
int rSep = p->cRowSep;
p->n = 0;
c = fgetc(p->in);
if( c==EOF || seenInterrupt ){
p->cTerm = EOF;
return 0;
}
while( c!=EOF && c!=cSep && c!=rSep ){
import_append_char(p, c);
c = fgetc(p->in);
}
if( c==rSep ){
p->nLine++;
}
p->cTerm = c;
if( p->z ) p->z[p->n] = 0;
return p->z;
}
/*
** Try to transfer data for table zTable. If an error is seen while
** moving forward, try to go backwards. The backwards movement won't
** work for WITHOUT ROWID tables.
*/
static void tryToCloneData(
ShellState *p,
sqlite3 *newDb,
const char *zTable
){
sqlite3_stmt *pQuery = 0;
sqlite3_stmt *pInsert = 0;
char *zQuery = 0;
char *zInsert = 0;
int rc;
int i, j, n;
int nTable = (int)strlen(zTable);
int k = 0;
int cnt = 0;
const int spinRate = 10000;
zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
utf8_printf(stderr, "Error %d: %s on [%s]\n",
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_data_xfer;
}
n = sqlite3_column_count(pQuery);
zInsert = sqlite3_malloc64(200 + nTable + n*3);
if( zInsert==0 ){
raw_printf(stderr, "out of memory\n");
goto end_data_xfer;
}
sqlite3_snprintf(200+nTable,zInsert,
"INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
i = (int)strlen(zInsert);
for(j=1; j<n; j++){
memcpy(zInsert+i, ",?", 2);
i += 2;
}
memcpy(zInsert+i, ");", 3);
rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
if( rc ){
utf8_printf(stderr, "Error %d: %s on [%s]\n",
sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
zQuery);
goto end_data_xfer;
}
for(k=0; k<2; k++){
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
for(i=0; i<n; i++){
switch( sqlite3_column_type(pQuery, i) ){
case SQLITE_NULL: {
sqlite3_bind_null(pInsert, i+1);
break;
}
case SQLITE_INTEGER: {
sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
break;
}
case SQLITE_FLOAT: {
sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
break;
}
case SQLITE_TEXT: {
sqlite3_bind_text(pInsert, i+1,
(const char*)sqlite3_column_text(pQuery,i),
-1, SQLITE_STATIC);
break;
}
case SQLITE_BLOB: {
sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
sqlite3_column_bytes(pQuery,i),
SQLITE_STATIC);
break;
}
}
} /* End for */
rc = sqlite3_step(pInsert);
if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
sqlite3_errmsg(newDb));
}
sqlite3_reset(pInsert);
cnt++;
if( (cnt%spinRate)==0 ){
printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
fflush(stdout);
}
} /* End while */
if( rc==SQLITE_DONE ) break;
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
zTable);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
break;
}
} /* End for(k=0...) */
end_data_xfer:
sqlite3_finalize(pQuery);
sqlite3_finalize(pInsert);
sqlite3_free(zQuery);
sqlite3_free(zInsert);
}
/*
** Try to transfer all rows of the schema that match zWhere. For
** each row, invoke xForEach() on the object defined by that row.
** If an error is encountered while moving forward through the
** sqlite_master table, try again moving backwards.
*/
static void tryToCloneSchema(
ShellState *p,
sqlite3 *newDb,
const char *zWhere,
void (*xForEach)(ShellState*,sqlite3*,const char*)
){
sqlite3_stmt *pQuery = 0;
char *zQuery = 0;
int rc;
const unsigned char *zName;
const unsigned char *zSql;
char *zErrMsg = 0;
zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
" WHERE %s", zWhere);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_schema_xfer;
}
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
zName = sqlite3_column_text(pQuery, 0);
zSql = sqlite3_column_text(pQuery, 1);
printf("%s... ", zName); fflush(stdout);
sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
if( zErrMsg ){
utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
sqlite3_free(zErrMsg);
zErrMsg = 0;
}
if( xForEach ){
xForEach(p, newDb, (const char*)zName);
}
printf("done\n");
}
if( rc!=SQLITE_DONE ){
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
" WHERE %s ORDER BY rowid DESC", zWhere);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_schema_xfer;
}
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
zName = sqlite3_column_text(pQuery, 0);
zSql = sqlite3_column_text(pQuery, 1);
printf("%s... ", zName); fflush(stdout);
sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
if( zErrMsg ){
utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
sqlite3_free(zErrMsg);
zErrMsg = 0;
}
if( xForEach ){
xForEach(p, newDb, (const char*)zName);
}
printf("done\n");
}
}
end_schema_xfer:
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
}
/*
** Open a new database file named "zNewDb". Try to recover as much information
** as possible out of the main database (which might be corrupt) and write it
** into zNewDb.
*/
static void tryToClone(ShellState *p, const char *zNewDb){
int rc;
sqlite3 *newDb = 0;
if( access(zNewDb,0)==0 ){
utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
return;
}
rc = sqlite3_open(zNewDb, &newDb);
if( rc ){
utf8_printf(stderr, "Cannot create output database: %s\n",
sqlite3_errmsg(newDb));
}else{
sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
tryToCloneSchema(p, newDb, "type!='table'", 0);
sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
}
sqlite3_close(newDb);
}
/*
** Change the output file back to stdout
*/
static void output_reset(ShellState *p){
if( p->outfile[0]=='|' ){
#ifndef SQLITE_OMIT_POPEN
pclose(p->out);
#endif
}else{
output_file_close(p->out);
}
p->outfile[0] = 0;
p->out = stdout;
}
/*
** Run an SQL command and return the single integer result.
*/
static int db_int(ShellState *p, const char *zSql){
sqlite3_stmt *pStmt;
int res = 0;
sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
res = sqlite3_column_int(pStmt,0);
}
sqlite3_finalize(pStmt);
return res;
}
/*
** Convert a 2-byte or 4-byte big-endian integer into a native integer
*/
static unsigned int get2byteInt(unsigned char *a){
return (a[0]<<8) + a[1];
}
static unsigned int get4byteInt(unsigned char *a){
return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
}
/*
** Implementation of the ".info" command.
**
** Return 1 on error, 2 to exit, and 0 otherwise.
*/
static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
static const struct { const char *zName; int ofst; } aField[] = {
{ "file change counter:", 24 },
{ "database page count:", 28 },
{ "freelist page count:", 36 },
{ "schema cookie:", 40 },
{ "schema format:", 44 },
{ "default cache size:", 48 },
{ "autovacuum top root:", 52 },
{ "incremental vacuum:", 64 },
{ "text encoding:", 56 },
{ "user version:", 60 },
{ "application id:", 68 },
{ "software version:", 96 },
};
static const struct { const char *zName; const char *zSql; } aQuery[] = {
{ "number of tables:",
"SELECT count(*) FROM %s WHERE type='table'" },
{ "number of indexes:",
"SELECT count(*) FROM %s WHERE type='index'" },
{ "number of triggers:",
"SELECT count(*) FROM %s WHERE type='trigger'" },
{ "number of views:",
"SELECT count(*) FROM %s WHERE type='view'" },
{ "schema size:",
"SELECT total(length(sql)) FROM %s" },
};
sqlite3_file *pFile = 0;
int i;
char *zSchemaTab;
char *zDb = nArg>=2 ? azArg[1] : "main";
unsigned char aHdr[100];
open_db(p, 0);
if( p->db==0 ) return 1;
sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
return 1;
}
i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
if( i!=SQLITE_OK ){
raw_printf(stderr, "unable to read database header\n");
return 1;
}
i = get2byteInt(aHdr+16);
if( i==1 ) i = 65536;
utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
for(i=0; i<ArraySize(aField); i++){
int ofst = aField[i].ofst;
unsigned int val = get4byteInt(aHdr + ofst);
utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
switch( ofst ){
case 56: {
if( val==1 ) raw_printf(p->out, " (utf8)");
if( val==2 ) raw_printf(p->out, " (utf16le)");
if( val==3 ) raw_printf(p->out, " (utf16be)");
}
}
raw_printf(p->out, "\n");
}
if( zDb==0 ){
zSchemaTab = sqlite3_mprintf("main.sqlite_master");
}else if( strcmp(zDb,"temp")==0 ){
zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
}else{
zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
}
for(i=0; i<ArraySize(aQuery); i++){
char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
int val = db_int(p, zSql);
sqlite3_free(zSql);
utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
}
sqlite3_free(zSchemaTab);
return 0;
}
/*
** Print the current sqlite3_errmsg() value to stderr and return 1.
*/
static int shellDatabaseError(sqlite3 *db){
const char *zErr = sqlite3_errmsg(db);
utf8_printf(stderr, "Error: %s\n", zErr);
return 1;
}
/*
** Print an out-of-memory message to stderr and return 1.
*/
static int shellNomemError(void){
raw_printf(stderr, "Error: out of memory\n");
return 1;
}
/*
** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
** if they match and FALSE (0) if they do not match.
**
** Globbing rules:
**
** '*' Matches any sequence of zero or more characters.
**
** '?' Matches exactly one character.
**
** [...] Matches one character from the enclosed list of
** characters.
**
** [^...] Matches one character not in the enclosed list.
**
** '#' Matches any sequence of one or more digits with an
** optional + or - sign in front
**
** ' ' Any span of whitespace matches any other span of
** whitespace.
**
** Extra whitespace at the end of z[] is ignored.
*/
static int testcase_glob(const char *zGlob, const char *z){
int c, c2;
int invert;
int seen;
while( (c = (*(zGlob++)))!=0 ){
if( IsSpace(c) ){
if( !IsSpace(*z) ) return 0;
while( IsSpace(*zGlob) ) zGlob++;
while( IsSpace(*z) ) z++;
}else if( c=='*' ){
while( (c=(*(zGlob++))) == '*' || c=='?' ){
if( c=='?' && (*(z++))==0 ) return 0;
}
if( c==0 ){
return 1;
}else if( c=='[' ){
while( *z && testcase_glob(zGlob-1,z)==0 ){
z++;
}
return (*z)!=0;
}
while( (c2 = (*(z++)))!=0 ){
while( c2!=c ){
c2 = *(z++);
if( c2==0 ) return 0;
}
if( testcase_glob(zGlob,z) ) return 1;
}
return 0;
}else if( c=='?' ){
if( (*(z++))==0 ) return 0;
}else if( c=='[' ){
int prior_c = 0;
seen = 0;
invert = 0;
c = *(z++);
if( c==0 ) return 0;
c2 = *(zGlob++);
if( c2=='^' ){
invert = 1;
c2 = *(zGlob++);
}
if( c2==']' ){
if( c==']' ) seen = 1;
c2 = *(zGlob++);
}
while( c2 && c2!=']' ){
if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
c2 = *(zGlob++);
if( c>=prior_c && c<=c2 ) seen = 1;
prior_c = 0;
}else{
if( c==c2 ){
seen = 1;
}
prior_c = c2;
}
c2 = *(zGlob++);
}
if( c2==0 || (seen ^ invert)==0 ) return 0;
}else if( c=='#' ){
if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
if( !IsDigit(z[0]) ) return 0;
z++;
while( IsDigit(z[0]) ){ z++; }
}else{
if( c!=(*(z++)) ) return 0;
}
}
while( IsSpace(*z) ){ z++; }
return *z==0;
}
/*
** Compare the string as a command-line option with either one or two
** initial "-" characters.
*/
static int optionMatch(const char *zStr, const char *zOpt){
if( zStr[0]!='-' ) return 0;
zStr++;
if( zStr[0]=='-' ) zStr++;
return strcmp(zStr, zOpt)==0;
}
/*
** Delete a file.
*/
int shellDeleteFile(const char *zFilename){
int rc;
#ifdef _WIN32
wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
rc = _wunlink(z);
sqlite3_free(z);
#else
rc = unlink(zFilename);
#endif
return rc;
}
/*
** The implementation of SQL scalar function fkey_collate_clause(), used
** by the ".lint fkey-indexes" command. This scalar function is always
** called with four arguments - the parent table name, the parent column name,
** the child table name and the child column name.
**
** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
**
** If either of the named tables or columns do not exist, this function
** returns an empty string. An empty string is also returned if both tables
** and columns exist but have the same default collation sequence. Or,
** if both exist but the default collation sequences are different, this
** function returns the string " COLLATE <parent-collation>", where
** <parent-collation> is the default collation sequence of the parent column.
*/
static void shellFkeyCollateClause(
sqlite3_context *pCtx,
int nVal,
sqlite3_value **apVal
){
sqlite3 *db = sqlite3_context_db_handle(pCtx);
const char *zParent;
const char *zParentCol;
const char *zParentSeq;
const char *zChild;
const char *zChildCol;
const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
int rc;
assert( nVal==4 );
zParent = (const char*)sqlite3_value_text(apVal[0]);
zParentCol = (const char*)sqlite3_value_text(apVal[1]);
zChild = (const char*)sqlite3_value_text(apVal[2]);
zChildCol = (const char*)sqlite3_value_text(apVal[3]);
sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
rc = sqlite3_table_column_metadata(
db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
);
if( rc==SQLITE_OK ){
rc = sqlite3_table_column_metadata(
db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
);
}
if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
sqlite3_free(z);
}
}
/*
** The implementation of dot-command ".lint fkey-indexes".
*/
static int lintFkeyIndexes(
ShellState *pState, /* Current shell tool state */
char **azArg, /* Array of arguments passed to dot command */
int nArg /* Number of entries in azArg[] */
){
sqlite3 *db = pState->db; /* Database handle to query "main" db of */
FILE *out = pState->out; /* Stream to write non-error output to */
int bVerbose = 0; /* If -verbose is present */
int bGroupByParent = 0; /* If -groupbyparent is present */
int i; /* To iterate through azArg[] */
const char *zIndent = ""; /* How much to indent CREATE INDEX by */
int rc; /* Return code */
sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
/*
** This SELECT statement returns one row for each foreign key constraint
** in the schema of the main database. The column values are:
**
** 0. The text of an SQL statement similar to:
**
** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
**
** This is the same SELECT that the foreign keys implementation needs
** to run internally on child tables. If there is an index that can
** be used to optimize this query, then it can also be used by the FK
** implementation to optimize DELETE or UPDATE statements on the parent
** table.
**
** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
** contains an index that can be used to optimize the query.
**
** 2. Human readable text that describes the child table and columns. e.g.
**
** "child_table(child_key1, child_key2)"
**
** 3. Human readable text that describes the parent table and columns. e.g.
**
** "parent_table(parent_key1, parent_key2)"
**
** 4. A full CREATE INDEX statement for an index that could be used to
** optimize DELETE or UPDATE statements on the parent table. e.g.
**
** "CREATE INDEX child_table_child_key ON child_table(child_key)"
**
** 5. The name of the parent table.
**
** These six values are used by the C logic below to generate the report.
*/
const char *zSql =
"SELECT "
" 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
" || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
" || fkey_collate_clause(f.[table], f.[to], s.name, f.[from]),' AND ')"
", "
" 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
" || group_concat('*=?', ' AND ') || ')'"
", "
" s.name || '(' || group_concat(f.[from], ', ') || ')'"
", "
" f.[table] || '(' || group_concat(COALESCE(f.[to], "
" (SELECT name FROM pragma_table_info(f.[table]) WHERE pk=seq+1)"
" )) || ')'"
", "
" 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
" || ' ON ' || quote(s.name) || '('"
" || group_concat(quote(f.[from]) ||"
" fkey_collate_clause(f.[table], f.[to], s.name, f.[from]), ', ')"
" || ');'"
", "
" f.[table] "
"FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
"GROUP BY s.name, f.id "
"ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
;
for(i=2; i<nArg; i++){
int n = (int)strlen(azArg[i]);
if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
bVerbose = 1;
}
else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
bGroupByParent = 1;
zIndent = " ";
}
else{
raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
azArg[0], azArg[1]
);
return SQLITE_ERROR;
}
}
/* Register the fkey_collate_clause() SQL function */
rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
0, shellFkeyCollateClause, 0, 0
);
if( rc==SQLITE_OK ){
rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
}
if( rc==SQLITE_OK ){
sqlite3_bind_int(pSql, 1, bGroupByParent);
}
if( rc==SQLITE_OK ){
int rc2;
char *zPrev = 0;
while( SQLITE_ROW==sqlite3_step(pSql) ){
int res = -1;
sqlite3_stmt *pExplain = 0;
const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
if( rc!=SQLITE_OK ) break;
if( SQLITE_ROW==sqlite3_step(pExplain) ){
const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
res = (0==sqlite3_strglob(zGlob, zPlan));
}
rc = sqlite3_finalize(pExplain);
if( rc!=SQLITE_OK ) break;
if( res<0 ){
raw_printf(stderr, "Error: internal error");
break;
}else{
if( bGroupByParent
&& (bVerbose || res==0)
&& (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
){
raw_printf(out, "-- Parent table %s\n", zParent);
sqlite3_free(zPrev);
zPrev = sqlite3_mprintf("%s", zParent);
}
if( res==0 ){
raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
}else if( bVerbose ){
raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
zIndent, zFrom, zTarget
);
}
}
}
sqlite3_free(zPrev);
if( rc!=SQLITE_OK ){
raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
}
rc2 = sqlite3_finalize(pSql);
if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
rc = rc2;
raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
}
}else{
raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
}
return rc;
}
/*
** Implementation of ".lint" dot command.
*/
static int lintDotCommand(
ShellState *pState, /* Current shell tool state */
char **azArg, /* Array of arguments passed to dot command */
int nArg /* Number of entries in azArg[] */
){
int n;
n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
return lintFkeyIndexes(pState, azArg, nArg);
usage:
raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
raw_printf(stderr, "Where sub-commands are:\n");
raw_printf(stderr, " fkey-indexes\n");
return SQLITE_ERROR;
}
/*
** If an input line begins with "." then invoke this routine to
** process that line.
**
** Return 1 on error, 2 to exit, and 0 otherwise.
*/
static int do_meta_command(char *zLine, ShellState *p){
int h = 1;
int nArg = 0;
int n, c;
int rc = 0;
char *azArg[50];
/* Parse the input line into tokens.
*/
while( zLine[h] && nArg<ArraySize(azArg) ){
while( IsSpace(zLine[h]) ){ h++; }
if( zLine[h]==0 ) break;
if( zLine[h]=='\'' || zLine[h]=='"' ){
int delim = zLine[h++];
azArg[nArg++] = &zLine[h];
while( zLine[h] && zLine[h]!=delim ){
if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
h++;
}
if( zLine[h]==delim ){
zLine[h++] = 0;
}
if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
}else{
azArg[nArg++] = &zLine[h];
while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
if( zLine[h] ) zLine[h++] = 0;
resolve_backslashes(azArg[nArg-1]);
}
}
/* Process the input line.
*/
if( nArg==0 ) return 0; /* no tokens, no error */
n = strlen30(azArg[0]);
c = azArg[0][0];
#ifndef SQLITE_OMIT_AUTHORIZATION
if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
if( nArg!=2 ){
raw_printf(stderr, "Usage: .auth ON|OFF\n");
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
if( booleanValue(azArg[1]) ){
sqlite3_set_authorizer(p->db, shellAuth, p);
}else{
sqlite3_set_authorizer(p->db, 0, 0);
}
}else
#endif
if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
|| (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
){
const char *zDestFile = 0;
const char *zDb = 0;
sqlite3 *pDest;
sqlite3_backup *pBackup;
int j;
for(j=1; j<nArg; j++){
const char *z = azArg[j];
if( z[0]=='-' ){
while( z[0]=='-' ) z++;
/* No options to process at this time */
{
utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
return 1;
}
}else if( zDestFile==0 ){
zDestFile = azArg[j];
}else if( zDb==0 ){
zDb = zDestFile;
zDestFile = azArg[j];
}else{
raw_printf(stderr, "too many arguments to .backup\n");
return 1;
}
}
if( zDestFile==0 ){
raw_printf(stderr, "missing FILENAME argument on .backup\n");
return 1;
}
if( zDb==0 ) zDb = "main";
rc = sqlite3_open(zDestFile, &pDest);
if( rc!=SQLITE_OK ){
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
sqlite3_close(pDest);
return 1;
}
open_db(p, 0);
pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
if( pBackup==0 ){
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
sqlite3_close(pDest);
return 1;
}
while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
sqlite3_backup_finish(pBackup);
if( rc==SQLITE_DONE ){
rc = 0;
}else{
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
rc = 1;
}
sqlite3_close(pDest);
}else
if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
if( nArg==2 ){
bail_on_error = booleanValue(azArg[1]);
}else{
raw_printf(stderr, "Usage: .bail on|off\n");
rc = 1;
}
}else
if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
if( nArg==2 ){
if( booleanValue(azArg[1]) ){
setBinaryMode(p->out, 1);
}else{
setTextMode(p->out, 1);
}
}else{
raw_printf(stderr, "Usage: .binary on|off\n");
rc = 1;
}
}else
/* The undocumented ".breakpoint" command causes a call to the no-op
** routine named test_breakpoint().
*/
if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
test_breakpoint();
}else
if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
if( nArg==2 ){
p->countChanges = booleanValue(azArg[1]);
}else{
raw_printf(stderr, "Usage: .changes on|off\n");
rc = 1;
}
}else
/* Cancel output redirection, if it is currently set (by .testcase)
** Then read the content of the testcase-out.txt file and compare against
** azArg[1]. If there are differences, report an error and exit.
*/
if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
char *zRes = 0;
output_reset(p);
if( nArg!=2 ){
raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
rc = 2;
}else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
rc = 2;
}else if( testcase_glob(azArg[1],zRes)==0 ){
utf8_printf(stderr,
"testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
p->zTestcase, azArg[1], zRes);
rc = 2;
}else{
utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
p->nCheck++;
}
sqlite3_free(zRes);
}else
if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
if( nArg==2 ){
tryToClone(p, azArg[1]);
}else{
raw_printf(stderr, "Usage: .clone FILENAME\n");
rc = 1;
}
}else
if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
ShellState data;
char *zErrMsg = 0;
open_db(p, 0);
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
data.cMode = data.mode = MODE_List;
sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
data.cnt = 0;
sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
callback, &data, &zErrMsg);
if( zErrMsg ){
utf8_printf(stderr,"Error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
rc = 1;
}
}else
if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
rc = shell_dbinfo_command(p, nArg, azArg);
}else
if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
open_db(p, 0);
/* When playing back a "dump", the content might appear in an order
** which causes immediate foreign key constraints to be violated.
** So disable foreign-key constraint enforcement to prevent problems. */
if( nArg!=1 && nArg!=2 ){
raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
rc = 1;
goto meta_command_exit;
}
raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
raw_printf(p->out, "BEGIN TRANSACTION;\n");
p->writableSchema = 0;
sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
p->nErr = 0;
if( nArg==1 ){
run_schema_dump_query(p,
"SELECT name, type, sql FROM sqlite_master "
"WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
);
run_schema_dump_query(p,
"SELECT name, type, sql FROM sqlite_master "
"WHERE name=='sqlite_sequence'"
);
run_table_dump_query(p,
"SELECT sql FROM sqlite_master "
"WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
);
}else{
int i;
for(i=1; i<nArg; i++){
zShellStatic = azArg[i];
run_schema_dump_query(p,
"SELECT name, type, sql FROM sqlite_master "
"WHERE tbl_name LIKE shellstatic() AND type=='table'"
" AND sql NOT NULL");
run_table_dump_query(p,
"SELECT sql FROM sqlite_master "
"WHERE sql NOT NULL"
" AND type IN ('index','trigger','view')"
" AND tbl_name LIKE shellstatic()", 0
);
zShellStatic = 0;
}
}
if( p->writableSchema ){
raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
p->writableSchema = 0;
}
sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
}else
if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
if( nArg==2 ){
p->echoOn = booleanValue(azArg[1]);
}else{
raw_printf(stderr, "Usage: .echo on|off\n");
rc = 1;
}
}else
if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
if( nArg==2 ){
if( strcmp(azArg[1],"full")==0 ){
p->autoEQP = 2;
}else{
p->autoEQP = booleanValue(azArg[1]);
}
}else{
raw_printf(stderr, "Usage: .eqp on|off|full\n");
rc = 1;
}
}else
if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
rc = 2;
}else
if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
int val = 1;
if( nArg>=2 ){
if( strcmp(azArg[1],"auto")==0 ){
val = 99;
}else{
val = booleanValue(azArg[1]);
}
}
if( val==1 && p->mode!=MODE_Explain ){
p->normalMode = p->mode;
p->mode = MODE_Explain;
p->autoExplain = 0;
}else if( val==0 ){
if( p->mode==MODE_Explain ) p->mode = p->normalMode;
p->autoExplain = 0;
}else if( val==99 ){
if( p->mode==MODE_Explain ) p->mode = p->normalMode;
p->autoExplain = 1;
}
}else
if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
ShellState data;
char *zErrMsg = 0;
int doStats = 0;
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
data.cMode = data.mode = MODE_Semi;
if( nArg==2 && optionMatch(azArg[1], "indent") ){
data.cMode = data.mode = MODE_Pretty;
nArg = 1;
}
if( nArg!=1 ){
raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
rc = sqlite3_exec(p->db,
"SELECT sql FROM"
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
" FROM sqlite_master UNION ALL"
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
"ORDER BY rowid",
callback, &data, &zErrMsg
);
if( rc==SQLITE_OK ){
sqlite3_stmt *pStmt;
rc = sqlite3_prepare_v2(p->db,
"SELECT rowid FROM sqlite_master"
" WHERE name GLOB 'sqlite_stat[134]'",
-1, &pStmt, 0);
doStats = sqlite3_step(pStmt)==SQLITE_ROW;
sqlite3_finalize(pStmt);
}
if( doStats==0 ){
raw_printf(p->out, "/* No STAT tables available */\n");
}else{
raw_printf(p->out, "ANALYZE sqlite_master;\n");
sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
callback, &data, &zErrMsg);
data.cMode = data.mode = MODE_Insert;
data.zDestTable = "sqlite_stat1";
shell_exec(p->db, "SELECT * FROM sqlite_stat1",
shell_callback, &data,&zErrMsg);
data.zDestTable = "sqlite_stat3";
shell_exec(p->db, "SELECT * FROM sqlite_stat3",
shell_callback, &data,&zErrMsg);
data.zDestTable = "sqlite_stat4";
shell_exec(p->db, "SELECT * FROM sqlite_stat4",
shell_callback, &data, &zErrMsg);
raw_printf(p->out, "ANALYZE sqlite_master;\n");
}
}else
if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
if( nArg==2 ){
p->showHeader = booleanValue(azArg[1]);
}else{
raw_printf(stderr, "Usage: .headers on|off\n");
rc = 1;
}
}else
if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
utf8_printf(p->out, "%s", zHelp);
}else
if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
char *zTable; /* Insert data into this table */
char *zFile; /* Name of file to extra content from */
sqlite3_stmt *pStmt = NULL; /* A statement */
int nCol; /* Number of columns in the table */
int nByte; /* Number of bytes in an SQL string */
int i, j; /* Loop counters */
int needCommit; /* True to COMMIT or ROLLBACK at end */
int nSep; /* Number of bytes in p->colSeparator[] */
char *zSql; /* An SQL statement */
ImportCtx sCtx; /* Reader context */
char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
if( nArg!=3 ){
raw_printf(stderr, "Usage: .import FILE TABLE\n");
goto meta_command_exit;
}
zFile = azArg[1];
zTable = azArg[2];
seenInterrupt = 0;
memset(&sCtx, 0, sizeof(sCtx));
open_db(p, 0);
nSep = strlen30(p->colSeparator);
if( nSep==0 ){
raw_printf(stderr,
"Error: non-null column separator required for import\n");
return 1;
}
if( nSep>1 ){
raw_printf(stderr, "Error: multi-character column separators not allowed"
" for import\n");
return 1;
}
nSep = strlen30(p->rowSeparator);
if( nSep==0 ){
raw_printf(stderr, "Error: non-null row separator required for import\n");
return 1;
}
if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
/* When importing CSV (only), if the row separator is set to the
** default output row separator, change it to the default input
** row separator. This avoids having to maintain different input
** and output row separators. */
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
nSep = strlen30(p->rowSeparator);
}
if( nSep>1 ){
raw_printf(stderr, "Error: multi-character row separators not allowed"
" for import\n");
return 1;
}
sCtx.zFile = zFile;
sCtx.nLine = 1;
if( sCtx.zFile[0]=='|' ){
#ifdef SQLITE_OMIT_POPEN
raw_printf(stderr, "Error: pipes are not supported in this OS\n");
return 1;
#else
sCtx.in = popen(sCtx.zFile+1, "r");
sCtx.zFile = "<pipe>";
xCloser = pclose;
#endif
}else{
sCtx.in = fopen(sCtx.zFile, "rb");
xCloser = fclose;
}
if( p->mode==MODE_Ascii ){
xRead = ascii_read_one_field;
}else{
xRead = csv_read_one_field;
}
if( sCtx.in==0 ){
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
return 1;
}
sCtx.cColSep = p->colSeparator[0];
sCtx.cRowSep = p->rowSeparator[0];
zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
if( zSql==0 ){
raw_printf(stderr, "Error: out of memory\n");
xCloser(sCtx.in);
return 1;
}
nByte = strlen30(zSql);
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
char cSep = '(';
while( xRead(&sCtx) ){
zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
cSep = ',';
if( sCtx.cTerm!=sCtx.cColSep ) break;
}
if( cSep=='(' ){
sqlite3_free(zCreate);
sqlite3_free(sCtx.z);
xCloser(sCtx.in);
utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
return 1;
}
zCreate = sqlite3_mprintf("%z\n)", zCreate);
rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
sqlite3_free(zCreate);
if( rc ){
utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
sqlite3_errmsg(p->db));
sqlite3_free(sCtx.z);
xCloser(sCtx.in);
return 1;
}
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
}
sqlite3_free(zSql);
if( rc ){
if (pStmt) sqlite3_finalize(pStmt);
utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
xCloser(sCtx.in);
return 1;
}
nCol = sqlite3_column_count(pStmt);
sqlite3_finalize(pStmt);
pStmt = 0;
if( nCol==0 ) return 0; /* no columns, no error */
zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
if( zSql==0 ){
raw_printf(stderr, "Error: out of memory\n");
xCloser(sCtx.in);
return 1;
}
sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
j = strlen30(zSql);
for(i=1; i<nCol; i++){
zSql[j++] = ',';
zSql[j++] = '?';
}
zSql[j++] = ')';
zSql[j] = 0;
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
sqlite3_free(zSql);
if( rc ){
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
if (pStmt) sqlite3_finalize(pStmt);
xCloser(sCtx.in);
return 1;
}
needCommit = sqlite3_get_autocommit(p->db);
if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
do{
int startLine = sCtx.nLine;
for(i=0; i<nCol; i++){
char *z = xRead(&sCtx);
/*
** Did we reach end-of-file before finding any columns?
** If so, stop instead of NULL filling the remaining columns.
*/
if( z==0 && i==0 ) break;
/*
** Did we reach end-of-file OR end-of-line before finding any
** columns in ASCII mode? If so, stop instead of NULL filling
** the remaining columns.
*/
if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
"filling the rest with NULL\n",
sCtx.zFile, startLine, nCol, i+1);
i += 2;
while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
}
}
if( sCtx.cTerm==sCtx.cColSep ){
do{
xRead(&sCtx);
i++;
}while( sCtx.cTerm==sCtx.cColSep );
utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
"extras ignored\n",
sCtx.zFile, startLine, nCol, i);
}
if( i>=nCol ){
sqlite3_step(pStmt);
rc = sqlite3_reset(pStmt);
if( rc!=SQLITE_OK ){
utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
startLine, sqlite3_errmsg(p->db));
}
}
}while( sCtx.cTerm!=EOF );
xCloser(sCtx.in);
sqlite3_free(sCtx.z);
sqlite3_finalize(pStmt);
if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
}else
#ifndef SQLITE_UNTESTABLE
if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
char *zSql;
char *zCollist = 0;
sqlite3_stmt *pStmt;
int tnum = 0;
int i;
if( nArg!=3 ){
utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
" WHERE name='%q' AND type='index'", azArg[1]);
sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
sqlite3_free(zSql);
if( sqlite3_step(pStmt)==SQLITE_ROW ){
tnum = sqlite3_column_int(pStmt, 0);
}
sqlite3_finalize(pStmt);
if( tnum==0 ){
utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
rc = 1;
goto meta_command_exit;
}
zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
sqlite3_free(zSql);
i = 0;
while( sqlite3_step(pStmt)==SQLITE_ROW ){
char zLabel[20];
const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
i++;
if( zCol==0 ){
if( sqlite3_column_int(pStmt,1)==-1 ){
zCol = "_ROWID_";
}else{
sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
zCol = zLabel;
}
}
if( zCollist==0 ){
zCollist = sqlite3_mprintf("\"%w\"", zCol);
}else{
zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
}
}
sqlite3_finalize(pStmt);
zSql = sqlite3_mprintf(
"CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
azArg[2], zCollist, zCollist);
sqlite3_free(zCollist);
rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
if( rc==SQLITE_OK ){
rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
if( rc ){
utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
}else{
utf8_printf(stdout, "%s;\n", zSql);
raw_printf(stdout,
"WARNING: writing to an imposter table will corrupt the index!\n"
);
}
}else{
raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
rc = 1;
}
sqlite3_free(zSql);
}else
#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
#ifdef SQLITE_ENABLE_IOTRACE
if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
if( iotrace && iotrace!=stdout ) fclose(iotrace);
iotrace = 0;
if( nArg<2 ){
sqlite3IoTrace = 0;
}else if( strcmp(azArg[1], "-")==0 ){
sqlite3IoTrace = iotracePrintf;
iotrace = stdout;
}else{
iotrace = fopen(azArg[1], "w");
if( iotrace==0 ){
utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
sqlite3IoTrace = 0;
rc = 1;
}else{
sqlite3IoTrace = iotracePrintf;
}
}
}else
#endif
if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
static const struct {
const char *zLimitName; /* Name of a limit */
int limitCode; /* Integer code for that limit */
} aLimit[] = {
{ "length", SQLITE_LIMIT_LENGTH },
{ "sql_length", SQLITE_LIMIT_SQL_LENGTH },
{ "column", SQLITE_LIMIT_COLUMN },
{ "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
{ "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
{ "vdbe_op", SQLITE_LIMIT_VDBE_OP },
{ "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
{ "attached", SQLITE_LIMIT_ATTACHED },
{ "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
{ "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
{ "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
{ "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
};
int i, n2;
open_db(p, 0);
if( nArg==1 ){
for(i=0; i<ArraySize(aLimit); i++){
printf("%20s %d\n", aLimit[i].zLimitName,
sqlite3_limit(p->db, aLimit[i].limitCode, -1));
}
}else if( nArg>3 ){
raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
rc = 1;
goto meta_command_exit;
}else{
int iLimit = -1;
n2 = strlen30(azArg[1]);
for(i=0; i<ArraySize(aLimit); i++){
if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
if( iLimit<0 ){
iLimit = i;
}else{
utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
rc = 1;
goto meta_command_exit;
}
}
}
if( iLimit<0 ){
utf8_printf(stderr, "unknown limit: \"%s\"\n"
"enter \".limits\" with no arguments for a list.\n",
azArg[1]);
rc = 1;
goto meta_command_exit;
}
if( nArg==3 ){
sqlite3_limit(p->db, aLimit[iLimit].limitCode,
(int)integerValue(azArg[2]));
}
printf("%20s %d\n", aLimit[iLimit].zLimitName,
sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
}
}else
if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
open_db(p, 0);
lintDotCommand(p, azArg, nArg);
}else
#ifndef SQLITE_OMIT_LOAD_EXTENSION
if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
const char *zFile, *zProc;
char *zErrMsg = 0;
if( nArg<2 ){
raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
rc = 1;
goto meta_command_exit;
}
zFile = azArg[1];
zProc = nArg>=3 ? azArg[2] : 0;
open_db(p, 0);
rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
if( rc!=SQLITE_OK ){
utf8_printf(stderr, "Error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
rc = 1;
}
}else
#endif
if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
if( nArg!=2 ){
raw_printf(stderr, "Usage: .log FILENAME\n");
rc = 1;
}else{
const char *zFile = azArg[1];
output_file_close(p->pLog);
p->pLog = output_file_open(zFile);
}
}else
if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
const char *zMode = nArg>=2 ? azArg[1] : "";
int n2 = (int)strlen(zMode);
int c2 = zMode[0];
if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
p->mode = MODE_Line;
}else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
p->mode = MODE_Column;
}else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
p->mode = MODE_List;
}else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
p->mode = MODE_Html;
}else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
p->mode = MODE_Tcl;
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
}else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
p->mode = MODE_Csv;
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
}else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
p->mode = MODE_List;
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
}else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
p->mode = MODE_Insert;
set_table_name(p, nArg>=3 ? azArg[2] : "table");
}else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
p->mode = MODE_Quote;
}else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
p->mode = MODE_Ascii;
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
}else {
raw_printf(stderr, "Error: mode should be one of: "
"ascii column csv html insert line list quote tabs tcl\n");
rc = 1;
}
p->cMode = p->mode;
}else
if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
if( nArg==2 ){
sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
"%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
}else{
raw_printf(stderr, "Usage: .nullvalue STRING\n");
rc = 1;
}
}else
if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
char *zNewFilename; /* Name of the database file to open */
int iName = 1; /* Index in azArg[] of the filename */
int newFlag = 0; /* True to delete file before opening */
/* Close the existing database */
session_close_all(p);
sqlite3_close(p->db);
p->db = 0;
sqlite3_free(p->zFreeOnClose);
p->zFreeOnClose = 0;
/* Check for command-line arguments */
for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
const char *z = azArg[iName];
if( optionMatch(z,"new") ){
newFlag = 1;
}else if( z[0]=='-' ){
utf8_printf(stderr, "unknown option: %s\n", z);
rc = 1;
goto meta_command_exit;
}
}
/* If a filename is specified, try to open it first */
zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
if( zNewFilename ){
if( newFlag ) shellDeleteFile(zNewFilename);
p->zDbFilename = zNewFilename;
open_db(p, 1);
if( p->db==0 ){
utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
sqlite3_free(zNewFilename);
}else{
p->zFreeOnClose = zNewFilename;
}
}
if( p->db==0 ){
/* As a fall-back open a TEMP database */
p->zDbFilename = 0;
open_db(p, 0);
}
}else
if( c=='o'
&& (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
){
const char *zFile = nArg>=2 ? azArg[1] : "stdout";
if( nArg>2 ){
utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
rc = 1;
goto meta_command_exit;
}
if( n>1 && strncmp(azArg[0], "once", n)==0 ){
if( nArg<2 ){
raw_printf(stderr, "Usage: .once FILE\n");
rc = 1;
goto meta_command_exit;
}
p->outCount = 2;
}else{
p->outCount = 0;
}
output_reset(p);
if( zFile[0]=='|' ){
#ifdef SQLITE_OMIT_POPEN
raw_printf(stderr, "Error: pipes are not supported in this OS\n");
rc = 1;
p->out = stdout;
#else
p->out = popen(zFile + 1, "w");
if( p->out==0 ){
utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
p->out = stdout;
rc = 1;
}else{
sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
}
#endif
}else{
p->out = output_file_open(zFile);
if( p->out==0 ){
if( strcmp(zFile,"off")!=0 ){
utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
}
p->out = stdout;
rc = 1;
} else {
sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
}
}
}else
if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
int i;
for(i=1; i<nArg; i++){
if( i>1 ) raw_printf(p->out, " ");
utf8_printf(p->out, "%s", azArg[i]);
}
raw_printf(p->out, "\n");
}else
if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
if( nArg >= 2) {
strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
}
if( nArg >= 3) {
strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
}
}else
if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
rc = 2;
}else
if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
FILE *alt;
if( nArg!=2 ){
raw_printf(stderr, "Usage: .read FILE\n");
rc = 1;
goto meta_command_exit;
}
alt = fopen(azArg[1], "rb");
if( alt==0 ){
utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
rc = 1;
}else{
rc = process_input(p, alt);
fclose(alt);
}
}else
if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
const char *zSrcFile;
const char *zDb;
sqlite3 *pSrc;
sqlite3_backup *pBackup;
int nTimeout = 0;
if( nArg==2 ){
zSrcFile = azArg[1];
zDb = "main";
}else if( nArg==3 ){
zSrcFile = azArg[2];
zDb = azArg[1];
}else{
raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_open(zSrcFile, &pSrc);
if( rc!=SQLITE_OK ){
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
sqlite3_close(pSrc);
return 1;
}
open_db(p, 0);
pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
if( pBackup==0 ){
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
sqlite3_close(pSrc);
return 1;
}
while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
|| rc==SQLITE_BUSY ){
if( rc==SQLITE_BUSY ){
if( nTimeout++ >= 3 ) break;
sqlite3_sleep(100);
}
}
sqlite3_backup_finish(pBackup);
if( rc==SQLITE_DONE ){
rc = 0;
}else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
raw_printf(stderr, "Error: source database is busy\n");
rc = 1;
}else{
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
rc = 1;
}
sqlite3_close(pSrc);
}else
if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
if( nArg==2 ){
p->scanstatsOn = booleanValue(azArg[1]);
#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
#endif
}else{
raw_printf(stderr, "Usage: .scanstats on|off\n");
rc = 1;
}
}else
if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
ShellState data;
char *zErrMsg = 0;
open_db(p, 0);
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
data.cMode = data.mode = MODE_Semi;
if( nArg>=2 && optionMatch(azArg[1], "indent") ){
data.cMode = data.mode = MODE_Pretty;
nArg--;
if( nArg==2 ) azArg[1] = azArg[2];
}
if( nArg==2 && azArg[1][0]!='-' ){
int i;
for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
if( strcmp(azArg[1],"sqlite_master")==0 ){
char *new_argv[2], *new_colv[2];
new_argv[0] = "CREATE TABLE sqlite_master (\n"
" type text,\n"
" name text,\n"
" tbl_name text,\n"
" rootpage integer,\n"
" sql text\n"
")";
new_argv[1] = 0;
new_colv[0] = "sql";
new_colv[1] = 0;
callback(&data, 1, new_argv, new_colv);
rc = SQLITE_OK;
}else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
char *new_argv[2], *new_colv[2];
new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
" type text,\n"
" name text,\n"
" tbl_name text,\n"
" rootpage integer,\n"
" sql text\n"
")";
new_argv[1] = 0;
new_colv[0] = "sql";
new_colv[1] = 0;
callback(&data, 1, new_argv, new_colv);
rc = SQLITE_OK;
}else{
zShellStatic = azArg[1];
rc = sqlite3_exec(p->db,
"SELECT sql FROM "
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
" FROM sqlite_master UNION ALL"
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
"WHERE lower(tbl_name) LIKE shellstatic()"
" AND type!='meta' AND sql NOTNULL "
"ORDER BY rowid",
callback, &data, &zErrMsg);
zShellStatic = 0;
}
}else if( nArg==1 ){
rc = sqlite3_exec(p->db,
"SELECT sql FROM "
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
" FROM sqlite_master UNION ALL"
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
"ORDER BY rowid",
callback, &data, &zErrMsg
);
}else{
raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
rc = 1;
goto meta_command_exit;
}
if( zErrMsg ){
utf8_printf(stderr,"Error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
rc = 1;
}else if( rc != SQLITE_OK ){
raw_printf(stderr,"Error: querying schema information\n");
rc = 1;
}else{
rc = 0;
}
}else
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
sqlite3SelectTrace = integerValue(azArg[1]);
}else
#endif
#if defined(SQLITE_ENABLE_SESSION)
if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
OpenSession *pSession = &p->aSession[0];
char **azCmd = &azArg[1];
int iSes = 0;
int nCmd = nArg - 1;
int i;
if( nArg<=1 ) goto session_syntax_error;
open_db(p, 0);
if( nArg>=3 ){
for(iSes=0; iSes<p->nSession; iSes++){
if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
}
if( iSes<p->nSession ){
pSession = &p->aSession[iSes];
azCmd++;
nCmd--;
}else{
pSession = &p->aSession[0];
iSes = 0;
}
}
/* .session attach TABLE
** Invoke the sqlite3session_attach() interface to attach a particular
** table so that it is never filtered.
*/
if( strcmp(azCmd[0],"attach")==0 ){
if( nCmd!=2 ) goto session_syntax_error;
if( pSession->p==0 ){
session_not_open:
raw_printf(stderr, "ERROR: No sessions are open\n");
}else{
rc = sqlite3session_attach(pSession->p, azCmd[1]);
if( rc ){
raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
rc = 0;
}
}
}else
/* .session changeset FILE
** .session patchset FILE
** Write a changeset or patchset into a file. The file is overwritten.
*/
if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
FILE *out = 0;
if( nCmd!=2 ) goto session_syntax_error;
if( pSession->p==0 ) goto session_not_open;
out = fopen(azCmd[1], "wb");
if( out==0 ){
utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
}else{
int szChng;
void *pChng;
if( azCmd[0][0]=='c' ){
rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
}else{
rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
}
if( rc ){
printf("Error: error code %d\n", rc);
rc = 0;
}
if( pChng
&& fwrite(pChng, szChng, 1, out)!=1 ){
raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
szChng);
}
sqlite3_free(pChng);
fclose(out);
}
}else
/* .session close
** Close the identified session
*/
if( strcmp(azCmd[0], "close")==0 ){
if( nCmd!=1 ) goto session_syntax_error;
if( p->nSession ){
session_close(pSession);
p->aSession[iSes] = p->aSession[--p->nSession];
}
}else
/* .session enable ?BOOLEAN?
** Query or set the enable flag
*/
if( strcmp(azCmd[0], "enable")==0 ){
int ii;
if( nCmd>2 ) goto session_syntax_error;
ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
if( p->nSession ){
ii = sqlite3session_enable(pSession->p, ii);
utf8_printf(p->out, "session %s enable flag = %d\n",
pSession->zName, ii);
}
}else
/* .session filter GLOB ....
** Set a list of GLOB patterns of table names to be excluded.
*/
if( strcmp(azCmd[0], "filter")==0 ){
int ii, nByte;
if( nCmd<2 ) goto session_syntax_error;
if( p->nSession ){
for(ii=0; ii<pSession->nFilter; ii++){
sqlite3_free(pSession->azFilter[ii]);
}
sqlite3_free(pSession->azFilter);
nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
pSession->azFilter = sqlite3_malloc( nByte );
if( pSession->azFilter==0 ){
raw_printf(stderr, "Error: out or memory\n");
exit(1);
}
for(ii=1; ii<nCmd; ii++){
pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
}
pSession->nFilter = ii-1;
}
}else
/* .session indirect ?BOOLEAN?
** Query or set the indirect flag
*/
if( strcmp(azCmd[0], "indirect")==0 ){
int ii;
if( nCmd>2 ) goto session_syntax_error;
ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
if( p->nSession ){
ii = sqlite3session_indirect(pSession->p, ii);
utf8_printf(p->out, "session %s indirect flag = %d\n",
pSession->zName, ii);
}
}else
/* .session isempty
** Determine if the session is empty
*/
if( strcmp(azCmd[0], "isempty")==0 ){
int ii;
if( nCmd!=1 ) goto session_syntax_error;
if( p->nSession ){
ii = sqlite3session_isempty(pSession->p);
utf8_printf(p->out, "session %s isempty flag = %d\n",
pSession->zName, ii);
}
}else
/* .session list
** List all currently open sessions
*/
if( strcmp(azCmd[0],"list")==0 ){
for(i=0; i<p->nSession; i++){
utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
}
}else
/* .session open DB NAME
** Open a new session called NAME on the attached database DB.
** DB is normally "main".
*/
if( strcmp(azCmd[0],"open")==0 ){
char *zName;
if( nCmd!=3 ) goto session_syntax_error;
zName = azCmd[2];
if( zName[0]==0 ) goto session_syntax_error;
for(i=0; i<p->nSession; i++){
if( strcmp(p->aSession[i].zName,zName)==0 ){
utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
goto meta_command_exit;
}
}
if( p->nSession>=ArraySize(p->aSession) ){
raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
goto meta_command_exit;
}
pSession = &p->aSession[p->nSession];
rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
if( rc ){
raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
rc = 0;
goto meta_command_exit;
}
pSession->nFilter = 0;
sqlite3session_table_filter(pSession->p, session_filter, pSession);
p->nSession++;
pSession->zName = sqlite3_mprintf("%s", zName);
}else
/* If no command name matches, show a syntax error */
session_syntax_error:
session_help(p);
}else
#endif
#ifdef SQLITE_DEBUG
/* Undocumented commands for internal testing. Subject to change
** without notice. */
if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
int i, v;
for(i=1; i<nArg; i++){
v = booleanValue(azArg[i]);
utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
}
}
if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
int i; sqlite3_int64 v;
for(i=1; i<nArg; i++){
char zBuf[200];
v = integerValue(azArg[i]);
sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
utf8_printf(p->out, "%s", zBuf);
}
}
}else
#endif
if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
if( nArg<2 || nArg>3 ){
raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
rc = 1;
}
if( nArg>=2 ){
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
"%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
}
if( nArg>=3 ){
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
"%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
}
}else
if( c=='s'
&& (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
){
char *zCmd;
int i, x;
if( nArg<2 ){
raw_printf(stderr, "Usage: .system COMMAND\n");
rc = 1;
goto meta_command_exit;
}
zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
for(i=2; i<nArg; i++){
zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
zCmd, azArg[i]);
}
x = system(zCmd);
sqlite3_free(zCmd);
if( x ) raw_printf(stderr, "System command returns %d\n", x);
}else
if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
static const char *azBool[] = { "off", "on", "full", "unk" };
int i;
if( nArg!=1 ){
raw_printf(stderr, "Usage: .show\n");
rc = 1;
goto meta_command_exit;
}
utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]);
utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
utf8_printf(p->out, "%12.12s: %s\n","explain",
p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
utf8_printf(p->out, "%12.12s: ", "nullvalue");
output_c_string(p->out, p->nullValue);
raw_printf(p->out, "\n");
utf8_printf(p->out,"%12.12s: %s\n","output",
strlen30(p->outfile) ? p->outfile : "stdout");
utf8_printf(p->out,"%12.12s: ", "colseparator");
output_c_string(p->out, p->colSeparator);
raw_printf(p->out, "\n");
utf8_printf(p->out,"%12.12s: ", "rowseparator");
output_c_string(p->out, p->rowSeparator);
raw_printf(p->out, "\n");
utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
utf8_printf(p->out, "%12.12s: ", "width");
for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
raw_printf(p->out, "%d ", p->colWidth[i]);
}
raw_printf(p->out, "\n");
utf8_printf(p->out, "%12.12s: %s\n", "filename",
p->zDbFilename ? p->zDbFilename : "");
}else
if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
if( nArg==2 ){
p->statsOn = booleanValue(azArg[1]);
}else if( nArg==1 ){
display_stats(p->db, p, 0);
}else{
raw_printf(stderr, "Usage: .stats ?on|off?\n");
rc = 1;
}
}else
if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
|| (c=='i' && (strncmp(azArg[0], "indices", n)==0
|| strncmp(azArg[0], "indexes", n)==0) )
){
sqlite3_stmt *pStmt;
char **azResult;
int nRow, nAlloc;
char *zSql = 0;
int ii;
open_db(p, 0);
rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
if( rc ) return shellDatabaseError(p->db);
/* Create an SQL statement to query for the list of tables in the
** main and all attached databases where the table name matches the
** LIKE pattern bound to variable "?1". */
if( c=='t' ){
zSql = sqlite3_mprintf(
"SELECT name FROM sqlite_master"
" WHERE type IN ('table','view')"
" AND name NOT LIKE 'sqlite_%%'"
" AND name LIKE ?1");
}else if( nArg>2 ){
/* It is an historical accident that the .indexes command shows an error
** when called with the wrong number of arguments whereas the .tables
** command does not. */
raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
rc = 1;
goto meta_command_exit;
}else{
zSql = sqlite3_mprintf(
"SELECT name FROM sqlite_master"
" WHERE type='index'"
" AND tbl_name LIKE ?1");
}
for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
if( zDbName==0 || ii==0 ) continue;
if( c=='t' ){
zSql = sqlite3_mprintf(
"%z UNION ALL "
"SELECT '%q.' || name FROM \"%w\".sqlite_master"
" WHERE type IN ('table','view')"
" AND name NOT LIKE 'sqlite_%%'"
" AND name LIKE ?1", zSql, zDbName, zDbName);
}else{
zSql = sqlite3_mprintf(
"%z UNION ALL "
"SELECT '%q.' || name FROM \"%w\".sqlite_master"
" WHERE type='index'"
" AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
}
}
rc = sqlite3_finalize(pStmt);
if( zSql && rc==SQLITE_OK ){
zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
}
sqlite3_free(zSql);
if( !zSql ) return shellNomemError();
if( rc ) return shellDatabaseError(p->db);
/* Run the SQL statement prepared by the above block. Store the results
** as an array of nul-terminated strings in azResult[]. */
nRow = nAlloc = 0;
azResult = 0;
if( nArg>1 ){
sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
}else{
sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
}
while( sqlite3_step(pStmt)==SQLITE_ROW ){
if( nRow>=nAlloc ){
char **azNew;
int n2 = nAlloc*2 + 10;
azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
if( azNew==0 ){
rc = shellNomemError();
break;
}
nAlloc = n2;
azResult = azNew;
}
azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
if( 0==azResult[nRow] ){
rc = shellNomemError();
break;
}
nRow++;
}
if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
rc = shellDatabaseError(p->db);
}
/* Pretty-print the contents of array azResult[] to the output */
if( rc==0 && nRow>0 ){
int len, maxlen = 0;
int i, j;
int nPrintCol, nPrintRow;
for(i=0; i<nRow; i++){
len = strlen30(azResult[i]);
if( len>maxlen ) maxlen = len;
}
nPrintCol = 80/(maxlen+2);
if( nPrintCol<1 ) nPrintCol = 1;
nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
for(i=0; i<nPrintRow; i++){
for(j=i; j<nRow; j+=nPrintRow){
char *zSp = j<nPrintRow ? "" : " ";
utf8_printf(p->out, "%s%-*s", zSp, maxlen,
azResult[j] ? azResult[j]:"");
}
raw_printf(p->out, "\n");
}
}
for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
sqlite3_free(azResult);
}else
/* Begin redirecting output to the file "testcase-out.txt" */
if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
output_reset(p);
p->out = output_file_open("testcase-out.txt");
if( p->out==0 ){
raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
}
if( nArg>=2 ){
sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
}else{
sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
}
}else
#ifndef SQLITE_UNTESTABLE
if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
static const struct {
const char *zCtrlName; /* Name of a test-control option */
int ctrlCode; /* Integer code for that option */
} aCtrl[] = {
{ "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
{ "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
{ "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
{ "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
{ "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
{ "assert", SQLITE_TESTCTRL_ASSERT },
{ "always", SQLITE_TESTCTRL_ALWAYS },
{ "reserve", SQLITE_TESTCTRL_RESERVE },
{ "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
{ "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
{ "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
{ "byteorder", SQLITE_TESTCTRL_BYTEORDER },
{ "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
{ "imposter", SQLITE_TESTCTRL_IMPOSTER },
};
int testctrl = -1;
int rc2 = 0;
int i, n2;
open_db(p, 0);
/* convert testctrl text option to value. allow any unique prefix
** of the option name, or a numerical value. */
n2 = strlen30(azArg[1]);
for(i=0; i<ArraySize(aCtrl); i++){
if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
if( testctrl<0 ){
testctrl = aCtrl[i].ctrlCode;
}else{
utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
testctrl = -1;
break;
}
}
}
if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
}else{
switch(testctrl){
/* sqlite3_test_control(int, db, int) */
case SQLITE_TESTCTRL_OPTIMIZATIONS:
case SQLITE_TESTCTRL_RESERVE:
if( nArg==3 ){
int opt = (int)strtol(azArg[2], 0, 0);
rc2 = sqlite3_test_control(testctrl, p->db, opt);
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
} else {
utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
azArg[1]);
}
break;
/* sqlite3_test_control(int) */
case SQLITE_TESTCTRL_PRNG_SAVE:
case SQLITE_TESTCTRL_PRNG_RESTORE:
case SQLITE_TESTCTRL_PRNG_RESET:
case SQLITE_TESTCTRL_BYTEORDER:
if( nArg==2 ){
rc2 = sqlite3_test_control(testctrl);
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
} else {
utf8_printf(stderr,"Error: testctrl %s takes no options\n",
azArg[1]);
}
break;
/* sqlite3_test_control(int, uint) */
case SQLITE_TESTCTRL_PENDING_BYTE:
if( nArg==3 ){
unsigned int opt = (unsigned int)integerValue(azArg[2]);
rc2 = sqlite3_test_control(testctrl, opt);
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
} else {
utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
" int option\n", azArg[1]);
}
break;
/* sqlite3_test_control(int, int) */
case SQLITE_TESTCTRL_ASSERT:
case SQLITE_TESTCTRL_ALWAYS:
case SQLITE_TESTCTRL_NEVER_CORRUPT:
if( nArg==3 ){
int opt = booleanValue(azArg[2]);
rc2 = sqlite3_test_control(testctrl, opt);
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
} else {
utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
azArg[1]);
}
break;
/* sqlite3_test_control(int, char *) */
#ifdef SQLITE_N_KEYWORD
case SQLITE_TESTCTRL_ISKEYWORD:
if( nArg==3 ){
const char *opt = azArg[2];
rc2 = sqlite3_test_control(testctrl, opt);
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
} else {
utf8_printf(stderr,
"Error: testctrl %s takes a single char * option\n",
azArg[1]);
}
break;
#endif
case SQLITE_TESTCTRL_IMPOSTER:
if( nArg==5 ){
rc2 = sqlite3_test_control(testctrl, p->db,
azArg[2],
integerValue(azArg[3]),
integerValue(azArg[4]));
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
}else{
raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
}
break;
case SQLITE_TESTCTRL_BITVEC_TEST:
case SQLITE_TESTCTRL_FAULT_INSTALL:
case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
case SQLITE_TESTCTRL_SCRATCHMALLOC:
default:
utf8_printf(stderr,
"Error: CLI support for testctrl %s not implemented\n",
azArg[1]);
break;
}
}
}else
if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
open_db(p, 0);
sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
}else
if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
if( nArg==2 ){
enableTimer = booleanValue(azArg[1]);
if( enableTimer && !HAS_TIMER ){
raw_printf(stderr, "Error: timer not available on this system.\n");
enableTimer = 0;
}
}else{
raw_printf(stderr, "Usage: .timer on|off\n");
rc = 1;
}
}else
if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
open_db(p, 0);
if( nArg!=2 ){
raw_printf(stderr, "Usage: .trace FILE|off\n");
rc = 1;
goto meta_command_exit;
}
output_file_close(p->traceOut);
p->traceOut = output_file_open(azArg[1]);
#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
if( p->traceOut==0 ){
sqlite3_trace_v2(p->db, 0, 0, 0);
}else{
sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
}
#endif
}else
#endif /* !defined(SQLITE_UNTESTABLE) */
#if SQLITE_USER_AUTHENTICATION
if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
if( nArg<2 ){
raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
if( strcmp(azArg[1],"login")==0 ){
if( nArg!=4 ){
raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
(int)strlen(azArg[3]));
if( rc ){
utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
rc = 1;
}
}else if( strcmp(azArg[1],"add")==0 ){
if( nArg!=5 ){
raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_add(p->db, azArg[2],
azArg[3], (int)strlen(azArg[3]),
booleanValue(azArg[4]));
if( rc ){
raw_printf(stderr, "User-Add failed: %d\n", rc);
rc = 1;
}
}else if( strcmp(azArg[1],"edit")==0 ){
if( nArg!=5 ){
raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_change(p->db, azArg[2],
azArg[3], (int)strlen(azArg[3]),
booleanValue(azArg[4]));
if( rc ){
raw_printf(stderr, "User-Edit failed: %d\n", rc);
rc = 1;
}
}else if( strcmp(azArg[1],"delete")==0 ){
if( nArg!=3 ){
raw_printf(stderr, "Usage: .user delete USER\n");
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_delete(p->db, azArg[2]);
if( rc ){
raw_printf(stderr, "User-Delete failed: %d\n", rc);
rc = 1;
}
}else{
raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
rc = 1;
goto meta_command_exit;
}
}else
#endif /* SQLITE_USER_AUTHENTICATION */
if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
sqlite3_libversion(), sqlite3_sourceid());
}else
if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
const char *zDbName = nArg==2 ? azArg[1] : "main";
sqlite3_vfs *pVfs;
if( p->db ){
sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
if( pVfs ){
utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
}
}
}else
if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
sqlite3_vfs *pVfs;
sqlite3_vfs *pCurrent = 0;
if( p->db ){
sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
}
for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
pVfs==pCurrent ? " <--- CURRENT" : "");
raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
if( pVfs->pNext ){
raw_printf(p->out, "-----------------------------------\n");
}
}
}else
if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
const char *zDbName = nArg==2 ? azArg[1] : "main";
char *zVfsName = 0;
if( p->db ){
sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
if( zVfsName ){
utf8_printf(p->out, "%s\n", zVfsName);
sqlite3_free(zVfsName);
}
}
}else
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
}else
#endif
if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
int j;
assert( nArg<=ArraySize(azArg) );
for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
p->colWidth[j-1] = (int)integerValue(azArg[j]);
}
}else
{
utf8_printf(stderr, "Error: unknown command or invalid arguments: "
" \"%s\". Enter \".help\" for help\n", azArg[0]);
rc = 1;
}
meta_command_exit:
if( p->outCount ){
p->outCount--;
if( p->outCount==0 ) output_reset(p);
}
return rc;
}
/*
** Return TRUE if a semicolon occurs anywhere in the first N characters
** of string z[].
*/
static int line_contains_semicolon(const char *z, int N){
int i;
for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
return 0;
}
/*
** Test to see if a line consists entirely of whitespace.
*/
static int _all_whitespace(const char *z){
for(; *z; z++){
if( IsSpace(z[0]) ) continue;
if( *z=='/' && z[1]=='*' ){
z += 2;
while( *z && (*z!='*' || z[1]!='/') ){ z++; }
if( *z==0 ) return 0;
z++;
continue;
}
if( *z=='-' && z[1]=='-' ){
z += 2;
while( *z && *z!='\n' ){ z++; }
if( *z==0 ) return 1;
continue;
}
return 0;
}
return 1;
}
/*
** Return TRUE if the line typed in is an SQL command terminator other
** than a semi-colon. The SQL Server style "go" command is understood
** as is the Oracle "/".
*/
static int line_is_command_terminator(const char *zLine){
while( IsSpace(zLine[0]) ){ zLine++; };
if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
return 1; /* Oracle */
}
if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
&& _all_whitespace(&zLine[2]) ){
return 1; /* SQL Server */
}
return 0;
}
/*
** Return true if zSql is a complete SQL statement. Return false if it
** ends in the middle of a string literal or C-style comment.
*/
static int line_is_complete(char *zSql, int nSql){
int rc;
if( zSql==0 ) return 1;
zSql[nSql] = ';';
zSql[nSql+1] = 0;
rc = sqlite3_complete(zSql);
zSql[nSql] = 0;
return rc;
}
/*
** Run a single line of SQL
*/
static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
int rc;
char *zErrMsg = 0;
open_db(p, 0);
if( p->backslashOn ) resolve_backslashes(zSql);
BEGIN_TIMER;
rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
END_TIMER;
if( rc || zErrMsg ){
char zPrefix[100];
if( in!=0 || !stdin_is_interactive ){
sqlite3_snprintf(sizeof(zPrefix), zPrefix,
"Error: near line %d:", startline);
}else{
sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
}
if( zErrMsg!=0 ){
utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
sqlite3_free(zErrMsg);
zErrMsg = 0;
}else{
utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
}
return 1;
}else if( p->countChanges ){
raw_printf(p->out, "changes: %3d total_changes: %d\n",
sqlite3_changes(p->db), sqlite3_total_changes(p->db));
}
return 0;
}
/*
** Read input from *in and process it. If *in==0 then input
** is interactive - the user is typing it it. Otherwise, input
** is coming from a file or device. A prompt is issued and history
** is saved only if input is interactive. An interrupt signal will
** cause this routine to exit immediately, unless input is interactive.
**
** Return the number of errors.
*/
static int process_input(ShellState *p, FILE *in){
char *zLine = 0; /* A single input line */
char *zSql = 0; /* Accumulated SQL text */
int nLine; /* Length of current line */
int nSql = 0; /* Bytes of zSql[] used */
int nAlloc = 0; /* Allocated zSql[] space */
int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
int rc; /* Error code */
int errCnt = 0; /* Number of errors seen */
int lineno = 0; /* Current line number */
int startline = 0; /* Line number for start of current input */
while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
fflush(p->out);
zLine = one_input_line(in, zLine, nSql>0);
if( zLine==0 ){
/* End of input */
if( in==0 && stdin_is_interactive ) printf("\n");
break;
}
if( seenInterrupt ){
if( in!=0 ) break;
seenInterrupt = 0;
}
lineno++;
if( nSql==0 && _all_whitespace(zLine) ){
if( p->echoOn ) printf("%s\n", zLine);
continue;
}
if( zLine && zLine[0]=='.' && nSql==0 ){
if( p->echoOn ) printf("%s\n", zLine);
rc = do_meta_command(zLine, p);
if( rc==2 ){ /* exit requested */
break;
}else if( rc ){
errCnt++;
}
continue;
}
if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
memcpy(zLine,";",2);
}
nLine = strlen30(zLine);
if( nSql+nLine+2>=nAlloc ){
nAlloc = nSql+nLine+100;
zSql = realloc(zSql, nAlloc);
if( zSql==0 ){
raw_printf(stderr, "Error: out of memory\n");
exit(1);
}
}
nSqlPrior = nSql;
if( nSql==0 ){
int i;
for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
assert( nAlloc>0 && zSql!=0 );
memcpy(zSql, zLine+i, nLine+1-i);
startline = lineno;
nSql = nLine-i;
}else{
zSql[nSql++] = '\n';
memcpy(zSql+nSql, zLine, nLine+1);
nSql += nLine;
}
if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
&& sqlite3_complete(zSql) ){
errCnt += runOneSqlLine(p, zSql, in, startline);
nSql = 0;
if( p->outCount ){
output_reset(p);
p->outCount = 0;
}
}else if( nSql && _all_whitespace(zSql) ){
if( p->echoOn ) printf("%s\n", zSql);
nSql = 0;
}
}
if( nSql && !_all_whitespace(zSql) ){
runOneSqlLine(p, zSql, in, startline);
}
free(zSql);
free(zLine);
return errCnt>0;
}
/*
** Return a pathname which is the user's home directory. A
** 0 return indicates an error of some kind.
*/
static char *find_home_dir(int clearFlag){
static char *home_dir = NULL;
if( clearFlag ){
free(home_dir);
home_dir = 0;
return 0;
}
if( home_dir ) return home_dir;
#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
&& !defined(__RTP__) && !defined(_WRS_KERNEL)
{
struct passwd *pwent;
uid_t uid = getuid();
if( (pwent=getpwuid(uid)) != NULL) {
home_dir = pwent->pw_dir;
}
}
#endif
#if defined(_WIN32_WCE)
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
*/
home_dir = "/";
#else
#if defined(_WIN32) || defined(WIN32)
if (!home_dir) {
home_dir = getenv("USERPROFILE");
}
#endif
if (!home_dir) {
home_dir = getenv("HOME");
}
#if defined(_WIN32) || defined(WIN32)
if (!home_dir) {
char *zDrive, *zPath;
int n;
zDrive = getenv("HOMEDRIVE");
zPath = getenv("HOMEPATH");
if( zDrive && zPath ){
n = strlen30(zDrive) + strlen30(zPath) + 1;
home_dir = malloc( n );
if( home_dir==0 ) return 0;
sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
return home_dir;
}
home_dir = "c:\\";
}
#endif
#endif /* !_WIN32_WCE */
if( home_dir ){
int n = strlen30(home_dir) + 1;
char *z = malloc( n );
if( z ) memcpy(z, home_dir, n);
home_dir = z;
}
return home_dir;
}
/*
** Read input from the file given by sqliterc_override. Or if that
** parameter is NULL, take input from ~/.sqliterc
**
** Returns the number of errors.
*/
static void process_sqliterc(
ShellState *p, /* Configuration data */
const char *sqliterc_override /* Name of config file. NULL to use default */
){
char *home_dir = NULL;
const char *sqliterc = sqliterc_override;
char *zBuf = 0;
FILE *in = NULL;
if (sqliterc == NULL) {
home_dir = find_home_dir(0);
if( home_dir==0 ){
raw_printf(stderr, "-- warning: cannot find home directory;"
" cannot read ~/.sqliterc\n");
return;
}
sqlite3_initialize();
zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
sqliterc = zBuf;
}
in = fopen(sqliterc,"rb");
if( in ){
if( stdin_is_interactive ){
utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
}
process_input(p,in);
fclose(in);
}
sqlite3_free(zBuf);
}
/*
** Show available command line options
*/
static const char zOptions[] =
" -ascii set output mode to 'ascii'\n"
" -bail stop after hitting an error\n"
" -batch force batch I/O\n"
" -column set output mode to 'column'\n"
" -cmd COMMAND run \"COMMAND\" before reading stdin\n"
" -csv set output mode to 'csv'\n"
" -echo print commands before execution\n"
" -init FILENAME read/process named file\n"
" -[no]header turn headers on or off\n"
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
" -heap SIZE Size of heap for memsys3 or memsys5\n"
#endif
" -help show this message\n"
" -html set output mode to HTML\n"
" -interactive force interactive I/O\n"
" -line set output mode to 'line'\n"
" -list set output mode to 'list'\n"
" -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
" -mmap N default mmap size set to N\n"
#ifdef SQLITE_ENABLE_MULTIPLEX
" -multiplex enable the multiplexor VFS\n"
#endif
" -newline SEP set output row separator. Default: '\\n'\n"
" -nullvalue TEXT set text string for NULL values. Default ''\n"
" -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
" -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
" -separator SEP set output column separator. Default: '|'\n"
" -stats print memory stats before each finalize\n"
" -version show SQLite version\n"
" -vfs NAME use NAME as the default VFS\n"
#ifdef SQLITE_ENABLE_VFSTRACE
" -vfstrace enable tracing of all VFS calls\n"
#endif
;
static void usage(int showDetail){
utf8_printf(stderr,
"Usage: %s [OPTIONS] FILENAME [SQL]\n"
"FILENAME is the name of an SQLite database. A new database is created\n"
"if the file does not previously exist.\n", Argv0);
if( showDetail ){
utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
}else{
raw_printf(stderr, "Use the -help option for additional information\n");
}
exit(1);
}
/*
** Initialize the state information in data
*/
static void main_init(ShellState *data) {
memset(data, 0, sizeof(*data));
data->normalMode = data->cMode = data->mode = MODE_List;
data->autoExplain = 1;
memcpy(data->colSeparator,SEP_Column, 2);
memcpy(data->rowSeparator,SEP_Row, 2);
data->showHeader = 0;
data->shellFlgs = SHFLG_Lookaside;
sqlite3_config(SQLITE_CONFIG_URI, 1);
sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
}
/*
** Output text to the console in a font that attracts extra attention.
*/
#ifdef _WIN32
static void printBold(const char *zText){
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
SetConsoleTextAttribute(out,
FOREGROUND_RED|FOREGROUND_INTENSITY
);
printf("%s", zText);
SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
}
#else
static void printBold(const char *zText){
printf("\033[1m%s\033[0m", zText);
}
#endif
/*
** Get the argument to an --option. Throw an error and die if no argument
** is available.
*/
static char *cmdline_option_value(int argc, char **argv, int i){
if( i==argc ){
utf8_printf(stderr, "%s: Error: missing argument to %s\n",
argv[0], argv[argc-1]);
exit(1);
}
return argv[i];
}
#ifndef SQLITE_SHELL_IS_UTF8
# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
# define SQLITE_SHELL_IS_UTF8 (0)
# else
# define SQLITE_SHELL_IS_UTF8 (1)
# endif
#endif
#if SQLITE_SHELL_IS_UTF8
int SQLITE_CDECL main(int argc, char **argv){
#else
int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
char **argv;
#endif
char *zErrMsg = 0;
ShellState data;
const char *zInitFile = 0;
int i;
int rc = 0;
int warnInmemoryDb = 0;
int readStdin = 1;
int nCmd = 0;
char **azCmd = 0;
setBinaryMode(stdin, 0);
setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
stdin_is_interactive = isatty(0);
stdout_is_console = isatty(1);
#if USE_SYSTEM_SQLITE+0!=1
if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
sqlite3_sourceid(), SQLITE_SOURCE_ID);
exit(1);
}
#endif
main_init(&data);
#if !SQLITE_SHELL_IS_UTF8
sqlite3_initialize();
argv = sqlite3_malloc64(sizeof(argv[0])*argc);
if( argv==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
for(i=0; i<argc; i++){
argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
if( argv[i]==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
}
#endif
assert( argc>=1 && argv && argv[0] );
Argv0 = argv[0];
/* Make sure we have a valid signal handler early, before anything
** else is done.
*/
#ifdef SIGINT
signal(SIGINT, interrupt_handler);
#endif
#ifdef SQLITE_SHELL_DBNAME_PROC
{
/* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
** of a C-function that will provide the name of the database file. Use
** this compile-time option to embed this shell program in larger
** applications. */
extern void SQLITE_SHELL_DBNAME_PROC(const char**);
SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
warnInmemoryDb = 0;
}
#endif
/* Do an initial pass through the command-line argument to locate
** the name of the database file, the name of the initialization file,
** the size of the alternative malloc heap,
** and the first command to execute.
*/
for(i=1; i<argc; i++){
char *z;
z = argv[i];
if( z[0]!='-' ){
if( data.zDbFilename==0 ){
data.zDbFilename = z;
}else{
/* Excesss arguments are interpreted as SQL (or dot-commands) and
** mean that nothing is read from stdin */
readStdin = 0;
nCmd++;
azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
if( azCmd==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
azCmd[nCmd-1] = z;
}
}
if( z[1]=='-' ) z++;
if( strcmp(z,"-separator")==0
|| strcmp(z,"-nullvalue")==0
|| strcmp(z,"-newline")==0
|| strcmp(z,"-cmd")==0
){
(void)cmdline_option_value(argc, argv, ++i);
}else if( strcmp(z,"-init")==0 ){
zInitFile = cmdline_option_value(argc, argv, ++i);
}else if( strcmp(z,"-batch")==0 ){
/* Need to check for batch mode here to so we can avoid printing
** informational messages (like from process_sqliterc) before
** we do the actual processing of arguments later in a second pass.
*/
stdin_is_interactive = 0;
}else if( strcmp(z,"-heap")==0 ){
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
const char *zSize;
sqlite3_int64 szHeap;
zSize = cmdline_option_value(argc, argv, ++i);
szHeap = integerValue(zSize);
if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
#else
(void)cmdline_option_value(argc, argv, ++i);
#endif
}else if( strcmp(z,"-scratch")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz>400000 ) sz = 400000;
if( sz<2500 ) sz = 2500;
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( n>10 ) n = 10;
if( n<1 ) n = 1;
sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
data.shellFlgs |= SHFLG_Scratch;
}else if( strcmp(z,"-pagecache")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz>70000 ) sz = 70000;
if( sz<0 ) sz = 0;
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
sqlite3_config(SQLITE_CONFIG_PAGECACHE,
(n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
data.shellFlgs |= SHFLG_Pagecache;
}else if( strcmp(z,"-lookaside")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz<0 ) sz = 0;
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( n<0 ) n = 0;
sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
#ifdef SQLITE_ENABLE_VFSTRACE
}else if( strcmp(z,"-vfstrace")==0 ){
extern int vfstrace_register(
const char *zTraceName,
const char *zOldVfsName,
int (*xOut)(const char*,void*),
void *pOutArg,
int makeDefault
);
vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
#endif
#ifdef SQLITE_ENABLE_MULTIPLEX
}else if( strcmp(z,"-multiplex")==0 ){
extern int sqlite3_multiple_initialize(const char*,int);
sqlite3_multiplex_initialize(0, 1);
#endif
}else if( strcmp(z,"-mmap")==0 ){
sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
}else if( strcmp(z,"-vfs")==0 ){
sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
if( pVfs ){
sqlite3_vfs_register(pVfs, 1);
}else{
utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
exit(1);
}
}
}
if( data.zDbFilename==0 ){
#ifndef SQLITE_OMIT_MEMORYDB
data.zDbFilename = ":memory:";
warnInmemoryDb = argc==1;
#else
utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
return 1;
#endif
}
data.out = stdout;
/* Go ahead and open the database file if it already exists. If the
** file does not exist, delay opening it. This prevents empty database
** files from being created if a user mistypes the database name argument
** to the sqlite command-line tool.
*/
if( access(data.zDbFilename, 0)==0 ){
open_db(&data, 0);
}
/* Process the initialization file if there is one. If no -init option
** is given on the command line, look for a file named ~/.sqliterc and
** try to process it.
*/
process_sqliterc(&data,zInitFile);
/* Make a second pass through the command-line argument and set
** options. This second pass is delayed until after the initialization
** file is processed so that the command-line arguments will override
** settings in the initialization file.
*/
for(i=1; i<argc; i++){
char *z = argv[i];
if( z[0]!='-' ) continue;
if( z[1]=='-' ){ z++; }
if( strcmp(z,"-init")==0 ){
i++;
}else if( strcmp(z,"-html")==0 ){
data.mode = MODE_Html;
}else if( strcmp(z,"-list")==0 ){
data.mode = MODE_List;
}else if( strcmp(z,"-line")==0 ){
data.mode = MODE_Line;
}else if( strcmp(z,"-column")==0 ){
data.mode = MODE_Column;
}else if( strcmp(z,"-csv")==0 ){
data.mode = MODE_Csv;
memcpy(data.colSeparator,",",2);
}else if( strcmp(z,"-ascii")==0 ){
data.mode = MODE_Ascii;
sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
SEP_Unit);
sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
SEP_Record);
}else if( strcmp(z,"-separator")==0 ){
sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
"%s",cmdline_option_value(argc,argv,++i));
}else if( strcmp(z,"-newline")==0 ){
sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
"%s",cmdline_option_value(argc,argv,++i));
}else if( strcmp(z,"-nullvalue")==0 ){
sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
"%s",cmdline_option_value(argc,argv,++i));
}else if( strcmp(z,"-header")==0 ){
data.showHeader = 1;
}else if( strcmp(z,"-noheader")==0 ){
data.showHeader = 0;
}else if( strcmp(z,"-echo")==0 ){
data.echoOn = 1;
}else if( strcmp(z,"-eqp")==0 ){
data.autoEQP = 1;
}else if( strcmp(z,"-eqpfull")==0 ){
data.autoEQP = 2;
}else if( strcmp(z,"-stats")==0 ){
data.statsOn = 1;
}else if( strcmp(z,"-scanstats")==0 ){
data.scanstatsOn = 1;
}else if( strcmp(z,"-backslash")==0 ){
/* Undocumented command-line option: -backslash
** Causes C-style backslash escapes to be evaluated in SQL statements
** prior to sending the SQL into SQLite. Useful for injecting
** crazy bytes in the middle of SQL statements for testing and debugging.
*/
data.backslashOn = 1;
}else if( strcmp(z,"-bail")==0 ){
bail_on_error = 1;
}else if( strcmp(z,"-version")==0 ){
printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
return 0;
}else if( strcmp(z,"-interactive")==0 ){
stdin_is_interactive = 1;
}else if( strcmp(z,"-batch")==0 ){
stdin_is_interactive = 0;
}else if( strcmp(z,"-heap")==0 ){
i++;
}else if( strcmp(z,"-scratch")==0 ){
i+=2;
}else if( strcmp(z,"-pagecache")==0 ){
i+=2;
}else if( strcmp(z,"-lookaside")==0 ){
i+=2;
}else if( strcmp(z,"-mmap")==0 ){
i++;
}else if( strcmp(z,"-vfs")==0 ){
i++;
#ifdef SQLITE_ENABLE_VFSTRACE
}else if( strcmp(z,"-vfstrace")==0 ){
i++;
#endif
#ifdef SQLITE_ENABLE_MULTIPLEX
}else if( strcmp(z,"-multiplex")==0 ){
i++;
#endif
}else if( strcmp(z,"-help")==0 ){
usage(1);
}else if( strcmp(z,"-cmd")==0 ){
/* Run commands that follow -cmd first and separately from commands
** that simply appear on the command-line. This seems goofy. It would
** be better if all commands ran in the order that they appear. But
** we retain the goofy behavior for historical compatibility. */
if( i==argc-1 ) break;
z = cmdline_option_value(argc,argv,++i);
if( z[0]=='.' ){
rc = do_meta_command(z, &data);
if( rc && bail_on_error ) return rc==2 ? 0 : rc;
}else{
open_db(&data, 0);
rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
if( zErrMsg!=0 ){
utf8_printf(stderr,"Error: %s\n", zErrMsg);
if( bail_on_error ) return rc!=0 ? rc : 1;
}else if( rc!=0 ){
utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
if( bail_on_error ) return rc;
}
}
}else{
utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
raw_printf(stderr,"Use -help for a list of options.\n");
return 1;
}
data.cMode = data.mode;
}
if( !readStdin ){
/* Run all arguments that do not begin with '-' as if they were separate
** command-line inputs, except for the argToSkip argument which contains
** the database filename.
*/
for(i=0; i<nCmd; i++){
if( azCmd[i][0]=='.' ){
rc = do_meta_command(azCmd[i], &data);
if( rc ) return rc==2 ? 0 : rc;
}else{
open_db(&data, 0);
rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
if( zErrMsg!=0 ){
utf8_printf(stderr,"Error: %s\n", zErrMsg);
return rc!=0 ? rc : 1;
}else if( rc!=0 ){
utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
return rc;
}
}
}
free(azCmd);
}else{
/* Run commands received from standard input
*/
if( stdin_is_interactive ){
char *zHome;
char *zHistory = 0;
int nHistory;
printf(
"SQLite version %s %.19s\n" /*extra-version-info*/
"Enter \".help\" for usage hints.\n",
sqlite3_libversion(), sqlite3_sourceid()
);
if( warnInmemoryDb ){
printf("Connected to a ");
printBold("transient in-memory database");
printf(".\nUse \".open FILENAME\" to reopen on a "
"persistent database.\n");
}
zHome = find_home_dir(0);
if( zHome ){
nHistory = strlen30(zHome) + 20;
if( (zHistory = malloc(nHistory))!=0 ){
sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
}
}
if( zHistory ){ shell_read_history(zHistory); }
rc = process_input(&data, 0);
if( zHistory ){
shell_stifle_history(100);
shell_write_history(zHistory);
free(zHistory);
}
}else{
rc = process_input(&data, stdin);
}
}
set_table_name(&data, 0);
if( data.db ){
session_close_all(&data);
sqlite3_close(data.db);
}
sqlite3_free(data.zFreeOnClose);
find_home_dir(1);
#if !SQLITE_SHELL_IS_UTF8
for(i=0; i<argc; i++) sqlite3_free(argv[i]);
sqlite3_free(argv);
#endif
return rc;
}
|
the_stack_data/62636471.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <search.h>
#include <errno.h>
#include <inttypes.h>
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define BIG_ENDIAN_HOST
#endif
#if defined (_WIN32) || defined (_WIN64)
typedef unsigned int lsearch_cnt_t;
#else
typedef size_t lsearch_cnt_t;
#endif
#pragma pack(1)
/**
* Name........: cap2hccapx.c
* Autor.......: Jens Steube <[email protected]>, Philipp "philsmd" Schmidt <[email protected]>
* License.....: MIT
*/
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
// from pcap.h
#define TCPDUMP_MAGIC 0xa1b2c3d4
#define TCPDUMP_CIGAM 0xd4c3b2a1
#define TCPDUMP_DECODE_LEN 65535
#define DLT_NULL 0 /* BSD loopback encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* IEEE 802 Networks */
#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_RAW 12 /* Raw headers (no link layer) */
#define DLT_RAW2 14
#define DLT_RAW3 101
#define DLT_IEEE802_11 105 /* IEEE 802.11 wireless */
#define DLT_IEEE802_11_PRISM 119
#define DLT_IEEE802_11_RADIO 127
#define DLT_IEEE802_11_PPI_HDR 192
struct pcap_file_header {
u32 magic;
u16 version_major;
u16 version_minor;
u32 thiszone; /* gmt to local correction */
u32 sigfigs; /* accuracy of timestamps */
u32 snaplen; /* max length saved portion of each pkt */
u32 linktype; /* data link type (LINKTYPE_*) */
};
struct pcap_pkthdr {
u32 tv_sec; /* timestamp seconds */
u32 tv_usec; /* timestamp microseconds */
u32 caplen; /* length of portion present */
u32 len; /* length this packet (off wire) */
};
typedef struct pcap_file_header pcap_file_header_t;
typedef struct pcap_pkthdr pcap_pkthdr_t;
// from linux/ieee80211.h
struct ieee80211_hdr_3addr {
u16 frame_control;
u16 duration_id;
u8 addr1[6];
u8 addr2[6];
u8 addr3[6];
u16 seq_ctrl;
} __attribute__((packed));
struct ieee80211_qos_hdr {
u16 frame_control;
u16 duration_id;
u8 addr1[6];
u8 addr2[6];
u8 addr3[6];
u16 seq_ctrl;
u16 qos_ctrl;
} __attribute__((packed));
typedef struct ieee80211_hdr_3addr ieee80211_hdr_3addr_t;
typedef struct ieee80211_qos_hdr ieee80211_qos_hdr_t;
struct ieee80211_llc_snap_header
{
/* LLC part: */
u8 dsap; /**< Destination SAP ID */
u8 ssap; /**< Source SAP ID */
u8 ctrl; /**< Control information */
/* SNAP part: */
u8 oui[3]; /**< Organization code, usually 0 */
u16 ethertype; /**< Ethernet Type field */
} __attribute__((packed));
typedef struct ieee80211_llc_snap_header ieee80211_llc_snap_header_t;
#define IEEE80211_FCTL_FTYPE 0x000c
#define IEEE80211_FCTL_STYPE 0x00f0
#define IEEE80211_FCTL_TODS 0x0100
#define IEEE80211_FCTL_FROMDS 0x0200
#define IEEE80211_FTYPE_MGMT 0x0000
#define IEEE80211_FTYPE_DATA 0x0008
#define IEEE80211_STYPE_ASSOC_REQ 0x0000
#define IEEE80211_STYPE_ASSOC_RESP 0x0010
#define IEEE80211_STYPE_REASSOC_REQ 0x0020
#define IEEE80211_STYPE_REASSOC_RESP 0x0030
#define IEEE80211_STYPE_PROBE_REQ 0x0040
#define IEEE80211_STYPE_PROBE_RESP 0x0050
#define IEEE80211_STYPE_BEACON 0x0080
#define IEEE80211_STYPE_QOS_DATA 0x0080
#define IEEE80211_STYPE_ATIM 0x0090
#define IEEE80211_STYPE_DISASSOC 0x00A0
#define IEEE80211_STYPE_AUTH 0x00B0
#define IEEE80211_STYPE_DEAUTH 0x00C0
#define IEEE80211_STYPE_ACTION 0x00D0
#define IEEE80211_LLC_DSAP 0xAA
#define IEEE80211_LLC_SSAP 0xAA
#define IEEE80211_LLC_CTRL 0x03
#define IEEE80211_DOT1X_AUTHENTICATION 0x8E88
/* Management Frame Information Element Types */
#define MFIE_TYPE_SSID 0
#define MFIE_TYPE_RATES 1
#define MFIE_TYPE_FH_SET 2
#define MFIE_TYPE_DS_SET 3
#define MFIE_TYPE_CF_SET 4
#define MFIE_TYPE_TIM 5
#define MFIE_TYPE_IBSS_SET 6
#define MFIE_TYPE_CHALLENGE 16
#define MFIE_TYPE_ERP 42
#define MFIE_TYPE_RSN 48
#define MFIE_TYPE_RATES_EX 50
#define MFIE_TYPE_GENERIC 221
// from ks7010/eap_packet.h
#define WBIT(n) (1 << (n))
#define WPA_KEY_INFO_TYPE_MASK (WBIT(0) | WBIT(1) | WBIT(2))
#define WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 WBIT(0)
#define WPA_KEY_INFO_TYPE_HMAC_SHA1_AES WBIT(1)
#define WPA_KEY_INFO_KEY_TYPE WBIT(3) /* 1 = Pairwise, 0 = Group key */
#define WPA_KEY_INFO_KEY_INDEX_MASK (WBIT(4) | WBIT(5))
#define WPA_KEY_INFO_KEY_INDEX_SHIFT 4
#define WPA_KEY_INFO_INSTALL WBIT(6) /* pairwise */
#define WPA_KEY_INFO_TXRX WBIT(6) /* group */
#define WPA_KEY_INFO_ACK WBIT(7)
#define WPA_KEY_INFO_MIC WBIT(8)
#define WPA_KEY_INFO_SECURE WBIT(9)
#define WPA_KEY_INFO_ERROR WBIT(10)
#define WPA_KEY_INFO_REQUEST WBIT(11)
#define WPA_KEY_INFO_ENCR_KEY_DATA WBIT(12) /* IEEE 802.11i/RSN only */
// radiotap header from http://www.radiotap.org/
struct ieee80211_radiotap_header
{
u8 it_version; /* set to 0 */
u8 it_pad;
u16 it_len; /* entire length */
u32 it_present; /* fields present */
} __attribute__((packed));
typedef struct ieee80211_radiotap_header ieee80211_radiotap_header_t;
// prism header
#define WLAN_DEVNAMELEN_MAX 16
struct prism_item
{
u32 did;
u16 status;
u16 len;
u32 data;
} __attribute__((packed));
struct prism_header
{
u32 msgcode;
u32 msglen;
char devname[WLAN_DEVNAMELEN_MAX];
struct prism_item hosttime;
struct prism_item mactime;
struct prism_item channel;
struct prism_item rssi;
struct prism_item sq;
struct prism_item signal;
struct prism_item noise;
struct prism_item rate;
struct prism_item istx;
struct prism_item frmlen;
} __attribute__((packed));
typedef struct prism_item prism_item_t;
typedef struct prism_header prism_header_t;
/* CACE PPI headers */
struct ppi_packet_header
{
uint8_t pph_version;
uint8_t pph_flags;
uint16_t pph_len;
uint32_t pph_dlt;
} __attribute__((packed));
typedef struct ppi_packet_header ppi_packet_header_t;
struct ppi_field_header
{
uint16_t pfh_datatype;
uint16_t pfh_datalen;
} __attribute__((__packed__));
typedef struct ppi_field_header ppi_field_header_t;
#define PPI_FIELD_11COMMON 2
#define PPI_FIELD_11NMAC 3
#define PPI_FIELD_11NMACPHY 4
#define PPI_FIELD_SPECMAP 5
#define PPI_FIELD_PROCINFO 6
#define PPI_FIELD_CAPINFO 7
// own structs
struct beaconinfo
{
u64 beacon_timestamp;
u16 beacon_interval;
u16 beacon_capabilities;
} __attribute__((packed));
typedef struct beaconinfo beacon_t;
struct associationreqf
{
u16 client_capabilities;
u16 client_listeninterval;
} __attribute__((packed));
typedef struct associationreqf assocreq_t;
struct reassociationreqf
{
u16 client_capabilities;
u16 client_listeninterval;
u8 addr[6];
} __attribute__((packed));
typedef struct reassociationreqf reassocreq_t;
struct auth_packet
{
u8 version;
u8 type;
u16 length;
u8 key_descriptor;
u16 key_information;
u16 key_length;
u64 replay_counter;
u8 wpa_key_nonce[32];
u8 wpa_key_iv[16];
u8 wpa_key_rsc[8];
u8 wpa_key_id[8];
u8 wpa_key_mic[16];
u16 wpa_key_data_length;
} __attribute__((packed));
typedef struct auth_packet auth_packet_t;
#define MAX_ESSID_LEN 32
typedef enum
{
ESSID_SOURCE_USER = 1,
ESSID_SOURCE_REASSOC = 2,
ESSID_SOURCE_ASSOC = 3,
ESSID_SOURCE_PROBE = 4,
ESSID_SOURCE_DIRECTED_PROBE = 5,
ESSID_SOURCE_BEACON = 6,
} essid_source_t;
typedef struct
{
u8 bssid[6];
char essid[MAX_ESSID_LEN + 4];
int essid_len;
int essid_source;
} essid_t;
#define EAPOL_TTL 1
#define TEST_REPLAYCOUNT 0
typedef enum
{
EXC_PKT_NUM_1 = 1,
EXC_PKT_NUM_2 = 2,
EXC_PKT_NUM_3 = 3,
EXC_PKT_NUM_4 = 4,
} exc_pkt_num_t;
typedef enum
{
MESSAGE_PAIR_M12E2 = 0,
MESSAGE_PAIR_M14E4 = 1,
MESSAGE_PAIR_M32E2 = 2,
MESSAGE_PAIR_M32E3 = 3,
MESSAGE_PAIR_M34E3 = 4,
MESSAGE_PAIR_M34E4 = 5,
} message_pair_t;
#define BROADCAST_MAC "\xff\xff\xff\xff\xff\xff"
typedef struct
{
int excpkt_num;
u32 tv_sec;
u32 tv_usec;
u64 replay_counter;
u8 mac_ap[6];
u8 mac_sta[6];
u8 nonce[32];
u16 eapol_len;
u8 eapol[256];
u8 keyver;
u8 keymic[16];
} excpkt_t;
// databases
#define DB_ESSID_MAX 50000
#define DB_EXCPKT_MAX 100000
essid_t *essids = NULL;
lsearch_cnt_t essids_cnt = 0;
excpkt_t *excpkts = NULL;
lsearch_cnt_t excpkts_cnt = 0;
// output
#define HCCAPX_VERSION 4
#define HCCAPX_SIGNATURE 0x58504348 // HCPX
struct hccapx
{
u32 signature;
u32 version;
u8 message_pair;
u8 essid_len;
u8 essid[32];
u8 keyver;
u8 keymic[16];
u8 mac_ap[6];
u8 nonce_ap[32];
u8 mac_sta[6];
u8 nonce_sta[32];
u16 eapol_len;
u8 eapol[256];
} __attribute__((packed));
typedef struct hccapx hccapx_t;
// functions
static u8 hex_convert (const u8 c)
{
return (c & 15) + (c >> 6) * 9;
}
static u8 hex_to_u8 (const u8 hex[2])
{
u8 v = 0;
v |= ((u8) hex_convert (hex[1]) << 0);
v |= ((u8) hex_convert (hex[0]) << 4);
return (v);
}
static u16 byte_swap_16 (const u16 n)
{
return (n & 0xff00) >> 8
| (n & 0x00ff) << 8;
}
static u32 byte_swap_32 (const u32 n)
{
return (n & 0xff000000) >> 24
| (n & 0x00ff0000) >> 8
| (n & 0x0000ff00) << 8
| (n & 0x000000ff) << 24;
}
static u64 byte_swap_64 (const u64 n)
{
return (n & 0xff00000000000000ULL) >> 56
| (n & 0x00ff000000000000ULL) >> 40
| (n & 0x0000ff0000000000ULL) >> 24
| (n & 0x000000ff00000000ULL) >> 8
| (n & 0x00000000ff000000ULL) << 8
| (n & 0x0000000000ff0000ULL) << 24
| (n & 0x000000000000ff00ULL) << 40
| (n & 0x00000000000000ffULL) << 56;
}
int comp_excpkt (const void *p1, const void *p2)
{
excpkt_t *e1 = (excpkt_t *) p1;
excpkt_t *e2 = (excpkt_t *) p2;
const int excpkt_diff = e1->excpkt_num - e2->excpkt_num;
if (excpkt_diff != 0) return excpkt_diff;
const int rc_nonce = memcmp (e1->nonce, e2->nonce, 32);
if (rc_nonce != 0) return rc_nonce;
const int rc_mac_ap = memcmp (e1->mac_ap, e2->mac_ap, 6);
if (rc_mac_ap != 0) return rc_mac_ap;
const int rc_mac_sta = memcmp (e1->mac_sta, e2->mac_sta, 6);
if (rc_mac_sta != 0) return rc_mac_sta;
if (e1->replay_counter < e2->replay_counter) return 1;
if (e1->replay_counter > e2->replay_counter) return -1;
return 0;
}
int comp_bssid (const void *p1, const void *p2)
{
essid_t *e1 = (essid_t *) p1;
essid_t *e2 = (essid_t *) p2;
return memcmp (e1->bssid, e2->bssid, 6);
}
static void db_excpkt_add (excpkt_t *excpkt, const u32 tv_sec, const u32 tv_usec, const u8 mac_ap[6], const u8 mac_sta[6])
{
if (essids_cnt == DB_EXCPKT_MAX)
{
fprintf (stderr, "Too many excpkt in dumpfile, aborting...\n");
exit (-1);
}
excpkt->tv_sec = tv_sec;
excpkt->tv_usec = tv_usec;
memcpy (excpkt->mac_ap, mac_ap, 6);
memcpy (excpkt->mac_sta, mac_sta, 6);
lsearch (excpkt, excpkts, &excpkts_cnt, sizeof (excpkt_t), comp_excpkt);
}
static void db_essid_add (essid_t *essid, const u8 addr3[6], const int essid_source)
{
if (essids_cnt == DB_ESSID_MAX)
{
fprintf (stderr, "Too many essid in dumpfile, aborting...\n");
exit (-1);
}
if (essid->essid_len == 0) return;
if (essid->essid[0] == 0) return;
memcpy (essid->bssid, addr3, 6);
void *ptr = lfind (essid, essids, &essids_cnt, sizeof (essid_t), comp_bssid);
if (ptr == NULL)
{
essid->essid_source = essid_source;
lsearch (essid, essids, &essids_cnt, sizeof (essid_t), comp_bssid);
}
else
{
essid_t *essid_old = (essid_t *) ptr;
if (essid_source > essid_old->essid_source)
{
memcpy (essid_old, essid, sizeof (essid_t));
essid_old->essid_source = essid_source;
}
}
}
static int handle_llc (const ieee80211_llc_snap_header_t *ieee80211_llc_snap_header)
{
if (ieee80211_llc_snap_header->dsap != IEEE80211_LLC_DSAP) return -1;
if (ieee80211_llc_snap_header->ssap != IEEE80211_LLC_SSAP) return -1;
if (ieee80211_llc_snap_header->ctrl != IEEE80211_LLC_CTRL) return -1;
if (ieee80211_llc_snap_header->ethertype != IEEE80211_DOT1X_AUTHENTICATION) return -1;
return 0;
}
static int handle_auth (const auth_packet_t *auth_packet, const int pkt_offset, const int pkt_size, excpkt_t *excpkt)
{
const u16 ap_length = byte_swap_16 (auth_packet->length);
const u16 ap_key_information = byte_swap_16 (auth_packet->key_information);
const u64 ap_replay_counter = byte_swap_64 (auth_packet->replay_counter);
const u16 ap_wpa_key_data_length = byte_swap_16 (auth_packet->wpa_key_data_length);
if (ap_length == 0) return -1;
// determine handshake exchange number
int excpkt_num = 0;
if (ap_key_information & WPA_KEY_INFO_ACK)
{
if (ap_key_information & WPA_KEY_INFO_INSTALL)
{
excpkt_num = EXC_PKT_NUM_3;
}
else
{
excpkt_num = EXC_PKT_NUM_1;
}
}
else
{
if (ap_key_information & WPA_KEY_INFO_SECURE)
{
excpkt_num = EXC_PKT_NUM_4;
}
else
{
excpkt_num = EXC_PKT_NUM_2;
}
}
// we're only interested in packets carrying a nonce
char zero[32] = { 0 };
if (memcmp (auth_packet->wpa_key_nonce, zero, 32) == 0) return -1;
// copy data
memcpy (excpkt->nonce, auth_packet->wpa_key_nonce, 32);
excpkt->replay_counter = ap_replay_counter;
excpkt->excpkt_num = excpkt_num;
excpkt->eapol_len = sizeof (auth_packet_t) + ap_wpa_key_data_length;
if ((pkt_offset + excpkt->eapol_len) > pkt_size) return -1;
if ((sizeof (auth_packet_t) + ap_wpa_key_data_length) > sizeof (excpkt->eapol)) return -1;
// we need to copy the auth_packet_t but have to clear the keymic
auth_packet_t auth_packet_orig;
memcpy (&auth_packet_orig, auth_packet, sizeof (auth_packet_t));
#ifdef BIG_ENDIAN_HOST
auth_packet_orig.length = byte_swap_16 (auth_packet_orig.length);
auth_packet_orig.key_information = byte_swap_16 (auth_packet_orig.key_information);
auth_packet_orig.key_length = byte_swap_16 (auth_packet_orig.key_length);
auth_packet_orig.replay_counter = byte_swap_64 (auth_packet_orig.replay_counter);
auth_packet_orig.wpa_key_data_length = byte_swap_16 (auth_packet_orig.wpa_key_data_length);
#endif
memset (auth_packet_orig.wpa_key_mic, 0, 16);
memcpy (excpkt->eapol, &auth_packet_orig, sizeof (auth_packet_t));
memcpy (excpkt->eapol + sizeof (auth_packet_t), auth_packet + 1, ap_wpa_key_data_length);
memcpy (excpkt->keymic, auth_packet->wpa_key_mic, 16);
excpkt->keyver = ap_key_information & WPA_KEY_INFO_TYPE_MASK;
if ((excpkt_num == EXC_PKT_NUM_3) || (excpkt_num == EXC_PKT_NUM_4))
{
excpkt->replay_counter--;
}
return 0;
}
static int get_essid_from_user (char *s, essid_t *essid)
{
char *man_essid = s;
char *man_bssid = strchr (man_essid, ':');
if (man_bssid == NULL)
{
fprintf (stderr, "Invalid format (%s), should be: MyESSID:d110391a58ac\n", s);
return -1;
}
*man_bssid = 0;
man_bssid++;
if (strlen (man_essid) >= 32)
{
fprintf (stderr, "Invalid format (%s), essid is too long\n", s);
return -1;
}
if (strlen (man_bssid) != 12)
{
fprintf (stderr, "Invalid format (%s), bssid must have length 12\n", s);
return -1;
}
strncpy (essid->essid, man_essid, 32);
essid->essid_len = strlen (essid->essid);
u8 bssid[6];
bssid[0] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[1] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[2] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[3] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[4] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
bssid[5] = hex_to_u8 ((u8 *) man_bssid); man_bssid += 2;
db_essid_add (essid, bssid, ESSID_SOURCE_USER);
return 0;
}
static int get_essid_from_tag (const u8 *packet, const pcap_pkthdr_t *header, u32 length_skip, essid_t *essid)
{
if (length_skip > header->caplen) return -1;
u32 length = header->caplen - length_skip;
const u8 *beacon = packet + length_skip;
const u8 *cur = beacon;
const u8 *end = beacon + length;
while (cur < end)
{
if ((cur + 2) >= end) break;
u8 tagtype = *cur++;
u8 taglen = *cur++;
if ((cur + taglen) >= end) break;
if (tagtype == MFIE_TYPE_SSID)
{
if (taglen < MAX_ESSID_LEN)
{
memcpy (essid->essid, cur, taglen);
essid->essid_len = taglen;
return 0;
}
}
cur += taglen;
}
return -1;
}
static void process_packet (const u8 *packet, const pcap_pkthdr_t *header)
{
if (header->caplen < sizeof (ieee80211_hdr_3addr_t)) return;
// our first header: ieee80211
ieee80211_hdr_3addr_t *ieee80211_hdr_3addr = (ieee80211_hdr_3addr_t *) packet;
#ifdef BIG_ENDIAN_HOST
ieee80211_hdr_3addr->frame_control = byte_swap_16 (ieee80211_hdr_3addr->frame_control);
ieee80211_hdr_3addr->duration_id = byte_swap_16 (ieee80211_hdr_3addr->duration_id);
ieee80211_hdr_3addr->seq_ctrl = byte_swap_16 (ieee80211_hdr_3addr->seq_ctrl);
#endif
const u16 frame_control = ieee80211_hdr_3addr->frame_control;
if ((frame_control & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT)
{
if (memcmp (ieee80211_hdr_3addr->addr3, BROADCAST_MAC, 6) == 0) return;
essid_t essid;
memset (&essid, 0, sizeof (essid_t));
const int stype = frame_control & IEEE80211_FCTL_STYPE;
if (stype == IEEE80211_STYPE_BEACON)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (beacon_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_BEACON);
}
else if (stype == IEEE80211_STYPE_PROBE_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_PROBE);
}
else if (stype == IEEE80211_STYPE_PROBE_RESP)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (beacon_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_PROBE);
}
else if (stype == IEEE80211_STYPE_ASSOC_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (assocreq_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_ASSOC);
}
else if (stype == IEEE80211_STYPE_REASSOC_REQ)
{
const u32 length_skip = sizeof (ieee80211_hdr_3addr_t) + sizeof (reassocreq_t);
const int rc_beacon = get_essid_from_tag (packet, header, length_skip, &essid);
if (rc_beacon == -1) return;
db_essid_add (&essid, ieee80211_hdr_3addr->addr3, ESSID_SOURCE_REASSOC);
}
}
else if ((frame_control & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_DATA)
{
// process header: ieee80211
int addr4_exist = ((frame_control & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
(IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS));
// find offset to llc/snap header
int llc_offset;
if ((frame_control & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_QOS_DATA)
{
llc_offset = sizeof (ieee80211_qos_hdr_t);
}
else
{
llc_offset = sizeof (ieee80211_hdr_3addr_t);
}
// process header: the llc/snap header
if (header->caplen < (llc_offset + sizeof (ieee80211_llc_snap_header_t))) return;
if (addr4_exist) llc_offset += 6;
ieee80211_llc_snap_header_t *ieee80211_llc_snap_header = (ieee80211_llc_snap_header_t *) &packet[llc_offset];
#ifdef BIG_ENDIAN_HOST
ieee80211_llc_snap_header->ethertype = byte_swap_16 (ieee80211_llc_snap_header->ethertype);
#endif
const int rc_llc = handle_llc (ieee80211_llc_snap_header);
if (rc_llc == -1) return;
// process header: the auth header
const int auth_offset = llc_offset + sizeof (ieee80211_llc_snap_header_t);
if (header->caplen < (auth_offset + sizeof (auth_packet_t))) return;
auth_packet_t *auth_packet = (auth_packet_t *) &packet[auth_offset];
#ifdef BIG_ENDIAN_HOST
auth_packet->length = byte_swap_16 (auth_packet->length);
auth_packet->key_information = byte_swap_16 (auth_packet->key_information);
auth_packet->key_length = byte_swap_16 (auth_packet->key_length);
auth_packet->replay_counter = byte_swap_64 (auth_packet->replay_counter);
auth_packet->wpa_key_data_length = byte_swap_16 (auth_packet->wpa_key_data_length);
#endif
excpkt_t excpkt;
memset (&excpkt, 0, sizeof (excpkt_t));
const int rc_auth = handle_auth (auth_packet, auth_offset, header->caplen, &excpkt);
if (rc_auth == -1) return;
if ((excpkt.excpkt_num == EXC_PKT_NUM_1) || (excpkt.excpkt_num == EXC_PKT_NUM_3))
{
db_excpkt_add (&excpkt, header->tv_sec, header->tv_usec, ieee80211_hdr_3addr->addr2, ieee80211_hdr_3addr->addr1);
}
else if ((excpkt.excpkt_num == EXC_PKT_NUM_2) || (excpkt.excpkt_num == EXC_PKT_NUM_4))
{
db_excpkt_add (&excpkt, header->tv_sec, header->tv_usec, ieee80211_hdr_3addr->addr1, ieee80211_hdr_3addr->addr2);
}
}
}
int main (int argc, char *argv[])
{
if ((argc != 3) && (argc != 4) && (argc != 5))
{
fprintf (stderr, "usage: %s input.pcap output.hccapx [filter by essid] [additional network essid:bssid]\n", argv[0]);
return -1;
}
char *in = argv[1];
char *out = argv[2];
char *essid_filter = NULL;
if (argc >= 4) essid_filter = argv[3];
// database initializations
essids = (essid_t *) calloc (DB_ESSID_MAX, sizeof (essid_t));
essids_cnt = 0;
excpkts = (excpkt_t *) calloc (DB_EXCPKT_MAX, sizeof (excpkt_t));
excpkts_cnt = 0;
// manual beacon
if (argc >= 5)
{
essid_t essid;
memset (&essid, 0, sizeof (essid_t));
const int rc = get_essid_from_user (argv[4], &essid);
if (rc == -1) return -1;
}
// start with pcap handling
FILE *pcap = fopen (in, "rb");
if (pcap == NULL)
{
fprintf (stderr, "%s: %s\n", in, strerror (errno));
return -1;
}
// check pcap header
pcap_file_header_t pcap_file_header;
const int nread = fread (&pcap_file_header, sizeof (pcap_file_header_t), 1, pcap);
if (nread != 1)
{
fprintf (stderr, "%s: Could not read pcap header\n", in);
return -1;
}
#ifdef BIG_ENDIAN_HOST
pcap_file_header.magic = byte_swap_32 (pcap_file_header.magic);
pcap_file_header.version_major = byte_swap_16 (pcap_file_header.version_major);
pcap_file_header.version_minor = byte_swap_16 (pcap_file_header.version_minor);
pcap_file_header.thiszone = byte_swap_32 (pcap_file_header.thiszone);
pcap_file_header.sigfigs = byte_swap_32 (pcap_file_header.sigfigs);
pcap_file_header.snaplen = byte_swap_32 (pcap_file_header.snaplen);
pcap_file_header.linktype = byte_swap_32 (pcap_file_header.linktype);
#endif
int bitness = 0;
if (pcap_file_header.magic == TCPDUMP_MAGIC)
{
bitness = 0;
}
else if (pcap_file_header.magic == TCPDUMP_CIGAM)
{
bitness = 1;
}
else
{
fprintf (stderr, "%s: Invalid pcap header\n", in);
return 1;
}
if (bitness == 1)
{
pcap_file_header.magic = byte_swap_32 (pcap_file_header.magic);
pcap_file_header.version_major = byte_swap_16 (pcap_file_header.version_major);
pcap_file_header.version_minor = byte_swap_16 (pcap_file_header.version_minor);
pcap_file_header.thiszone = byte_swap_32 (pcap_file_header.thiszone);
pcap_file_header.sigfigs = byte_swap_32 (pcap_file_header.sigfigs);
pcap_file_header.snaplen = byte_swap_32 (pcap_file_header.snaplen);
pcap_file_header.linktype = byte_swap_32 (pcap_file_header.linktype);
}
if ((pcap_file_header.linktype != DLT_IEEE802_11)
&& (pcap_file_header.linktype != DLT_IEEE802_11_PRISM)
&& (pcap_file_header.linktype != DLT_IEEE802_11_RADIO)
&& (pcap_file_header.linktype != DLT_IEEE802_11_PPI_HDR))
{
fprintf (stderr, "%s: Unsupported linktype detected\n", in);
return -1;
}
// walk the packets
while (!feof (pcap))
{
pcap_pkthdr_t header;
const int nread1 = fread (&header, sizeof (pcap_pkthdr_t), 1, pcap);
if (nread1 != 1) continue;
#ifdef BIG_ENDIAN_HOST
header.tv_sec = byte_swap_32 (header.tv_sec);
header.tv_usec = byte_swap_32 (header.tv_usec);
header.caplen = byte_swap_32 (header.caplen);
header.len = byte_swap_32 (header.len);
#endif
if (bitness == 1)
{
header.tv_sec = byte_swap_32 (header.tv_sec);
header.tv_usec = byte_swap_32 (header.tv_usec);
header.caplen = byte_swap_32 (header.caplen);
header.len = byte_swap_32 (header.len);
}
if ((header.tv_sec == 0) && (header.tv_usec == 0))
{
fprintf (stderr, "Zero value timestamps detected in file: %s.\n", in);
fprintf (stderr, "This prevents correct EAPOL-Key timeout calculation.\n");
fprintf (stderr, "Do not preprocess the capture file with tools such as wpaclean.\n");
return -1;
}
u8 packet[TCPDUMP_DECODE_LEN];
if (header.caplen >= TCPDUMP_DECODE_LEN || (signed)header.caplen < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
const u32 nread2 = fread (&packet, sizeof (u8), header.caplen, pcap);
if (nread2 != header.caplen)
{
fprintf (stderr, "%s: Could not read pcap packet data\n", in);
break;
}
u8 *packet_ptr = packet;
if (pcap_file_header.linktype == DLT_IEEE802_11_PRISM)
{
if (header.caplen < sizeof (prism_header_t))
{
fprintf (stderr, "%s: Could not read prism header\n", in);
break;
}
prism_header_t *prism_header = (prism_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
prism_header->msgcode = byte_swap_32 (prism_header->msgcode);
prism_header->msglen = byte_swap_32 (prism_header->msglen);
#endif
if ((signed)prism_header->msglen < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
if ((signed)(header.caplen - prism_header->msglen) < 0)
{
fprintf (stderr, "%s: Oversized packet detected\n", in);
break;
}
packet_ptr += prism_header->msglen;
header.caplen -= prism_header->msglen;
header.len -= prism_header->msglen;
}
else if (pcap_file_header.linktype == DLT_IEEE802_11_RADIO)
{
if (header.caplen < sizeof (ieee80211_radiotap_header_t))
{
fprintf (stderr, "%s: Could not read radiotap header\n", in);
break;
}
ieee80211_radiotap_header_t *ieee80211_radiotap_header = (ieee80211_radiotap_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
ieee80211_radiotap_header->it_len = byte_swap_16 (ieee80211_radiotap_header->it_len);
ieee80211_radiotap_header->it_present = byte_swap_32 (ieee80211_radiotap_header->it_present);
#endif
if (ieee80211_radiotap_header->it_version != 0)
{
fprintf (stderr, "%s: Invalid radiotap header\n", in);
break;
}
packet_ptr += ieee80211_radiotap_header->it_len;
header.caplen -= ieee80211_radiotap_header->it_len;
header.len -= ieee80211_radiotap_header->it_len;
}
else if (pcap_file_header.linktype == DLT_IEEE802_11_PPI_HDR)
{
if (header.caplen < sizeof (ppi_packet_header_t))
{
fprintf (stderr, "%s: Could not read ppi header\n", in);
break;
}
ppi_packet_header_t *ppi_packet_header = (ppi_packet_header_t *) packet;
#ifdef BIG_ENDIAN_HOST
ppi_packet_header->pph_len = byte_swap_16 (ppi_packet_header->pph_len);
#endif
packet_ptr += ppi_packet_header->pph_len;
header.caplen -= ppi_packet_header->pph_len;
header.len -= ppi_packet_header->pph_len;
}
process_packet (packet_ptr, &header);
}
fclose (pcap);
// inform the user
printf ("Networks detected: %d\n", (int) essids_cnt);
printf ("\n");
if (essids_cnt == 0) return 0;
// prepare output files
FILE *fp = fopen (out, "wb");
if (fp == NULL)
{
fprintf (stderr, "%s: %s\n", out, strerror (errno));
return -1;
}
int written = 0;
// find matching packets
for (lsearch_cnt_t essids_pos = 0; essids_pos < essids_cnt; essids_pos++)
{
const essid_t *essid = essids + essids_pos;
if (essid_filter) if (strcmp (essid->essid, essid_filter)) continue;
printf ("[*] BSSID=%02x:%02x:%02x:%02x:%02x:%02x ESSID=%s (Length: %d)\n",
essid->bssid[0],
essid->bssid[1],
essid->bssid[2],
essid->bssid[3],
essid->bssid[4],
essid->bssid[5],
essid->essid,
essid->essid_len);
for (lsearch_cnt_t excpkt_ap_pos = 0; excpkt_ap_pos < excpkts_cnt; excpkt_ap_pos++)
{
const excpkt_t *excpkt_ap = excpkts + excpkt_ap_pos;
if ((excpkt_ap->excpkt_num != EXC_PKT_NUM_1) && (excpkt_ap->excpkt_num != EXC_PKT_NUM_3)) continue;
if (memcmp (essid->bssid, excpkt_ap->mac_ap, 6) != 0) continue;
for (lsearch_cnt_t excpkt_sta_pos = 0; excpkt_sta_pos < excpkts_cnt; excpkt_sta_pos++)
{
const excpkt_t *excpkt_sta = excpkts + excpkt_sta_pos;
if ((excpkt_sta->excpkt_num != EXC_PKT_NUM_2) && (excpkt_sta->excpkt_num != EXC_PKT_NUM_4)) continue;
if (memcmp (excpkt_ap->mac_ap, excpkt_sta->mac_ap, 6) != 0) continue;
if (memcmp (excpkt_ap->mac_sta, excpkt_sta->mac_sta, 6) != 0) continue;
const bool valid_replay_counter = (excpkt_ap->replay_counter == excpkt_sta->replay_counter) ? true : false;
if (excpkt_ap->excpkt_num < excpkt_sta->excpkt_num)
{
if (excpkt_ap->tv_sec > excpkt_sta->tv_sec) continue;
if ((excpkt_ap->tv_sec + EAPOL_TTL) < excpkt_sta->tv_sec) continue;
}
else
{
if (excpkt_sta->tv_sec > excpkt_ap->tv_sec) continue;
if ((excpkt_sta->tv_sec + EAPOL_TTL) < excpkt_ap->tv_sec) continue;
}
u8 message_pair = 255;
if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_1) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_2))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M12E2;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_1) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_4))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M14E4;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_3) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_2))
{
if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M32E2;
}
else if (excpkt_ap->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M32E3;
}
else
{
continue;
}
}
else if ((excpkt_ap->excpkt_num == EXC_PKT_NUM_3) && (excpkt_sta->excpkt_num == EXC_PKT_NUM_4))
{
if (excpkt_ap->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M34E3;
}
else if (excpkt_sta->eapol_len > 0)
{
message_pair = MESSAGE_PAIR_M34E4;
}
else
{
continue;
}
}
else
{
fprintf (stderr, "BUG!!! AP:%d STA:%d\n", excpkt_ap->excpkt_num, excpkt_sta->excpkt_num);
}
int export = 1;
switch (message_pair)
{
case MESSAGE_PAIR_M32E3: export = 0; break;
case MESSAGE_PAIR_M34E3: export = 0; break;
}
if (export == 1)
{
printf (" --> STA=%02x:%02x:%02x:%02x:%02x:%02x, Message Pair=%u, Replay Counter=%" PRIu64 "\n",
excpkt_sta->mac_sta[0],
excpkt_sta->mac_sta[1],
excpkt_sta->mac_sta[2],
excpkt_sta->mac_sta[3],
excpkt_sta->mac_sta[4],
excpkt_sta->mac_sta[5],
message_pair,
excpkt_sta->replay_counter);
}
else
{
printf (" --> STA=%02x:%02x:%02x:%02x:%02x:%02x, Message Pair=%u [Skipped Export]\n",
excpkt_sta->mac_sta[0],
excpkt_sta->mac_sta[1],
excpkt_sta->mac_sta[2],
excpkt_sta->mac_sta[3],
excpkt_sta->mac_sta[4],
excpkt_sta->mac_sta[5],
message_pair);
continue;
}
// finally, write hccapx
hccapx_t hccapx;
memset (&hccapx, 0, sizeof (hccapx));
hccapx.signature = HCCAPX_SIGNATURE;
hccapx.version = HCCAPX_VERSION;
hccapx.message_pair = message_pair;
if (valid_replay_counter == false)
{
hccapx.message_pair |= 0x80;
}
hccapx.essid_len = essid->essid_len;
memcpy (&hccapx.essid, essid->essid, 32);
memcpy (&hccapx.mac_ap, excpkt_ap->mac_ap, 6);
memcpy (&hccapx.nonce_ap, excpkt_ap->nonce, 32);
memcpy (&hccapx.mac_sta, excpkt_sta->mac_sta, 6);
memcpy (&hccapx.nonce_sta, excpkt_sta->nonce, 32);
if (excpkt_sta->eapol_len > 0)
{
hccapx.keyver = excpkt_sta->keyver;
memcpy (&hccapx.keymic, excpkt_sta->keymic, 16);
hccapx.eapol_len = excpkt_sta->eapol_len;
memcpy (&hccapx.eapol, excpkt_sta->eapol, 256);
}
else
{
hccapx.keyver = excpkt_ap->keyver;
memcpy (&hccapx.keymic, excpkt_ap->keymic, 16);
hccapx.eapol_len = excpkt_ap->eapol_len;
memcpy (&hccapx.eapol, excpkt_ap->eapol, 256);
}
#ifdef BIG_ENDIAN_HOST
hccapx.signature = byte_swap_32 (hccapx.signature);
hccapx.version = byte_swap_32 (hccapx.version);
hccapx.eapol_len = byte_swap_16 (hccapx.eapol_len);
#endif
fwrite (&hccapx, sizeof (hccapx_t), 1, fp);
written++;
}
}
}
printf ("\n");
printf ("Written %d WPA Handshakes to: %s\n", written, out);
fclose (fp);
// clean up
free (excpkts);
free (essids);
return 0;
}
|
the_stack_data/945612.c | /**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize)
{
// 两次查询,一次向下取整,找到左边界,一次向上取整,找到右边界
int l = 0;
int r = numsSize;
int *res = malloc(sizeof(int) * 2);
memset(res, 0, sizeof(int) * 2);
*returnSize = 2;
while (l < r) {
int mid = l + (r - l) / 2; // 向下取整
if (nums[mid] < target) { // 如果小于 target。target 左边一定不包含等于 target 的元素,如果最后的左边界小于 target,还会加 1,尝试右边界
l = mid + 1;
} else {
r = mid;
}
}
res[0] = (l != numsSize && nums[l] == target) ? l : -1;
l = 0;
r = numsSize -1;
while (l < r) {
int mid = l + (r - l + 1) / 2; // 向上取整
if (nums[mid] > target) { // 如果大于 target,target 右边一定不包含等于 target 的元素,如果最后的右边界大于 target,还会减 1,尝试左边界
r = mid - 1;
} else { // 如果
l = mid;
}
}
res[1] = (r != -1 && nums[r] == target) ? r : -1;
return res;
} |
the_stack_data/167330395.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
void insertionSort(int ar_size, int *ar) {
int i=1;
int j=0;
int count =0;
for(;i<ar_size;i++){
int hole = i;
int value = ar[i];
while(hole > 0 && (value < ar[hole-1])){
ar[hole] = ar[hole-1];
count++;
hole = hole-1;
}
ar[hole] = value;
}
printf("%d",count);
}
int main(void) {
int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
scanf("%d", &_ar[_ar_i]);
}
insertionSort(_ar_size, _ar);
return 0;
}
|
the_stack_data/154826710.c | /* Simple PuzzleBox */
/* Author: Theódór S. Andrésson
* Email: [email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Name: Random(int max)
* Takes: int max
* Gives: Random value from 0 to max
* Desc: Randomization
* Note: Probably not the best method
*/
int Random(int max)
{
return rand() % max;
}
/* Name: CheckBoard(int Board)
* Takes: A 2D array, int n
* Gives: Value 1 or 0
* Desc: True if the board is sorted. False otherwise.
*/
int CheckBoard(int **Board, int n)
{
int count = 0; // Count how many rows are sorted
for(int i = 0; i < n+2; i++)
{ // Loop through all rows
if( Board[i][0] == Board[i][1] && Board[i][1] == Board[i][2] && Board[i][2] == Board[i][3] )
{
count++; // Row completed
}
}
if( count == n+2 )
{
return 1;
}
return 0;
}
/* Name: GetAllNumbers(int n)
* Takes: int n (How many numbers)
* Gives: int* (n numbers 4 times each)
* Desc: A list with range [1..n] with each number 4 times
*/
int* GetAllNumbers(int n)
{
int nf = n*4;
int* numbers = (int*) malloc(nf*sizeof(int)); // All possible numbers
int num = 1; // Number to fill in
for( int i = 0; i < nf; i++)
{ // Fill in all needed numbers
int count = 0;
while( count < 4 )
{ // Every number 4 times
numbers[i] = num;
i++;
count++;
}
num++; // Increase number
i--; // This just looks ugly....
}
return numbers;
}
/* Name: CreateBoard(int n)
* Takes: int n (How many numbers)
* Gives: int** (2D array of the board with 2 empty sets)
* Desc: Creates the board used to play with
*/
int** CreateBoard(int n)
{
// Create a 2D array as the game board with 2 extra rows
int **Board = malloc( (n+2) * sizeof(int)); // Rows
for ( int i = 0; i < (n+2); i++)
{ // Columns
Board[i] = malloc(4 * sizeof(int));
}
int* numbers = GetAllNumbers(n);
int range = n*4;
for(int i = 0; i < n; i++)
{
for( int j = 0; j < 4; j++)
{
int p = Random(range); // Randomize number
while ( numbers[p] == 0 )
p = Random(range);
Board[i][j] = numbers[p];
numbers[p] = 0; // So it isn't repeated
}
}
// Free memory
free(numbers);
// Return 2D array of the board
return Board;
}
/* Name: void Move(int** Board, int x, int y, int Bx, int By)
* Needs: pointer to 2D Board, placement on board, placement on board,
* placement to move to, placement to move to
* Desc: Responsible to move from one place on
* the board to another place.
* Note: Should remove By as we don't need the column.
* Number should always go on top
*/
void Move(int** Board, int x, int Bx)
{
// Do nothing if moving to the same row.
// Why does it move up ??
if(x == Bx) return;
int y = 3; // Placement of moving number
// Lets figure out what number we're moving
while(y != 0)
{
if(Board[x][y] != 0) break;
y--;
}
if(Board[Bx][3] != 0)
{ // Full
return;
}
if(Board[Bx][2] != 0 && Board[x][y] == Board[Bx][2])
{ // Possible to move (E.g move 1 to the row 2310 -> 2311)
Board[Bx][3] = Board[x][y];
Board[x][y] = 0;
return;
}
if(Board[Bx][1] != 0 && Board[x][y] == Board[Bx][1])
{ //Possible to move (E.g move 1 to the row 2100 -> 2110)
Board[Bx][2] = Board[x][y];
Board[x][y] = 0;
return;
}
if(Board[Bx][0] != 0 && Board[x][y] == Board[Bx][0])
{ // Possible to move (E.g move 1 to the row 1000 -> 1100)
Board[Bx][1] = Board[x][y];
Board[x][y] = 0;
return;
}
if(Board[Bx][0] == 0)
{ // Possible to move 1 to 0000 -> 1000
Board[Bx][0] = Board[x][y];
Board[x][y] = 0;
return;
}
return;
}
/* Name: DisplayBoard(int **Board)
* Needs: A 2D board
* Returns: Board printed out to stdout
*/
void DisplayBoard(int **Board, int n)
{
// Print out the board
for (int i = 0; i < n+2; i++)
{
printf("%d: ", i);
for( int j = 0; j < 4; j++)
{
if(Board[i][j] == 0)
{ // Lets leave 0's out
printf(" ");
} else {
printf("%d ", Board[i][j]);
}
}
printf("\n");
}
}
/* Name: Main()
* Needs: Argument from command line
* Desc: Main start of the application
*/
int main(int argc, char* argv[]) {
srand(time(0)); // A seed for randomization
if(argc == 1)
{ // The game requires one argument
printf("The game requires at least one argument passed to it");
exit(0);
}
int n = atoi(argv[1]); // Convert the argument from char to int
// Disallow 1 or 2
if( n == 1 || n == 2 )
{
printf("Minimum amount of numbers is 3\n");
exit(0);
}
// Create a board
int** A = CreateBoard(n);
while(1)
{
DisplayBoard(A, n);
int x, Bx;
printf("\n(Element to move)X value: ");
scanf("%d", &x);
printf("\n(Placement)Bx value: ");
scanf("%d", &Bx);
// Make the move
Move(A, x, Bx);
// Clear output
printf("\e[1;1H\e[2J");
// Check if the board is sorted
if(CheckBoard(A, n) == 1)
{
printf("\t\t-----> You won the game <---- ");
break;
}
}
// Free Memory used by board
for( int i = 0; i < n+2; i++ )
{
free(A[i]);
}
free(A);
}
/***************
* Error list: *
***************/
/** Program crashes on input 1 & 2 **
*
* Input 1: Program finishes first empty row but returns a seg fault before the second
* Input 2: Program does not finish printing out 0's in board. (extra rows)
*/
|
the_stack_data/132953693.c | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int size;
void (*(*_vtable)[])();
} metadata;
typedef struct {
metadata *clazz;
} object;
object *alloc(metadata *clazz) {
object *p = malloc(clazz->size);
p->clazz = clazz;
return p;
}
// D e f i n e C l a s s Employee
typedef struct {
metadata *clazz;
int ID;
} Employee;
#define Employee_getID_SLOT 0
#define Employee_setID_SLOT 1
int Employee_getID(Employee *this)
{
return this->ID;
}
void Employee_setID(Employee *this, int ID)
{
this->ID = ID;
}
void (*Employee_vtable[])() = {
(void (*)())&Employee_getID,
(void (*)())&Employee_setID
};
metadata Employee_metadata = {"Employee", sizeof(Employee), &Employee_vtable};
// D e f i n e C l a s s Mgr
typedef struct {
metadata *clazz;
int ID;
int level;
} Mgr;
#define Mgr_getID_SLOT 0
#define Mgr_setID_SLOT 1
void (*Mgr_vtable[])() = {
(void (*)())&Employee_getID,
(void (*)())&Employee_setID
};
metadata Mgr_metadata = {"Mgr", sizeof(Mgr), &Mgr_vtable};
// D e f i n e C l a s s Coder
typedef struct {
metadata *clazz;
int ID;
float salary;
Mgr * boss;
} Coder;
#define Coder_getID_SLOT 0
#define Coder_setID_SLOT 1
#define Coder_raise_SLOT 2
#define Coder_speak_SLOT 3
#define Coder_workFor_SLOT 4
void Coder_raise(Coder *this, float v)
{
this->salary = v;
}
void Coder_speak(Coder *this)
{
printf("I am %d\n", this->ID);
}
void Coder_workFor(Coder *this, Employee * e)
{
this->boss = ((Mgr *)e);
}
void (*Coder_vtable[])() = {
(void (*)())&Employee_getID,
(void (*)())&Employee_setID,
(void (*)())&Coder_raise,
(void (*)())&Coder_speak,
(void (*)())&Coder_workFor
};
metadata Coder_metadata = {"Coder", sizeof(Coder), &Coder_vtable};
int main(int argc, char *argv[])
{
int ID;
Coder * c;
ID = 1;
c = ((Coder *)alloc(&Coder_metadata));
c->ID = ID;
c->boss = ((Mgr *)alloc(&Mgr_metadata));
c->boss->level = 99;
c->boss->ID = 4;
printf("%d\n", (*(int (*)(Employee *))(*(c->boss)->clazz->_vtable)[Mgr_getID_SLOT])(((Employee *)c->boss)));
(*(void (*)(Coder *))(*(c)->clazz->_vtable)[Coder_speak_SLOT])(((Coder *)c));
} |
the_stack_data/6388186.c | #include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
printf("Error while forking: ");
switch (errno) {
case ENOMEM: printf("The process requires more space than the system can supply. \n"); break;
case EAGAIN: printf("Too many processes running.\n"); break;
}
exit(EXIT_FAILURE);
}
if (pid > 0) {
printf("Successfully forked: %d\n", pid);
exit(EXIT_SUCCESS);
}
umask(0);
// New sid for cp
pid_t sid = setsid();
if (sid < 0) {
printf("Error while requesting new session: ");
switch (errno) {
case EPERM: printf("The process group ID of any process equals the PID of the calling process."); break;
}
exit(EXIT_FAILURE);
}
if (chdir("/") == -1) {
switch (errno) {
// NOTE: ENOTDIR, ENOENT, ENAMETOOLONG, ELOOP skipped because they most likely will not occur.
case EACCES: printf("Search permission is denied for any component of the pathname."); break;
}
exit(EXIT_FAILURE);
}
// Close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while (1) {
pid_t pid = fork();
if (pid == 0) {
char* argv[] = {"notify-send", "hej", NULL};
if (execvp("notify-send", argv) == -1) {
// TODO: Log to the syslog (To fix in SO-03-syslog)
_exit(EXIT_FAILURE);
}
}
if (pid == -1) {
_exit(EXIT_FAILURE);
}
sleep(20);
}
}
|
the_stack_data/150140131.c | /*
Modified version of safe-bank-balance.c
Shows how one thread can starve others if the critical section isn't
carefully selected.
@author Marissa Schmidt
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
struct account {
double balance;
pthread_mutex_t mutex;
};
void *run(void *);
void goodSession(int, FILE *);
void badSession(int, FILE *);
/* Global variables */
struct account *myacct;
pthread_t *tids;
int numThreads;
int good = 0;
/**
* Creates a new account with an initial balance and initializes
* the account's mutex.
* @param balance The starting balance of the account.
*/
struct account *createAccount(double balance)
{
myacct = (struct account *) malloc(sizeof(struct account));
myacct->balance = balance;
pthread_mutex_init(&(myacct->mutex), NULL);
return myacct;
}
/**
* Deposits the specified amount into the account.
*/
void deposit(struct account *acct, double amount)
{
acct->balance += amount;
}
/**
* Withdraws the specified amount from the account.
*/
void withdraw(struct account *acct, double amount)
{
acct->balance -= amount;
}
int main(int argc, char **argv)
{
int i;
int *value;
if (argc < 3) {
fprintf(stderr, "Usage: %s <numThreads (1-3)> <good|bad>\n", argv[0]);
exit(1);
}
numThreads = atoi(argv[1]);
if (numThreads > 3) {
fprintf(stderr, "Usage: %s Too many threads specified. Defaulting to 3.\n", argv[0]);
numThreads = 3;
}
char *goodArg = argv[2];
if(strcmp(goodArg, "good") == 0) {
good = 1;
printf("Running good version...\n");
} else {
good = 0;
printf("Running bad version...\n");
}
/* Initialize account */
myacct = createAccount(0.0);
printf("initial balance = %lf\n", myacct->balance);
/* Create threads */
tids = (pthread_t *) malloc(sizeof(pthread_t)*numThreads);
for (i=0; i<numThreads; i++) {
value = (int *) malloc(sizeof(int));
*value = i;
pthread_create(&tids[i], NULL, run, (void *) value);
}
/* Wait for all threads to finish */
for (i=0; i<numThreads; i++) {
pthread_join(tids[i], NULL);
}
printf("final balance = %lf\n", myacct->balance);
exit(0);
}
/**
* This is where the threads start.
*
* Each thread will read input from their own file. This kind of simulates
* multiple users accessing the same account from different terminals.
*
* Each thread will read from a file called "input_<id>.txt". The file
* should just have a list of floating point values. When a thread reads
* a value < 1, then it will sleep for 30 seconds to simulate a user
* starting a transaction, but not ending it.
*/
void *run(void *ptr)
{
int id = *((int *)ptr);
char filename[80];
FILE *fp;
/* Thread will read from file input_x.txt */
sprintf(filename, "transactions_%d.txt", id);
fp = fopen(filename, "r");
if(fp == NULL) {
fprintf(stderr, "Can't open input file %s\n", filename);
exit(1);
}
printf("Thread [%d]: Session started\n", id);
if(good == 1) {
goodSession(id, fp);
} else {
badSession(id, fp);
}
printf("Thread [%d]: Session ended\n", id);
pthread_exit(NULL);
}
/**
* Starves the other threads from depositing if this thread goes to sleep.
*/
void badSession(int id, FILE *fp)
{
double amount;
/* This is not a good place to lock! */
pthread_mutex_lock(&(myacct->mutex));
while(fscanf(fp, "%lf", &amount) != EOF) {
if(amount < 1) {
sleep(30); // Simulates user walking away from machine.
}
deposit(myacct, amount); // Uses shared myacct variable.
printf("\tThread [%d]: Deposited: %f\n", id, amount);
fflush(stdout);
}
pthread_mutex_unlock(&(myacct->mutex));
}
/**
* Other threads can continue depositing if this thread goes to sleep. This
* is good.
*/
void goodSession(int id, FILE *fp)
{
double amount;
while(fscanf(fp, "%lf", &amount) != EOF) {
if(amount < 1) {
sleep(30); // Simulates user walking away from machine.
}
/* lock around smallest chunk of code possible. */
pthread_mutex_lock(&(myacct->mutex));
deposit(myacct, amount); // Uses shared myacct variable.
pthread_mutex_unlock(&(myacct->mutex));
printf("\tThread [%d]: Deposited: %f\n", id, amount);
fflush(stdout);
}
}
|
the_stack_data/198579692.c | #ifndef REGTEST
#include <threads.h>
#include <pthread.h>
int mtx_unlock(mtx_t* mtx)
{
if (pthread_mutex_unlock(mtx) == 0)
return thrd_success;
return thrd_error;
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
int main(void) { return TEST_RESULTS; }
#endif
|
the_stack_data/23576399.c | #include<stdio.h>
// Power Using Recursion
int powRecursion(int mul, int num)
{
if(num == 0)
{
return 1;
}
else
{
return powRecursion(mul, num - 1) * mul;
}
}
// Power Using Modified Recursion
int powRecursionModified(int mul, int num)
{
if(num == 0)
{
return 1;
}
if(num % 2 == 0)
{
return powRecursionModified(mul * mul, num / 2);
}
else
{
return mul * powRecursionModified(mul * mul, num / 2);
}
}
// Power Using Loop
int powLoop(mul, num)
{
int pow = 1;
for(int i = 1; i <= num; i++)
{
pow = pow * mul;
}
return pow;
}
int main()
{
int mul = 2, num = 9;
printf("Power of %d - %d times Using Recursion: %d\n", mul, num, powRecursion(mul, num));
printf("Power of %d - %d times Using Modified Recursion: %d\n", mul, num, powRecursionModified(mul, num));
printf("Power of %d - %d times Using Loop: %d\n", mul, num, powLoop(mul, num));
return 0;
}
|
the_stack_data/64201478.c | //1-100 arasında bulunan, toplamı 100 eden ikişer adet sayıyı bulan program:
#include <stdio.h>
int isPrime(int n);
void writePrimes(int n);
int main(void) {
writePrimes(100);
return 0;
}
int isPrime(int n){
// asal sayı kodunu buraya yazınız
int i;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
void writePrimes(int n){
int primes[50];
int j,firstPrime,secondPrime,i;
for(j=2;j<n;j++){
for(i=2;i<j;i++){
if(isPrime(j) == 1){
primes[j] = j;
if(primes[j]+primes[i]==n){
firstPrime = primes[j];
secondPrime = primes[i];
printf("%d + %d = %d\n",firstPrime,secondPrime,n);
}
}
}
}
}
|
the_stack_data/43886970.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
int maxXor(int l, int r) {
int maxSum = 0;
int temp;
for (int i=l; i<r; i++){
for (int j=i+1;j<=r;j++){
temp = i^j;
if (maxSum<temp){
maxSum = temp;
}
}
}
return maxSum;
}
int main() {
int res;
int _l;
scanf("%d", &_l);
int _r;
scanf("%d", &_r);
res = maxXor(_l, _r);
printf("%d", res);
return 0;
}
|
the_stack_data/132222.c | int main(void)
{
int x = 0;
while (x < 2)
++x;
__CPROVER_assert(x == 4, "A");
return 0;
}
|
the_stack_data/115564.c | /* Autogenerated: 'src/ExtractionOCaml/unsaturated_solinas' --static --use-value-barrier p448 64 8 '2^448 - 2^224 - 1' carry_mul carry_square carry add sub opp selectznz to_bytes from_bytes */
/* curve description: p448 */
/* machine_wordsize = 64 (from "64") */
/* requested operations: carry_mul, carry_square, carry, add, sub, opp, selectznz, to_bytes, from_bytes */
/* n = 8 (from "8") */
/* s-c = 2^448 - [(2^224, 1), (1, 1)] (from "2^448 - 2^224 - 1") */
/* tight_bounds_multiplier = 1 (from "") */
/* */
/* Computed values: */
/* carry_chain = [3, 7, 4, 0, 5, 1, 6, 2, 7, 3, 4, 0] */
/* eval z = z[0] + (z[1] << 56) + (z[2] << 112) + (z[3] << 168) + (z[4] << 224) + (z[5] << 0x118) + (z[6] << 0x150) + (z[7] << 0x188) */
/* bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) + (z[32] << 256) + (z[33] << 0x108) + (z[34] << 0x110) + (z[35] << 0x118) + (z[36] << 0x120) + (z[37] << 0x128) + (z[38] << 0x130) + (z[39] << 0x138) + (z[40] << 0x140) + (z[41] << 0x148) + (z[42] << 0x150) + (z[43] << 0x158) + (z[44] << 0x160) + (z[45] << 0x168) + (z[46] << 0x170) + (z[47] << 0x178) + (z[48] << 0x180) + (z[49] << 0x188) + (z[50] << 0x190) + (z[51] << 0x198) + (z[52] << 0x1a0) + (z[53] << 0x1a8) + (z[54] << 0x1b0) + (z[55] << 0x1b8) */
/* balance = [0x1fffffffffffffe, 0x1fffffffffffffe, 0x1fffffffffffffe, 0x1fffffffffffffe, 0x1fffffffffffffc, 0x1fffffffffffffe, 0x1fffffffffffffe, 0x1fffffffffffffe] */
#include <stdint.h>
typedef unsigned char fiat_p448_uint1;
typedef signed char fiat_p448_int1;
#ifdef __GNUC__
# define FIAT_P448_FIAT_EXTENSION __extension__
#else
# define FIAT_P448_FIAT_EXTENSION
#endif
FIAT_P448_FIAT_EXTENSION typedef signed __int128 fiat_p448_int128;
FIAT_P448_FIAT_EXTENSION typedef unsigned __int128 fiat_p448_uint128;
#if (-1 & 3) != 3
#error "This code only works on a two's complement system"
#endif
#if !defined(FIAT_P448_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
static __inline__ uint64_t fiat_p448_value_barrier_u64(uint64_t a) {
__asm__("" : "+r"(a) : /* no inputs */);
return a;
}
#else
# define fiat_p448_value_barrier_u64(x) (x)
#endif
/*
* The function fiat_p448_addcarryx_u56 is an addition with carry.
*
* Postconditions:
* out1 = (arg1 + arg2 + arg3) mod 2^56
* out2 = ⌊(arg1 + arg2 + arg3) / 2^56⌋
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffff]
* out2: [0x0 ~> 0x1]
*/
static void fiat_p448_addcarryx_u56(uint64_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint64_t arg2, uint64_t arg3) {
uint64_t x1;
uint64_t x2;
fiat_p448_uint1 x3;
x1 = ((arg1 + arg2) + arg3);
x2 = (x1 & UINT64_C(0xffffffffffffff));
x3 = (fiat_p448_uint1)(x1 >> 56);
*out1 = x2;
*out2 = x3;
}
/*
* The function fiat_p448_subborrowx_u56 is a subtraction with borrow.
*
* Postconditions:
* out1 = (-arg1 + arg2 + -arg3) mod 2^56
* out2 = -⌊(-arg1 + arg2 + -arg3) / 2^56⌋
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffff]
* out2: [0x0 ~> 0x1]
*/
static void fiat_p448_subborrowx_u56(uint64_t* out1, fiat_p448_uint1* out2, fiat_p448_uint1 arg1, uint64_t arg2, uint64_t arg3) {
int64_t x1;
fiat_p448_int1 x2;
uint64_t x3;
x1 = ((int64_t)(arg2 - (int64_t)arg1) - (int64_t)arg3);
x2 = (fiat_p448_int1)(x1 >> 56);
x3 = (x1 & UINT64_C(0xffffffffffffff));
*out1 = x3;
*out2 = (fiat_p448_uint1)(0x0 - x2);
}
/*
* The function fiat_p448_cmovznz_u64 is a single-word conditional move.
*
* Postconditions:
* out1 = (if arg1 = 0 then arg2 else arg3)
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffffff]
*/
static void fiat_p448_cmovznz_u64(uint64_t* out1, fiat_p448_uint1 arg1, uint64_t arg2, uint64_t arg3) {
fiat_p448_uint1 x1;
uint64_t x2;
uint64_t x3;
x1 = (!(!arg1));
x2 = ((fiat_p448_int1)(0x0 - x1) & UINT64_C(0xffffffffffffffff));
x3 = ((fiat_p448_value_barrier_u64(x2) & arg3) | (fiat_p448_value_barrier_u64((~x2)) & arg2));
*out1 = x3;
}
/*
* The function fiat_p448_carry_mul multiplies two field elements and reduces the result.
*
* Postconditions:
* eval out1 mod m = (eval arg1 * eval arg2) mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
* arg2: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
*/
static void fiat_p448_carry_mul(uint64_t out1[8], const uint64_t arg1[8], const uint64_t arg2[8]) {
fiat_p448_uint128 x1;
fiat_p448_uint128 x2;
fiat_p448_uint128 x3;
fiat_p448_uint128 x4;
fiat_p448_uint128 x5;
fiat_p448_uint128 x6;
fiat_p448_uint128 x7;
fiat_p448_uint128 x8;
fiat_p448_uint128 x9;
fiat_p448_uint128 x10;
fiat_p448_uint128 x11;
fiat_p448_uint128 x12;
fiat_p448_uint128 x13;
fiat_p448_uint128 x14;
fiat_p448_uint128 x15;
fiat_p448_uint128 x16;
fiat_p448_uint128 x17;
fiat_p448_uint128 x18;
fiat_p448_uint128 x19;
fiat_p448_uint128 x20;
fiat_p448_uint128 x21;
fiat_p448_uint128 x22;
fiat_p448_uint128 x23;
fiat_p448_uint128 x24;
fiat_p448_uint128 x25;
fiat_p448_uint128 x26;
fiat_p448_uint128 x27;
fiat_p448_uint128 x28;
fiat_p448_uint128 x29;
fiat_p448_uint128 x30;
fiat_p448_uint128 x31;
fiat_p448_uint128 x32;
fiat_p448_uint128 x33;
fiat_p448_uint128 x34;
fiat_p448_uint128 x35;
fiat_p448_uint128 x36;
fiat_p448_uint128 x37;
fiat_p448_uint128 x38;
fiat_p448_uint128 x39;
fiat_p448_uint128 x40;
fiat_p448_uint128 x41;
fiat_p448_uint128 x42;
fiat_p448_uint128 x43;
fiat_p448_uint128 x44;
fiat_p448_uint128 x45;
fiat_p448_uint128 x46;
fiat_p448_uint128 x47;
fiat_p448_uint128 x48;
fiat_p448_uint128 x49;
fiat_p448_uint128 x50;
fiat_p448_uint128 x51;
fiat_p448_uint128 x52;
fiat_p448_uint128 x53;
fiat_p448_uint128 x54;
fiat_p448_uint128 x55;
fiat_p448_uint128 x56;
fiat_p448_uint128 x57;
fiat_p448_uint128 x58;
fiat_p448_uint128 x59;
fiat_p448_uint128 x60;
fiat_p448_uint128 x61;
fiat_p448_uint128 x62;
fiat_p448_uint128 x63;
fiat_p448_uint128 x64;
fiat_p448_uint128 x65;
fiat_p448_uint128 x66;
fiat_p448_uint128 x67;
fiat_p448_uint128 x68;
fiat_p448_uint128 x69;
fiat_p448_uint128 x70;
fiat_p448_uint128 x71;
fiat_p448_uint128 x72;
fiat_p448_uint128 x73;
fiat_p448_uint128 x74;
fiat_p448_uint128 x75;
fiat_p448_uint128 x76;
fiat_p448_uint128 x77;
fiat_p448_uint128 x78;
fiat_p448_uint128 x79;
fiat_p448_uint128 x80;
fiat_p448_uint128 x81;
fiat_p448_uint128 x82;
fiat_p448_uint128 x83;
fiat_p448_uint128 x84;
fiat_p448_uint128 x85;
fiat_p448_uint128 x86;
fiat_p448_uint128 x87;
fiat_p448_uint128 x88;
fiat_p448_uint128 x89;
fiat_p448_uint128 x90;
fiat_p448_uint128 x91;
fiat_p448_uint128 x92;
fiat_p448_uint128 x93;
fiat_p448_uint128 x94;
fiat_p448_uint128 x95;
fiat_p448_uint128 x96;
fiat_p448_uint128 x97;
fiat_p448_uint128 x98;
fiat_p448_uint128 x99;
uint64_t x100;
uint64_t x101;
fiat_p448_uint128 x102;
fiat_p448_uint128 x103;
fiat_p448_uint128 x104;
fiat_p448_uint128 x105;
fiat_p448_uint128 x106;
fiat_p448_uint128 x107;
fiat_p448_uint128 x108;
fiat_p448_uint128 x109;
uint64_t x110;
uint64_t x111;
fiat_p448_uint128 x112;
uint64_t x113;
uint64_t x114;
fiat_p448_uint128 x115;
fiat_p448_uint128 x116;
uint64_t x117;
uint64_t x118;
fiat_p448_uint128 x119;
uint64_t x120;
uint64_t x121;
fiat_p448_uint128 x122;
uint64_t x123;
uint64_t x124;
fiat_p448_uint128 x125;
uint64_t x126;
uint64_t x127;
uint64_t x128;
uint64_t x129;
uint64_t x130;
uint64_t x131;
uint64_t x132;
uint64_t x133;
uint64_t x134;
uint64_t x135;
uint64_t x136;
uint64_t x137;
uint64_t x138;
fiat_p448_uint1 x139;
uint64_t x140;
uint64_t x141;
fiat_p448_uint1 x142;
uint64_t x143;
uint64_t x144;
x1 = ((fiat_p448_uint128)(arg1[7]) * (arg2[7]));
x2 = ((fiat_p448_uint128)(arg1[7]) * (arg2[6]));
x3 = ((fiat_p448_uint128)(arg1[7]) * (arg2[5]));
x4 = ((fiat_p448_uint128)(arg1[6]) * (arg2[7]));
x5 = ((fiat_p448_uint128)(arg1[6]) * (arg2[6]));
x6 = ((fiat_p448_uint128)(arg1[5]) * (arg2[7]));
x7 = ((fiat_p448_uint128)(arg1[7]) * (arg2[7]));
x8 = ((fiat_p448_uint128)(arg1[7]) * (arg2[6]));
x9 = ((fiat_p448_uint128)(arg1[7]) * (arg2[5]));
x10 = ((fiat_p448_uint128)(arg1[6]) * (arg2[7]));
x11 = ((fiat_p448_uint128)(arg1[6]) * (arg2[6]));
x12 = ((fiat_p448_uint128)(arg1[5]) * (arg2[7]));
x13 = ((fiat_p448_uint128)(arg1[7]) * (arg2[7]));
x14 = ((fiat_p448_uint128)(arg1[7]) * (arg2[6]));
x15 = ((fiat_p448_uint128)(arg1[7]) * (arg2[5]));
x16 = ((fiat_p448_uint128)(arg1[7]) * (arg2[4]));
x17 = ((fiat_p448_uint128)(arg1[7]) * (arg2[3]));
x18 = ((fiat_p448_uint128)(arg1[7]) * (arg2[2]));
x19 = ((fiat_p448_uint128)(arg1[7]) * (arg2[1]));
x20 = ((fiat_p448_uint128)(arg1[6]) * (arg2[7]));
x21 = ((fiat_p448_uint128)(arg1[6]) * (arg2[6]));
x22 = ((fiat_p448_uint128)(arg1[6]) * (arg2[5]));
x23 = ((fiat_p448_uint128)(arg1[6]) * (arg2[4]));
x24 = ((fiat_p448_uint128)(arg1[6]) * (arg2[3]));
x25 = ((fiat_p448_uint128)(arg1[6]) * (arg2[2]));
x26 = ((fiat_p448_uint128)(arg1[5]) * (arg2[7]));
x27 = ((fiat_p448_uint128)(arg1[5]) * (arg2[6]));
x28 = ((fiat_p448_uint128)(arg1[5]) * (arg2[5]));
x29 = ((fiat_p448_uint128)(arg1[5]) * (arg2[4]));
x30 = ((fiat_p448_uint128)(arg1[5]) * (arg2[3]));
x31 = ((fiat_p448_uint128)(arg1[4]) * (arg2[7]));
x32 = ((fiat_p448_uint128)(arg1[4]) * (arg2[6]));
x33 = ((fiat_p448_uint128)(arg1[4]) * (arg2[5]));
x34 = ((fiat_p448_uint128)(arg1[4]) * (arg2[4]));
x35 = ((fiat_p448_uint128)(arg1[3]) * (arg2[7]));
x36 = ((fiat_p448_uint128)(arg1[3]) * (arg2[6]));
x37 = ((fiat_p448_uint128)(arg1[3]) * (arg2[5]));
x38 = ((fiat_p448_uint128)(arg1[2]) * (arg2[7]));
x39 = ((fiat_p448_uint128)(arg1[2]) * (arg2[6]));
x40 = ((fiat_p448_uint128)(arg1[1]) * (arg2[7]));
x41 = ((fiat_p448_uint128)(arg1[7]) * (arg2[4]));
x42 = ((fiat_p448_uint128)(arg1[7]) * (arg2[3]));
x43 = ((fiat_p448_uint128)(arg1[7]) * (arg2[2]));
x44 = ((fiat_p448_uint128)(arg1[7]) * (arg2[1]));
x45 = ((fiat_p448_uint128)(arg1[6]) * (arg2[5]));
x46 = ((fiat_p448_uint128)(arg1[6]) * (arg2[4]));
x47 = ((fiat_p448_uint128)(arg1[6]) * (arg2[3]));
x48 = ((fiat_p448_uint128)(arg1[6]) * (arg2[2]));
x49 = ((fiat_p448_uint128)(arg1[5]) * (arg2[6]));
x50 = ((fiat_p448_uint128)(arg1[5]) * (arg2[5]));
x51 = ((fiat_p448_uint128)(arg1[5]) * (arg2[4]));
x52 = ((fiat_p448_uint128)(arg1[5]) * (arg2[3]));
x53 = ((fiat_p448_uint128)(arg1[4]) * (arg2[7]));
x54 = ((fiat_p448_uint128)(arg1[4]) * (arg2[6]));
x55 = ((fiat_p448_uint128)(arg1[4]) * (arg2[5]));
x56 = ((fiat_p448_uint128)(arg1[4]) * (arg2[4]));
x57 = ((fiat_p448_uint128)(arg1[3]) * (arg2[7]));
x58 = ((fiat_p448_uint128)(arg1[3]) * (arg2[6]));
x59 = ((fiat_p448_uint128)(arg1[3]) * (arg2[5]));
x60 = ((fiat_p448_uint128)(arg1[2]) * (arg2[7]));
x61 = ((fiat_p448_uint128)(arg1[2]) * (arg2[6]));
x62 = ((fiat_p448_uint128)(arg1[1]) * (arg2[7]));
x63 = ((fiat_p448_uint128)(arg1[7]) * (arg2[0]));
x64 = ((fiat_p448_uint128)(arg1[6]) * (arg2[1]));
x65 = ((fiat_p448_uint128)(arg1[6]) * (arg2[0]));
x66 = ((fiat_p448_uint128)(arg1[5]) * (arg2[2]));
x67 = ((fiat_p448_uint128)(arg1[5]) * (arg2[1]));
x68 = ((fiat_p448_uint128)(arg1[5]) * (arg2[0]));
x69 = ((fiat_p448_uint128)(arg1[4]) * (arg2[3]));
x70 = ((fiat_p448_uint128)(arg1[4]) * (arg2[2]));
x71 = ((fiat_p448_uint128)(arg1[4]) * (arg2[1]));
x72 = ((fiat_p448_uint128)(arg1[4]) * (arg2[0]));
x73 = ((fiat_p448_uint128)(arg1[3]) * (arg2[4]));
x74 = ((fiat_p448_uint128)(arg1[3]) * (arg2[3]));
x75 = ((fiat_p448_uint128)(arg1[3]) * (arg2[2]));
x76 = ((fiat_p448_uint128)(arg1[3]) * (arg2[1]));
x77 = ((fiat_p448_uint128)(arg1[3]) * (arg2[0]));
x78 = ((fiat_p448_uint128)(arg1[2]) * (arg2[5]));
x79 = ((fiat_p448_uint128)(arg1[2]) * (arg2[4]));
x80 = ((fiat_p448_uint128)(arg1[2]) * (arg2[3]));
x81 = ((fiat_p448_uint128)(arg1[2]) * (arg2[2]));
x82 = ((fiat_p448_uint128)(arg1[2]) * (arg2[1]));
x83 = ((fiat_p448_uint128)(arg1[2]) * (arg2[0]));
x84 = ((fiat_p448_uint128)(arg1[1]) * (arg2[6]));
x85 = ((fiat_p448_uint128)(arg1[1]) * (arg2[5]));
x86 = ((fiat_p448_uint128)(arg1[1]) * (arg2[4]));
x87 = ((fiat_p448_uint128)(arg1[1]) * (arg2[3]));
x88 = ((fiat_p448_uint128)(arg1[1]) * (arg2[2]));
x89 = ((fiat_p448_uint128)(arg1[1]) * (arg2[1]));
x90 = ((fiat_p448_uint128)(arg1[1]) * (arg2[0]));
x91 = ((fiat_p448_uint128)(arg1[0]) * (arg2[7]));
x92 = ((fiat_p448_uint128)(arg1[0]) * (arg2[6]));
x93 = ((fiat_p448_uint128)(arg1[0]) * (arg2[5]));
x94 = ((fiat_p448_uint128)(arg1[0]) * (arg2[4]));
x95 = ((fiat_p448_uint128)(arg1[0]) * (arg2[3]));
x96 = ((fiat_p448_uint128)(arg1[0]) * (arg2[2]));
x97 = ((fiat_p448_uint128)(arg1[0]) * (arg2[1]));
x98 = ((fiat_p448_uint128)(arg1[0]) * (arg2[0]));
x99 = (x95 + (x88 + (x82 + (x77 + (x31 + (x27 + (x22 + x16)))))));
x100 = (uint64_t)(x99 >> 56);
x101 = (uint64_t)(x99 & UINT64_C(0xffffffffffffff));
x102 = (x91 + (x84 + (x78 + (x73 + (x69 + (x66 + (x64 + (x63 + (x53 + (x49 + (x45 + x41)))))))))));
x103 = (x92 + (x85 + (x79 + (x74 + (x70 + (x67 + (x65 + (x57 + (x54 + (x50 + (x46 + (x42 + (x13 + x7)))))))))))));
x104 = (x93 + (x86 + (x80 + (x75 + (x71 + (x68 + (x60 + (x58 + (x55 + (x51 + (x47 + (x43 + (x20 + (x14 + (x10 + x8)))))))))))))));
x105 = (x94 + (x87 + (x81 + (x76 + (x72 + (x62 + (x61 + (x59 + (x56 + (x52 + (x48 + (x44 + (x26 + (x21 + (x15 + (x12 + (x11 + x9)))))))))))))))));
x106 = (x96 + (x89 + (x83 + (x35 + (x32 + (x28 + (x23 + (x17 + x1))))))));
x107 = (x97 + (x90 + (x38 + (x36 + (x33 + (x29 + (x24 + (x18 + (x4 + x2)))))))));
x108 = (x98 + (x40 + (x39 + (x37 + (x34 + (x30 + (x25 + (x19 + (x6 + (x5 + x3))))))))));
x109 = (x100 + x105);
x110 = (uint64_t)(x102 >> 56);
x111 = (uint64_t)(x102 & UINT64_C(0xffffffffffffff));
x112 = (x109 + x110);
x113 = (uint64_t)(x112 >> 56);
x114 = (uint64_t)(x112 & UINT64_C(0xffffffffffffff));
x115 = (x108 + x110);
x116 = (x113 + x104);
x117 = (uint64_t)(x115 >> 56);
x118 = (uint64_t)(x115 & UINT64_C(0xffffffffffffff));
x119 = (x117 + x107);
x120 = (uint64_t)(x116 >> 56);
x121 = (uint64_t)(x116 & UINT64_C(0xffffffffffffff));
x122 = (x120 + x103);
x123 = (uint64_t)(x119 >> 56);
x124 = (uint64_t)(x119 & UINT64_C(0xffffffffffffff));
x125 = (x123 + x106);
x126 = (uint64_t)(x122 >> 56);
x127 = (uint64_t)(x122 & UINT64_C(0xffffffffffffff));
x128 = (x126 + x111);
x129 = (uint64_t)(x125 >> 56);
x130 = (uint64_t)(x125 & UINT64_C(0xffffffffffffff));
x131 = (x129 + x101);
x132 = (x128 >> 56);
x133 = (x128 & UINT64_C(0xffffffffffffff));
x134 = (x131 >> 56);
x135 = (x131 & UINT64_C(0xffffffffffffff));
x136 = (x114 + x132);
x137 = (x118 + x132);
x138 = (x134 + x136);
x139 = (fiat_p448_uint1)(x138 >> 56);
x140 = (x138 & UINT64_C(0xffffffffffffff));
x141 = (x139 + x121);
x142 = (fiat_p448_uint1)(x137 >> 56);
x143 = (x137 & UINT64_C(0xffffffffffffff));
x144 = (x142 + x124);
out1[0] = x143;
out1[1] = x144;
out1[2] = x130;
out1[3] = x135;
out1[4] = x140;
out1[5] = x141;
out1[6] = x127;
out1[7] = x133;
}
/*
* The function fiat_p448_carry_square squares a field element and reduces the result.
*
* Postconditions:
* eval out1 mod m = (eval arg1 * eval arg1) mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
*/
static void fiat_p448_carry_square(uint64_t out1[8], const uint64_t arg1[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
uint64_t x9;
uint64_t x10;
uint64_t x11;
uint64_t x12;
uint64_t x13;
uint64_t x14;
uint64_t x15;
uint64_t x16;
uint64_t x17;
uint64_t x18;
uint64_t x19;
uint64_t x20;
uint64_t x21;
fiat_p448_uint128 x22;
fiat_p448_uint128 x23;
fiat_p448_uint128 x24;
fiat_p448_uint128 x25;
fiat_p448_uint128 x26;
fiat_p448_uint128 x27;
fiat_p448_uint128 x28;
fiat_p448_uint128 x29;
fiat_p448_uint128 x30;
fiat_p448_uint128 x31;
fiat_p448_uint128 x32;
fiat_p448_uint128 x33;
fiat_p448_uint128 x34;
fiat_p448_uint128 x35;
fiat_p448_uint128 x36;
fiat_p448_uint128 x37;
fiat_p448_uint128 x38;
fiat_p448_uint128 x39;
fiat_p448_uint128 x40;
fiat_p448_uint128 x41;
fiat_p448_uint128 x42;
fiat_p448_uint128 x43;
fiat_p448_uint128 x44;
fiat_p448_uint128 x45;
fiat_p448_uint128 x46;
fiat_p448_uint128 x47;
fiat_p448_uint128 x48;
fiat_p448_uint128 x49;
fiat_p448_uint128 x50;
fiat_p448_uint128 x51;
fiat_p448_uint128 x52;
fiat_p448_uint128 x53;
fiat_p448_uint128 x54;
fiat_p448_uint128 x55;
fiat_p448_uint128 x56;
fiat_p448_uint128 x57;
fiat_p448_uint128 x58;
fiat_p448_uint128 x59;
fiat_p448_uint128 x60;
fiat_p448_uint128 x61;
fiat_p448_uint128 x62;
fiat_p448_uint128 x63;
fiat_p448_uint128 x64;
fiat_p448_uint128 x65;
fiat_p448_uint128 x66;
fiat_p448_uint128 x67;
fiat_p448_uint128 x68;
fiat_p448_uint128 x69;
fiat_p448_uint128 x70;
fiat_p448_uint128 x71;
fiat_p448_uint128 x72;
fiat_p448_uint128 x73;
fiat_p448_uint128 x74;
fiat_p448_uint128 x75;
fiat_p448_uint128 x76;
fiat_p448_uint128 x77;
fiat_p448_uint128 x78;
uint64_t x79;
uint64_t x80;
fiat_p448_uint128 x81;
fiat_p448_uint128 x82;
fiat_p448_uint128 x83;
fiat_p448_uint128 x84;
fiat_p448_uint128 x85;
fiat_p448_uint128 x86;
fiat_p448_uint128 x87;
fiat_p448_uint128 x88;
uint64_t x89;
uint64_t x90;
fiat_p448_uint128 x91;
uint64_t x92;
uint64_t x93;
fiat_p448_uint128 x94;
fiat_p448_uint128 x95;
uint64_t x96;
uint64_t x97;
fiat_p448_uint128 x98;
uint64_t x99;
uint64_t x100;
fiat_p448_uint128 x101;
uint64_t x102;
uint64_t x103;
fiat_p448_uint128 x104;
uint64_t x105;
uint64_t x106;
uint64_t x107;
uint64_t x108;
uint64_t x109;
uint64_t x110;
uint64_t x111;
uint64_t x112;
uint64_t x113;
uint64_t x114;
uint64_t x115;
uint64_t x116;
uint64_t x117;
fiat_p448_uint1 x118;
uint64_t x119;
uint64_t x120;
fiat_p448_uint1 x121;
uint64_t x122;
uint64_t x123;
x1 = (arg1[7]);
x2 = (arg1[7]);
x3 = (x1 * 0x2);
x4 = (x2 * 0x2);
x5 = ((arg1[7]) * 0x2);
x6 = (arg1[6]);
x7 = (arg1[6]);
x8 = (x6 * 0x2);
x9 = (x7 * 0x2);
x10 = ((arg1[6]) * 0x2);
x11 = (arg1[5]);
x12 = (arg1[5]);
x13 = (x11 * 0x2);
x14 = (x12 * 0x2);
x15 = ((arg1[5]) * 0x2);
x16 = (arg1[4]);
x17 = (arg1[4]);
x18 = ((arg1[4]) * 0x2);
x19 = ((arg1[3]) * 0x2);
x20 = ((arg1[2]) * 0x2);
x21 = ((arg1[1]) * 0x2);
x22 = ((fiat_p448_uint128)(arg1[7]) * x1);
x23 = ((fiat_p448_uint128)(arg1[6]) * x3);
x24 = ((fiat_p448_uint128)(arg1[6]) * x6);
x25 = ((fiat_p448_uint128)(arg1[5]) * x3);
x26 = ((fiat_p448_uint128)(arg1[7]) * x1);
x27 = ((fiat_p448_uint128)(arg1[6]) * x3);
x28 = ((fiat_p448_uint128)(arg1[6]) * x6);
x29 = ((fiat_p448_uint128)(arg1[5]) * x3);
x30 = ((fiat_p448_uint128)(arg1[7]) * x2);
x31 = ((fiat_p448_uint128)(arg1[6]) * x4);
x32 = ((fiat_p448_uint128)(arg1[6]) * x7);
x33 = ((fiat_p448_uint128)(arg1[5]) * x4);
x34 = ((fiat_p448_uint128)(arg1[5]) * x9);
x35 = ((fiat_p448_uint128)(arg1[5]) * x8);
x36 = ((fiat_p448_uint128)(arg1[5]) * x12);
x37 = ((fiat_p448_uint128)(arg1[5]) * x11);
x38 = ((fiat_p448_uint128)(arg1[4]) * x4);
x39 = ((fiat_p448_uint128)(arg1[4]) * x3);
x40 = ((fiat_p448_uint128)(arg1[4]) * x9);
x41 = ((fiat_p448_uint128)(arg1[4]) * x8);
x42 = ((fiat_p448_uint128)(arg1[4]) * x14);
x43 = ((fiat_p448_uint128)(arg1[4]) * x13);
x44 = ((fiat_p448_uint128)(arg1[4]) * x17);
x45 = ((fiat_p448_uint128)(arg1[4]) * x16);
x46 = ((fiat_p448_uint128)(arg1[3]) * x4);
x47 = ((fiat_p448_uint128)(arg1[3]) * x3);
x48 = ((fiat_p448_uint128)(arg1[3]) * x9);
x49 = ((fiat_p448_uint128)(arg1[3]) * x8);
x50 = ((fiat_p448_uint128)(arg1[3]) * x14);
x51 = ((fiat_p448_uint128)(arg1[3]) * x13);
x52 = ((fiat_p448_uint128)(arg1[3]) * x18);
x53 = ((fiat_p448_uint128)(arg1[3]) * (arg1[3]));
x54 = ((fiat_p448_uint128)(arg1[2]) * x4);
x55 = ((fiat_p448_uint128)(arg1[2]) * x3);
x56 = ((fiat_p448_uint128)(arg1[2]) * x9);
x57 = ((fiat_p448_uint128)(arg1[2]) * x8);
x58 = ((fiat_p448_uint128)(arg1[2]) * x15);
x59 = ((fiat_p448_uint128)(arg1[2]) * x18);
x60 = ((fiat_p448_uint128)(arg1[2]) * x19);
x61 = ((fiat_p448_uint128)(arg1[2]) * (arg1[2]));
x62 = ((fiat_p448_uint128)(arg1[1]) * x4);
x63 = ((fiat_p448_uint128)(arg1[1]) * x3);
x64 = ((fiat_p448_uint128)(arg1[1]) * x10);
x65 = ((fiat_p448_uint128)(arg1[1]) * x15);
x66 = ((fiat_p448_uint128)(arg1[1]) * x18);
x67 = ((fiat_p448_uint128)(arg1[1]) * x19);
x68 = ((fiat_p448_uint128)(arg1[1]) * x20);
x69 = ((fiat_p448_uint128)(arg1[1]) * (arg1[1]));
x70 = ((fiat_p448_uint128)(arg1[0]) * x5);
x71 = ((fiat_p448_uint128)(arg1[0]) * x10);
x72 = ((fiat_p448_uint128)(arg1[0]) * x15);
x73 = ((fiat_p448_uint128)(arg1[0]) * x18);
x74 = ((fiat_p448_uint128)(arg1[0]) * x19);
x75 = ((fiat_p448_uint128)(arg1[0]) * x20);
x76 = ((fiat_p448_uint128)(arg1[0]) * x21);
x77 = ((fiat_p448_uint128)(arg1[0]) * (arg1[0]));
x78 = (x74 + (x68 + (x38 + x34)));
x79 = (uint64_t)(x78 >> 56);
x80 = (uint64_t)(x78 & UINT64_C(0xffffffffffffff));
x81 = (x70 + (x64 + (x58 + (x52 + (x39 + x35)))));
x82 = (x71 + (x65 + (x59 + (x53 + (x47 + (x41 + (x37 + (x30 + x26))))))));
x83 = (x72 + (x66 + (x60 + (x55 + (x49 + (x43 + (x31 + x27)))))));
x84 = (x73 + (x67 + (x63 + (x61 + (x57 + (x51 + (x45 + (x33 + (x32 + (x29 + x28))))))))));
x85 = (x75 + (x69 + (x46 + (x40 + (x36 + x22)))));
x86 = (x76 + (x54 + (x48 + (x42 + x23))));
x87 = (x77 + (x62 + (x56 + (x50 + (x44 + (x25 + x24))))));
x88 = (x79 + x84);
x89 = (uint64_t)(x81 >> 56);
x90 = (uint64_t)(x81 & UINT64_C(0xffffffffffffff));
x91 = (x88 + x89);
x92 = (uint64_t)(x91 >> 56);
x93 = (uint64_t)(x91 & UINT64_C(0xffffffffffffff));
x94 = (x87 + x89);
x95 = (x92 + x83);
x96 = (uint64_t)(x94 >> 56);
x97 = (uint64_t)(x94 & UINT64_C(0xffffffffffffff));
x98 = (x96 + x86);
x99 = (uint64_t)(x95 >> 56);
x100 = (uint64_t)(x95 & UINT64_C(0xffffffffffffff));
x101 = (x99 + x82);
x102 = (uint64_t)(x98 >> 56);
x103 = (uint64_t)(x98 & UINT64_C(0xffffffffffffff));
x104 = (x102 + x85);
x105 = (uint64_t)(x101 >> 56);
x106 = (uint64_t)(x101 & UINT64_C(0xffffffffffffff));
x107 = (x105 + x90);
x108 = (uint64_t)(x104 >> 56);
x109 = (uint64_t)(x104 & UINT64_C(0xffffffffffffff));
x110 = (x108 + x80);
x111 = (x107 >> 56);
x112 = (x107 & UINT64_C(0xffffffffffffff));
x113 = (x110 >> 56);
x114 = (x110 & UINT64_C(0xffffffffffffff));
x115 = (x93 + x111);
x116 = (x97 + x111);
x117 = (x113 + x115);
x118 = (fiat_p448_uint1)(x117 >> 56);
x119 = (x117 & UINT64_C(0xffffffffffffff));
x120 = (x118 + x100);
x121 = (fiat_p448_uint1)(x116 >> 56);
x122 = (x116 & UINT64_C(0xffffffffffffff));
x123 = (x121 + x103);
out1[0] = x122;
out1[1] = x123;
out1[2] = x109;
out1[3] = x114;
out1[4] = x119;
out1[5] = x120;
out1[6] = x106;
out1[7] = x112;
}
/*
* The function fiat_p448_carry reduces a field element.
*
* Postconditions:
* eval out1 mod m = eval arg1 mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
*/
static void fiat_p448_carry(uint64_t out1[8], const uint64_t arg1[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
uint64_t x9;
uint64_t x10;
uint64_t x11;
fiat_p448_uint1 x12;
uint64_t x13;
uint64_t x14;
uint64_t x15;
uint64_t x16;
uint64_t x17;
uint64_t x18;
uint64_t x19;
uint64_t x20;
uint64_t x21;
uint64_t x22;
x1 = (arg1[3]);
x2 = (arg1[7]);
x3 = (x2 >> 56);
x4 = (((x1 >> 56) + (arg1[4])) + x3);
x5 = ((arg1[0]) + x3);
x6 = ((x4 >> 56) + (arg1[5]));
x7 = ((x5 >> 56) + (arg1[1]));
x8 = ((x6 >> 56) + (arg1[6]));
x9 = ((x7 >> 56) + (arg1[2]));
x10 = ((x8 >> 56) + (x2 & UINT64_C(0xffffffffffffff)));
x11 = ((x9 >> 56) + (x1 & UINT64_C(0xffffffffffffff)));
x12 = (fiat_p448_uint1)(x10 >> 56);
x13 = ((x5 & UINT64_C(0xffffffffffffff)) + (uint64_t)x12);
x14 = ((fiat_p448_uint1)(x11 >> 56) + ((x4 & UINT64_C(0xffffffffffffff)) + (uint64_t)x12));
x15 = (x13 & UINT64_C(0xffffffffffffff));
x16 = ((fiat_p448_uint1)(x13 >> 56) + (x7 & UINT64_C(0xffffffffffffff)));
x17 = (x9 & UINT64_C(0xffffffffffffff));
x18 = (x11 & UINT64_C(0xffffffffffffff));
x19 = (x14 & UINT64_C(0xffffffffffffff));
x20 = ((fiat_p448_uint1)(x14 >> 56) + (x6 & UINT64_C(0xffffffffffffff)));
x21 = (x8 & UINT64_C(0xffffffffffffff));
x22 = (x10 & UINT64_C(0xffffffffffffff));
out1[0] = x15;
out1[1] = x16;
out1[2] = x17;
out1[3] = x18;
out1[4] = x19;
out1[5] = x20;
out1[6] = x21;
out1[7] = x22;
}
/*
* The function fiat_p448_add adds two field elements.
*
* Postconditions:
* eval out1 mod m = (eval arg1 + eval arg2) mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* arg2: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
*/
static void fiat_p448_add(uint64_t out1[8], const uint64_t arg1[8], const uint64_t arg2[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
x1 = ((arg1[0]) + (arg2[0]));
x2 = ((arg1[1]) + (arg2[1]));
x3 = ((arg1[2]) + (arg2[2]));
x4 = ((arg1[3]) + (arg2[3]));
x5 = ((arg1[4]) + (arg2[4]));
x6 = ((arg1[5]) + (arg2[5]));
x7 = ((arg1[6]) + (arg2[6]));
x8 = ((arg1[7]) + (arg2[7]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
out1[7] = x8;
}
/*
* The function fiat_p448_sub subtracts two field elements.
*
* Postconditions:
* eval out1 mod m = (eval arg1 - eval arg2) mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* arg2: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
*/
static void fiat_p448_sub(uint64_t out1[8], const uint64_t arg1[8], const uint64_t arg2[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
x1 = ((UINT64_C(0x1fffffffffffffe) + (arg1[0])) - (arg2[0]));
x2 = ((UINT64_C(0x1fffffffffffffe) + (arg1[1])) - (arg2[1]));
x3 = ((UINT64_C(0x1fffffffffffffe) + (arg1[2])) - (arg2[2]));
x4 = ((UINT64_C(0x1fffffffffffffe) + (arg1[3])) - (arg2[3]));
x5 = ((UINT64_C(0x1fffffffffffffc) + (arg1[4])) - (arg2[4]));
x6 = ((UINT64_C(0x1fffffffffffffe) + (arg1[5])) - (arg2[5]));
x7 = ((UINT64_C(0x1fffffffffffffe) + (arg1[6])) - (arg2[6]));
x8 = ((UINT64_C(0x1fffffffffffffe) + (arg1[7])) - (arg2[7]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
out1[7] = x8;
}
/*
* The function fiat_p448_opp negates a field element.
*
* Postconditions:
* eval out1 mod m = -eval arg1 mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000], [0x0 ~> 0x300000000000000]]
*/
static void fiat_p448_opp(uint64_t out1[8], const uint64_t arg1[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
x1 = (UINT64_C(0x1fffffffffffffe) - (arg1[0]));
x2 = (UINT64_C(0x1fffffffffffffe) - (arg1[1]));
x3 = (UINT64_C(0x1fffffffffffffe) - (arg1[2]));
x4 = (UINT64_C(0x1fffffffffffffe) - (arg1[3]));
x5 = (UINT64_C(0x1fffffffffffffc) - (arg1[4]));
x6 = (UINT64_C(0x1fffffffffffffe) - (arg1[5]));
x7 = (UINT64_C(0x1fffffffffffffe) - (arg1[6]));
x8 = (UINT64_C(0x1fffffffffffffe) - (arg1[7]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
out1[7] = x8;
}
/*
* The function fiat_p448_selectznz is a multi-limb conditional select.
*
* Postconditions:
* eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
* arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
* Output Bounds:
* out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
*/
static void fiat_p448_selectznz(uint64_t out1[8], fiat_p448_uint1 arg1, const uint64_t arg2[8], const uint64_t arg3[8]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
fiat_p448_cmovznz_u64(&x1, arg1, (arg2[0]), (arg3[0]));
fiat_p448_cmovznz_u64(&x2, arg1, (arg2[1]), (arg3[1]));
fiat_p448_cmovznz_u64(&x3, arg1, (arg2[2]), (arg3[2]));
fiat_p448_cmovznz_u64(&x4, arg1, (arg2[3]), (arg3[3]));
fiat_p448_cmovznz_u64(&x5, arg1, (arg2[4]), (arg3[4]));
fiat_p448_cmovznz_u64(&x6, arg1, (arg2[5]), (arg3[5]));
fiat_p448_cmovznz_u64(&x7, arg1, (arg2[6]), (arg3[6]));
fiat_p448_cmovznz_u64(&x8, arg1, (arg2[7]), (arg3[7]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
out1[7] = x8;
}
/*
* The function fiat_p448_to_bytes serializes a field element to bytes in little-endian order.
*
* Postconditions:
* out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..55]
*
* Input Bounds:
* arg1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
* Output Bounds:
* out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
*/
static void fiat_p448_to_bytes(uint8_t out1[56], const uint64_t arg1[8]) {
uint64_t x1;
fiat_p448_uint1 x2;
uint64_t x3;
fiat_p448_uint1 x4;
uint64_t x5;
fiat_p448_uint1 x6;
uint64_t x7;
fiat_p448_uint1 x8;
uint64_t x9;
fiat_p448_uint1 x10;
uint64_t x11;
fiat_p448_uint1 x12;
uint64_t x13;
fiat_p448_uint1 x14;
uint64_t x15;
fiat_p448_uint1 x16;
uint64_t x17;
uint64_t x18;
fiat_p448_uint1 x19;
uint64_t x20;
fiat_p448_uint1 x21;
uint64_t x22;
fiat_p448_uint1 x23;
uint64_t x24;
fiat_p448_uint1 x25;
uint64_t x26;
fiat_p448_uint1 x27;
uint64_t x28;
fiat_p448_uint1 x29;
uint64_t x30;
fiat_p448_uint1 x31;
uint64_t x32;
fiat_p448_uint1 x33;
uint8_t x34;
uint64_t x35;
uint8_t x36;
uint64_t x37;
uint8_t x38;
uint64_t x39;
uint8_t x40;
uint64_t x41;
uint8_t x42;
uint64_t x43;
uint8_t x44;
uint8_t x45;
uint8_t x46;
uint64_t x47;
uint8_t x48;
uint64_t x49;
uint8_t x50;
uint64_t x51;
uint8_t x52;
uint64_t x53;
uint8_t x54;
uint64_t x55;
uint8_t x56;
uint8_t x57;
uint8_t x58;
uint64_t x59;
uint8_t x60;
uint64_t x61;
uint8_t x62;
uint64_t x63;
uint8_t x64;
uint64_t x65;
uint8_t x66;
uint64_t x67;
uint8_t x68;
uint8_t x69;
uint8_t x70;
uint64_t x71;
uint8_t x72;
uint64_t x73;
uint8_t x74;
uint64_t x75;
uint8_t x76;
uint64_t x77;
uint8_t x78;
uint64_t x79;
uint8_t x80;
uint8_t x81;
uint8_t x82;
uint64_t x83;
uint8_t x84;
uint64_t x85;
uint8_t x86;
uint64_t x87;
uint8_t x88;
uint64_t x89;
uint8_t x90;
uint64_t x91;
uint8_t x92;
uint8_t x93;
uint8_t x94;
uint64_t x95;
uint8_t x96;
uint64_t x97;
uint8_t x98;
uint64_t x99;
uint8_t x100;
uint64_t x101;
uint8_t x102;
uint64_t x103;
uint8_t x104;
uint8_t x105;
uint8_t x106;
uint64_t x107;
uint8_t x108;
uint64_t x109;
uint8_t x110;
uint64_t x111;
uint8_t x112;
uint64_t x113;
uint8_t x114;
uint64_t x115;
uint8_t x116;
uint8_t x117;
uint8_t x118;
uint64_t x119;
uint8_t x120;
uint64_t x121;
uint8_t x122;
uint64_t x123;
uint8_t x124;
uint64_t x125;
uint8_t x126;
uint64_t x127;
uint8_t x128;
uint8_t x129;
fiat_p448_subborrowx_u56(&x1, &x2, 0x0, (arg1[0]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x3, &x4, x2, (arg1[1]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x5, &x6, x4, (arg1[2]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x7, &x8, x6, (arg1[3]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x9, &x10, x8, (arg1[4]), UINT64_C(0xfffffffffffffe));
fiat_p448_subborrowx_u56(&x11, &x12, x10, (arg1[5]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x13, &x14, x12, (arg1[6]), UINT64_C(0xffffffffffffff));
fiat_p448_subborrowx_u56(&x15, &x16, x14, (arg1[7]), UINT64_C(0xffffffffffffff));
fiat_p448_cmovznz_u64(&x17, x16, 0x0, UINT64_C(0xffffffffffffffff));
fiat_p448_addcarryx_u56(&x18, &x19, 0x0, x1, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x20, &x21, x19, x3, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x22, &x23, x21, x5, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x24, &x25, x23, x7, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x26, &x27, x25, x9, (x17 & UINT64_C(0xfffffffffffffe)));
fiat_p448_addcarryx_u56(&x28, &x29, x27, x11, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x30, &x31, x29, x13, (x17 & UINT64_C(0xffffffffffffff)));
fiat_p448_addcarryx_u56(&x32, &x33, x31, x15, (x17 & UINT64_C(0xffffffffffffff)));
x34 = (uint8_t)(x18 & UINT8_C(0xff));
x35 = (x18 >> 8);
x36 = (uint8_t)(x35 & UINT8_C(0xff));
x37 = (x35 >> 8);
x38 = (uint8_t)(x37 & UINT8_C(0xff));
x39 = (x37 >> 8);
x40 = (uint8_t)(x39 & UINT8_C(0xff));
x41 = (x39 >> 8);
x42 = (uint8_t)(x41 & UINT8_C(0xff));
x43 = (x41 >> 8);
x44 = (uint8_t)(x43 & UINT8_C(0xff));
x45 = (uint8_t)(x43 >> 8);
x46 = (uint8_t)(x20 & UINT8_C(0xff));
x47 = (x20 >> 8);
x48 = (uint8_t)(x47 & UINT8_C(0xff));
x49 = (x47 >> 8);
x50 = (uint8_t)(x49 & UINT8_C(0xff));
x51 = (x49 >> 8);
x52 = (uint8_t)(x51 & UINT8_C(0xff));
x53 = (x51 >> 8);
x54 = (uint8_t)(x53 & UINT8_C(0xff));
x55 = (x53 >> 8);
x56 = (uint8_t)(x55 & UINT8_C(0xff));
x57 = (uint8_t)(x55 >> 8);
x58 = (uint8_t)(x22 & UINT8_C(0xff));
x59 = (x22 >> 8);
x60 = (uint8_t)(x59 & UINT8_C(0xff));
x61 = (x59 >> 8);
x62 = (uint8_t)(x61 & UINT8_C(0xff));
x63 = (x61 >> 8);
x64 = (uint8_t)(x63 & UINT8_C(0xff));
x65 = (x63 >> 8);
x66 = (uint8_t)(x65 & UINT8_C(0xff));
x67 = (x65 >> 8);
x68 = (uint8_t)(x67 & UINT8_C(0xff));
x69 = (uint8_t)(x67 >> 8);
x70 = (uint8_t)(x24 & UINT8_C(0xff));
x71 = (x24 >> 8);
x72 = (uint8_t)(x71 & UINT8_C(0xff));
x73 = (x71 >> 8);
x74 = (uint8_t)(x73 & UINT8_C(0xff));
x75 = (x73 >> 8);
x76 = (uint8_t)(x75 & UINT8_C(0xff));
x77 = (x75 >> 8);
x78 = (uint8_t)(x77 & UINT8_C(0xff));
x79 = (x77 >> 8);
x80 = (uint8_t)(x79 & UINT8_C(0xff));
x81 = (uint8_t)(x79 >> 8);
x82 = (uint8_t)(x26 & UINT8_C(0xff));
x83 = (x26 >> 8);
x84 = (uint8_t)(x83 & UINT8_C(0xff));
x85 = (x83 >> 8);
x86 = (uint8_t)(x85 & UINT8_C(0xff));
x87 = (x85 >> 8);
x88 = (uint8_t)(x87 & UINT8_C(0xff));
x89 = (x87 >> 8);
x90 = (uint8_t)(x89 & UINT8_C(0xff));
x91 = (x89 >> 8);
x92 = (uint8_t)(x91 & UINT8_C(0xff));
x93 = (uint8_t)(x91 >> 8);
x94 = (uint8_t)(x28 & UINT8_C(0xff));
x95 = (x28 >> 8);
x96 = (uint8_t)(x95 & UINT8_C(0xff));
x97 = (x95 >> 8);
x98 = (uint8_t)(x97 & UINT8_C(0xff));
x99 = (x97 >> 8);
x100 = (uint8_t)(x99 & UINT8_C(0xff));
x101 = (x99 >> 8);
x102 = (uint8_t)(x101 & UINT8_C(0xff));
x103 = (x101 >> 8);
x104 = (uint8_t)(x103 & UINT8_C(0xff));
x105 = (uint8_t)(x103 >> 8);
x106 = (uint8_t)(x30 & UINT8_C(0xff));
x107 = (x30 >> 8);
x108 = (uint8_t)(x107 & UINT8_C(0xff));
x109 = (x107 >> 8);
x110 = (uint8_t)(x109 & UINT8_C(0xff));
x111 = (x109 >> 8);
x112 = (uint8_t)(x111 & UINT8_C(0xff));
x113 = (x111 >> 8);
x114 = (uint8_t)(x113 & UINT8_C(0xff));
x115 = (x113 >> 8);
x116 = (uint8_t)(x115 & UINT8_C(0xff));
x117 = (uint8_t)(x115 >> 8);
x118 = (uint8_t)(x32 & UINT8_C(0xff));
x119 = (x32 >> 8);
x120 = (uint8_t)(x119 & UINT8_C(0xff));
x121 = (x119 >> 8);
x122 = (uint8_t)(x121 & UINT8_C(0xff));
x123 = (x121 >> 8);
x124 = (uint8_t)(x123 & UINT8_C(0xff));
x125 = (x123 >> 8);
x126 = (uint8_t)(x125 & UINT8_C(0xff));
x127 = (x125 >> 8);
x128 = (uint8_t)(x127 & UINT8_C(0xff));
x129 = (uint8_t)(x127 >> 8);
out1[0] = x34;
out1[1] = x36;
out1[2] = x38;
out1[3] = x40;
out1[4] = x42;
out1[5] = x44;
out1[6] = x45;
out1[7] = x46;
out1[8] = x48;
out1[9] = x50;
out1[10] = x52;
out1[11] = x54;
out1[12] = x56;
out1[13] = x57;
out1[14] = x58;
out1[15] = x60;
out1[16] = x62;
out1[17] = x64;
out1[18] = x66;
out1[19] = x68;
out1[20] = x69;
out1[21] = x70;
out1[22] = x72;
out1[23] = x74;
out1[24] = x76;
out1[25] = x78;
out1[26] = x80;
out1[27] = x81;
out1[28] = x82;
out1[29] = x84;
out1[30] = x86;
out1[31] = x88;
out1[32] = x90;
out1[33] = x92;
out1[34] = x93;
out1[35] = x94;
out1[36] = x96;
out1[37] = x98;
out1[38] = x100;
out1[39] = x102;
out1[40] = x104;
out1[41] = x105;
out1[42] = x106;
out1[43] = x108;
out1[44] = x110;
out1[45] = x112;
out1[46] = x114;
out1[47] = x116;
out1[48] = x117;
out1[49] = x118;
out1[50] = x120;
out1[51] = x122;
out1[52] = x124;
out1[53] = x126;
out1[54] = x128;
out1[55] = x129;
}
/*
* The function fiat_p448_from_bytes deserializes a field element from bytes in little-endian order.
*
* Postconditions:
* eval out1 mod m = bytes_eval arg1 mod m
*
* Input Bounds:
* arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
* Output Bounds:
* out1: [[0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000], [0x0 ~> 0x100000000000000]]
*/
static void fiat_p448_from_bytes(uint64_t out1[8], const uint8_t arg1[56]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint8_t x7;
uint64_t x8;
uint64_t x9;
uint64_t x10;
uint64_t x11;
uint64_t x12;
uint64_t x13;
uint8_t x14;
uint64_t x15;
uint64_t x16;
uint64_t x17;
uint64_t x18;
uint64_t x19;
uint64_t x20;
uint8_t x21;
uint64_t x22;
uint64_t x23;
uint64_t x24;
uint64_t x25;
uint64_t x26;
uint64_t x27;
uint8_t x28;
uint64_t x29;
uint64_t x30;
uint64_t x31;
uint64_t x32;
uint64_t x33;
uint64_t x34;
uint8_t x35;
uint64_t x36;
uint64_t x37;
uint64_t x38;
uint64_t x39;
uint64_t x40;
uint64_t x41;
uint8_t x42;
uint64_t x43;
uint64_t x44;
uint64_t x45;
uint64_t x46;
uint64_t x47;
uint64_t x48;
uint8_t x49;
uint64_t x50;
uint64_t x51;
uint64_t x52;
uint64_t x53;
uint64_t x54;
uint64_t x55;
uint8_t x56;
uint64_t x57;
uint64_t x58;
uint64_t x59;
uint64_t x60;
uint64_t x61;
uint64_t x62;
uint64_t x63;
uint64_t x64;
uint64_t x65;
uint64_t x66;
uint64_t x67;
uint64_t x68;
uint64_t x69;
uint64_t x70;
uint64_t x71;
uint64_t x72;
uint64_t x73;
uint64_t x74;
uint64_t x75;
uint64_t x76;
uint64_t x77;
uint64_t x78;
uint64_t x79;
uint64_t x80;
uint64_t x81;
uint64_t x82;
uint64_t x83;
uint64_t x84;
uint64_t x85;
uint64_t x86;
uint64_t x87;
uint64_t x88;
uint64_t x89;
uint64_t x90;
uint64_t x91;
uint64_t x92;
uint64_t x93;
uint64_t x94;
uint64_t x95;
uint64_t x96;
uint64_t x97;
uint64_t x98;
uint64_t x99;
uint64_t x100;
uint64_t x101;
uint64_t x102;
uint64_t x103;
uint64_t x104;
x1 = ((uint64_t)(arg1[55]) << 48);
x2 = ((uint64_t)(arg1[54]) << 40);
x3 = ((uint64_t)(arg1[53]) << 32);
x4 = ((uint64_t)(arg1[52]) << 24);
x5 = ((uint64_t)(arg1[51]) << 16);
x6 = ((uint64_t)(arg1[50]) << 8);
x7 = (arg1[49]);
x8 = ((uint64_t)(arg1[48]) << 48);
x9 = ((uint64_t)(arg1[47]) << 40);
x10 = ((uint64_t)(arg1[46]) << 32);
x11 = ((uint64_t)(arg1[45]) << 24);
x12 = ((uint64_t)(arg1[44]) << 16);
x13 = ((uint64_t)(arg1[43]) << 8);
x14 = (arg1[42]);
x15 = ((uint64_t)(arg1[41]) << 48);
x16 = ((uint64_t)(arg1[40]) << 40);
x17 = ((uint64_t)(arg1[39]) << 32);
x18 = ((uint64_t)(arg1[38]) << 24);
x19 = ((uint64_t)(arg1[37]) << 16);
x20 = ((uint64_t)(arg1[36]) << 8);
x21 = (arg1[35]);
x22 = ((uint64_t)(arg1[34]) << 48);
x23 = ((uint64_t)(arg1[33]) << 40);
x24 = ((uint64_t)(arg1[32]) << 32);
x25 = ((uint64_t)(arg1[31]) << 24);
x26 = ((uint64_t)(arg1[30]) << 16);
x27 = ((uint64_t)(arg1[29]) << 8);
x28 = (arg1[28]);
x29 = ((uint64_t)(arg1[27]) << 48);
x30 = ((uint64_t)(arg1[26]) << 40);
x31 = ((uint64_t)(arg1[25]) << 32);
x32 = ((uint64_t)(arg1[24]) << 24);
x33 = ((uint64_t)(arg1[23]) << 16);
x34 = ((uint64_t)(arg1[22]) << 8);
x35 = (arg1[21]);
x36 = ((uint64_t)(arg1[20]) << 48);
x37 = ((uint64_t)(arg1[19]) << 40);
x38 = ((uint64_t)(arg1[18]) << 32);
x39 = ((uint64_t)(arg1[17]) << 24);
x40 = ((uint64_t)(arg1[16]) << 16);
x41 = ((uint64_t)(arg1[15]) << 8);
x42 = (arg1[14]);
x43 = ((uint64_t)(arg1[13]) << 48);
x44 = ((uint64_t)(arg1[12]) << 40);
x45 = ((uint64_t)(arg1[11]) << 32);
x46 = ((uint64_t)(arg1[10]) << 24);
x47 = ((uint64_t)(arg1[9]) << 16);
x48 = ((uint64_t)(arg1[8]) << 8);
x49 = (arg1[7]);
x50 = ((uint64_t)(arg1[6]) << 48);
x51 = ((uint64_t)(arg1[5]) << 40);
x52 = ((uint64_t)(arg1[4]) << 32);
x53 = ((uint64_t)(arg1[3]) << 24);
x54 = ((uint64_t)(arg1[2]) << 16);
x55 = ((uint64_t)(arg1[1]) << 8);
x56 = (arg1[0]);
x57 = (x55 + (uint64_t)x56);
x58 = (x54 + x57);
x59 = (x53 + x58);
x60 = (x52 + x59);
x61 = (x51 + x60);
x62 = (x50 + x61);
x63 = (x48 + (uint64_t)x49);
x64 = (x47 + x63);
x65 = (x46 + x64);
x66 = (x45 + x65);
x67 = (x44 + x66);
x68 = (x43 + x67);
x69 = (x41 + (uint64_t)x42);
x70 = (x40 + x69);
x71 = (x39 + x70);
x72 = (x38 + x71);
x73 = (x37 + x72);
x74 = (x36 + x73);
x75 = (x34 + (uint64_t)x35);
x76 = (x33 + x75);
x77 = (x32 + x76);
x78 = (x31 + x77);
x79 = (x30 + x78);
x80 = (x29 + x79);
x81 = (x27 + (uint64_t)x28);
x82 = (x26 + x81);
x83 = (x25 + x82);
x84 = (x24 + x83);
x85 = (x23 + x84);
x86 = (x22 + x85);
x87 = (x20 + (uint64_t)x21);
x88 = (x19 + x87);
x89 = (x18 + x88);
x90 = (x17 + x89);
x91 = (x16 + x90);
x92 = (x15 + x91);
x93 = (x13 + (uint64_t)x14);
x94 = (x12 + x93);
x95 = (x11 + x94);
x96 = (x10 + x95);
x97 = (x9 + x96);
x98 = (x8 + x97);
x99 = (x6 + (uint64_t)x7);
x100 = (x5 + x99);
x101 = (x4 + x100);
x102 = (x3 + x101);
x103 = (x2 + x102);
x104 = (x1 + x103);
out1[0] = x62;
out1[1] = x68;
out1[2] = x74;
out1[3] = x80;
out1[4] = x86;
out1[5] = x92;
out1[6] = x98;
out1[7] = x104;
}
|
the_stack_data/45450089.c | /**
* file: game-of-life.c
*
* Simulate "Conway's Game of Life"
* See https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
* Play with it: https://playgameoflife.com/
*
* Created by hengxin on 10/30/21.
*/
#include <stdio.h>
#include <unistd.h>
#define ROUND 10
#define SIZE 6
int board[SIZE][SIZE] = {
{0},
{0},
{0, 0, 1, 1, 1, 0},
{0, 1, 1, 1, 0, 0},
{0},
{0}};
int main() {
/**
* (extended) old board
*/
int old_board[SIZE + 2][SIZE + 2];
for (int row = 0; row < SIZE + 2; row++) {
for (int col = 0; col < SIZE + 2; col++) {
if (row == 0 || row == SIZE + 1 || col == 0 || col == SIZE + 1) {
old_board[row][col] = 0;
} else {
old_board[row][col] = board[row - 1][col - 1];
}
}
}
/**
* print the current configuration
*/
for (int row = 1; row < SIZE + 1; row++) {
for (int col = 1; col < SIZE + 1; col++) {
printf("%c ", old_board[row][col] ? '*' : ' ');
}
printf("\n");
}
/**
* windows: clrscr() (#include <conio.h>)
*/
printf("\033c");
/*
* new board in the next round
*/
int new_board[SIZE + 2][SIZE + 2];
for (int round = 0; round < ROUND; round++) {
for (int row = 1; row < SIZE + 1; row++) {
for (int col = 1; col < SIZE + 1; col++) {
int neighbours = old_board[row - 1][col - 1]
+ old_board[row - 1][col]
+ old_board[row - 1][col + 1]
+ old_board[row][col - 1]
+ old_board[row][col + 1]
+ old_board[row + 1][col - 1]
+ old_board[row + 1][col]
+ old_board[row + 1][col + 1];
new_board[row][col] =
(old_board[row][col] && (neighbours == 2 || neighbours == 3))
|| (!old_board[row][col] && neighbours == 3);
}
}
/**
* print the new configuration
*/
for (int row = 1; row < SIZE + 1; row++) {
for (int col = 1; col < SIZE + 1; col++) {
printf("%c ", new_board[row][col] ? '*' : ' ');
}
printf("\n");
}
sleep(1);
printf("\033c");
for (int row = 1; row < SIZE + 1; row++) {
for (int col = 1; col < SIZE + 1; col++) {
old_board[row][col] = new_board[row][col];
}
}
}
return 0;
}
|
the_stack_data/24557.c |
long
__mulsi3(unsigned long a, unsigned long b)
{
long res = 0;
while (a)
{
if (a & 1)
{
res += b;
}
b <<= 1;
a >>=1;
}
return res;
} |
the_stack_data/45451301.c | #include <stdio.h>
#define TAM 3
int soma_diagonal_s(int mat[TAM][TAM]){
int i,j, soma=0;
for(i=0;i<TAM;i++){
soma+=mat[i][(TAM-1)-i];
}
return soma;
}
void main(){
int i,j,mat[TAM][TAM];
for(i=0;i<TAM;i++){
for(j=0;j<TAM;j++){
printf("Informe a pos [%d][%d]: ",i,j);
scanf("%d", &mat[i][j]);
}
}
printf("Soma da diagonal secundaria: %d\n", soma_diagonal_s(mat));
} |
the_stack_data/178265772.c | /**
* Hangman Judge, UVa489
*
* 用一个数组记录字符是否存在于答案中且没被猜过,接下来查表即可
* 此外还需要记录尚未被猜出的字符数和剩下多少次机会
* 注意维护表格,一旦出结果就及时跳出
**/
#include<stdio.h>
#include<string.h>
#define maxm 30
#define maxn 1005
#define WIN "You win."
#define LOSE "You lose."
#define CO "You chickened out."
#define IND(c) c-'a'
char ans[maxn], guess[maxn];
int main() {
int mark[maxm];
int round;
while (scanf("%d", &round) == 1 && round != -1) {
memset(mark, 0, sizeof(mark));
scanf("%s%s", ans, guess);
int c1 = 0, c2 = 7;
for (int i = 0; ans[i]; i++) {
if (!mark[IND(ans[i])]) {
mark[IND(ans[i])] = 1;
c1++;
}
}
for (int i = 0; c1 && c2 && guess[i]; i++) {
if (mark[IND(guess[i])]) {
mark[IND(guess[i])] = 0;
c1--;
} else {
c2--;
}
}
printf("Round %d\n", round);
if (!c1) printf("%s\n", WIN);
else if (!c2) printf("%s\n", LOSE);
else printf("%s\n", CO);
}
return 0;
} |
the_stack_data/445171.c | //*****************************************************************************
//
// uart_handler.c
//
// Copyright (c) 2006-2014 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.0.12573 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#include <stdint.h>
#ifdef __WIN32
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#else
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#endif
//*****************************************************************************
//
//! \addtogroup uart_handler UART Handler API
//! This section describes the functions that are responsible for handling the
//! transfer of data over the UART port. These functions use Microsoft Windows
//! APIs to communicate with the UART.
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
//! This variable holds the open handle to the UART in use by this
//! application.
//
//*****************************************************************************
#ifdef __WIN32
static HANDLE g_hComPort;
#else
static int32_t g_i32ComPort = -1;
#endif
//*****************************************************************************
//
//! OpenUART() opens the UART port.
//!
//! \param pcComPort is the text representation of the COM port to be
//! opened. "COM1" is the valid string to use to open COM port 1 on the
//! host.
//! \param ui32BaudRate is the baud rate to configure the UART to use.
//!
//! This function is used to open the host UART with the given baud rate. The
//! rest of the settings are fixed at No Parity, 8 data bits and 1 stop bit.
//!
//! \return The function returns zero to indicated success while any non-zero
//! value indicates a failure.
//
//*****************************************************************************
int32_t
OpenUART(char *pcComPort, uint32_t ui32BaudRate)
{
#ifdef __WIN32
DCB sDCB;
COMMTIMEOUTS sCommTimeouts;
g_hComPort = CreateFile(pcComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL);
if(g_hComPort == INVALID_HANDLE_VALUE)
{
return(-1);
}
if(GetCommState(g_hComPort, &sDCB) == 0)
{
return(-1);
}
sDCB.BaudRate = ui32BaudRate;
sDCB.ByteSize = 8;
sDCB.Parity = NOPARITY;
sDCB.StopBits = ONESTOPBIT;
sDCB.fAbortOnError = TRUE;
sDCB.fOutxCtsFlow = FALSE;
sDCB.fOutxDsrFlow = FALSE;
sDCB.fDtrControl = DTR_CONTROL_ENABLE;
if(SetCommState(g_hComPort, &sDCB) == 0)
{
return(-1);
}
if(GetCommTimeouts(g_hComPort, &sCommTimeouts) == 0)
{
return(-1);
}
sCommTimeouts.ReadIntervalTimeout = 8000;
sCommTimeouts.ReadTotalTimeoutConstant = 8000;
sCommTimeouts.ReadTotalTimeoutMultiplier = 8000;
sCommTimeouts.WriteTotalTimeoutConstant = 8000;
sCommTimeouts.WriteTotalTimeoutMultiplier = 8000;
if(SetCommTimeouts(g_hComPort, &sCommTimeouts) == 0)
{
return(-1);
}
return(0);
#else
struct termios sOptions;
g_i32ComPort = open(pcComPort, O_RDWR | O_NOCTTY | O_NDELAY);
if(g_i32ComPort == -1)
{
return(-1);
}
fcntl(g_i32ComPort, F_SETFL, 0);
tcgetattr(g_i32ComPort, &sOptions);
if(ui32BaudRate == 9600)
{
cfsetispeed(&sOptions, B9600);
cfsetospeed(&sOptions, B9600);
}
else if(ui32BaudRate == 19200)
{
cfsetispeed(&sOptions, B19200);
cfsetospeed(&sOptions, B19200);
}
else if(ui32BaudRate == 38400)
{
cfsetispeed(&sOptions, B38400);
cfsetospeed(&sOptions, B38400);
}
else if(ui32BaudRate == 57600)
{
cfsetispeed(&sOptions, B57600);
cfsetospeed(&sOptions, B57600);
}
else if(ui32BaudRate == 115200)
{
cfsetispeed(&sOptions, B115200);
cfsetospeed(&sOptions, B115200);
}
else
{
cfsetispeed(&sOptions, B230400);
cfsetospeed(&sOptions, B230400);
}
sOptions.c_cflag |= (CLOCAL | CREAD);
sOptions.c_cflag &= ~(CSIZE);
sOptions.c_cflag |= CS8;
sOptions.c_cflag &= ~(PARENB);
sOptions.c_cflag &= ~(CSTOPB);
sOptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
sOptions.c_oflag &= ~(OPOST);
tcsetattr(g_i32ComPort, TCSANOW, &sOptions);
return(0);
#endif
}
//*****************************************************************************
//
//! CloseUART() closes the UART port.
//!
//! This function closes the UART port that was opened by a call to OpenUART().
//!
//! \returns This function returns zero to indicate success while any non-zero
//! value indicates a failure.
//
//*****************************************************************************
int32_t
CloseUART(void)
{
#ifdef __WIN32
return(CloseHandle(g_hComPort));
#else
if(g_i32ComPort != -1)
{
close(g_i32ComPort);
}
return(0);
#endif
}
//*****************************************************************************
//
//! UARTSendData() sends data over a UART port.
//!
//! \param pui8Data
//! The buffer to write out to the UART port.
//! \param ui8Size
//! The number of bytes provided in pui8Data buffer that should be written
//! out to the port.
//!
//! This function sends ui8Size bytes of data from the buffer pointed to by
//! pui8Data via the UART port that was opened by a call to OpenUART().
//!
//! \return This function returns zero to indicate success while any non-zero
//! value indicates a failure.
//
//*****************************************************************************
int32_t
UARTSendData(uint8_t const *pui8Data, uint8_t ui8Size)
{
#ifdef __WIN32
unsigned long ulNumBytes;
//
// Send the Ack back to the device.
//
if(WriteFile(g_hComPort, pui8Data, ui8Size, &ulNumBytes, NULL) == 0)
{
return(-1);
}
if(ulNumBytes != ui8Size)
{
return(-1);
}
return(0);
#else
if(write(g_i32ComPort, pui8Data, ui8Size) != ui8Size)
{
return(-1);
}
return(0);
#endif
}
//*****************************************************************************
//
//! UARTReceiveData() receives data over a UART port.
//!
//! \param pui8Data is the buffer to read data into from the UART port.
//! \param ui8Size is the number of bytes provided in pui8Data buffer that should
//! be written with data from the UART port.
//!
//! This function reads back ui8Size bytes of data from the UART port, that was
//! opened by a call to OpenUART(), into the buffer that is pointed to by
//! pui8Data.
//!
//! \return This function returns zero to indicate success while any non-zero
//! value indicates a failure.
//
//*****************************************************************************
int32_t
UARTReceiveData(uint8_t *pui8Data, uint8_t ui8Size)
{
#ifdef __WIN32
unsigned long ulNumBytes;
if(ReadFile(g_hComPort, pui8Data, ui8Size, &ulNumBytes, NULL) == 0)
{
return(-1);
}
if(ulNumBytes != ui8Size)
{
return(-1);
}
return(0);
#else
if(read(g_i32ComPort, pui8Data, ui8Size) != ui8Size)
{
return(-1);
}
return(0);
#endif
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
|
the_stack_data/165766968.c | /**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
for (int i = digitsSize-1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
*returnSize = digitsSize;
return digits;
} else {
digits[i] = 0;
}
}
int* newdigit = (int*)malloc((digitsSize+1) * sizeof(int));
newdigit[0] = 1;
for (int i = 1; i < (digitsSize+1); i++) {
newdigit[i] = digits[i-1];
}
*returnSize = digitsSize+1;
return newdigit;
} |
the_stack_data/168891945.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define SIZE 50
// implements a set and checks that the insert and remove function maintain the structure
int insert( int set [] , int size , int value ) {
set[ size ] = value;
return size + 1;
}
int elem_exists( int set [ ] , int size , int value ) {
int i;
for ( i = 0 ; i < size ; i++ ) {
if ( set[ i ] == value ) return 1;
}
return 0;
}
int main( ) {
int n = 0;
int set[ SIZE ];
// this is trivial
int x;
int y;
for ( x = 0 ; x < n ; x++ ) {
for ( y = x + 1 ; y < n ; y++ ) {
__VERIFIER_assert( set[ x ] != set[ y ] );
}
}
// we have an array of values to insert
int values[ SIZE ];
// insert them in the array -- note that nothing ensures that values is not containing duplicates!
int v;
for ( v = 0 ; v < SIZE ; v++ ) {
// check if the element exists, if not insert it.
if ( !elem_exists( set , n , values[ v ] ) ) {
// parametes are passed by reference
n = insert( set , n , values[ v ] );
}
}
// this is not trivial!
for ( x = 0 ; x < n ; x++ ) {
for ( y = x + 1 ; y < n ; y++ ) {
__VERIFIER_assert( set[ x ] != set[ y ] );
}
}
return 0;
}
|
the_stack_data/90765666.c | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
/* Arrays of Character Strings */
// Not a good idea to take advantage of this property
return 0;
} |
the_stack_data/162644378.c | #include <wchar.h>
size_t wcslen(const wchar_t *s)
{
const wchar_t *a;
for (a=s; *s; s++);
return s-a;
}
|
the_stack_data/48575565.c | /* Copyright (c) 1994 Burra Gopal, Udi Manber. All Rights Reserved. */
/* bgopal: used if search in compressed text files is not being performed */
/* Always say could not be compressed */
int
quick_tcompress()
{
return 0;
}
/* Always say could not be uncompressed */
int
quick_tuncompress()
{
return 0;
}
/* Always return uncompressible */
int
tuncompressible()
{
return 0;
}
/* Always return uncompressible */
int
tuncompressible_filename()
{
return 0;
}
/* Always return uncompressible */
int
tuncompressible_file()
{
return 0;
}
/* Always return uncompressible */
int
tuncompressible_fp()
{
return 0;
}
int
exists_tcompressed_word()
{
return -1;
}
unsigned char *
forward_tcompressed_word(begin, end, delim, len, outtail, flags)
unsigned char *begin, *end, *delim;
int len, outtail, flags;
{
return begin;
}
unsigned char *
backward_tcompressed_word(end, begin, delim, len, outtail, flags)
unsigned char *begin, *end, *delim;
int len, outtail, flags;
{
return end;
}
int
tcompress_file()
{
return 0;
}
int
tuncompress_file()
{
return 0;
}
int
initialize_tcompress()
{
return 0;
}
int
initialize_tuncompress()
{
return 0;
}
int
initialize_common()
{
return 0;
}
int
uninitialize_tuncompress()
{
return 0;
}
int
compute_dictionary()
{
return 0;
}
int
uninitialize_common()
{
return 0;
}
int
uninitialize_tcompress()
{
return 0;
}
int usemalloc = 0;
int
set_usemalloc()
{
return 0;
}
int
unset_usemalloc()
{
return 0;
}
|
the_stack_data/122378.c | /*
* mbed Microcontroller Library
* Copyright (c) 2017-2018 Future Electronics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if DEVICE_SERIAL
#include <string.h>
#include "cmsis.h"
#include "mbed_assert.h"
#include "mbed_error.h"
#include "PeripheralPins.h"
#include "pinmap.h"
#include "serial_api.h"
#include "psoc6_utils.h"
#include "cy_sysclk.h"
#include "cy_gpio.h"
#include "cy_scb_uart.h"
#include "cy_sysint.h"
#define UART_OVERSAMPLE 12
#define UART_DEFAULT_BAUDRATE 115200
#define NUM_SERIAL_PORTS 8
#define SERIAL_DEFAULT_IRQ_PRIORITY 3
typedef struct serial_s serial_obj_t;
#if DEVICE_SERIAL_ASYNCH
#define OBJ_P(in) (&(in->serial))
#else
#define OBJ_P(in) (in)
#endif
/*
* NOTE: Cypress PDL high level API implementation of USART doe not
* align well with Mbed interface for interrupt-driven serial I/O.
* For this reason only low level PDL API is used here.
*/
static const cy_stc_scb_uart_config_t default_uart_config = {
.uartMode = CY_SCB_UART_STANDARD,
.enableMutliProcessorMode = false,
.smartCardRetryOnNack = false,
.irdaInvertRx = false,
.irdaEnableLowPowerReceiver = false,
.oversample = UART_OVERSAMPLE,
.enableMsbFirst = false,
.dataWidth = 8UL,
.parity = CY_SCB_UART_PARITY_NONE,
.stopBits = CY_SCB_UART_STOP_BITS_1,
.enableInputFilter = false,
.breakWidth = 11UL,
.dropOnFrameError = false,
.dropOnParityError = false,
.receiverAddress = 0x0UL,
.receiverAddressMask = 0x0UL,
.acceptAddrInFifo = false,
.enableCts = false,
.ctsPolarity = CY_SCB_UART_ACTIVE_LOW,
.rtsRxFifoLevel = 20UL,
.rtsPolarity = CY_SCB_UART_ACTIVE_LOW,
.rxFifoTriggerLevel = 0UL,
.rxFifoIntEnableMask = 0x0UL,
.txFifoTriggerLevel = 0UL,
.txFifoIntEnableMask = 0x0UL
};
int stdio_uart_inited = false;
serial_t stdio_uart;
typedef struct irq_info_s {
serial_obj_t *serial_obj;
uart_irq_handler handler;
uint32_t id_arg;
IRQn_Type irqn;
#if defined (TARGET_MCU_PSOC6_M0)
cy_en_intr_t cm0p_irq_src;
#endif
} irq_info_t;
static irq_info_t irq_info[NUM_SERIAL_PORTS] = {
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn},
{NULL, NULL, 0, unconnected_IRQn}
};
static void serial_irq_dispatcher(uint32_t serial_id)
{
MBED_ASSERT(serial_id < NUM_SERIAL_PORTS);
irq_info_t *info = &irq_info[serial_id];
serial_obj_t *obj = info->serial_obj;
MBED_ASSERT(obj);
#if DEVICE_SERIAL_ASYNCH
if (obj->async_handler) {
obj->async_handler();
return;
}
#endif
if (Cy_SCB_GetRxInterruptStatusMasked(obj->base) & CY_SCB_RX_INTR_NOT_EMPTY) {
info->handler(info->id_arg, RxIrq);
Cy_SCB_ClearRxInterrupt(obj->base, CY_SCB_RX_INTR_NOT_EMPTY);
}
if (Cy_SCB_GetTxInterruptStatusMasked(obj->base) & (CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE)) {
info->handler(info->id_arg, TxIrq);
}
}
static void serial_irq_dispatcher_uart0(void)
{
serial_irq_dispatcher(0);
}
static void serial_irq_dispatcher_uart1(void)
{
serial_irq_dispatcher(1);
}
static void serial_irq_dispatcher_uart2(void)
{
serial_irq_dispatcher(2);
}
static void serial_irq_dispatcher_uart3(void)
{
serial_irq_dispatcher(3);
}
static void serial_irq_dispatcher_uart4(void)
{
serial_irq_dispatcher(4);
}
static void serial_irq_dispatcher_uart5(void)
{
serial_irq_dispatcher(5);
}
void serial_irq_dispatcher_uart6(void)
{
serial_irq_dispatcher(6);
}
static void serial_irq_dispatcher_uart7(void)
{
serial_irq_dispatcher(7);
}
static void (*irq_dispatcher_table[])(void) = {
serial_irq_dispatcher_uart0,
serial_irq_dispatcher_uart1,
serial_irq_dispatcher_uart2,
serial_irq_dispatcher_uart3,
serial_irq_dispatcher_uart4,
serial_irq_dispatcher_uart5,
serial_irq_dispatcher_uart6,
serial_irq_dispatcher_uart7
};
static IRQn_Type serial_irq_allocate_channel(serial_obj_t *obj)
{
#if defined (TARGET_MCU_PSOC6_M0)
irq_info[obj->serial_id].cm0p_irq_src = scb_0_interrupt_IRQn + obj->serial_id;
return cy_m0_nvic_allocate_channel(CY_SERIAL_IRQN_ID + obj->serial_id);
#else
return (IRQn_Type)(scb_0_interrupt_IRQn + obj->serial_id);
#endif // M0
}
static void serial_irq_release_channel(IRQn_Type channel, uint32_t serial_id)
{
#if defined (TARGET_MCU_PSOC6_M0)
cy_m0_nvic_release_channel(channel, CY_SERIAL_IRQN_ID + serial_id);
#endif //M0
}
static int serial_irq_setup_channel(serial_obj_t *obj)
{
cy_stc_sysint_t irq_config;
irq_info_t *info = &irq_info[obj->serial_id];
if (info->irqn == unconnected_IRQn) {
IRQn_Type irqn = serial_irq_allocate_channel(obj);
if (irqn < 0) {
return (-1);
}
// Configure NVIC
irq_config.intrPriority = SERIAL_DEFAULT_IRQ_PRIORITY;
irq_config.intrSrc = irqn;
#if defined (TARGET_MCU_PSOC6_M0)
irq_config.cm0pSrc = info->cm0p_irq_src;
#endif
if (Cy_SysInt_Init(&irq_config, irq_dispatcher_table[obj->serial_id]) != CY_SYSINT_SUCCESS) {
return(-1);
}
info->irqn = irqn;
info->serial_obj = obj;
NVIC_EnableIRQ(irqn);
}
return 0;
}
/*
* Calculates fractional divider value.
*/
static uint32_t divider_value(uint32_t frequency, uint32_t frac_bits)
{
/* UARTs use peripheral clock */
return ((CY_CLK_PERICLK_FREQ_HZ * (1 << frac_bits)) + (frequency / 2)) / frequency;
}
static cy_en_sysclk_status_t serial_init_clock(serial_obj_t *obj, uint32_t baudrate)
{
cy_en_sysclk_status_t status = CY_SYSCLK_BAD_PARAM;
if (obj->div_num == CY_INVALID_DIVIDER) {
uint32_t divider_num = cy_clk_allocate_divider(CY_SYSCLK_DIV_16_5_BIT);
if (divider_num < PERI_DIV_16_5_NR) {
/* Assign fractional divider. */
status = Cy_SysClk_PeriphAssignDivider(obj->clock, CY_SYSCLK_DIV_16_5_BIT, divider_num);
if (status == CY_SYSCLK_SUCCESS) {
obj->div_type = CY_SYSCLK_DIV_16_5_BIT;
obj->div_num = divider_num;
}
} else {
// Try 16-bit divider.
divider_num = cy_clk_allocate_divider(CY_SYSCLK_DIV_16_BIT);
if (divider_num < PERI_DIV_16_NR) {
/* Assign 16-bit divider. */
status = Cy_SysClk_PeriphAssignDivider(obj->clock, CY_SYSCLK_DIV_16_BIT, divider_num);
if (status == CY_SYSCLK_SUCCESS) {
obj->div_type = CY_SYSCLK_DIV_16_BIT;
obj->div_num = divider_num;
}
} else {
error("Serial: cannot assign clock divider.");
}
}
} else {
status = CY_SYSCLK_SUCCESS;
}
if (status == CY_SYSCLK_SUCCESS) {
/* Set baud rate */
if (obj->div_type == CY_SYSCLK_DIV_16_5_BIT) {
Cy_SysClk_PeriphDisableDivider(CY_SYSCLK_DIV_16_5_BIT, obj->div_num);
uint32_t divider = divider_value(baudrate * UART_OVERSAMPLE, 5);
status = Cy_SysClk_PeriphSetFracDivider(CY_SYSCLK_DIV_16_5_BIT,
obj->div_num,
(divider >> 5) - 1, // integral part
divider & 0x1F); // fractional part
Cy_SysClk_PeriphEnableDivider(CY_SYSCLK_DIV_16_5_BIT, obj->div_num);
} else if (obj->div_type == CY_SYSCLK_DIV_16_BIT) {
Cy_SysClk_PeriphDisableDivider(CY_SYSCLK_DIV_16_BIT, obj->div_num);
status = Cy_SysClk_PeriphSetDivider(CY_SYSCLK_DIV_16_BIT,
obj->div_num,
divider_value(baudrate * UART_OVERSAMPLE, 0));
Cy_SysClk_PeriphEnableDivider(CY_SYSCLK_DIV_16_BIT, obj->div_num);
}
}
return status;
}
/*
* Initializes i/o pins for UART tx/rx.
*/
static void serial_init_pins(serial_obj_t *obj)
{
int tx_function = pinmap_function(obj->pin_tx, PinMap_UART_TX);
int rx_function = pinmap_function(obj->pin_rx, PinMap_UART_RX);
if (cy_reserve_io_pin(obj->pin_tx) || cy_reserve_io_pin(obj->pin_rx)) {
error("Serial TX/RX pin reservation conflict.");
}
pin_function(obj->pin_tx, tx_function);
pin_function(obj->pin_rx, rx_function);
}
/*
* Initializes i/o pins for UART flow control.
*/
static void serial_init_flow_pins(serial_obj_t *obj)
{
if (obj->pin_rts != NC) {
int rts_function = pinmap_function(obj->pin_rts, PinMap_UART_RTS);
if (cy_reserve_io_pin(obj->pin_rts)) {
error("Serial RTS pin reservation conflict.");
}
pin_function(obj->pin_rts, rts_function);
}
if (obj->pin_cts != NC) {
int cts_function = pinmap_function(obj->pin_cts, PinMap_UART_CTS);
if (cy_reserve_io_pin(obj->pin_cts)) {
error("Serial CTS pin reservation conflict.");
}
pin_function(obj->pin_cts, cts_function);
}
}
/*
* Initializes and enables UART/SCB.
*/
static void serial_init_peripheral(serial_obj_t *obj)
{
cy_stc_scb_uart_config_t uart_config = default_uart_config;
uart_config.dataWidth = obj->data_width;
uart_config.parity = obj->parity;
uart_config.stopBits = obj->stop_bits;
uart_config.enableCts = (obj->pin_cts != NC);
Cy_SCB_UART_Init(obj->base, &uart_config, NULL);
Cy_SCB_UART_Enable(obj->base);
}
#if DEVICE_SLEEP && DEVICE_LPTICKER && SERIAL_PM_CALLBACK_ENABLED
static cy_en_syspm_status_t serial_pm_callback(cy_stc_syspm_callback_params_t *params)
{
serial_obj_t *obj = (serial_obj_t *)params->context;
cy_en_syspm_status_t status = CY_SYSPM_FAIL;
switch (params->mode) {
case CY_SYSPM_CHECK_READY:
/* If all data elements are transmitted from the TX FIFO and
* shifter and the RX FIFO is empty: the UART is ready to enter
* Deep Sleep mode.
*/
if (Cy_SCB_UART_IsTxComplete(obj->base)) {
if (0UL == Cy_SCB_UART_GetNumInRxFifo(obj->base)) {
/* Disable the UART. The transmitter stops driving the
* lines and the receiver stops receiving data until
* the UART is enabled.
* This happens when the device failed to enter Deep
* Sleep or it is awaken from Deep Sleep mode.
*/
Cy_SCB_UART_Disable(obj->base, NULL);
status = CY_SYSPM_SUCCESS;
}
}
break;
case CY_SYSPM_CHECK_FAIL:
/* Enable the UART to operate */
Cy_SCB_UART_Enable(obj->base);
status = CY_SYSPM_SUCCESS;
break;
case CY_SYSPM_BEFORE_TRANSITION:
status = CY_SYSPM_SUCCESS;
break;
case CY_SYSPM_AFTER_TRANSITION:
/* Enable the UART to operate */
Cy_SCB_UART_Enable(obj->base);
status = CY_SYSPM_SUCCESS;
break;
default:
break;
}
return status;
}
#endif // DEVICE_SLEEP && DEVICE_LPTICKER
void serial_init(serial_t *obj_in, PinName tx, PinName rx)
{
serial_obj_t *obj = OBJ_P(obj_in);
bool is_stdio = (tx == CY_STDIO_UART_TX) || (rx == CY_STDIO_UART_RX);
if (is_stdio && stdio_uart_inited) {
memcpy(obj_in, &stdio_uart, sizeof(serial_t));
return;
}
{
uint32_t uart = pinmap_peripheral(tx, PinMap_UART_TX);
uart = pinmap_merge(uart, pinmap_peripheral(rx, PinMap_UART_RX));
if (uart != (uint32_t)NC) {
obj->base = (CySCB_Type*)uart;
obj->serial_id = ((UARTName)uart - UART_0) / (UART_1 - UART_0);
obj->pin_tx = tx;
obj->pin_rx = rx;
obj->clock = CY_PIN_CLOCK(pinmap_function(tx, PinMap_UART_TX));
obj->div_num = CY_INVALID_DIVIDER;
obj->data_width = 8;
obj->stop_bits = CY_SCB_UART_STOP_BITS_1;
obj->parity = CY_SCB_UART_PARITY_NONE;
obj->pin_rts = NC;
obj->pin_cts = NC;
serial_init_clock(obj, UART_DEFAULT_BAUDRATE);
serial_init_peripheral(obj);
//Cy_GPIO_Write(Cy_GPIO_PortToAddr(CY_PORT(P13_6)), CY_PIN(P13_6), 1);
serial_init_pins(obj);
//Cy_GPIO_Write(Cy_GPIO_PortToAddr(CY_PORT(P13_6)), CY_PIN(P13_6), 0);
#if DEVICE_SLEEP && DEVICE_LPTICKER && SERIAL_PM_CALLBACK_ENABLED
obj->pm_callback_handler.callback = serial_pm_callback;
obj->pm_callback_handler.type = CY_SYSPM_DEEPSLEEP;
obj->pm_callback_handler.skipMode = 0;
obj->pm_callback_handler.callbackParams = &obj->pm_callback_params;
obj->pm_callback_params.base = obj->base;
obj->pm_callback_params.context = obj;
if (!Cy_SysPm_RegisterCallback(&obj->pm_callback_handler)) {
error("PM callback registration failed!");
}
#endif // DEVICE_SLEEP && DEVICE_LPTICKER
if (is_stdio) {
memcpy(&stdio_uart, obj_in, sizeof(serial_t));
stdio_uart_inited = true;
}
} else {
error("Serial pinout mismatch. Requested pins Rx and Tx can't be used for the same Serial communication.");
}
}
}
void serial_baud(serial_t *obj_in, int baudrate)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
serial_init_clock(obj, baudrate);
Cy_SCB_UART_Enable(obj->base);
}
void serial_format(serial_t *obj_in, int data_bits, SerialParity parity, int stop_bits)
{
serial_obj_t *obj = OBJ_P(obj_in);
if ((data_bits >= 5) && (data_bits <= 9)) {
obj->data_width = data_bits;
}
switch (parity) {
case ParityNone:
obj->parity = CY_SCB_UART_PARITY_NONE;
break;
case ParityOdd:
obj->parity = CY_SCB_UART_PARITY_ODD;
break;
case ParityEven:
obj->parity = CY_SCB_UART_PARITY_EVEN;
break;
case ParityForced1:
case ParityForced0:
MBED_ASSERT("Serial parity mode not supported!");
break;
}
switch (stop_bits) {
case 1:
obj->stop_bits = CY_SCB_UART_STOP_BITS_1;
break;
case 2:
obj->stop_bits = CY_SCB_UART_STOP_BITS_2;
break;
case 3:
obj->stop_bits = CY_SCB_UART_STOP_BITS_3;
break;
case 4:
obj->stop_bits = CY_SCB_UART_STOP_BITS_4;
break;
}
Cy_SCB_UART_Disable(obj->base, NULL);
serial_init_peripheral(obj);
}
void serial_putc(serial_t *obj_in, int c)
{
serial_obj_t *obj = OBJ_P(obj_in);
while (!serial_writable(obj_in)) {
// empty
}
Cy_SCB_UART_Put(obj->base, c);
}
int serial_getc(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
while (!serial_readable(obj_in)) {
// empty
}
return Cy_SCB_UART_Get(obj->base);
}
int serial_readable(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
return Cy_SCB_GetNumInRxFifo(obj->base) != 0;
}
int serial_writable(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
return Cy_SCB_GetNumInTxFifo(obj->base) != Cy_SCB_GetFifoSize(obj->base);
}
void serial_clear(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
Cy_SCB_ClearTxFifo(obj->base);
Cy_SCB_ClearRxFifo(obj->base);
serial_init_peripheral(obj);
}
void serial_break_set(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
/* Cypress SCB does not support transmitting break directly.
* We emulate functionality by switching TX pin to GPIO mode.
*/
GPIO_PRT_Type *port_tx = Cy_GPIO_PortToAddr(CY_PORT(obj->pin_tx));
Cy_GPIO_Pin_FastInit(port_tx, CY_PIN(obj->pin_tx), CY_GPIO_DM_STRONG_IN_OFF, 0, HSIOM_SEL_GPIO);
Cy_GPIO_Write(port_tx, CY_PIN(obj->pin_tx), 0);
}
void serial_break_clear(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
/* Connect TX pin back to SCB, see a comment in serial_break_set() above */
GPIO_PRT_Type *port_tx = Cy_GPIO_PortToAddr(CY_PORT(obj->pin_tx));
int tx_function = pinmap_function(obj->pin_tx, PinMap_UART_TX);
Cy_GPIO_Pin_FastInit(port_tx, CY_PIN(obj->pin_tx), CY_GPIO_DM_STRONG_IN_OFF, 0, CY_PIN_HSIOM(tx_function));
}
void serial_set_flow_control(serial_t *obj_in, FlowControl type, PinName rxflow, PinName txflow)
{
serial_obj_t *obj = OBJ_P(obj_in);
Cy_SCB_UART_Disable(obj->base, NULL);
switch (type) {
case FlowControlNone:
obj->pin_rts = NC;
obj->pin_cts = NC;
break;
case FlowControlRTS:
obj->pin_rts = rxflow;
obj->pin_cts = NC;
break;
case FlowControlCTS:
obj->pin_rts = NC;
obj->pin_cts = txflow;
break;
case FlowControlRTSCTS:
obj->pin_rts = rxflow;
obj->pin_cts = txflow;
break;
}
serial_init_peripheral(obj);
serial_init_flow_pins(obj);
}
const PinMap *serial_tx_pinmap()
{
return PinMap_UART_TX;
}
const PinMap *serial_rx_pinmap()
{
return PinMap_UART_RX;
}
const PinMap *serial_cts_pinmap()
{
return PinMap_UART_CTS;
}
const PinMap *serial_rts_pinmap()
{
return PinMap_UART_RTS;
}
#if DEVICE_SERIAL_ASYNCH
void serial_irq_handler(serial_t *obj_in, uart_irq_handler handler, uint32_t id)
{
serial_obj_t *obj = OBJ_P(obj_in);
irq_info_t *info = &irq_info[obj->serial_id];
if (info->irqn != unconnected_IRQn) {
NVIC_DisableIRQ(info->irqn);
}
info->handler = handler;
info->id_arg = id;
serial_irq_setup_channel(obj);
}
void serial_irq_set(serial_t *obj_in, SerialIrq irq, uint32_t enable)
{
serial_obj_t *obj = OBJ_P(obj_in);
switch (irq) {
case RxIrq:
if (enable) {
Cy_SCB_SetRxInterruptMask(obj->base, CY_SCB_RX_INTR_NOT_EMPTY);
} else {
Cy_SCB_SetRxInterruptMask(obj->base, 0);
}
break;
case TxIrq:
if (enable) {
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE);
} else {
Cy_SCB_SetTxInterruptMask(obj->base, 0);
}
break;
}
}
static void serial_finish_tx_asynch(serial_obj_t *obj)
{
Cy_SCB_SetTxInterruptMask(obj->base, 0);
obj->tx_pending = false;
}
static void serial_finish_rx_asynch(serial_obj_t *obj)
{
Cy_SCB_SetRxInterruptMask(obj->base, 0);
obj->rx_pending = false;
}
int serial_tx_asynch(serial_t *obj_in, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint)
{
serial_obj_t *obj = OBJ_P(obj_in);
const uint8_t *p_buf = tx;
(void)tx_width; // Obsolete argument
(void)hint; // At the moment we do not support DAM transfers, so this parameter gets ignored.
if (obj->tx_pending) {
return 0;
}
obj->tx_events = event;
obj->async_handler = (cy_israddress)handler;
if (serial_irq_setup_channel(obj) < 0) {
return 0;
}
// Write as much as possible into the FIFO first.
while ((tx_length > 0) && Cy_SCB_UART_Put(obj->base, *p_buf)) {
++p_buf;
--tx_length;
}
if (tx_length > 0) {
obj_in->tx_buff.buffer = (void *)p_buf;
obj_in->tx_buff.length = tx_length;
obj_in->tx_buff.pos = 0;
obj->tx_pending = true;
// Enable interrupts to complete transmission.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_TX_INTR_LEVEL | CY_SCB_UART_TX_DONE);
} else {
// Enable interrupt to signal completing of the transmission.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_UART_TX_DONE);
}
return tx_length;
}
void serial_rx_asynch(serial_t *obj_in, void *rx, size_t rx_length, uint8_t rx_width, uint32_t handler, uint32_t event, uint8_t char_match, DMAUsage hint)
{
serial_obj_t *obj = OBJ_P(obj_in);
(void)rx_width; // Obsolete argument
(void)hint; // At the moment we do not support DAM transfers, so this parameter gets ignored.
if (obj->rx_pending || (rx_length == 0)) {
return;
}
obj_in->char_match = char_match;
obj_in->char_found = false;
obj->rx_events = event;
obj_in->rx_buff.buffer = rx;
obj_in->rx_buff.length = rx_length;
obj_in->rx_buff.pos = 0;
obj->async_handler = (cy_israddress)handler;
if (serial_irq_setup_channel(obj) < 0) {
return;
}
obj->rx_pending = true;
// Enable interrupts to start receiving.
Cy_SCB_SetRxInterruptMask(obj->base, CY_SCB_UART_RX_INTR_MASK & ~CY_SCB_RX_INTR_UART_BREAK_DETECT);
}
uint8_t serial_tx_active(serial_t *obj)
{
return obj->serial.tx_pending;
}
uint8_t serial_rx_active(serial_t *obj)
{
return obj->serial.rx_pending;
}
int serial_irq_handler_asynch(serial_t *obj_in)
{
uint32_t cur_events = 0;
uint32_t tx_status;
uint32_t rx_status;
serial_obj_t *obj = OBJ_P(obj_in);
rx_status = Cy_SCB_GetRxInterruptStatusMasked(obj->base);
tx_status = Cy_SCB_GetTxInterruptStatusMasked(obj->base);
if (tx_status & CY_SCB_TX_INTR_LEVEL) {
// FIFO has space available for more TX
uint8_t *ptr = obj_in->tx_buff.buffer;
ptr += obj_in->tx_buff.pos;
while ((obj_in->tx_buff.pos < obj_in->tx_buff.length) &&
Cy_SCB_UART_Put(obj->base, *ptr)) {
++ptr;
++(obj_in->tx_buff.pos);
}
if (obj_in->tx_buff.pos == obj_in->tx_buff.length) {
// No more bytes to follow; check to see if we need to signal completion.
if (obj->tx_events & SERIAL_EVENT_TX_COMPLETE) {
// Disable FIFO interrupt as there are no more bytes to follow.
Cy_SCB_SetTxInterruptMask(obj->base, CY_SCB_UART_TX_DONE);
} else {
// Nothing more to do, mark end of transmission.
serial_finish_tx_asynch(obj);
}
}
}
if (tx_status & CY_SCB_TX_INTR_UART_DONE) {
// Mark end of the transmission.
serial_finish_tx_asynch(obj);
cur_events |= SERIAL_EVENT_TX_COMPLETE & obj->tx_events;
}
Cy_SCB_ClearTxInterrupt(obj->base, tx_status);
if (rx_status & CY_SCB_RX_INTR_OVERFLOW) {
cur_events |= SERIAL_EVENT_RX_OVERRUN_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_UART_FRAME_ERROR) {
cur_events |= SERIAL_EVENT_RX_FRAMING_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_UART_PARITY_ERROR) {
cur_events |= SERIAL_EVENT_RX_PARITY_ERROR & obj->rx_events;
}
if (rx_status & CY_SCB_RX_INTR_LEVEL) {
uint8_t *ptr = obj_in->rx_buff.buffer;
ptr += obj_in->rx_buff.pos;
uint32_t fifo_cnt = Cy_SCB_UART_GetNumInRxFifo(obj->base);
while ((obj_in->rx_buff.pos < obj_in->rx_buff.length) && fifo_cnt) {
uint32_t c = Cy_SCB_UART_Get(obj->base);
*ptr++ = (uint8_t)c;
++(obj_in->rx_buff.pos);
--fifo_cnt;
// Check for character match condition.
if (obj_in->char_match != SERIAL_RESERVED_CHAR_MATCH) {
if (c == obj_in->char_match) {
obj_in->char_found = true;
cur_events |= SERIAL_EVENT_RX_CHARACTER_MATCH & obj->rx_events;
// Clamp RX.
obj_in->rx_buff.length = obj_in->rx_buff.pos;
break;
}
}
}
if (obj_in->rx_buff.pos == obj_in->rx_buff.length) {
cur_events |= SERIAL_EVENT_RX_COMPLETE & obj->rx_events;
}
}
// Any event should end operation.
if (cur_events & SERIAL_EVENT_RX_ALL) {
serial_finish_rx_asynch(obj);
}
Cy_SCB_ClearRxInterrupt(obj->base, rx_status);
return cur_events;
}
void serial_tx_abort_asynch(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
serial_finish_tx_asynch(obj);
Cy_SCB_UART_ClearTxFifo(obj->base);
}
void serial_rx_abort_asynch(serial_t *obj_in)
{
serial_obj_t *obj = OBJ_P(obj_in);
serial_finish_rx_asynch(obj);
Cy_SCB_UART_ClearRxFifo(obj->base);
}
#endif // DEVICE_SERIAL_ASYNCH
#endif // DEVICE_SERIAL
|
the_stack_data/64845.c | // RUN: %clang_builtins %s %librt -o %t && %run %t
// REQUIRES: librt_has_atomic
//===-- atomic_test.c - Test support functions for atomic operations ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file performs some simple testing of the support functions for the
// atomic builtins. All tests are single-threaded, so this is only a sanity
// check.
//
//===----------------------------------------------------------------------===//
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// We directly test the library atomic functions, not using the C builtins. This
// should avoid confounding factors, ensuring that we actually test the
// functions themselves, regardless of how the builtins are lowered. We need to
// use asm labels because we can't redeclare the builtins.
void __atomic_load_c(int size, const void *src, void *dest,
int model) asm("__atomic_load");
uint8_t __atomic_load_1(uint8_t *src, int model);
uint16_t __atomic_load_2(uint16_t *src, int model);
uint32_t __atomic_load_4(uint32_t *src, int model);
uint64_t __atomic_load_8(uint64_t *src, int model);
void __atomic_store_c(int size, void *dest, const void *src,
int model) asm("__atomic_store");
void __atomic_store_1(uint8_t *dest, uint8_t val, int model);
void __atomic_store_2(uint16_t *dest, uint16_t val, int model);
void __atomic_store_4(uint32_t *dest, uint32_t val, int model);
void __atomic_store_8(uint64_t *dest, uint64_t val, int model);
void __atomic_exchange_c(int size, void *ptr, const void *val, void *old,
int model) asm("__atomic_exchange");
uint8_t __atomic_exchange_1(uint8_t *dest, uint8_t val, int model);
uint16_t __atomic_exchange_2(uint16_t *dest, uint16_t val, int model);
uint32_t __atomic_exchange_4(uint32_t *dest, uint32_t val, int model);
uint64_t __atomic_exchange_8(uint64_t *dest, uint64_t val, int model);
int __atomic_compare_exchange_c(int size, void *ptr, void *expected,
const void *desired, int success, int failure)
asm("__atomic_compare_exchange");
bool __atomic_compare_exchange_1(uint8_t *ptr, uint8_t *expected,
uint8_t desired, int success, int failure);
bool __atomic_compare_exchange_2(uint16_t *ptr, uint16_t *expected,
uint16_t desired, int success, int failure);
bool __atomic_compare_exchange_4(uint32_t *ptr, uint32_t *expected,
uint32_t desired, int success, int failure);
bool __atomic_compare_exchange_8(uint64_t *ptr, uint64_t *expected,
uint64_t desired, int success, int failure);
uint8_t __atomic_fetch_add_1(uint8_t *ptr, uint8_t val, int model);
uint16_t __atomic_fetch_add_2(uint16_t *ptr, uint16_t val, int model);
uint32_t __atomic_fetch_add_4(uint32_t *ptr, uint32_t val, int model);
uint64_t __atomic_fetch_add_8(uint64_t *ptr, uint64_t val, int model);
uint8_t __atomic_fetch_sub_1(uint8_t *ptr, uint8_t val, int model);
uint16_t __atomic_fetch_sub_2(uint16_t *ptr, uint16_t val, int model);
uint32_t __atomic_fetch_sub_4(uint32_t *ptr, uint32_t val, int model);
uint64_t __atomic_fetch_sub_8(uint64_t *ptr, uint64_t val, int model);
uint8_t __atomic_fetch_and_1(uint8_t *ptr, uint8_t val, int model);
uint16_t __atomic_fetch_and_2(uint16_t *ptr, uint16_t val, int model);
uint32_t __atomic_fetch_and_4(uint32_t *ptr, uint32_t val, int model);
uint64_t __atomic_fetch_and_8(uint64_t *ptr, uint64_t val, int model);
uint8_t __atomic_fetch_or_1(uint8_t *ptr, uint8_t val, int model);
uint16_t __atomic_fetch_or_2(uint16_t *ptr, uint16_t val, int model);
uint32_t __atomic_fetch_or_4(uint32_t *ptr, uint32_t val, int model);
uint64_t __atomic_fetch_or_8(uint64_t *ptr, uint64_t val, int model);
uint8_t __atomic_fetch_xor_1(uint8_t *ptr, uint8_t val, int model);
uint16_t __atomic_fetch_xor_2(uint16_t *ptr, uint16_t val, int model);
uint32_t __atomic_fetch_xor_4(uint32_t *ptr, uint32_t val, int model);
uint64_t __atomic_fetch_xor_8(uint64_t *ptr, uint64_t val, int model);
// We conditionally test the *_16 atomic function variants based on the same
// condition that compiler_rt (atomic.c) uses to conditionally generate them.
// Currently atomic.c tests if __SIZEOF_INT128__ is defined (which can be the
// case on 32-bit platforms, by using -fforce-enable-int128), instead of using
// CRT_HAS_128BIT.
#ifdef __SIZEOF_INT128__
#define TEST_16
#endif
#ifdef TEST_16
typedef __uint128_t uint128_t;
typedef uint128_t maxuint_t;
uint128_t __atomic_load_16(uint128_t *src, int model);
void __atomic_store_16(uint128_t *dest, uint128_t val, int model);
uint128_t __atomic_exchange_16(uint128_t *dest, uint128_t val, int model);
bool __atomic_compare_exchange_16(uint128_t *ptr, uint128_t *expected,
uint128_t desired, int success, int failure);
uint128_t __atomic_fetch_add_16(uint128_t *ptr, uint128_t val, int model);
uint128_t __atomic_fetch_sub_16(uint128_t *ptr, uint128_t val, int model);
uint128_t __atomic_fetch_and_16(uint128_t *ptr, uint128_t val, int model);
uint128_t __atomic_fetch_or_16(uint128_t *ptr, uint128_t val, int model);
uint128_t __atomic_fetch_xor_16(uint128_t *ptr, uint128_t val, int model);
#else
typedef uint64_t maxuint_t;
#endif
#define U8(value) ((uint8_t)(value))
#define U16(value) ((uint16_t)(value))
#define U32(value) ((uint32_t)(value))
#define U64(value) ((uint64_t)(value))
#ifdef TEST_16
#define V ((((uint128_t)0x4243444546474849) << 64) | 0x4a4b4c4d4e4f5051)
#define ONES ((((uint128_t)0x0101010101010101) << 64) | 0x0101010101010101)
#else
#define V 0x4243444546474849
#define ONES 0x0101010101010101
#endif
#define LEN(array) (sizeof(array) / sizeof(array[0]))
__attribute__((aligned(16))) static const char data[] = {
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
};
uint8_t a8, b8;
uint16_t a16, b16;
uint32_t a32, b32;
uint64_t a64, b64;
#ifdef TEST_16
uint128_t a128, b128;
#endif
void set_a_values(maxuint_t value) {
a8 = U8(value);
a16 = U16(value);
a32 = U32(value);
a64 = U64(value);
#ifdef TEST_16
a128 = value;
#endif
}
void set_b_values(maxuint_t value) {
b8 = U8(value);
b16 = U16(value);
b32 = U32(value);
b64 = U64(value);
#ifdef TEST_16
b128 = value;
#endif
}
void test_loads(void) {
static int atomic_load_models[] = {
__ATOMIC_RELAXED,
__ATOMIC_CONSUME,
__ATOMIC_ACQUIRE,
__ATOMIC_SEQ_CST,
};
for (int m = 0; m < LEN(atomic_load_models); m++) {
int model = atomic_load_models[m];
// Test with aligned data.
for (int n = 1; n <= LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)] = {0};
__atomic_load_c(n, data, dst, model);
if (memcmp(dst, data, n) != 0)
abort();
}
// Test with unaligned data.
for (int n = 1; n < LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)] = {0};
__atomic_load_c(n, data + 1, dst + 1, model);
if (memcmp(dst + 1, data + 1, n) != 0)
abort();
}
set_a_values(V + m);
if (__atomic_load_1(&a8, model) != U8(V + m))
abort();
if (__atomic_load_2(&a16, model) != U16(V + m))
abort();
if (__atomic_load_4(&a32, model) != U32(V + m))
abort();
if (__atomic_load_8(&a64, model) != U64(V + m))
abort();
#ifdef TEST_16
if (__atomic_load_16(&a128, model) != V + m)
abort();
#endif
}
}
void test_stores(void) {
static int atomic_store_models[] = {
__ATOMIC_RELAXED,
__ATOMIC_RELEASE,
__ATOMIC_SEQ_CST,
};
for (int m = 0; m < LEN(atomic_store_models); m++) {
int model = atomic_store_models[m];
// Test with aligned data.
for (int n = 1; n <= LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)];
__atomic_store_c(n, dst, data, model);
if (memcmp(data, dst, n) != 0)
abort();
}
// Test with unaligned data.
for (int n = 1; n < LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)];
__atomic_store_c(n, dst + 1, data + 1, model);
if (memcmp(data + 1, dst + 1, n) != 0)
abort();
}
__atomic_store_1(&a8, U8(V + m), model);
if (a8 != U8(V + m))
abort();
__atomic_store_2(&a16, U16(V + m), model);
if (a16 != U16(V + m))
abort();
__atomic_store_4(&a32, U32(V + m), model);
if (a32 != U32(V + m))
abort();
__atomic_store_8(&a64, U64(V + m), model);
if (a64 != U64(V + m))
abort();
#ifdef TEST_16
__atomic_store_16(&a128, V + m, model);
if (a128 != V + m)
abort();
#endif
}
}
void test_exchanges(void) {
static int atomic_exchange_models[] = {
__ATOMIC_RELAXED,
__ATOMIC_ACQUIRE,
__ATOMIC_RELEASE,
__ATOMIC_ACQ_REL,
__ATOMIC_SEQ_CST,
};
set_a_values(V);
for (int m = 0; m < LEN(atomic_exchange_models); m++) {
int model = atomic_exchange_models[m];
// Test with aligned data.
for (int n = 1; n <= LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)];
__attribute__((aligned(16))) char old[LEN(data)];
for (int i = 0; i < LEN(dst); i++)
dst[i] = i + m;
__atomic_exchange_c(n, dst, data, old, model);
for (int i = 0; i < n; i++) {
if (dst[i] != 0x10 + i || old[i] != i + m)
abort();
}
}
// Test with unaligned data.
for (int n = 1; n < LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)];
__attribute__((aligned(16))) char old[LEN(data)];
for (int i = 1; i < LEN(dst); i++)
dst[i] = i - 1 + m;
__atomic_exchange_c(n, dst + 1, data + 1, old + 1, model);
for (int i = 1; i < n; i++) {
if (dst[i] != 0x10 + i || old[i] != i - 1 + m)
abort();
}
}
if (__atomic_exchange_1(&a8, U8(V + m + 1), model) != U8(V + m))
abort();
if (__atomic_exchange_2(&a16, U16(V + m + 1), model) != U16(V + m))
abort();
if (__atomic_exchange_4(&a32, U32(V + m + 1), model) != U32(V + m))
abort();
if (__atomic_exchange_8(&a64, U64(V + m + 1), model) != U64(V + m))
abort();
#ifdef TEST_16
if (__atomic_exchange_16(&a128, V + m + 1, model) != V + m)
abort();
#endif
}
}
void test_compare_exchanges(void) {
static int atomic_compare_exchange_models[] = {
__ATOMIC_RELAXED,
__ATOMIC_CONSUME,
__ATOMIC_ACQUIRE,
__ATOMIC_SEQ_CST,
__ATOMIC_RELEASE,
__ATOMIC_ACQ_REL,
};
for (int m1 = 0; m1 < LEN(atomic_compare_exchange_models); m1++) {
// Skip the last two: __ATOMIC_RELEASE and __ATOMIC_ACQ_REL.
// See <http://wg21.link/p0418> for details.
for (int m2 = 0; m2 < LEN(atomic_compare_exchange_models) - 2; m2++) {
int m_succ = atomic_compare_exchange_models[m1];
int m_fail = atomic_compare_exchange_models[m2];
// Test with aligned data.
for (int n = 1; n <= LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)] = {0};
__attribute__((aligned(16))) char exp[LEN(data)] = {0};
if (!__atomic_compare_exchange_c(n, dst, exp, data, m_succ, m_fail))
abort();
if (memcmp(dst, data, n) != 0)
abort();
if (__atomic_compare_exchange_c(n, dst, exp, data, m_succ, m_fail))
abort();
if (memcmp(exp, data, n) != 0)
abort();
}
// Test with unaligned data.
for (int n = 1; n < LEN(data); n++) {
__attribute__((aligned(16))) char dst[LEN(data)] = {0};
__attribute__((aligned(16))) char exp[LEN(data)] = {0};
if (!__atomic_compare_exchange_c(n, dst + 1, exp + 1, data + 1,
m_succ, m_fail))
abort();
if (memcmp(dst + 1, data + 1, n) != 0)
abort();
if (__atomic_compare_exchange_c(n, dst + 1, exp + 1, data + 1, m_succ,
m_fail))
abort();
if (memcmp(exp + 1, data + 1, n) != 0)
abort();
}
set_a_values(ONES);
set_b_values(ONES * 2);
if (__atomic_compare_exchange_1(&a8, &b8, U8(V + m1), m_succ, m_fail))
abort();
if (a8 != U8(ONES) || b8 != U8(ONES))
abort();
if (!__atomic_compare_exchange_1(&a8, &b8, U8(V + m1), m_succ, m_fail))
abort();
if (a8 != U8(V + m1) || b8 != U8(ONES))
abort();
if (__atomic_compare_exchange_2(&a16, &b16, U16(V + m1), m_succ, m_fail))
abort();
if (a16 != U16(ONES) || b16 != U16(ONES))
abort();
if (!__atomic_compare_exchange_2(&a16, &b16, U16(V + m1), m_succ, m_fail))
abort();
if (a16 != U16(V + m1) || b16 != U16(ONES))
abort();
if (__atomic_compare_exchange_4(&a32, &b32, U32(V + m1), m_succ, m_fail))
abort();
if (a32 != U32(ONES) || b32 != U32(ONES))
abort();
if (!__atomic_compare_exchange_4(&a32, &b32, U32(V + m1), m_succ, m_fail))
abort();
if (a32 != U32(V + m1) || b32 != U32(ONES))
abort();
if (__atomic_compare_exchange_8(&a64, &b64, U64(V + m1), m_succ, m_fail))
abort();
if (a64 != U64(ONES) || b64 != U64(ONES))
abort();
if (!__atomic_compare_exchange_8(&a64, &b64, U64(V + m1), m_succ, m_fail))
abort();
if (a64 != U64(V + m1) || b64 != U64(ONES))
abort();
#ifdef TEST_16
if (__atomic_compare_exchange_16(&a128, &b128, V + m1, m_succ, m_fail))
abort();
if (a128 != ONES || b128 != ONES)
abort();
if (!__atomic_compare_exchange_16(&a128, &b128, V + m1, m_succ, m_fail))
abort();
if (a128 != V + m1 || b128 != ONES)
abort();
#endif
}
}
}
void test_fetch_op(void) {
static int atomic_fetch_models[] = {
__ATOMIC_RELAXED,
__ATOMIC_CONSUME,
__ATOMIC_ACQUIRE,
__ATOMIC_RELEASE,
__ATOMIC_ACQ_REL,
__ATOMIC_SEQ_CST,
};
for (int m = 0; m < LEN(atomic_fetch_models); m++) {
int model = atomic_fetch_models[m];
// Fetch add.
set_a_values(V + m);
set_b_values(0);
b8 = __atomic_fetch_add_1(&a8, U8(ONES), model);
if (b8 != U8(V + m) || a8 != U8(V + m + ONES))
abort();
b16 = __atomic_fetch_add_2(&a16, U16(ONES), model);
if (b16 != U16(V + m) || a16 != U16(V + m + ONES))
abort();
b32 = __atomic_fetch_add_4(&a32, U32(ONES), model);
if (b32 != U32(V + m) || a32 != U32(V + m + ONES))
abort();
b64 = __atomic_fetch_add_8(&a64, U64(ONES), model);
if (b64 != U64(V + m) || a64 != U64(V + m + ONES))
abort();
#ifdef TEST_16
b128 = __atomic_fetch_add_16(&a128, ONES, model);
if (b128 != V + m || a128 != V + m + ONES)
abort();
#endif
// Fetch sub.
set_a_values(V + m);
set_b_values(0);
b8 = __atomic_fetch_sub_1(&a8, U8(ONES), model);
if (b8 != U8(V + m) || a8 != U8(V + m - ONES))
abort();
b16 = __atomic_fetch_sub_2(&a16, U16(ONES), model);
if (b16 != U16(V + m) || a16 != U16(V + m - ONES))
abort();
b32 = __atomic_fetch_sub_4(&a32, U32(ONES), model);
if (b32 != U32(V + m) || a32 != U32(V + m - ONES))
abort();
b64 = __atomic_fetch_sub_8(&a64, U64(ONES), model);
if (b64 != U64(V + m) || a64 != U64(V + m - ONES))
abort();
#ifdef TEST_16
b128 = __atomic_fetch_sub_16(&a128, ONES, model);
if (b128 != V + m || a128 != V + m - ONES)
abort();
#endif
// Fetch and.
set_a_values(V + m);
set_b_values(0);
b8 = __atomic_fetch_and_1(&a8, U8(V + m), model);
if (b8 != U8(V + m) || a8 != U8(V + m))
abort();
b16 = __atomic_fetch_and_2(&a16, U16(V + m), model);
if (b16 != U16(V + m) || a16 != U16(V + m))
abort();
b32 = __atomic_fetch_and_4(&a32, U32(V + m), model);
if (b32 != U32(V + m) || a32 != U32(V + m))
abort();
b64 = __atomic_fetch_and_8(&a64, U64(V + m), model);
if (b64 != U64(V + m) || a64 != U64(V + m))
abort();
#ifdef TEST_16
b128 = __atomic_fetch_and_16(&a128, V + m, model);
if (b128 != V + m || a128 != V + m)
abort();
#endif
// Fetch or.
set_a_values(V + m);
set_b_values(0);
b8 = __atomic_fetch_or_1(&a8, U8(ONES), model);
if (b8 != U8(V + m) || a8 != U8((V + m) | ONES))
abort();
b16 = __atomic_fetch_or_2(&a16, U16(ONES), model);
if (b16 != U16(V + m) || a16 != U16((V + m) | ONES))
abort();
b32 = __atomic_fetch_or_4(&a32, U32(ONES), model);
if (b32 != U32(V + m) || a32 != U32((V + m) | ONES))
abort();
b64 = __atomic_fetch_or_8(&a64, U64(ONES), model);
if (b64 != U64(V + m) || a64 != U64((V + m) | ONES))
abort();
#ifdef TEST_16
b128 = __atomic_fetch_or_16(&a128, ONES, model);
if (b128 != V + m || a128 != ((V + m) | ONES))
abort();
#endif
// Fetch xor.
set_a_values(V + m);
set_b_values(0);
b8 = __atomic_fetch_xor_1(&a8, U8(ONES), model);
if (b8 != U8(V + m) || a8 != U8((V + m) ^ ONES))
abort();
b16 = __atomic_fetch_xor_2(&a16, U16(ONES), model);
if (b16 != U16(V + m) || a16 != U16((V + m) ^ ONES))
abort();
b32 = __atomic_fetch_xor_4(&a32, U32(ONES), model);
if (b32 != U32(V + m) || a32 != U32((V + m) ^ ONES))
abort();
b64 = __atomic_fetch_xor_8(&a64, U64(ONES), model);
if (b64 != U64(V + m) || a64 != U64((V + m) ^ ONES))
abort();
#ifdef TEST_16
b128 = __atomic_fetch_xor_16(&a128, ONES, model);
if (b128 != (V + m) || a128 != ((V + m) ^ ONES))
abort();
#endif
// Check signed integer overflow behavior
set_a_values(V + m);
__atomic_fetch_add_1(&a8, U8(V), model);
if (a8 != U8(V * 2 + m))
abort();
__atomic_fetch_sub_1(&a8, U8(V), model);
if (a8 != U8(V + m))
abort();
__atomic_fetch_add_2(&a16, U16(V), model);
if (a16 != U16(V * 2 + m))
abort();
__atomic_fetch_sub_2(&a16, U16(V), model);
if (a16 != U16(V + m))
abort();
__atomic_fetch_add_4(&a32, U32(V), model);
if (a32 != U32(V * 2 + m))
abort();
__atomic_fetch_sub_4(&a32, U32(V), model);
if (a32 != U32(V + m))
abort();
__atomic_fetch_add_8(&a64, U64(V), model);
if (a64 != U64(V * 2 + m))
abort();
__atomic_fetch_sub_8(&a64, U64(V), model);
if (a64 != U64(V + m))
abort();
#ifdef TEST_16
__atomic_fetch_add_16(&a128, V, model);
if (a128 != V * 2 + m)
abort();
__atomic_fetch_sub_16(&a128, V, model);
if (a128 != V + m)
abort();
#endif
}
}
int main() {
test_loads();
test_stores();
test_exchanges();
test_compare_exchanges();
test_fetch_op();
return 0;
}
|
the_stack_data/140766587.c | #define CHARS_IN_ALPHABET 26
// @klee
int getPositionInAlphabet_DoWhile(char c) {
int offset = -1;
do {
offset++;
} while (offset < CHARS_IN_ALPHABET && 'a' + offset != c);
if (offset == CHARS_IN_ALPHABET) {
return -1;
}
return offset;
}
// @klee
int getPositionInAlphabet_While(char c) {
int offset = 0;
while (offset < CHARS_IN_ALPHABET) {
if ('a' + offset == c) {
break;
}
offset++;
}
if (offset == CHARS_IN_ALPHABET) {
return -1;
}
return offset;
}
// @klee
int getPositionInAlphabet_For(char c) {
for (int offset = 0; offset < CHARS_IN_ALPHABET; offset++) {
if ('a' + offset != c) {
continue;
}
return offset;
}
return -1;
}
|
the_stack_data/35785.c | /* $OpenBSD: version.c,v 1.2 1998/08/22 07:17:23 smurph Exp $ */
/*
* make a random change to this file when you want the bootblock
* revision to increase. like change this q to an x, or something.
*/
char *version = "$Revision: 1.2 $";
|
the_stack_data/87639068.c | #include <stdio.h>
#include <math.h>
float exponential(x,n) {
float sum = 1;
for (int i = n - 1; i > 0; i--)
sum = 1 + x * sum / i;
return sum;
}
double exponential_(x,n) {
double sum = 1;
for (int i = n - 1; i > 0; i--)
sum *= (1 + 1 / i);
/*
for (int i = n - 1; i > 0; i--)
sum = 1 + x * sum / i;
*/return sum;
}
int main() {
float x = 1;
for (int j = 0; j < 100; j++)
printf("value of e %.7f %.15f \n", exponential(x,j), exponential_(x,j));
}
|
the_stack_data/155876.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2015-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
/* Number of threads. Each thread continuously steps over a
breakpoint. */
#define NTHREADS 10
pthread_t threads[NTHREADS];
pthread_barrier_t barrier;
/* Used to create a conditional breakpoint that always fails. */
volatile int zero;
static void *
thread_func (void *arg)
{
pthread_barrier_wait (&barrier);
while (1)
{
usleep (1); /* set break here */
}
return NULL;
}
int
main (void)
{
int ret;
int i;
/* Don't run forever. */
alarm (180);
pthread_barrier_init (&barrier, NULL, NTHREADS + 1);
/* Start the threads that constantly hits a conditional breakpoint
that needs to be stepped over. */
for (i = 0; i < NTHREADS; i++)
{
ret = pthread_create (&threads[i], NULL, thread_func, NULL);
assert (ret == 0);
}
/* Wait until all threads are up and running. */
pthread_barrier_wait (&barrier);
/* Let them start hitting the breakpoint. */
usleep (100);
/* Exit abruptly. */
return 0;
}
|
the_stack_data/6387190.c | #include <stdio.h>
#include <string.h>
#define N 2000001
#define NIL -1
#define INF (2e9+1)
int parent(int);
int left(int);
int right(int);
int heapExtractMax();
void swap(int*,int*);
void maxHeapify(int);
void buildMaxHeap();
void MaxHeapInsert(int);
void heapIncreaseKey(int,int);
int A[N],H=0;
int main()
{
char inst[8];
int num;
while(1){
scanf("%s",inst);
if(!strcmp(inst,"insert")){
scanf("%d",&num);
MaxHeapInsert(num);
}
else if(!strcmp(inst,"extract")){
printf("%d\n",heapExtractMax());
}
else if(!strcmp(inst,"end")) break;
else printf("invalid input!\n");
}
return 0;
}
int parent(int x)
{
if(x==1) return NIL;
else return x/2;
}
int left(int x)
{
if(x*2>H) return NIL;
else return x*2;
}
int right(int x)
{
if(x*2+1>H) return NIL;
else return x*2+1;
}
void swap(int *x,int *y)
{
int tmp=*x;
*x=*y;
*y=tmp;
}
int heapExtractMax()
{
if(H<1){
printf("heap underflow!\n");
return -INF;
}
else{
int max=A[1];
A[1]=A[H];
H--;
maxHeapify(1);
return max;
}
}
void MaxHeapInsert(int key)
{
H++;
A[H]=-INF;
heapIncreaseKey(H,key);
}
void heapIncreaseKey(int i,int key)
{
if(key<A[i]) printf("new key is smaller than current key!\n");
else{
A[i]=key;
while(i>1 && A[parent(i)]<A[i]){
swap(&A[parent(i)],&A[i]);
i=parent(i);
}
}
}
void maxHeapify(int i)
{
int l,r,largest;
l=left(i);
r=right(i);
if(l!=NIL && A[l]>A[i]) largest=l;
else largest=i;
if(r!=NIL && A[r]>A[largest]) largest=r;
if(largest!=i){
swap(&A[i],&A[largest]);
maxHeapify(largest);
}
}
void buildMaxHeap()
{
for(int i=H/2;i>=1;i--) maxHeapify(i);
}
|
the_stack_data/97011740.c | #include <stdio.h>
int main()
{
int n,m,i,x=1,y=1,z;
scanf ("%d%d",&m,&n);
for(i=m;i>m-n;i--)
x*=i;
for(i=1;i<=n;i++)
y*=i;
z=x/y;
printf("%d",z);
return 0;
} |
the_stack_data/1167878.c | /* A call will clobber all call-saved registers.
If #pragma nosave_low_regs is specified, do not save/restore r0..r7.
(On SH3* and SH4* r0..r7 are banked)
Call-saved registers r8..r14 also don't need to be restored.
To test that we look for register push insns such as 'mov.l r0,@-r15'. */
/* { dg-do compile { target { { banked_r0r7_isr } && nonpic } } } */
/* { dg-options "-O" } */
/* { dg-final { scan-assembler-times "rte" 1 } } */
/* { dg-final { scan-assembler-not "mov.l\tr\[0-9\],@-r15" } } */
/* { dg-final { scan-assembler-not "mov.l\tr1\[0-4\],@-r15" } } */
/* { dg-final { scan-assembler-times "macl" 2 } } */
extern void foo (void);
#pragma interrupt
#pragma nosave_low_regs
void
isr (void)
{
foo ();
}
|
the_stack_data/98294.c | // RUN: %clang_cc1 -fsyntax-only %s
void bla1(void) {
struct XXX;
int XXX;
}
|
the_stack_data/118821.c | /*
** Morgan Brenner
** [email protected]
** CS 372 Program 1
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#define MAX_MESSAGE 500
#define MAX_HANDLE 10
/*
** Function: initiateContact
**
** Description: fills out hints struct, prepares to connect,
** makes socket, and connects to server
** Parameters: hostname: server's host name, port: server's port, status:
** Returns: socket file descriptor
*/
int initiateContact(char *hostname, char *port, int status) {
struct addrinfo hints, *res;
char ipstr[INET_ADDRSTRLEN];
int socketfd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM; //TCP
hints.ai_flags = AI_PASSIVE;
//fill addrinfo struct
if ((status = getaddrinfo(hostname, port, &hints, &res)) != 0) {
fprintf(stderr,"error: getaddrinfo: %s\n", gai_strerror(status)); exit(1);
}
//create socket
socketfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (socketfd == -1) { fprintf(stderr,"error: socket\n"); exit(1); }
//establish connection
status = connect(socketfd, res->ai_addr, res->ai_addrlen);
if (status == -1) {
fprintf(stderr,"error: connect\n");
close(socketfd);
exit(1);
}
freeaddrinfo(res); //free linked list
return socketfd;
}
/*
** Function: exchangeHandles
**
** Description: retrieves and stores handles for both client and server users
** Parameters: socketfd: , handleA: buffer to hold client user's handle,
** handleB: buffer to hold server user's handle
*/
void exchangeHandles(int socketfd, char *handleA, char *handleB) {
int charsWritten, charsRead;
//get handle from user
printf("Enter handle: "); //prompt
memset(handleB, 0, MAX_HANDLE + 2); //prepare buffer, stdin, stdout
fflush(stdout); fflush(stdin);
fgets(handleB, MAX_HANDLE + 2, stdin);
handleB[strcspn(handleB, "\n")] = 0; //trim newline
//send handle to server
charsWritten = send(socketfd, handleB, strlen(handleB), 0);
if (charsWritten < 0) { fprintf(stderr,"error: send handle\n"); exit(1); };
//get handle from server
memset(handleA, 0, MAX_HANDLE + 2);
charsRead = recv(socketfd, handleA, MAX_HANDLE + 1, 0);
if (charsRead < 0) { fprintf(stderr,"error: receive handle\n"); exit(1); };
}
/*
** Function: sendMessage
**
** Description: displays prompt, gets message from user, sends to server, and
** quits program if user has entered quit command
** Parameters: socketfd: socket file descriptor, message: buffer to hold user input
handleB: handle of client/hostB's user
** Returns: 1 to quit chat,
0 to continue
*/
int sendMessage(int socketfd, char *message, char *handleB) {
int charsWritten;
char *quitChat = "\\quit";
//get message from user
printf("%s> ", handleB); //prompt
memset(message, 0, MAX_MESSAGE + 2); //prepare buffer, stdin, stdout
fflush(stdout); fflush(stdin);
fgets(message, MAX_MESSAGE + 2, stdin); //account for newline in size
message[strcspn(message, "\n")] = 0; //trim newline
//send message to server
charsWritten = send(socketfd, message, strlen(message), 0);
if (charsWritten < 0) { fprintf(stderr,"error: send message\n"); exit(1); };
//check for quit command
if (strcmp(quitChat, message) == 0) {
return 1;
}
return 0;
}
/*
** Function: receiveMessage
**
** Description: receives message from server, quits program if quit command is received,
** or prints message to console in as: "handleA> reply"
** Parameters: socketfd: socket file descriptor, reply: buffer to hold server response
handleA: handle of server/host A's user
** Returns: 1 to quit chat,
0 to continue
*/
int receiveMessage(int socketfd, char *reply, char *handleA) {
int charsRead;
char *quitChat = "\\quit";
//get reply from server
memset(reply, 0, MAX_MESSAGE + 1);
charsRead = recv(socketfd, reply, MAX_MESSAGE + 1, 0);
if (charsRead < 0) { fprintf(stderr,"error: receive message\n"); exit(1); };
//check for quit command
if (strcmp(quitChat, reply) == 0) {
return 1;
}
//print reply from server
printf("%s> %s\n", handleA, reply);
return 0;
}
int main(int argc, char *argv[]) {
char *hostname, *port;
char handleA[MAX_HANDLE+1], handleB[MAX_HANDLE+2];
char message[MAX_MESSAGE+2], reply[MAX_MESSAGE+1];
int status = 0;
int socketfd;
/*
** check args for correct usage
*/
if (argc < 3) { fprintf(stderr,"USAGE: ./chatclient <server-hostname> <port #>\n"); exit(1); }
hostname = argv[1];
port = argv[2];
/*
** establish connection with server
*/
socketfd = initiateContact(hostname, port, status);
/*
** exchange handles
*/
exchangeHandles(socketfd, handleA, handleB);
/*
** run chat until either client or server quits
*/
while(1) {
if (sendMessage(socketfd, message, handleB) == 1) {
printf("ending chat and exiting\n");
close(socketfd);
return 0;
};
if (receiveMessage(socketfd, reply, handleA) == 1) {
printf("ending chat and exiting\n");
close(socketfd);
return 0;
}
}
close(socketfd);
return 0;
} |
the_stack_data/154829706.c | struct s {
int a;
int b;
};
int f0(void)
{
struct s s;
s.a = 0;
s.b = 1;
return s.a;
}
int f1(void)
{
struct s s;
s.a = 1;
s.b = 0;
return s.b;
}
/*
* check-name: struct
* check-command: test-linearize -Wno-decl $file
*
* check-output-ignore
* check-output-pattern(2): ret.32 *\\$0
*/
|
the_stack_data/739819.c | /*
* The problem
* -----------
* On platforms that use a two-level symbol namespace for dynamic libraries
* (most notably MacOS X), integrating tcmalloc requires special modifications.
*
* Most Unix platforms use a flat namespace for symbol lookup, which is why
* linking to tcmalloc causes it override malloc() and free() for the entire
* process. This is not the case on OS X: if Ruby calls a function from library
* that's not compiled with -flat_namespace, then that library will use the
* system's memory allocator instead of tcmalloc.
*
* The Ruby readline extension is a good example of how things can go wrong.
* The readline extension calls the readline() function in the readline library.
* This library is not compiled with -flat_namespace; readline() returns a string
* that's allocated by the system memory allocator. The Ruby readline extension
* then frees this string by passing it to tcmalloc's free() function. This
* results in a crash.
* Note that setting DYLD_FORCE_FLAT_NAMESPACE on OS X does not work: the
* resulting Ruby interpreter will crash immediately.
*
*
* The solution
* ------------
* This can be fixed by making it possible for Ruby extensions to call the
* system's memory allocator functions, instead of tcmalloc's, if it knows
* that a piece of memory is allocated by the system's memory allocator.
*
* This library, libsystem_allocator provides wrapper functions for the system
* memory allocator. libsystem_allocator will be compiled without -flat_namespace
* on OS X, and so it will always use the system's memory allocator instead of
* tcmalloc.
*
* libsystem_allocator will not be compiled on systems that only support flat
* namespaces (e.g. Linux). On those platforms, system_malloc() and
* system_free() have no special effect.
*/
#include <stdlib.h>
void *
system_malloc(long size)
{
return malloc(size);
}
void
system_free(void *ptr)
{
free(ptr);
}
|
the_stack_data/243892628.c | /*
* SPDX-License-Identifier: MIT
* MIT License
*
* Copyright (c) 2019 Western Digital Corporation or its affiliates.
*
* 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 (including the next paragraph) shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
int foo(void);
int getStart(int pivot);
int getEnd(int pivot);
int getLCM(int a, int b);
int foo(void)
{
int i=0;
int j=100;
int x=0;
i=getStart(i);
j=getEnd(j);
j=getLCM(i, j);
for(i; i< j; i++)
x += i;
return 0;
}
int getStart(int pivot)
{
int start = 0;
if (pivot > 0)
start = pivot;
else
start = 100;
return start;
}
int getEnd(int pivot)
{
int end = 0;
if (pivot > 0)
end = pivot;
else
end = 100;
return end;
}
int getLCM(int a, int b)
{
int num1, num2, maxValue, result;
num1 = a;
num2 = b;
maxValue = (num1 > num2) ? num1 : num2;
while(1)
{
if ((maxValue % num1 == 0) && (maxValue % num2 == 0))
{
result = maxValue;
break;
}
++maxValue;
}
return result;
}
|
the_stack_data/3263483.c | #include <stdlib.h>
#include <string.h>
int dfs(int N, int (*graph)[N], int* quiet, int* res, int index)
{
if (res[index] != -1)
return res[index];
res[index] = index;
for (int i = 0; i < N; ++i)
{
if (graph[index][i] == 1)
{
int person = dfs(N, graph, quiet, res, i);
if (quiet[person] < quiet[res[index]])
res[index] = person;
}
}
return res[index];
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* loudAndRich(int** richer, int richerSize, int* richerColSize, int* quiet, int quietSize, int* returnSize)
{
int N = quietSize, graph[N][N];
memset(graph, 0, sizeof(graph));
for (int i = 0; i < richerSize; ++i)
graph[richer[i][1]][richer[i][0]] = 1;
*returnSize = N;
int* res = (int*)malloc(sizeof(int) * (*returnSize));
memset(res, -1, sizeof(int) * (*returnSize));
for (int i = 0; i < N; ++i)
dfs(N, graph, quiet, res, i);
return res;
}
|
the_stack_data/7193.c | #include <stdio.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
// If one may tell me the way to portable identify endianness on preprocessing stage, i'll be greatly appreciating it.
#if !defined _LITTLE_ENDIAN && !defined __LITTLE_ENDIAN && (!defined __BYTE_ORDER__ || !defined __ORDER_LITTLE_ENDIAN__ || (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__))
#error This source may be built only on little-endian architecture.
#endif
struct header_t
{
char identifier[4];
uint32_t items;
uint32_t directory;
};
struct directory_t
{
uint32_t start;
uint32_t size;
char lumpname[8];
};
int usage(char *progname)
{
printf("\
WAD file decompiler.\n\
Usage: %s <wadfile> <directory>\n\
wadfile - filename of wadfile;\n\
directory - where to place resulting lumps (created if necessary).\n\n\
Example: %s mywad.wad ./output\n", progname, progname);
return 1;
}
int main(int argc, char *argv[])
{
if (argc != 3) return usage(argv[0]);
int i;
size_t l;
char *wadfile = argv[1];
char *path = argv[2];
printf("Analyzing %s:\n", wadfile);
FILE *wadfile_f = fopen(wadfile, "r");
struct header_t header;
l = fread(&header, sizeof(struct header_t), 1, wadfile_f);
if (feof(wadfile_f) || l < 1) goto file_error;
switch(*(uint32_t*)header.identifier)
{
case 0x44415749: /* IWAD */
printf("IWAD, "); break;
case 0x44415750: /* PWAD */
printf("PWAD, "); break;
default:
printf("Unknown header magic: %lX.\n", *(uint32_t*)header.identifier);
fclose(wadfile_f);
return 3;
}
printf("%d entries, directory at 0x%08lX.\n", header.items, header.directory);
// Non-portable, but easiest way.
if (path[strlen(path) - 1] == '/') path[strlen(path) - 1] = '\0';
char *mkdir_cmd = malloc(10 + strlen(path));
sprintf(mkdir_cmd, "mkdir -p %s", path);
system(mkdir_cmd);
free(mkdir_cmd);
struct directory_t *directory = malloc (header.items * sizeof(struct directory_t));
fseek(wadfile_f, header.directory, SEEK_SET);
l = fread(directory, sizeof(struct directory_t), header.items, wadfile_f);
if (feof(wadfile_f) || l < header.items) goto file_error;
char *filename = malloc(strlen(path) + 19);
for (i = 0; i < header.items; ++i)
{
char sane_lumpname[9], lumpname[9] = "\0\0\0\0\0\0\0\0";
snprintf(lumpname, 9, "%s", directory[i].lumpname);
for (l = 0; l < 9; ++l)
{
char c = lumpname[l];
switch(c)
{
case '\\':
case '[':
case ']':
c = '_';
default:
sane_lumpname[l] = c;
}
}
sprintf(filename, "%s/%04u_%s.lmp", path, i + 1, sane_lumpname);
printf(" Extracting %-8s [offset 0x%08X, size %10lu] -> %s ... ", lumpname, directory[i].start, directory[i].size, filename);
FILE *lumpfile_f = fopen(filename,"w");
if (directory[i].size > 0)
{
void *lumpdata = malloc(directory[i].size);
fseek(wadfile_f, directory[i].start, SEEK_SET);
l = fread (lumpdata, 1, directory[i].size, wadfile_f);
if (feof(wadfile_f) || l < directory[i].size) { fclose(lumpfile_f); goto file_error; }
l = fwrite(lumpdata, 1, directory[i].size, lumpfile_f);
printf ((l < directory[i].size) ? "Failure!\n" : "OK\n");
free(lumpdata);
}
else printf ("Empty file\n");
fclose(lumpfile_f);
}
fclose(wadfile_f);
free(filename);
free(directory);
printf("Finished.\n");
return 0;
file_error:
printf("Unexpected end of WAD file. Terminating.\n");
fclose(wadfile_f);
return 2;
} |
the_stack_data/296806.c | // ==============================================================
// Copyright (c) 1986 - 2020 Xilinx Inc. All rights reserved.
// SPDX-License-Identifier: MIT
// ==============================================================
#ifndef __linux__
#include "xstatus.h"
#include "xparameters.h"
#include "xv_demosaic.h"
#ifndef XPAR_XV_DEMOSAIC_NUM_INSTANCES
#define XPAR_XV_DEMOSAIC_NUM_INSTANCES 0
#endif
extern XV_demosaic_Config XV_demosaic_ConfigTable[];
XV_demosaic_Config *XV_demosaic_LookupConfig(u16 DeviceId) {
XV_demosaic_Config *ConfigPtr = NULL;
int Index;
for (Index = 0; Index < XPAR_XV_DEMOSAIC_NUM_INSTANCES; Index++) {
if (XV_demosaic_ConfigTable[Index].DeviceId == DeviceId) {
ConfigPtr = &XV_demosaic_ConfigTable[Index];
break;
}
}
return ConfigPtr;
}
int XV_demosaic_Initialize(XV_demosaic *InstancePtr, u16 DeviceId) {
XV_demosaic_Config *ConfigPtr;
Xil_AssertNonvoid(InstancePtr != NULL);
ConfigPtr = XV_demosaic_LookupConfig(DeviceId);
if (ConfigPtr == NULL) {
InstancePtr->IsReady = 0;
return (XST_DEVICE_NOT_FOUND);
}
return XV_demosaic_CfgInitialize(InstancePtr,
ConfigPtr,
ConfigPtr->BaseAddress);
}
#endif
|
the_stack_data/1021509.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rev_print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: exam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 12:33:14 by evgenkarlson #+# #+# */
/* Updated: 2020/02/15 10:51:23 by evgenkarlson ### ########.fr */
/* */
/* ************************************************************************** */
/* ************************************************************************** */
/* ************************************************************************** */
/* **************************************************************************
Assignment name : rev_print
Expected files : rev_print.c
Allowed functions: write
--------------------------------------------------------------------------------
Напишите программу, которая принимает строку и отображает строку в обратном
порядке, за которой следует новая строка.
Если количество параметров не равно 1, программа отображает новую строку.
Примеры:
$> ./rev_print "zaz" | cat -e
zaz$
$> ./rev_print "dub0 a POIL" | cat -e
LIOP a 0bud$
$> ./rev_print | cat -e
$
************************************************************************** */
/* ************************************************************************** */
/* ************************************************************************** */
#include <unistd.h>
int main(int argc, char *argv[]) /* здесь принимаем количество строк в массиве и сам массив со строками */
{
if (argc == 2) /* Проверяем есть ли там кроме имени программы в аргументах еще одна строка
* которую мы хотим зареверсить если строки две то запускаем процесс печати реверса строки */
{
int i; /* для начала обьявим переменную для подсчета количества символов в массиве */
i = 0; /* инициализируем ее нулем */
while(argv[1][i]) /* запускаем цикл который будет считать символы и записывать их в i пока не дойдет до конца
* массива(до завершающего нуля в массиве)*/
i++; /* увеличиваем i для перехода к проверке сл символа */ /* количество накопленных i будет говорить
* о количестве символо внутри массива */
while(i) /* Запустим цикл который будет печатать каждый символ начиная с конца массива c помощью i */
write(1, &argv[1][--i], 1); /* печатаем ячейку массива на которую указывает i и уменьшаем i чтобы при след итерации цикла
*печатать уже др по счету ячейку. и так пока не дойдем до самого начала */
}
write(1 ,"\n", 1); /* после печати массива напечатаем символ перехода на новкю строку */
return (0); /* говорим функции майн что дошли до конца и завершаем программу */
}
|
the_stack_data/41250.c | /*
Copyright (c) 2016, Alexey Frunze
2-clause BSD license.
*/
#ifdef __SMALLER_C_32__
#include <math.h>
float tanhf(float x)
{
int neg;
float e;
if (x == 0)
return x; // preserve sign of 0
if ((neg = x < 0) != 0)
x = -x;
if (x >= 10)
{
// +/-INF handled here
e = 1;
}
else if (x < 1)
{
e = expm1f(x * 2);
e = e / (e + 2);
}
else
{
// NAN handled here
e = expm1f(x * 2);
e = 1 - 2 / (e + 2);
}
return neg ? -e : e;
}
double tanh(double x)
{
return tanhf(x);
}
#endif
|
the_stack_data/66516.c | #include <stdio.h>
const int N = 1e5;
int lis(int a[], int n) {
int i, j;
int dp[N];
for(i = 0; i < n; ++i)
dp[i] = 1;
for(i = 0; i < n; ++i)
for(j = 0; j < i; ++j)
if(a[j] < a[i])
if(dp[i] < dp[j] + 1)
dp[i] = dp[j] + 1;
int mx = 0;
for(i = 0; i < n; ++i)
if(mx < dp[i])
mx = dp[i];
return mx;
}
int main() {
int n;
scanf("%d", &n);
int a[N];
int i;
for(i = 0; i < n; ++i)
scanf("%d", &a[i]);
printf("%d\n", lis(a, n));
} |
the_stack_data/111077297.c | /*
* Autor: Cristobal Liendo I.
* Fecha: 11/09/17
* Imprime los primeros 50 multiplos de tres
*/
#include <stdio.h>
int main() {
int m, i;
printf("Primeros 50 multiplos de 3: \n\n");
for (m = i = 0; i < 50; i++, m += 3) {
if (i < 49)
printf("%d, ", m);
else
printf("%d\n\n", m);
}
return 0;
}
|
the_stack_data/168893416.c | // RUN: %clang_cc1 %s -ffreestanding -triple x86_64-apple-darwin -emit-llvm37 -o - | FileCheck %s --check-prefix=CHECK-64
// RUN: %clang_cc1 %s -ffreestanding -triple i386 -emit-llvm37 -o - | FileCheck %s --check-prefix=CHECK-32
#include <cpuid.h>
// CHECK-64: {{.*}} call { i32, i32, i32, i32 } asm " xchgq %rbx,${1:q}\0A cpuid\0A xchgq %rbx,${1:q}", "={ax},=r,={cx},={dx},0,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}})
// CHECK-64: {{.*}} call { i32, i32, i32, i32 } asm " xchgq %rbx,${1:q}\0A cpuid\0A xchgq %rbx,${1:q}", "={ax},=r,={cx},={dx},0,2,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}}, i32 %{{[a-z0-9]+}})
// CHECK-32: {{.*}} call { i32, i32, i32, i32 } asm "cpuid", "={ax},={bx},={cx},={dx},0,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}})
// CHECK-32: {{.*}} call { i32, i32, i32, i32 } asm "cpuid", "={ax},={bx},={cx},={dx},0,2,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}}, i32 %{{[a-z0-9]+}})
unsigned eax0, ebx0, ecx0, edx0;
unsigned eax1, ebx1, ecx1, edx1;
void test_cpuid(unsigned level, unsigned count) {
__cpuid(level, eax1, ebx1, ecx1, edx1);
__cpuid_count(level, count, eax0, ebx0, ecx0, edx0);
}
|
the_stack_data/153266992.c | /* { dg-options "-Winline" } */
void quit_mined ();
void bottom_line ();
typedef enum { False, True } FLAG;
inline void
nextfile (FLAG exitiflast)
{
if (exitiflast)
quit_mined ();
else
bottom_line ();
nextfile (True);
}
|
the_stack_data/1137430.c | #include <stdio.h>
#include <stdlib.h>
void insert_array(int tamanho, int *vetor) //funçao para ler valores para vetores.
{
int i; //i - contador
for ( i = 0; i < tamanho; i += 1 )
{
scanf("%d", &vetor[i]); //lê valores para um vetor.
}
}
void insert_matrix(int linha, int ncoluna, int **matriz) //funçao para ler valores para matrizes
{
int i; //i - contador
for ( i = 0; i < linha; i += 1 )
{
matriz[i] = (int*) malloc (ncoluna*sizeof(int*)); //declara o tamanho da matriz
insert_array(ncoluna,matriz[i]); // lê valores para o elemento da matriz(que é um vetor).
}
}
void make_result(int *R, int *V, int **A, int n, int m) //funçao para calcular o vetor resultado.
{
int i, j, aux = 0; //i - contador, j - contador, aux - acumulador
for(i = 0; i < n; i++)
{
aux = 0; //aux recebe o valor 0 depois de cada iteração do 'i'
for(j = 0; j < m; j++)
{
aux += V[j] * A[j][i]; //aux acumula o produto da matriz pelo vetor.
}
R[i] = aux; //vetor resultado recebe o valor do acumulador.
}
}
|
the_stack_data/86050.c | #include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#define MAX_PLATFORMS 32
#define MAX_DEVICES 32
int
main(void)
{
cl_int err;
cl_platform_id platforms[MAX_PLATFORMS];
cl_uint nplatforms;
cl_device_id devices[MAX_DEVICES];
cl_uint ndevices;
cl_uint i, j;
err = clGetPlatformIDs(MAX_PLATFORMS, platforms, &nplatforms);
if (err != CL_SUCCESS)
return EXIT_FAILURE;
for (i = 0; i < nplatforms; i++)
{
err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, MAX_DEVICES,
devices, &ndevices);
if (err != CL_SUCCESS)
return EXIT_FAILURE;
for (j = 0; j < ndevices; j++)
{
cl_context context = clCreateContext(NULL, 1, &devices[j], NULL, NULL, &err);
if (err != CL_SUCCESS)
return EXIT_FAILURE;
cl_command_queue queue = clCreateCommandQueue(context, devices[j], 0, &err);
if (err != CL_SUCCESS)
return EXIT_FAILURE;
const int buf_size = 1024;
cl_int host_buf[buf_size];
cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_int) * buf_size, NULL, &err);
if (err != CL_SUCCESS)
return EXIT_FAILURE;
cl_event buf_event;
if (clEnqueueReadBuffer(queue, buf, CL_TRUE, 0, sizeof(cl_int) * buf_size, &host_buf, 0, NULL, &buf_event) != CL_SUCCESS)
return EXIT_FAILURE;
clFinish(queue);
cl_command_queue event_command_queue;
size_t param_val_size_ret;
if (clGetEventInfo(buf_event, CL_EVENT_COMMAND_QUEUE, sizeof(cl_command_queue), &event_command_queue, ¶m_val_size_ret) != CL_SUCCESS)
return EXIT_FAILURE;
if (param_val_size_ret != sizeof(cl_command_queue) || event_command_queue != queue)
return EXIT_FAILURE;
cl_command_type command_type;
if (clGetEventInfo(buf_event, CL_EVENT_COMMAND_TYPE, sizeof(cl_command_type), &command_type, ¶m_val_size_ret) != CL_SUCCESS)
return EXIT_FAILURE;
if (param_val_size_ret != sizeof(cl_command_type) || command_type != CL_COMMAND_READ_BUFFER)
return EXIT_FAILURE;
cl_int execution_status;
if (clGetEventInfo(buf_event, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &execution_status, ¶m_val_size_ret) != CL_SUCCESS)
return EXIT_FAILURE;
if (param_val_size_ret != sizeof(cl_int) || execution_status != CL_COMPLETE)
return EXIT_FAILURE;
clReleaseEvent(buf_event);
clReleaseMemObject(buf);
clReleaseCommandQueue(queue);
}
}
return EXIT_SUCCESS;
}
|
the_stack_data/29812.c | int main(void) {
~0; // Negative zero for sign/mag.
return 0;
}
|
the_stack_data/148469.c | // BUG: unable to handle kernel paging request in do_con_trol
// https://syzkaller.appspot.com/bug?id=04775771a119c1ba4974a07c365475ada756a40d
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <endian.h>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_link.h>
#include <linux/in6.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/veth.h>
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 int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
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;
}
const int kInitNetNsFd = 239;
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_CMD_RELOAD 37
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
#define DEVLINK_ATTR_NETNS_FD 138
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static void netlink_devlink_netns_move(const char* bus_name,
const char* dev_name, int netns_fd)
{
struct genlmsghdr genlhdr;
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_RELOAD;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd));
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
static void initialize_devlink_pci(void)
{
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
exit(1);
int ret = setns(kInitNetNsFd, 0);
if (ret == -1)
exit(1);
netlink_devlink_netns_move("pci", "0000:00:10.0", netns);
ret = setns(netns, 0);
if (ret == -1)
exit(1);
close(netns);
initialize_devlink_ports("pci", "0000:00:10.0", "netpci");
}
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;
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);
}
}
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
intptr_t res = 0;
memcpy((void*)0x20000100, "/dev/fb0\000", 9);
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000100ul, 0ul, 0ul);
if (res != -1)
r[0] = res;
*(uint32_t*)0x20000140 = 0;
*(uint32_t*)0x20000144 = 0;
*(uint32_t*)0x20000148 = 0;
*(uint32_t*)0x2000014c = 0;
*(uint32_t*)0x20000150 = 0;
*(uint32_t*)0x20000154 = 0;
*(uint32_t*)0x20000158 = 8;
*(uint32_t*)0x2000015c = 0;
*(uint32_t*)0x20000160 = 0;
*(uint32_t*)0x20000164 = 0;
*(uint32_t*)0x20000168 = 0;
*(uint32_t*)0x2000016c = 0;
*(uint32_t*)0x20000170 = 0;
*(uint32_t*)0x20000174 = 0;
*(uint32_t*)0x20000178 = 0;
*(uint32_t*)0x2000017c = 0;
*(uint32_t*)0x20000180 = 0;
*(uint32_t*)0x20000184 = 0;
*(uint32_t*)0x20000188 = 0;
*(uint32_t*)0x2000018c = 0;
*(uint32_t*)0x20000190 = 0;
*(uint32_t*)0x20000194 = 0;
*(uint32_t*)0x20000198 = 0;
*(uint32_t*)0x2000019c = 0;
*(uint32_t*)0x200001a0 = 0;
*(uint32_t*)0x200001a4 = 0;
*(uint32_t*)0x200001a8 = 0;
*(uint32_t*)0x200001ac = 0;
*(uint32_t*)0x200001b0 = 0;
*(uint32_t*)0x200001b4 = 0;
*(uint32_t*)0x200001b8 = 0;
*(uint32_t*)0x200001bc = 0;
*(uint32_t*)0x200001c0 = 0;
*(uint32_t*)0x200001c4 = 3;
*(uint32_t*)0x200001c8 = 0;
*(uint32_t*)0x200001cc = 0;
*(uint32_t*)0x200001d0 = 0;
*(uint32_t*)0x200001d4 = 0;
*(uint32_t*)0x200001d8 = 0;
*(uint32_t*)0x200001dc = 0;
syscall(__NR_ioctl, r[0], 0x4601ul, 0x20000140ul);
res = syz_open_dev(0xc, 4, 0x14);
if (res != -1)
r[1] = res;
*(uint8_t*)0x20000200 = 0x1b;
*(uint8_t*)0x20000201 = 0x5b;
*(uint8_t*)0x20000202 = 0x4b;
*(uint8_t*)0x20000203 = 0x9b;
*(uint8_t*)0x20000204 = 0;
*(uint8_t*)0x20000205 = 0;
*(uint8_t*)0x20000206 = 0;
*(uint8_t*)0x20000207 = 0;
*(uint64_t*)0x20000208 = 0;
*(uint16_t*)0x20000210 = 0;
*(uint16_t*)0x20000212 = 0;
*(uint32_t*)0x20000214 = 0;
*(uint64_t*)0x20000218 = 0;
*(uint64_t*)0x20000220 = 0x40;
*(uint64_t*)0x20000228 = 0;
*(uint32_t*)0x20000230 = 0;
*(uint16_t*)0x20000234 = 0;
*(uint16_t*)0x20000236 = 0x38;
*(uint16_t*)0x20000238 = 0;
*(uint16_t*)0x2000023a = 0;
*(uint16_t*)0x2000023c = 0;
*(uint16_t*)0x2000023e = 0;
*(uint32_t*)0x20000240 = 0;
*(uint32_t*)0x20000244 = 0;
*(uint64_t*)0x20000248 = 0;
*(uint64_t*)0x20000250 = 0;
*(uint64_t*)0x20000258 = 0;
*(uint64_t*)0x20000260 = 0;
*(uint64_t*)0x20000268 = 0;
*(uint64_t*)0x20000270 = 0;
syscall(__NR_write, r[1], 0x20000200ul, 0x78ul);
return 0;
}
|
the_stack_data/647362.c | #include <stdio.h>
int main(void)
{
int num, position, new_num, bit_status;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter bit position: ");
scanf("%d", &position);
/* Right shift num, position times and perform bitwise AND with 1 */
bit_status = (num >> position) & 1;
printf("The %d bit is set to %d\n", position, bit_status);
/* Left shift 1, n times and perform bitwise OR with num */
new_num = ( 1 << position ) | num;
printf("\nBit set successfully.\n\n");
printf("Before: %d\n", num);
printf("After: %d\n", new_num);
return 0;
}
|
the_stack_data/1019303.c | unsigned short read2Target(unsigned char * ptr )
{
if (1 /* targetNotLikeHost */) {
return ((unsigned short )(((int )(*ptr) << 8) + (int )(*(ptr + 1))));
} else {
return ((*((unsigned short *)ptr)));
}
}
int readStructTarget(unsigned char * filePtr ,
unsigned char * fileEnd , ...) {
int x = read2Target(fileEnd);
return x;
}
|
the_stack_data/140250.c | /********************************\
* Return ASCII Number *
* of a characer. *
* *
* Author: @theteachr *
\********************************/
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s [character]\n", argv[0]);
return -1;
}
printf("ord('%c') = %u\n", argv[1][0], argv[1][0]);
return 0;
}
|
the_stack_data/1251768.c | /** @file patest_buffer.c
@ingroup test_src
@brief Test opening streams with different buffer sizes.
@author Phil Burk http://www.softsynth.com
*/
/*
* $Id: patest_buffer.c 1097 2006-08-26 08:27:53Z rossb $
*
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "portaudio.h"
#define NUM_SECONDS (3)
#define SAMPLE_RATE (44100)
#ifndef M_PI
#define M_PI (3.14159265)
#endif
#define TABLE_SIZE (200)
#define BUFFER_TABLE 14
long buffer_table[] = {paFramesPerBufferUnspecified,16,32,64,128,200,256,500,512,600,723,1000,1024,2345};
typedef struct
{
short sine[TABLE_SIZE];
int left_phase;
int right_phase;
unsigned int sampsToGo;
}
paTestData;
PaError TestOnce( int buffersize, PaDeviceIndex );
/* This routine will be called by the PortAudio engine when audio is needed.
** It may called at interrupt level on some machines so don't do anything
** that could mess up the system like calling malloc() or free().
*/
static int patest1Callback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
paTestData *data = (paTestData*)userData;
short *out = (short*)outputBuffer;
unsigned int i;
int finished = 0;
(void) inputBuffer; /* Prevent "unused variable" warnings. */
if( data->sampsToGo < framesPerBuffer )
{
/* final buffer... */
for( i=0; i<data->sampsToGo; i++ )
{
*out++ = data->sine[data->left_phase]; /* left */
*out++ = data->sine[data->right_phase]; /* right */
data->left_phase += 1;
if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE;
data->right_phase += 3; /* higher pitch so we can distinguish left and right. */
if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE;
}
/* zero remainder of final buffer */
for( ; i<framesPerBuffer; i++ )
{
*out++ = 0; /* left */
*out++ = 0; /* right */
}
finished = 1;
}
else
{
for( i=0; i<framesPerBuffer; i++ )
{
*out++ = data->sine[data->left_phase]; /* left */
*out++ = data->sine[data->right_phase]; /* right */
data->left_phase += 1;
if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE;
data->right_phase += 3; /* higher pitch so we can distinguish left and right. */
if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE;
}
data->sampsToGo -= framesPerBuffer;
}
return finished;
}
/*******************************************************************/
int main(int argc, char **args);
int main(int argc, char **args)
{
int i;
int device = -1;
PaError err;
printf("Test opening streams with different buffer sizes\n");
if( argc > 1 ) {
device=atoi( args[1] );
printf("Using device number %d.\n\n", device );
} else {
printf("Using default device.\n\n" );
}
for (i = 0 ; i < BUFFER_TABLE; i++)
{
printf("Buffer size %ld\n", buffer_table[i]);
err = TestOnce(buffer_table[i], device);
if( err < 0 ) return 0;
}
return 0;
}
PaError TestOnce( int buffersize, PaDeviceIndex device )
{
PaStreamParameters outputParameters;
PaStream *stream;
PaError err;
paTestData data;
int i;
int totalSamps;
/* initialise sinusoidal wavetable */
for( i=0; i<TABLE_SIZE; i++ )
{
data.sine[i] = (short) (32767.0 * sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ));
}
data.left_phase = data.right_phase = 0;
data.sampsToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */
err = Pa_Initialize();
if( err != paNoError ) goto error;
if( device == -1 )
outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
else
outputParameters.device = device ;
outputParameters.channelCount = 2; /* stereo output */
outputParameters.sampleFormat = paInt16; /* 32 bit floating point output */
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(
&stream,
NULL, /* no input */
&outputParameters,
SAMPLE_RATE,
buffersize, /* frames per buffer */
(paClipOff | paDitherOff),
patest1Callback,
&data );
if( err != paNoError ) goto error;
err = Pa_StartStream( stream );
if( err != paNoError ) goto error;
printf("Waiting for sound to finish.\n");
Pa_Sleep(1000*NUM_SECONDS);
err = Pa_CloseStream( stream );
if( err != paNoError ) goto error;
Pa_Terminate();
return paNoError;
error:
Pa_Terminate();
fprintf( stderr, "An error occured while using the portaudio stream\n" );
fprintf( stderr, "Error number: %d\n", err );
fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
fprintf( stderr, "Host Error message: %s\n", Pa_GetLastHostErrorInfo()->errorText );
return err;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.