code stringlengths 2 2.01M | language stringclasses 1
value |
|---|---|
/*
* Copyright 2010, Google Inc.
*
* 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.
*/
#ifndef TESSERACT_JNI_COMMON_H
#define TESSERACT_JNI_COMMON_H
#include <jni.h>
#include <android/log.h>
#include <assert.h>
#define LOG_TAG "Tesseract(native)"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__)
#endif
| C |
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<fmemopen>>---open a stream around a fixed-length string
INDEX
fmemopen
ANSI_SYNOPSIS
#include <stdio.h>
FILE *fmemopen(void *restrict <[buf]>, size_t <[size]>,
const char *restrict <[mode]>);
DESCRIPTION
<<fmemopen>> creates a seekable <<FILE>> stream that wraps a
fixed-length buffer of <[size]> bytes starting at <[buf]>. The stream
is opened with <[mode]> treated as in <<fopen>>, where append mode
starts writing at the first NUL byte. If <[buf]> is NULL, then
<[size]> bytes are automatically provided as if by <<malloc>>, with
the initial size of 0, and <[mode]> must contain <<+>> so that data
can be read after it is written.
The stream maintains a current position, which moves according to
bytes read or written, and which can be one past the end of the array.
The stream also maintains a current file size, which is never greater
than <[size]>. If <[mode]> starts with <<r>>, the position starts at
<<0>>, and file size starts at <[size]> if <[buf]> was provided. If
<[mode]> starts with <<w>>, the position and file size start at <<0>>,
and if <[buf]> was provided, the first byte is set to NUL. If
<[mode]> starts with <<a>>, the position and file size start at the
location of the first NUL byte, or else <[size]> if <[buf]> was
provided.
When reading, NUL bytes have no significance, and reads cannot exceed
the current file size. When writing, the file size can increase up to
<[size]> as needed, and NUL bytes may be embedded in the stream (see
<<open_memstream>> for an alternative that automatically enlarges the
buffer). When the stream is flushed or closed after a write that
changed the file size, a NUL byte is written at the current position
if there is still room; if the stream is not also open for reading, a
NUL byte is additionally written at the last byte of <[buf]> when the
stream has exceeded <[size]>, so that a write-only <[buf]> is always
NUL-terminated when the stream is flushed or closed (and the initial
<[size]> should take this into account). It is not possible to seek
outside the bounds of <[size]>. A NUL byte written during a flush is
restored to its previous value when seeking elsewhere in the string.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if <[size]>
is zero or <[mode]> is invalid, ENOMEM if <[buf]> was NULL and memory
could not be allocated, or EMFILE if too many streams are already
open.
PORTABILITY
This function is being added to POSIX 200x, but is not in POSIX 2001.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <malloc.h>
#include "extrastdio.h"
/* Describe details of an open memstream. */
typedef struct fmemcookie {
void *storage; /* storage to free on close */
char *buf; /* buffer start */
size_t pos; /* current position */
size_t eof; /* current file size */
size_t max; /* maximum file size */
char append; /* nonzero if appending */
char writeonly; /* 1 if write-only */
char saved; /* saved character that lived at pos before write-only NUL */
} fmemcookie;
/* Read up to non-zero N bytes into BUF from stream described by
COOKIE; return number of bytes read (0 on EOF). */
static int
fmemread(void *cookie, char *buf, int n)
{
fmemcookie *c = (fmemcookie *) cookie;
/* Can't read beyond current size, but EOF condition is not an error. */
if (c->pos > c->eof)
return 0;
if (n >= c->eof - c->pos)
n = c->eof - c->pos;
memcpy (buf, c->buf + c->pos, n);
c->pos += n;
return n;
}
/* Write up to non-zero N bytes of BUF into the stream described by COOKIE,
returning the number of bytes written or EOF on failure. */
static int
fmemwrite(void *cookie, const char *buf, int n)
{
fmemcookie *c = (fmemcookie *) cookie;
int adjust = 0; /* true if at EOF, but still need to write NUL. */
/* Append always seeks to eof; otherwise, if we have previously done
a seek beyond eof, ensure all intermediate bytes are NUL. */
if (c->append)
c->pos = c->eof;
else if (c->pos > c->eof)
memset (c->buf + c->eof, '\0', c->pos - c->eof);
/* Do not write beyond EOF; saving room for NUL on write-only stream. */
if (c->pos + n > c->max - c->writeonly)
{
adjust = c->writeonly;
n = c->max - c->pos;
}
/* Now n is the number of bytes being modified, and adjust is 1 if
the last byte is NUL instead of from buf. Write a NUL if
write-only; or if read-write, eof changed, and there is still
room. When we are within the file contents, remember what we
overwrite so we can restore it if we seek elsewhere later. */
if (c->pos + n > c->eof)
{
c->eof = c->pos + n;
if (c->eof - adjust < c->max)
c->saved = c->buf[c->eof - adjust] = '\0';
}
else if (c->writeonly)
{
if (n)
{
c->saved = c->buf[c->pos + n - adjust];
c->buf[c->pos + n - adjust] = '\0';
}
else
adjust = 0;
}
c->pos += n;
if (n - adjust)
memcpy (c->buf + c->pos - n, buf, n - adjust);
else
{
return EOF;
}
return n;
}
/* Seek to position POS relative to WHENCE within stream described by
COOKIE; return resulting position or fail with EOF. */
static fpos_t
fmemseek(void *cookie, fpos_t pos, int whence)
{
fmemcookie *c = (fmemcookie *) cookie;
off_t offset = (off_t) pos;
if (whence == SEEK_CUR)
offset += c->pos;
else if (whence == SEEK_END)
offset += c->eof;
if (offset < 0)
{
offset = -1;
}
else if (offset > c->max)
{
offset = -1;
}
else
{
if (c->writeonly && c->pos < c->eof)
{
c->buf[c->pos] = c->saved;
c->saved = '\0';
}
c->pos = offset;
if (c->writeonly && c->pos < c->eof)
{
c->saved = c->buf[c->pos];
c->buf[c->pos] = '\0';
}
}
return (fpos_t) offset;
}
/* Reclaim resources used by stream described by COOKIE. */
static int
fmemclose(void *cookie)
{
fmemcookie *c = (fmemcookie *) cookie;
free (c->storage);
return 0;
}
/* Open a memstream around buffer BUF of SIZE bytes, using MODE.
Return the new stream, or fail with NULL. */
FILE *
fmemopen(void *buf, size_t size, const char *mode)
{
FILE *fp;
fmemcookie *c;
int flags;
int dummy;
if ((flags = __sflags (mode, &dummy)) == 0)
return NULL;
if (!size || !(buf || flags & __SAPP))
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (fmemcookie *) malloc (sizeof *c + (buf ? 0 : size))) == NULL)
{
fp->_flags = 0; /* release */
return NULL;
}
c->storage = c;
c->max = size;
/* 9 modes to worry about. */
/* w/a, buf or no buf: Guarantee a NUL after any file writes. */
c->writeonly = (flags & __SWR) != 0;
c->saved = '\0';
if (!buf)
{
/* r+/w+/a+, and no buf: file starts empty. */
c->buf = (char *) (c + 1);
*(char *) buf = '\0';
c->pos = c->eof = 0;
c->append = (flags & __SAPP) != 0;
}
else
{
c->buf = (char *) buf;
switch (*mode)
{
case 'a':
/* a/a+ and buf: position and size at first NUL. */
buf = memchr (c->buf, '\0', size);
c->eof = c->pos = buf ? (char *) buf - c->buf : size;
if (!buf && c->writeonly)
/* a: guarantee a NUL within size even if no writes. */
c->buf[size - 1] = '\0';
c->append = 1;
break;
case 'r':
/* r/r+ and buf: read at beginning, full size available. */
c->pos = c->append = 0;
c->eof = size;
break;
case 'w':
/* w/w+ and buf: write at beginning, truncate to empty. */
c->pos = c->append = c->eof = 0;
*c->buf = '\0';
break;
default:
abort();
}
}
fp->_file = -1;
fp->_flags = flags;
fp->_cookie = c;
fp->_read = flags & (__SRD | __SRW) ? fmemread : NULL;
fp->_write = flags & (__SWR | __SRW) ? fmemwrite : NULL;
fp->_seek = fmemseek;
fp->_close = fmemclose;
return fp;
}
| C |
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<open_memstream>>---open a write stream around an arbitrary-length string
INDEX
open_memstream
ANSI_SYNOPSIS
#include <stdio.h>
FILE *open_memstream(char **restrict <[buf]>,
size_t *restrict <[size]>);
DESCRIPTION
<<open_memstream>> creates a seekable <<FILE>> stream that wraps an
arbitrary-length buffer, created as if by <<malloc>>. The current
contents of *<[buf]> are ignored; this implementation uses *<[size]>
as a hint of the maximum size expected, but does not fail if the hint
was wrong. The parameters <[buf]> and <[size]> are later stored
through following any call to <<fflush>> or <<fclose>>, set to the
current address and usable size of the allocated string; although
after fflush, the pointer is only valid until another stream operation
that results in a write. Behavior is undefined if the user alters
either *<[buf]> or *<[size]> prior to <<fclose>>.
The stream is write-only, since the user can directly read *<[buf]>
after a flush; see <<fmemopen>> for a way to wrap a string with a
readable stream. The user is responsible for calling <<free>> on
the final *<[buf]> after <<fclose>>.
Any time the stream is flushed, a NUL byte is written at the current
position (but is not counted in the buffer length), so that the string
is always NUL-terminated after at most *<[size]> bytes. However, data
previously written beyond the current stream offset is not lost, and
the NUL byte written during a flush is restored to its previous value
when seeking elsewhere in the string.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if <[buf]>
or <[size]> is NULL, ENOMEM if memory could not be allocated, or
EMFILE if too many streams are already open.
PORTABILITY
This function is being added to POSIX 200x, but is not in POSIX 2001.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <malloc.h>
#include "extrastdio.h"
/* Describe details of an open memstream. */
typedef struct memstream {
void *storage; /* storage to free on close */
char **pbuf; /* pointer to the current buffer */
size_t *psize; /* pointer to the current size, smaller of pos or eof */
size_t pos; /* current position */
size_t eof; /* current file size */
size_t max; /* current malloc buffer size, always > eof */
char saved; /* saved character that lived at *psize before NUL */
} memstream;
/* Write up to non-zero N bytes of BUF into the stream described by COOKIE,
returning the number of bytes written or EOF on failure. */
static int
memwrite(void *cookie, const char *buf, int n)
{
memstream *c = (memstream *) cookie;
char *cbuf = *c->pbuf;
/* size_t is unsigned, but off_t is signed. Don't let stream get so
big that user cannot do ftello. */
if (sizeof (off_t) == sizeof (size_t) && (ssize_t) (c->pos + n) < 0)
{
return EOF;
}
/* Grow the buffer, if necessary. Choose a geometric growth factor
to avoid quadratic realloc behavior, but use a rate less than
(1+sqrt(5))/2 to accomodate malloc overhead. Overallocate, so
that we can add a trailing \0 without reallocating. The new
allocation should thus be max(prev_size*1.5, c->pos+n+1). */
if (c->pos + n >= c->max)
{
size_t newsize = c->max * 3 / 2;
if (newsize < c->pos + n + 1)
newsize = c->pos + n + 1;
cbuf = realloc (cbuf, newsize);
if (! cbuf)
return EOF; /* errno already set to ENOMEM */
*c->pbuf = cbuf;
c->max = newsize;
}
/* If we have previously done a seek beyond eof, ensure all
intermediate bytes are NUL. */
if (c->pos > c->eof)
memset (cbuf + c->eof, '\0', c->pos - c->eof);
memcpy (cbuf + c->pos, buf, n);
c->pos += n;
/* If the user has previously written further, remember what the
trailing NUL is overwriting. Otherwise, extend the stream. */
if (c->pos > c->eof)
c->eof = c->pos;
else
c->saved = cbuf[c->pos];
cbuf[c->pos] = '\0';
*c->psize = c->pos;
return n;
}
/* Seek to position POS relative to WHENCE within stream described by
COOKIE; return resulting position or fail with EOF. */
static fpos_t
memseek(void *cookie, fpos_t pos, int whence)
{
memstream *c = (memstream *) cookie;
off_t offset = (off_t) pos;
if (whence == SEEK_CUR)
offset += c->pos;
else if (whence == SEEK_END)
offset += c->eof;
if (offset < 0)
{
offset = -1;
}
else if ((size_t) offset != offset)
{
offset = -1;
}
else
{
if (c->pos < c->eof)
{
(*c->pbuf)[c->pos] = c->saved;
c->saved = '\0';
}
c->pos = offset;
if (c->pos < c->eof)
{
c->saved = (*c->pbuf)[c->pos];
(*c->pbuf)[c->pos] = '\0';
*c->psize = c->pos;
}
else
*c->psize = c->eof;
}
return (fpos_t) offset;
}
/* Reclaim resources used by stream described by COOKIE. */
static int
memclose(void *cookie)
{
memstream *c = (memstream *) cookie;
char *buf;
/* Be nice and try to reduce any unused memory. */
buf = realloc (*c->pbuf, *c->psize + 1);
if (buf)
*c->pbuf = buf;
free (c->storage);
return 0;
}
/* Open a memstream that tracks a dynamic buffer in BUF and SIZE.
Return the new stream, or fail with NULL. */
FILE *
open_memstream(char **buf, size_t *size)
{
FILE *fp;
memstream *c;
int flags;
if (!buf || !size)
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (memstream *) malloc (sizeof *c)) == NULL)
{
fp->_flags = 0; /* release */
return NULL;
}
/* Use *size as a hint for initial sizing, but bound the initial
malloc between 64 bytes (same as asprintf, to avoid frequent
mallocs on small strings) and 64k bytes (to avoid overusing the
heap if *size was garbage). */
c->max = *size;
if (c->max < 64)
c->max = 64;
else if (c->max > 64 * 1024)
c->max = 64 * 1024;
*size = 0;
*buf = malloc (c->max);
if (!*buf)
{
fp->_flags = 0; /* release */
free (c);
return NULL;
}
**buf = '\0';
c->storage = c;
c->pbuf = buf;
c->psize = size;
c->eof = 0;
c->saved = '\0';
fp->_file = -1;
fp->_flags = __SWR;
fp->_cookie = c;
fp->_read = NULL;
fp->_write = memwrite;
fp->_seek = memseek;
fp->_close = memclose;
return fp;
}
| C |
#ifndef LEPTONICA__STDIO_H
#define LEPTONICA__STDIO_H
#ifndef BUILD_HOST
#include <stdio.h>
#include <stdint.h>
typedef struct cookie_io_functions_t {
ssize_t (*read)(void *cookie, char *buf, size_t n);
ssize_t (*write)(void *cookie, const char *buf, size_t n);
int (*seek)(void *cookie, off_t *pos, int whence);
int (*close)(void *cookie);
} cookie_io_functions_t;
FILE *fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions);
FILE *fmemopen(void *buf, size_t size, const char *mode);
FILE *open_memstream(char **buf, size_t *size);
#endif
#endif /* LEPTONICA__STDIO_H */
| C |
/* Copyright (C) 2007 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*
* Modifications for Android written Jul 2009 by Alan Viverette
*/
/*
FUNCTION
<<fopencookie>>---open a stream with custom callbacks
INDEX
fopencookie
ANSI_SYNOPSIS
#include <stdio.h>
typedef ssize_t (*cookie_read_function_t)(void *_cookie, char *_buf,
size_t _n);
typedef ssize_t (*cookie_write_function_t)(void *_cookie,
const char *_buf, size_t _n);
typedef int (*cookie_seek_function_t)(void *_cookie, off_t *_off,
int _whence);
typedef int (*cookie_close_function_t)(void *_cookie);
FILE *fopencookie(const void *<[cookie]>, const char *<[mode]>,
cookie_io_functions_t <[functions]>);
DESCRIPTION
<<fopencookie>> creates a <<FILE>> stream where I/O is performed using
custom callbacks. The callbacks are registered via the structure:
. typedef struct
. {
. cookie_read_function_t *read;
. cookie_write_function_t *write;
. cookie_seek_function_t *seek;
. cookie_close_function_t *close;
. } cookie_io_functions_t;
The stream is opened with <[mode]> treated as in <<fopen>>. The
callbacks <[functions.read]> and <[functions.write]> may only be NULL
when <[mode]> does not require them.
<[functions.read]> should return -1 on failure, or else the number of
bytes read (0 on EOF). It is similar to <<read>>, except that
<[cookie]> will be passed as the first argument.
<[functions.write]> should return -1 on failure, or else the number of
bytes written. It is similar to <<write>>, except that <[cookie]>
will be passed as the first argument.
<[functions.seek]> should return -1 on failure, and 0 on success, with
*<[_off]> set to the current file position. It is a cross between
<<lseek>> and <<fseek>>, with the <[_whence]> argument interpreted in
the same manner. A NULL <[functions.seek]> makes the stream behave
similarly to a pipe in relation to stdio functions that require
positioning.
<[functions.close]> should return -1 on failure, or 0 on success. It
is similar to <<close>>, except that <[cookie]> will be passed as the
first argument. A NULL <[functions.close]> merely flushes all data
then lets <<fclose>> succeed. A failed close will still invalidate
the stream.
Read and write I/O functions are allowed to change the underlying
buffer on fully buffered or line buffered streams by calling
<<setvbuf>>. They are also not required to completely fill or empty
the buffer. They are not, however, allowed to change streams from
unbuffered to buffered or to change the state of the line buffering
flag. They must also be prepared to have read or write calls occur on
buffers other than the one most recently specified.
RETURNS
The return value is an open FILE pointer on success. On error,
<<NULL>> is returned, and <<errno>> will be set to EINVAL if a
function pointer is missing or <[mode]> is invalid, ENOMEM if the
stream cannot be created, or EMFILE if too many streams are already
open.
PORTABILITY
This function is a newlib extension, copying the prototype from Linux.
It is not portable. See also the <<funopen>> interface from BSD.
Supporting OS subroutines required: <<sbrk>>.
*/
#include <stdio.h>
#include <errno.h>
#include <malloc.h>
#include "extrastdio.h"
typedef struct fccookie {
void *cookie;
FILE *fp;
ssize_t (*readfn)(void *, char *, size_t);
ssize_t (*writefn)(void *, const char *, size_t);
int (*seekfn)(void *, off_t *, int);
int (*closefn)(void *);
} fccookie;
static int
fcread(void *cookie, char *buf, int n)
{
int result;
fccookie *c = (fccookie *) cookie;
result = c->readfn (c->cookie, buf, n);
return result;
}
static int
fcwrite(void *cookie, const char *buf, int n)
{
int result;
fccookie *c = (fccookie *) cookie;
if (c->fp->_flags & __SAPP && c->fp->_seek)
{
c->fp->_seek (cookie, 0, SEEK_END);
}
result = c->writefn (c->cookie, buf, n);
return result;
}
static fpos_t
fcseek(void *cookie, fpos_t pos, int whence)
{
fccookie *c = (fccookie *) cookie;
off_t offset = (off_t) pos;
c->seekfn (c->cookie, &offset, whence);
return (fpos_t) offset;
}
static int
fcclose(void *cookie)
{
int result = 0;
fccookie *c = (fccookie *) cookie;
if (c->closefn)
{
result = c->closefn (c->cookie);
}
free (c);
return result;
}
FILE *
fopencookie(void *cookie, const char *mode, cookie_io_functions_t functions)
{
FILE *fp;
fccookie *c;
int flags;
int dummy;
if ((flags = __sflags (mode, &dummy)) == 0)
return NULL;
if (((flags & (__SRD | __SRW)) && !functions.read)
|| ((flags & (__SWR | __SRW)) && !functions.write))
{
return NULL;
}
if ((fp = (FILE *) __sfp ()) == NULL)
return NULL;
if ((c = (fccookie *) malloc (sizeof *c)) == NULL)
{
fp->_flags = 0;
return NULL;
}
fp->_file = -1;
fp->_flags = flags;
c->cookie = cookie;
c->fp = fp;
fp->_cookie = c;
c->readfn = functions.read;
fp->_read = fcread;
c->writefn = functions.write;
fp->_write = fcwrite;
c->seekfn = functions.seek;
fp->_seek = functions.seek ? fcseek : NULL;
c->closefn = functions.close;
fp->_close = fcclose;
return fp;
}
| C |
/*
* Copyright 2010, Google Inc.
*
* 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.
*/
#ifndef LEPTONICA_JNI_CONFIG_AUTO_H
#define LEPTONICA_JNI_CONFIG_AUTO_H
#define HAVE_LIBJPEG 0
#define HAVE_LIBTIFF 0
#define HAVE_LIBPNG 0
#define HAVE_LIBZ 1
#define HAVE_LIBGIF 0
#define HAVE_LIBUNGIF 0
#define HAVE_FMEMOPEN 1
#endif
| C |
/*
* Copyright 2010, Google Inc.
*
* 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.
*/
#ifndef LEPTONICA_JNI_COMMON_H
#define LEPTONICA_JNI_COMMON_H
#include <jni.h>
#include <assert.h>
#include <allheaders.h>
#include <android/log.h>
#include <asm/byteorder.h>
#ifdef __BIG_ENDIAN
#define SK_A32_SHIFT 0
#define SK_R32_SHIFT 8
#define SK_G32_SHIFT 16
#define SK_B32_SHIFT 24
#else
#define SK_A32_SHIFT 24
#define SK_R32_SHIFT 16
#define SK_G32_SHIFT 8
#define SK_B32_SHIFT 0
#endif /* __BIG_ENDIAN */
#define LOG_TAG "Leptonica(native)"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOG_ASSERT(_cond, ...) if (!_cond) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__)
#endif
| C |
/*
---------------------------------------------------------------------------
Copyright (c) 2003, Dominik Reichl <dominik.reichl@t-online.de>, Germany.
All rights reserved.
Distributed under the terms of the GNU General Public License v2.
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
*/
#ifndef ___CRC32_H___
#define ___CRC32_H___
void crc32Init(unsigned long *pCrc32);
void crc32Update(unsigned long *pCrc32, unsigned char *pData, unsigned long uSize);
void crc32Finish(unsigned long *pCrc32);
#endif /* ___CRC32_H___ */
| C |
/*
___________________________________________________
Opcode Length Disassembler.
Coded By Ms-Rem ( Ms-Rem@yandex.ru ) ICQ 286370715
---------------------------------------------------
12.08.2005 - fixed many bugs...
09.08.2005 - fixed bug with 0F BA opcode.
07.08.2005 - added SSE, SSE2, SSE3 and 3Dnow instruction support.
06.08.2005 - fixed bug with F6 and F7 opcodes.
29.07.2005 - fixed bug with OP_WORD opcodes.
*/
#include "LDasm.h"
#define OP_NONE 0x00
#define OP_MODRM 0x01
#define OP_DATA_I8 0x02
#define OP_DATA_I16 0x04
#define OP_DATA_I32 0x08
#define OP_DATA_PRE66_67 0x10
#define OP_WORD 0x20
#define OP_REL32 0x40
#define UCHAR unsigned char
#define ULONG unsigned long
#define PVOID void*
#define PUCHAR unsigned char*
#define BOOLEAN char
#define FALSE 0
#define TRUE 1
UCHAR OpcodeFlags[256] =
{
OP_MODRM, // 00
OP_MODRM, // 01
OP_MODRM, // 02
OP_MODRM, // 03
OP_DATA_I8, // 04
OP_DATA_PRE66_67, // 05
OP_NONE, // 06
OP_NONE, // 07
OP_MODRM, // 08
OP_MODRM, // 09
OP_MODRM, // 0A
OP_MODRM, // 0B
OP_DATA_I8, // 0C
OP_DATA_PRE66_67, // 0D
OP_NONE, // 0E
OP_NONE, // 0F
OP_MODRM, // 10
OP_MODRM, // 11
OP_MODRM, // 12
OP_MODRM, // 13
OP_DATA_I8, // 14
OP_DATA_PRE66_67, // 15
OP_NONE, // 16
OP_NONE, // 17
OP_MODRM, // 18
OP_MODRM, // 19
OP_MODRM, // 1A
OP_MODRM, // 1B
OP_DATA_I8, // 1C
OP_DATA_PRE66_67, // 1D
OP_NONE, // 1E
OP_NONE, // 1F
OP_MODRM, // 20
OP_MODRM, // 21
OP_MODRM, // 22
OP_MODRM, // 23
OP_DATA_I8, // 24
OP_DATA_PRE66_67, // 25
OP_NONE, // 26
OP_NONE, // 27
OP_MODRM, // 28
OP_MODRM, // 29
OP_MODRM, // 2A
OP_MODRM, // 2B
OP_DATA_I8, // 2C
OP_DATA_PRE66_67, // 2D
OP_NONE, // 2E
OP_NONE, // 2F
OP_MODRM, // 30
OP_MODRM, // 31
OP_MODRM, // 32
OP_MODRM, // 33
OP_DATA_I8, // 34
OP_DATA_PRE66_67, // 35
OP_NONE, // 36
OP_NONE, // 37
OP_MODRM, // 38
OP_MODRM, // 39
OP_MODRM, // 3A
OP_MODRM, // 3B
OP_DATA_I8, // 3C
OP_DATA_PRE66_67, // 3D
OP_NONE, // 3E
OP_NONE, // 3F
OP_NONE, // 40
OP_NONE, // 41
OP_NONE, // 42
OP_NONE, // 43
OP_NONE, // 44
OP_NONE, // 45
OP_NONE, // 46
OP_NONE, // 47
OP_NONE, // 48
OP_NONE, // 49
OP_NONE, // 4A
OP_NONE, // 4B
OP_NONE, // 4C
OP_NONE, // 4D
OP_NONE, // 4E
OP_NONE, // 4F
OP_NONE, // 50
OP_NONE, // 51
OP_NONE, // 52
OP_NONE, // 53
OP_NONE, // 54
OP_NONE, // 55
OP_NONE, // 56
OP_NONE, // 57
OP_NONE, // 58
OP_NONE, // 59
OP_NONE, // 5A
OP_NONE, // 5B
OP_NONE, // 5C
OP_NONE, // 5D
OP_NONE, // 5E
OP_NONE, // 5F
OP_NONE, // 60
OP_NONE, // 61
OP_MODRM, // 62
OP_MODRM, // 63
OP_NONE, // 64
OP_NONE, // 65
OP_NONE, // 66
OP_NONE, // 67
OP_DATA_PRE66_67, // 68
OP_MODRM | OP_DATA_PRE66_67, // 69
OP_DATA_I8, // 6A
OP_MODRM | OP_DATA_I8, // 6B
OP_NONE, // 6C
OP_NONE, // 6D
OP_NONE, // 6E
OP_NONE, // 6F
OP_DATA_I8, // 70
OP_DATA_I8, // 71
OP_DATA_I8, // 72
OP_DATA_I8, // 73
OP_DATA_I8, // 74
OP_DATA_I8, // 75
OP_DATA_I8, // 76
OP_DATA_I8, // 77
OP_DATA_I8, // 78
OP_DATA_I8, // 79
OP_DATA_I8, // 7A
OP_DATA_I8, // 7B
OP_DATA_I8, // 7C
OP_DATA_I8, // 7D
OP_DATA_I8, // 7E
OP_DATA_I8, // 7F
OP_MODRM | OP_DATA_I8, // 80
OP_MODRM | OP_DATA_PRE66_67, // 81
OP_MODRM | OP_DATA_I8, // 82
OP_MODRM | OP_DATA_I8, // 83
OP_MODRM, // 84
OP_MODRM, // 85
OP_MODRM, // 86
OP_MODRM, // 87
OP_MODRM, // 88
OP_MODRM, // 89
OP_MODRM, // 8A
OP_MODRM, // 8B
OP_MODRM, // 8C
OP_MODRM, // 8D
OP_MODRM, // 8E
OP_MODRM, // 8F
OP_NONE, // 90
OP_NONE, // 91
OP_NONE, // 92
OP_NONE, // 93
OP_NONE, // 94
OP_NONE, // 95
OP_NONE, // 96
OP_NONE, // 97
OP_NONE, // 98
OP_NONE, // 99
OP_DATA_I16 | OP_DATA_PRE66_67,// 9A
OP_NONE, // 9B
OP_NONE, // 9C
OP_NONE, // 9D
OP_NONE, // 9E
OP_NONE, // 9F
OP_DATA_PRE66_67, // A0
OP_DATA_PRE66_67, // A1
OP_DATA_PRE66_67, // A2
OP_DATA_PRE66_67, // A3
OP_NONE, // A4
OP_NONE, // A5
OP_NONE, // A6
OP_NONE, // A7
OP_DATA_I8, // A8
OP_DATA_PRE66_67, // A9
OP_NONE, // AA
OP_NONE, // AB
OP_NONE, // AC
OP_NONE, // AD
OP_NONE, // AE
OP_NONE, // AF
OP_DATA_I8, // B0
OP_DATA_I8, // B1
OP_DATA_I8, // B2
OP_DATA_I8, // B3
OP_DATA_I8, // B4
OP_DATA_I8, // B5
OP_DATA_I8, // B6
OP_DATA_I8, // B7
OP_DATA_PRE66_67, // B8
OP_DATA_PRE66_67, // B9
OP_DATA_PRE66_67, // BA
OP_DATA_PRE66_67, // BB
OP_DATA_PRE66_67, // BC
OP_DATA_PRE66_67, // BD
OP_DATA_PRE66_67, // BE
OP_DATA_PRE66_67, // BF
OP_MODRM | OP_DATA_I8, // C0
OP_MODRM | OP_DATA_I8, // C1
OP_DATA_I16, // C2
OP_NONE, // C3
OP_MODRM, // C4
OP_MODRM, // C5
OP_MODRM | OP_DATA_I8, // C6
OP_MODRM | OP_DATA_PRE66_67, // C7
OP_DATA_I8 | OP_DATA_I16, // C8
OP_NONE, // C9
OP_DATA_I16, // CA
OP_NONE, // CB
OP_NONE, // CC
OP_DATA_I8, // CD
OP_NONE, // CE
OP_NONE, // CF
OP_MODRM, // D0
OP_MODRM, // D1
OP_MODRM, // D2
OP_MODRM, // D3
OP_DATA_I8, // D4
OP_DATA_I8, // D5
OP_NONE, // D6
OP_NONE, // D7
OP_WORD, // D8
OP_WORD, // D9
OP_WORD, // DA
OP_WORD, // DB
OP_WORD, // DC
OP_WORD, // DD
OP_WORD, // DE
OP_WORD, // DF
OP_DATA_I8, // E0
OP_DATA_I8, // E1
OP_DATA_I8, // E2
OP_DATA_I8, // E3
OP_DATA_I8, // E4
OP_DATA_I8, // E5
OP_DATA_I8, // E6
OP_DATA_I8, // E7
OP_DATA_PRE66_67 | OP_REL32, // E8
OP_DATA_PRE66_67 | OP_REL32, // E9
OP_DATA_I16 | OP_DATA_PRE66_67,// EA
OP_DATA_I8, // EB
OP_NONE, // EC
OP_NONE, // ED
OP_NONE, // EE
OP_NONE, // EF
OP_NONE, // F0
OP_NONE, // F1
OP_NONE, // F2
OP_NONE, // F3
OP_NONE, // F4
OP_NONE, // F5
OP_MODRM, // F6
OP_MODRM, // F7
OP_NONE, // F8
OP_NONE, // F9
OP_NONE, // FA
OP_NONE, // FB
OP_NONE, // FC
OP_NONE, // FD
OP_MODRM, // FE
OP_MODRM | OP_REL32 // FF
};
UCHAR OpcodeFlagsExt[256] =
{
OP_MODRM, // 00
OP_MODRM, // 01
OP_MODRM, // 02
OP_MODRM, // 03
OP_NONE, // 04
OP_NONE, // 05
OP_NONE, // 06
OP_NONE, // 07
OP_NONE, // 08
OP_NONE, // 09
OP_NONE, // 0A
OP_NONE, // 0B
OP_NONE, // 0C
OP_MODRM, // 0D
OP_NONE, // 0E
OP_MODRM | OP_DATA_I8, // 0F
OP_MODRM, // 10
OP_MODRM, // 11
OP_MODRM, // 12
OP_MODRM, // 13
OP_MODRM, // 14
OP_MODRM, // 15
OP_MODRM, // 16
OP_MODRM, // 17
OP_MODRM, // 18
OP_NONE, // 19
OP_NONE, // 1A
OP_NONE, // 1B
OP_NONE, // 1C
OP_NONE, // 1D
OP_NONE, // 1E
OP_NONE, // 1F
OP_MODRM, // 20
OP_MODRM, // 21
OP_MODRM, // 22
OP_MODRM, // 23
OP_MODRM, // 24
OP_NONE, // 25
OP_MODRM, // 26
OP_NONE, // 27
OP_MODRM, // 28
OP_MODRM, // 29
OP_MODRM, // 2A
OP_MODRM, // 2B
OP_MODRM, // 2C
OP_MODRM, // 2D
OP_MODRM, // 2E
OP_MODRM, // 2F
OP_NONE, // 30
OP_NONE, // 31
OP_NONE, // 32
OP_NONE, // 33
OP_NONE, // 34
OP_NONE, // 35
OP_NONE, // 36
OP_NONE, // 37
OP_NONE, // 38
OP_NONE, // 39
OP_NONE, // 3A
OP_NONE, // 3B
OP_NONE, // 3C
OP_NONE, // 3D
OP_NONE, // 3E
OP_NONE, // 3F
OP_MODRM, // 40
OP_MODRM, // 41
OP_MODRM, // 42
OP_MODRM, // 43
OP_MODRM, // 44
OP_MODRM, // 45
OP_MODRM, // 46
OP_MODRM, // 47
OP_MODRM, // 48
OP_MODRM, // 49
OP_MODRM, // 4A
OP_MODRM, // 4B
OP_MODRM, // 4C
OP_MODRM, // 4D
OP_MODRM, // 4E
OP_MODRM, // 4F
OP_MODRM, // 50
OP_MODRM, // 51
OP_MODRM, // 52
OP_MODRM, // 53
OP_MODRM, // 54
OP_MODRM, // 55
OP_MODRM, // 56
OP_MODRM, // 57
OP_MODRM, // 58
OP_MODRM, // 59
OP_MODRM, // 5A
OP_MODRM, // 5B
OP_MODRM, // 5C
OP_MODRM, // 5D
OP_MODRM, // 5E
OP_MODRM, // 5F
OP_MODRM, // 60
OP_MODRM, // 61
OP_MODRM, // 62
OP_MODRM, // 63
OP_MODRM, // 64
OP_MODRM, // 65
OP_MODRM, // 66
OP_MODRM, // 67
OP_MODRM, // 68
OP_MODRM, // 69
OP_MODRM, // 6A
OP_MODRM, // 6B
OP_MODRM, // 6C
OP_MODRM, // 6D
OP_MODRM, // 6E
OP_MODRM, // 6F
OP_MODRM | OP_DATA_I8, // 70
OP_MODRM | OP_DATA_I8, // 71
OP_MODRM | OP_DATA_I8, // 72
OP_MODRM | OP_DATA_I8, // 73
OP_MODRM, // 74
OP_MODRM, // 75
OP_MODRM, // 76
OP_NONE, // 77
OP_NONE, // 78
OP_NONE, // 79
OP_NONE, // 7A
OP_NONE, // 7B
OP_MODRM, // 7C
OP_MODRM, // 7D
OP_MODRM, // 7E
OP_MODRM, // 7F
OP_DATA_PRE66_67 | OP_REL32, // 80
OP_DATA_PRE66_67 | OP_REL32, // 81
OP_DATA_PRE66_67 | OP_REL32, // 82
OP_DATA_PRE66_67 | OP_REL32, // 83
OP_DATA_PRE66_67 | OP_REL32, // 84
OP_DATA_PRE66_67 | OP_REL32, // 85
OP_DATA_PRE66_67 | OP_REL32, // 86
OP_DATA_PRE66_67 | OP_REL32, // 87
OP_DATA_PRE66_67 | OP_REL32, // 88
OP_DATA_PRE66_67 | OP_REL32, // 89
OP_DATA_PRE66_67 | OP_REL32, // 8A
OP_DATA_PRE66_67 | OP_REL32, // 8B
OP_DATA_PRE66_67 | OP_REL32, // 8C
OP_DATA_PRE66_67 | OP_REL32, // 8D
OP_DATA_PRE66_67 | OP_REL32, // 8E
OP_DATA_PRE66_67 | OP_REL32, // 8F
OP_MODRM, // 90
OP_MODRM, // 91
OP_MODRM, // 92
OP_MODRM, // 93
OP_MODRM, // 94
OP_MODRM, // 95
OP_MODRM, // 96
OP_MODRM, // 97
OP_MODRM, // 98
OP_MODRM, // 99
OP_MODRM, // 9A
OP_MODRM, // 9B
OP_MODRM, // 9C
OP_MODRM, // 9D
OP_MODRM, // 9E
OP_MODRM, // 9F
OP_NONE, // A0
OP_NONE, // A1
OP_NONE, // A2
OP_MODRM, // A3
OP_MODRM | OP_DATA_I8, // A4
OP_MODRM, // A5
OP_NONE, // A6
OP_NONE, // A7
OP_NONE, // A8
OP_NONE, // A9
OP_NONE, // AA
OP_MODRM, // AB
OP_MODRM | OP_DATA_I8, // AC
OP_MODRM, // AD
OP_MODRM, // AE
OP_MODRM, // AF
OP_MODRM, // B0
OP_MODRM, // B1
OP_MODRM, // B2
OP_MODRM, // B3
OP_MODRM, // B4
OP_MODRM, // B5
OP_MODRM, // B6
OP_MODRM, // B7
OP_NONE, // B8
OP_NONE, // B9
OP_MODRM | OP_DATA_I8, // BA
OP_MODRM, // BB
OP_MODRM, // BC
OP_MODRM, // BD
OP_MODRM, // BE
OP_MODRM, // BF
OP_MODRM, // C0
OP_MODRM, // C1
OP_MODRM | OP_DATA_I8, // C2
OP_MODRM, // C3
OP_MODRM | OP_DATA_I8, // C4
OP_MODRM | OP_DATA_I8, // C5
OP_MODRM | OP_DATA_I8, // C6
OP_MODRM, // C7
OP_NONE, // C8
OP_NONE, // C9
OP_NONE, // CA
OP_NONE, // CB
OP_NONE, // CC
OP_NONE, // CD
OP_NONE, // CE
OP_NONE, // CF
OP_MODRM, // D0
OP_MODRM, // D1
OP_MODRM, // D2
OP_MODRM, // D3
OP_MODRM, // D4
OP_MODRM, // D5
OP_MODRM, // D6
OP_MODRM, // D7
OP_MODRM, // D8
OP_MODRM, // D9
OP_MODRM, // DA
OP_MODRM, // DB
OP_MODRM, // DC
OP_MODRM, // DD
OP_MODRM, // DE
OP_MODRM, // DF
OP_MODRM, // E0
OP_MODRM, // E1
OP_MODRM, // E2
OP_MODRM, // E3
OP_MODRM, // E4
OP_MODRM, // E5
OP_MODRM, // E6
OP_MODRM, // E7
OP_MODRM, // E8
OP_MODRM, // E9
OP_MODRM, // EA
OP_MODRM, // EB
OP_MODRM, // EC
OP_MODRM, // ED
OP_MODRM, // EE
OP_MODRM, // EF
OP_MODRM, // F0
OP_MODRM, // F1
OP_MODRM, // F2
OP_MODRM, // F3
OP_MODRM, // F4
OP_MODRM, // F5
OP_MODRM, // F6
OP_MODRM, // F7
OP_MODRM, // F8
OP_MODRM, // F9
OP_MODRM, // FA
OP_MODRM, // FB
OP_MODRM, // FC
OP_MODRM, // FD
OP_MODRM, // FE
OP_NONE // FF
};
unsigned long __fastcall SizeOfCode(void *Code, unsigned char **pOpcode)
{
PUCHAR cPtr;
UCHAR Flags;
BOOLEAN PFX66, PFX67;
BOOLEAN SibPresent;
UCHAR iMod, iRM, iReg;
UCHAR OffsetSize, Add;
UCHAR Opcode;
OffsetSize = 0;
PFX66 = FALSE;
PFX67 = FALSE;
cPtr = (PUCHAR)Code;
while ( (*cPtr == 0x2E) || (*cPtr == 0x3E) || (*cPtr == 0x36) ||
(*cPtr == 0x26) || (*cPtr == 0x64) || (*cPtr == 0x65) ||
(*cPtr == 0xF0) || (*cPtr == 0xF2) || (*cPtr == 0xF3) ||
(*cPtr == 0x66) || (*cPtr == 0x67) )
{
if (*cPtr == 0x66) PFX66 = TRUE;
if (*cPtr == 0x67) PFX67 = TRUE;
cPtr++;
if (cPtr > (PUCHAR)Code + 16) return 0;
}
Opcode = *cPtr;
if (pOpcode) *pOpcode = cPtr;
if (*cPtr == 0x0F)
{
cPtr++;
Flags = OpcodeFlagsExt[*cPtr];
} else
{
Flags = OpcodeFlags[Opcode];
if (Opcode >= 0xA0 && Opcode <= 0xA3) PFX66 = !PFX66;
}
cPtr++;
if (Flags & OP_WORD)cPtr++;
if (Flags & OP_MODRM)
{
iMod = *cPtr >> 6;
iReg = (*cPtr & 0x38) >> 3;
iRM = *cPtr & 7;
cPtr++;
if ((Opcode == 0xF6) && !iReg) Flags |= OP_DATA_I8;
if ((Opcode == 0xF7) && !iReg) Flags |= OP_DATA_PRE66_67;
SibPresent = !PFX67 & (iRM == 4);
switch (iMod)
{
case 0:
if ( PFX67 && (iRM == 6)) OffsetSize = 2;
if (!PFX67 && (iRM == 5)) OffsetSize = 4;
break;
case 1: OffsetSize = 1;
break;
case 2: if (PFX67) OffsetSize = 2; else OffsetSize = 4;
break;
case 3: SibPresent = FALSE;
}
if (SibPresent)
{
if (((*cPtr & 7) == 5) && ( (!iMod) || (iMod == 2) )) OffsetSize = 4;
cPtr++;
}
cPtr = (PUCHAR)(ULONG)cPtr + OffsetSize;
}
if (Flags & OP_DATA_I8) cPtr++;
if (Flags & OP_DATA_I16) cPtr += 2;
if (Flags & OP_DATA_I32) cPtr += 4;
if (PFX66) Add = 2; else Add = 4;
if (Flags & OP_DATA_PRE66_67) cPtr += Add;
return (ULONG)cPtr - (ULONG)Code;
}
unsigned long __fastcall SizeOfProc(void *Proc)
{
ULONG Length;
PUCHAR pOpcode;
ULONG Result = 0;
do
{
Length = SizeOfCode(Proc, &pOpcode);
Result += Length;
if ((Length == 1) && (*pOpcode == 0xC3)) break;
Proc = (PVOID)((ULONG)Proc + Length);
} while (Length);
return Result;
}
char __fastcall IsRelativeCmd(unsigned char *pOpcode)
{
UCHAR Flags;
if (*pOpcode == 0x0F) Flags = OpcodeFlagsExt[*(PUCHAR)((ULONG)pOpcode + 1)];
else Flags = OpcodeFlags[*pOpcode];
return (Flags & OP_REL32);
} | C |
#ifndef _LDASM_
#define _LDASM_
#ifdef __cplusplus
extern "C" {
#endif
unsigned long __fastcall SizeOfCode(void *Code, unsigned char **pOpcode);
unsigned long __fastcall SizeOfProc(void *Proc);
char __fastcall IsRelativeCmd(unsigned char *pOpcode);
#ifdef __cplusplus
}
#endif
#endif | C |
#ifndef __NONAME_UNDOCUMENT_H__
#define __NONAME_UNDOCUMENT_H__
#include <ntifs.h>
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0
typedef struct _IMAGE_EXPORT_DIRECTORY {
ULONG Characteristics;
ULONG TimeDateStamp;
USHORT MajorVersion;
USHORT MinorVersion;
ULONG Name;
ULONG Base;
ULONG NumberOfFunctions;
ULONG NumberOfNames;
ULONG AddressOfFunctions; // RVA from base of image
ULONG AddressOfNames; // RVA from base of image
ULONG AddressOfNameOrdinals; // RVA from base of image
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;
typedef struct _NON_PAGED_DEBUG_INFO {
USHORT Signature;
USHORT Flags;
ULONG Size;
USHORT Machine;
USHORT Characteristics;
ULONG TimeDateStamp;
ULONG CheckSum;
ULONG SizeOfImage;
ULONGLONG ImageBase;
} NON_PAGED_DEBUG_INFO, *PNON_PAGED_DEBUG_INFO;
typedef struct _KLDR_DATA_TABLE_ENTRY {
LIST_ENTRY InLoadOrderLinks;
PVOID ExceptionTable;
ULONG ExceptionTableSize;
// ULONG padding on IA64
PVOID GpValue;
PNON_PAGED_DEBUG_INFO NonPagedDebugInfo;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT __Unused5;
PVOID SectionPointer;
ULONG CheckSum;
// ULONG padding on IA64
PVOID LoadedImports;
PVOID PatchInformation;
} KLDR_DATA_TABLE_ENTRY, *PKLDR_DATA_TABLE_ENTRY;
#ifdef __cplusplus
extern "C" {
#endif
NTKERNELAPI
NTSTATUS
KeSetAffinityThread(
PKTHREAD Thread,
KAFFINITY Affinity
);
NTKERNELAPI
PVOID
RtlImageDirectoryEntryToData (
IN PVOID Base,
IN BOOLEAN MappedAsImage,
IN USHORT DirectoryEntry,
OUT PULONG Size
);
#ifdef __cplusplus
};
#endif
#endif | C |
#ifndef __SECTOR_MON_H__
#define __SECTOR_MON_H__
#include <ntifs.h>
#include <Ntddvol.h>
#define DEVICE_TYPE_CTRL 0
#define DEVICE_TYPE_FILTER 1
typedef struct _DISK_FLT_DEVICE_EXT {
ULONG DeviceType;
PDEVICE_OBJECT FilterDeviceObject;
PDEVICE_OBJECT LowerDeviceObject;
PDEVICE_OBJECT PhysicalDeviceObject;
LIST_ENTRY ReqList;
KSPIN_LOCK ReqLock;
KEVENT ReqEvent;
BOOLEAN ThreadFlag;
PETHREAD ThreadObject;
PAGED_LOOKASIDE_LIST WriteElemHeader;
PAGED_LOOKASIDE_LIST SectorBufHeader;
} DISK_FLT_DEVICE_EXT, *PDISK_FLT_DEVICE_EXT;
typedef struct _WRITE_ELEMENT {
LIST_ENTRY ListEntry;
HANDLE File;
PVOID Buffer;
ULONG Length;
LARGE_INTEGER Offset;
BOOLEAN NeedFree;
ULONG Tag;
} WRITE_ELEMENT, *PWRITE_ELEMENT;
typedef struct _GLOBAL_CONTEXT {
HANDLE FileHandle;
PVOID MapBuffer;
ULONG MapSize;
HANDLE SparseFileHandle;
} GLOBAL_CONTEXT, *PGLOBAL_CONTEXT;
#pragma pack(push, 1)
typedef struct _NTFS_BPB {
USHORT BytesPerSector;
UCHAR SectorsPerCluster;
USHORT ReservedSectors;
UCHAR NumberOfFATs; // always 0
USHORT RootEntries; // always 0
USHORT SmallSectors; // not used by NTFS
UCHAR MediaDescriptor;
USHORT SectorsPerFAT; // always 0
USHORT SectorsPerTrack;
USHORT NumberOfHeads;
ULONG HiddenSectors;
ULONG LargeSectors; // not used by NTFS
} NTFS_BPB, *PNTFS_BPB;
typedef struct _NTFS_EXBPB { // Extended BIOS parameter block for FAT16
ULONG Reserved; // not used by NTFS
ULONGLONG TotalSectors;
ULONGLONG MFT;
ULONGLONG MFTMirr;
ULONG ClustersPerFileRecordSegment;
ULONG ClustersPerIndexBlock;
ULONGLONG VolumeSerialNumber;
ULONG Checksum;
} NTFS_EXBPB, *PNTFS_EXBPB;
typedef struct _NTFS_BOOT_SEC {
UCHAR JumpInstruction[3];
UCHAR OemID[8];
NTFS_BPB Bpb;
NTFS_EXBPB ExBpb;
UCHAR BootstrapCode[426];
UCHAR EndOfSector[2];
} NTFS_BOOT_SEC, *PNTFS_BOOT_SEC;
#pragma pack(pop)
#define DIRECT_READ 0
#define DIRECT_WRITE 1
#define BITOFF_TO_MAPOFF(off) (ULONG)(off >> 3)
#define BITLEN_TO_MAPLEN(off, len) ((ULONG)((off + len) >> 3) - BITOFF_TO_MAPOFF(off) + 1)
#define BYTEOFF_TO_BITOFF(off) (off / BytesPerSector)
#define BYTELEN_TO_BITLEN(len) (len / BytesPerSector)
NTSTATUS SkipAndCallDriver( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS SyncIrpCompletionRoutine( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PVOID Context );
NTSTATUS SendSyncIrp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DispatchPassThrough( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DispatchPower( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DispatchPnp( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DispatchReadWrite( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DispatchDeviceControl( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp );
NTSTATUS DirectReadWrite( __in PDEVICE_OBJECT DeviceObject, __in ULONG ReadWrite, __out PVOID Buffer, __in PLARGE_INTEGER Offset, __in ULONG Length );
LONGLONG GetFileSize( __in HANDLE Handle );
BOOLEAN __fastcall SetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit );
BOOLEAN __fastcall ClearBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit );
ULONG __fastcall GetBit( __in PUCHAR BitBuf, __in ULONG BitSize, __in ULONGLONG Bit );
NTSTATUS OpenMapping( __in PWCHAR Name, __out PHANDLE File, __out PVOID *Buffer, __out ULONG *BufferSize );
VOID CloseMapping( __in HANDLE File, __in PVOID Buffer );
NTSTATUS CreateSparseFile( __out PHANDLE Handle, __in PWCHAR FileName, __in ULONGLONG FileSize, __in BOOLEAN Restore );
NTSTATUS AddDevice( __in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject );
VOID Unload( __in PDRIVER_OBJECT DriverObject );
VOID ReinitializationRoutine( __in PDRIVER_OBJECT DriverObject, __in PVOID Context, __in ULONG Count );
NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath );
NTSTATUS FlushBuffer( __in PDISK_FLT_DEVICE_EXT DevExt, __in HANDLE File, __in PVOID Buffer, __in ULONG Offset, __in ULONG Size );
NTSTATUS __fastcall BackupSectorAndSetBit( __in PDEVICE_OBJECT PhysicalDeviceObject, __in HANDLE File, __in PLARGE_INTEGER Offset, __in ULONG Length, __in PDISK_FLT_DEVICE_EXT DevExt );
VOID WriteWorkThread( __in PVOID Context );
NTSTATUS RestoreDisk( __in PDISK_FLT_DEVICE_EXT DevExt );
BOOLEAN IsRestoreDisk();
#endif | C |
#include "SectorMon.h"
BOOLEAN StartFilter = FALSE;
BOOLEAN InitFilter = FALSE;
NTFS_BOOT_SEC BootSec;
GLOBAL_CONTEXT GlobalContext = {0};
USHORT BytesPerSector = 512;
NTSTATUS
RecoverBootStatus()
{
NTSTATUS ns;
HANDLE FileHandle;
OBJECT_ATTRIBUTES oa;
IO_STATUS_BLOCK Iob;
LARGE_INTEGER Offset = {0};
UCHAR Buffer[16];
DECLARE_CONST_UNICODE_STRING(FileName, L"\\??\\C:\\Windows\\bootstat.dat");
InitializeObjectAttributes(&oa, (PUNICODE_STRING)&FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
ns = ZwCreateFile(&FileHandle,
FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE,
&oa,
&Iob,
NULL,
0,
FILE_SHARE_READ,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
if (!NT_SUCCESS(ns)) {
return ns;
}
ns = ZwReadFile(FileHandle,
NULL,
NULL,
NULL,
&Iob,
Buffer,
16,
&Offset,
NULL);
if (!NT_SUCCESS(ns)) {
ZwClose(FileHandle);
return ns;
}
if (Buffer[10] == 0) {
Buffer[10] = 1;
}
ns = ZwWriteFile(FileHandle,
NULL,
NULL,
NULL,
&Iob,
Buffer,
16,
&Offset,
NULL);
ZwClose(FileHandle);
return ns;
}
BOOLEAN
IsRestoreDisk()
{
NTSTATUS ns;
UNICODE_STRING SecMonName;
UNICODE_STRING RestoreDiskName;
OBJECT_ATTRIBUTES oa;
HANDLE SecMonHandle;
UCHAR ValueBuffer[128];
ULONG RetLength;
PKEY_VALUE_PARTIAL_INFORMATION Value = (PKEY_VALUE_PARTIAL_INFORMATION)ValueBuffer;
RtlInitUnicodeString(&SecMonName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\SecMon");
InitializeObjectAttributes(&oa,
&SecMonName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
ns = ZwOpenKey(&SecMonHandle,
KEY_READ,
&oa);
if (!NT_SUCCESS(ns)) {
return FALSE;
}
RtlInitUnicodeString(&RestoreDiskName, L"Current");
ns = ZwQueryValueKey(SecMonHandle,
&RestoreDiskName,
KeyValuePartialInformation,
ValueBuffer,
sizeof(ValueBuffer),
&RetLength);
ZwClose(SecMonHandle);
if (!NT_SUCCESS(ns)) {
return FALSE;
}
if (*((ULONG *)Value->Data) == 0) {
return FALSE;
}
return TRUE;
}
NTSTATUS
RestoreDisk(
__in PDISK_FLT_DEVICE_EXT DevExt
)
{
ULONGLONG BitCount;
PVOID BitBuf = GlobalContext.MapBuffer;
ULONG BitSize = GlobalContext.MapSize;
LARGE_INTEGER Offset;
ULONGLONG i;
LONG Ret;
PVOID SectorBuf;
NTSTATUS ns = STATUS_SUCCESS;
IO_STATUS_BLOCK Iob;
HANDLE FileHandle = GlobalContext.SparseFileHandle;
PDEVICE_OBJECT PhyDevObj = DevExt->PhysicalDeviceObject;
FILE_DISPOSITION_INFORMATION FileDisInfo;
LARGE_INTEGER Mm3Second = {(ULONG)(-3 * 1000 * 1000 * 10), -1};
BitCount = BitSize << 3;
SectorBuf = ExAllocatePoolWithTag(PagedPool, BytesPerSector, 'rsdk');
for (i = 0; i < BitCount; i++) {
if (i % 0x1000 == 0) {
KdPrint(("Per : %I64d / %I64d\n", i, BitCount));
}
Ret = GetBit(BitBuf, BitSize, i);
ASSERT(Ret != -1);
if (Ret == -1) {
ns = STATUS_UNSUCCESSFUL;
break;
}
else if (Ret == 1) {
Offset.QuadPart = i * BytesPerSector;
ns = ZwReadFile(FileHandle,
NULL,
NULL,
NULL,
&Iob,
SectorBuf,
BytesPerSector,
&Offset,
NULL);
ASSERT(NT_SUCCESS(ns));
if (!NT_SUCCESS(ns)) {
break;
}
ns = DirectReadWrite(PhyDevObj,
DIRECT_WRITE,
SectorBuf,
&Offset,
BytesPerSector);
ASSERT(NT_SUCCESS(ns));
if (!NT_SUCCESS(ns)) {
break;
}
}
}
ExFreePoolWithTag(SectorBuf, 'rsdk');
if (!NT_SUCCESS(ns)) {
return ns;
}
Offset.QuadPart = 0;
RtlZeroMemory(BitBuf, BitSize);
ns = ZwWriteFile(GlobalContext.FileHandle,
NULL,
NULL,
NULL,
&Iob,
BitBuf,
BitSize,
&Offset,
NULL);
if (!NT_SUCCESS(ns)) {
return ns;
}
FileDisInfo.DeleteFile = TRUE;
ns = ZwSetInformationFile(FileHandle,
&Iob,
&FileDisInfo,
sizeof(FILE_DISPOSITION_INFORMATION),
FileDispositionInformation);
if (!NT_SUCCESS(ns)) {
return ns;
}
ZwClose(FileHandle);
ns = RecoverBootStatus();
KeDelayExecutionThread(KernelMode, FALSE, &Mm3Second);
KeBugCheck(POWER_FAILURE_SIMULATE);
}
VOID
WriteWorkThread(
__in PVOID Context
)
{
PWRITE_ELEMENT ReqEntry = NULL;
PDISK_FLT_DEVICE_EXT DevExt = (PDISK_FLT_DEVICE_EXT)Context;
IO_STATUS_BLOCK Iob;
KeSetPriorityThread(KeGetCurrentThread(), LOW_REALTIME_PRIORITY);
for(;;) {
KeWaitForSingleObject(
&DevExt->ReqEvent,
Executive,
KernelMode,
FALSE,
NULL
);
if (DevExt->ThreadFlag) {
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
while ((ReqEntry = (PWRITE_ELEMENT)ExInterlockedRemoveHeadList(&DevExt->ReqList,
&DevExt->ReqLock)) != NULL) {
ZwWriteFile(ReqEntry->File,
NULL,
NULL,
NULL,
&Iob,
ReqEntry->Buffer,
ReqEntry->Length,
&ReqEntry->Offset,
NULL);
if (ReqEntry->NeedFree) {
ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, ReqEntry->Buffer);
}
ExFreeToPagedLookasideList(&DevExt->WriteElemHeader, ReqEntry);
}
}
}
NTSTATUS
SkipAndCallDriver(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
IoSkipCurrentIrpStackLocation(Irp);
return IoCallDriver(DeviceObject, Irp);
}
NTSTATUS
SyncIrpCompletionRoutine(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp,
__in PVOID Context
)
{
PKEVENT Event = (PKEVENT) Context;
UNREFERENCED_PARAMETER(DeviceObject);
if (Irp->PendingReturned) {
KeSetEvent(Event, IO_NO_INCREMENT, FALSE);
}
return STATUS_MORE_PROCESSING_REQUIRED;
}
NTSTATUS
SendSyncIrp(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
KEVENT Event;
NTSTATUS ns;
KeInitializeEvent(&Event, NotificationEvent, FALSE);
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(
Irp,
SyncIrpCompletionRoutine,
&Event,
TRUE,
TRUE,
TRUE);
ns = IoCallDriver(DeviceObject, Irp);
if (ns == STATUS_PENDING) {
KeWaitForSingleObject(
&Event,
Executive,
KernelMode,
FALSE,
NULL);
ns = Irp->IoStatus.Status;
}
return ns;
}
NTSTATUS
DispatchPassThrough(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension;
return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
}
NTSTATUS
DispatchPower(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension;
#if (NTDDI_VERSION < NTDDI_VISTA)
PoStartNextPowerIrp(Irp);
IoSkipCurrentIrpStackLocation(Irp);
return PoCallDriver(DevExt->LowerDeviceObject, Irp);
#else
return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
#endif
}
NTSTATUS
DispatchPnp(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension;
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS ns;
switch (IrpSp->MinorFunction) {
case IRP_MN_REMOVE_DEVICE:
{
StartFilter = FALSE;
if (DevExt->LowerDeviceObject != NULL) {
IoDetachDevice(DevExt->LowerDeviceObject);
DevExt->LowerDeviceObject = NULL;
}
if (DevExt->ThreadObject != NULL && DevExt->ThreadFlag != TRUE) {
DevExt->ThreadFlag = TRUE;
KeSetEvent(&DevExt->ReqEvent,
(KPRIORITY)0,
FALSE);
KeWaitForSingleObject(
DevExt->ThreadObject,
Executive,
KernelMode,
FALSE,
NULL
);
ObDereferenceObject(DevExt->ThreadObject);
DevExt->ThreadObject = NULL;
}
ExDeletePagedLookasideList(&DevExt->SectorBufHeader);
ExDeletePagedLookasideList(&DevExt->WriteElemHeader);
if (DevExt->FilterDeviceObject != NULL) {
IoDeleteDevice(DevExt->FilterDeviceObject);
}
if (GlobalContext.FileHandle != NULL) {
CloseMapping(GlobalContext.FileHandle,
GlobalContext.MapBuffer);
GlobalContext.FileHandle = NULL;
}
if (GlobalContext.SparseFileHandle != NULL) {
ZwClose(GlobalContext.SparseFileHandle);
GlobalContext.SparseFileHandle = NULL;
}
}
break;
case IRP_MN_DEVICE_USAGE_NOTIFICATION:
{
if (IrpSp->Parameters.UsageNotification.Type != DeviceUsageTypePaging) {
ns = SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
return ns;
}
ns = SendSyncIrp(DevExt->LowerDeviceObject, Irp);
if (NT_SUCCESS(ns)) {
if (DevExt->LowerDeviceObject->Flags & DO_POWER_PAGABLE) {
DeviceObject->Flags |= DO_POWER_PAGABLE;
}
else {
DeviceObject->Flags &= ~DO_POWER_PAGABLE;
}
}
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return ns;
}
break;
default:
break;
}
return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
}
NTSTATUS
DispatchReadWrite(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension;
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS ns;
if (StartFilter && InitFilter) {
if (IrpSp->MajorFunction == IRP_MJ_READ) {
// KdPrint(("Read Offset:%016I64X Length:%08X\n",
// IrpSp->Parameters.Read.ByteOffset.QuadPart,
// IrpSp->Parameters.Read.Length));
}
else {
// KdPrint(("Write Offset:%016I64X Length:%08X\n",
// IrpSp->Parameters.Write.ByteOffset.QuadPart,
// IrpSp->Parameters.Write.Length));
ns = BackupSectorAndSetBit(DevExt->PhysicalDeviceObject,
GlobalContext.SparseFileHandle,
&IrpSp->Parameters.Write.ByteOffset,
IrpSp->Parameters.Write.Length,
DevExt);
if (!NT_SUCCESS(ns)) {
KdPrint(("[FAILED] Write Offset:%016I64X Length:%08X\n",
IrpSp->Parameters.Write.ByteOffset.QuadPart,
IrpSp->Parameters.Write.Length));
}
}
}
return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
}
NTSTATUS
DispatchDeviceControl(
__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp
)
{
PDISK_FLT_DEVICE_EXT DevExt = DeviceObject->DeviceExtension;
NTSTATUS ns;
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);
KEVENT Event;
PIRP SynIrp;
UCHAR DBR[512];
ULONG DBRLength = 512;
IO_STATUS_BLOCK Iob;
LARGE_INTEGER ReadOffset = {0};
switch (IrpSp->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_VOLUME_ONLINE:
{
KeInitializeEvent(&Event, NotificationEvent, FALSE);
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(Irp,
SyncIrpCompletionRoutine,
&Event,
TRUE,
TRUE,
TRUE);
ns = IoCallDriver(DevExt->LowerDeviceObject, Irp);
if (ns == STATUS_PENDING) {
KeWaitForSingleObject(&Event,
Executive,
KernelMode,
FALSE,
NULL);
}
KeClearEvent(&Event);
SynIrp = IoBuildAsynchronousFsdRequest(IRP_MJ_READ,
DevExt->PhysicalDeviceObject,
DBR,
DBRLength,
&ReadOffset,
&Iob);
if (SynIrp != NULL) {
IoSetCompletionRoutine(SynIrp,
SyncIrpCompletionRoutine,
&Event,
TRUE,
TRUE,
TRUE);
ns = IoCallDriver(DevExt->PhysicalDeviceObject, SynIrp);
if(ns == STATUS_PENDING) {
KeWaitForSingleObject(&Event,
Executive,
KernelMode,
FALSE,
NULL);
}
ns = SynIrp->IoStatus.Status;
IoFreeIrp(SynIrp);
if (NT_SUCCESS(ns)) {
RtlCopyMemory(&BootSec, DBR, sizeof(NTFS_BOOT_SEC));
BytesPerSector = BootSec.Bpb.BytesPerSector;
ExInitializePagedLookasideList(&DevExt->SectorBufHeader,
NULL,
NULL,
0,
BytesPerSector,
'back',
0);
StartFilter = TRUE;
}
}
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return ns;
}
break;
default:
break;
}
return SkipAndCallDriver(DevExt->LowerDeviceObject, Irp);
}
NTSTATUS
__fastcall
BackupSectorAndSetBit(
__in PDEVICE_OBJECT PhysicalDeviceObject,
__in HANDLE File,
__in PLARGE_INTEGER Offset,
__in ULONG Length,
__in PDISK_FLT_DEVICE_EXT DevExt
)
{
ULONGLONG BitOffset = BYTEOFF_TO_BITOFF(Offset->QuadPart);
ULONG BitLength = BYTELEN_TO_BITLEN(Length);
ULONG i;
ULONG BitStatus;
BOOLEAN BitRet;
PUCHAR BitBuf = (PUCHAR)GlobalContext.MapBuffer;
ULONG BitSize = GlobalContext.MapSize;
LARGE_INTEGER BackupOffset;
PUCHAR BackupBuf;
NTSTATUS ns;
PWRITE_ELEMENT WriteElem;
ASSERT((Offset->QuadPart % BytesPerSector) == 0);
ASSERT((Length % BytesPerSector) == 0);
for (i = 0; i < BitLength; i++) {
BitStatus = GetBit(BitBuf, BitSize, BitOffset + i);
if (BitStatus == -1) {
return STATUS_UNSUCCESSFUL;
}
else if (BitStatus == 0) {
BackupBuf = ExAllocateFromPagedLookasideList(&DevExt->SectorBufHeader);
BackupOffset.QuadPart = (i + BitOffset) * BytesPerSector;
ns = DirectReadWrite(PhysicalDeviceObject,
DIRECT_READ,
BackupBuf,
&BackupOffset,
BytesPerSector);
if (!NT_SUCCESS(ns)) {
ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, BackupBuf);
return ns;
}
WriteElem = (PWRITE_ELEMENT)ExAllocateFromPagedLookasideList(&DevExt->WriteElemHeader);
if (WriteElem == NULL) {
ExFreeToPagedLookasideList(&DevExt->SectorBufHeader, BackupBuf);
return STATUS_INSUFFICIENT_RESOURCES;
}
WriteElem->File = File;
WriteElem->Buffer = BackupBuf;
WriteElem->Length = BytesPerSector;
WriteElem->Offset.QuadPart = BackupOffset.QuadPart;
WriteElem->NeedFree = TRUE;
WriteElem->Tag = 'back';
ExInterlockedInsertTailList(&DevExt->ReqList,
&WriteElem->ListEntry,
&DevExt->ReqLock);
KeSetEvent(&DevExt->ReqEvent,
(KPRIORITY)0,
FALSE);
BitRet = SetBit(BitBuf, BitSize, BitOffset + i);
if (!BitRet) {
return STATUS_UNSUCCESSFUL;
}
}
}
FlushBuffer(DevExt,
GlobalContext.FileHandle,
BitBuf,
BITOFF_TO_MAPOFF(BitOffset),
BITLEN_TO_MAPLEN(BitOffset, BitLength));
return STATUS_SUCCESS;
}
NTSTATUS
FlushBuffer(
__in PDISK_FLT_DEVICE_EXT DevExt,
__in HANDLE File,
__in PVOID Buffer,
__in ULONG Offset,
__in ULONG Size
)
{
PUCHAR FlushBuf = (PUCHAR)Buffer;
PWRITE_ELEMENT WriteElem = (PWRITE_ELEMENT)ExAllocateFromPagedLookasideList(&DevExt->WriteElemHeader);
if (WriteElem == NULL) {
return STATUS_INSUFFICIENT_RESOURCES;
}
WriteElem->File = File;
WriteElem->Buffer = FlushBuf + Offset;
WriteElem->Length = Size;
WriteElem->Offset.QuadPart = (LONGLONG)Offset;
WriteElem->NeedFree = FALSE;
ExInterlockedInsertTailList(&DevExt->ReqList,
&WriteElem->ListEntry,
&DevExt->ReqLock);
KeSetEvent(&DevExt->ReqEvent,
(KPRIORITY)0,
FALSE);
return STATUS_SUCCESS;
}
NTSTATUS
DirectReadWrite(
__in PDEVICE_OBJECT DeviceObject,
__in ULONG ReadWrite,
__out PVOID Buffer,
__in PLARGE_INTEGER Offset,
__in ULONG Length
)
{
NTSTATUS ns;
ULONG MjFunc;
KEVENT Event;
PIRP Irp;
IO_STATUS_BLOCK Iob;
PMDL NextMdl;
if (ReadWrite == DIRECT_READ) {
MjFunc = IRP_MJ_READ;
}
else if (ReadWrite == DIRECT_WRITE) {
MjFunc = IRP_MJ_WRITE;
}
else {
return STATUS_INVALID_PARAMETER;
}
KeInitializeEvent(&Event, NotificationEvent, FALSE);
Irp = IoBuildAsynchronousFsdRequest(MjFunc,
DeviceObject,
Buffer,
Length,
Offset,
&Iob);
if (Irp == NULL) {
return STATUS_INSUFFICIENT_RESOURCES;
}
IoSetCompletionRoutine(Irp,
SyncIrpCompletionRoutine,
&Event,
TRUE,
TRUE,
TRUE);
ns = IoCallDriver(DeviceObject, Irp);
if(ns == STATUS_PENDING) {
KeWaitForSingleObject(&Event,
Executive,
KernelMode,
FALSE,
NULL);
}
ns = Irp->IoStatus.Status;
while (Irp->MdlAddress != NULL) {
NextMdl = Irp->MdlAddress->Next;
MmUnlockPages(Irp->MdlAddress);
IoFreeMdl(Irp->MdlAddress);
Irp->MdlAddress = NextMdl;
}
IoFreeIrp(Irp);
return ns;
}
LONGLONG GetFileSize(
__in HANDLE Handle
)
{
IO_STATUS_BLOCK Iob;
FILE_STANDARD_INFORMATION FileStdInfo;
NTSTATUS ns;
ns = ZwQueryInformationFile(Handle,
&Iob,
&FileStdInfo,
sizeof(FILE_STANDARD_INFORMATION),
FileStandardInformation);
if (!NT_SUCCESS(ns)) {
return 0;
}
return FileStdInfo.EndOfFile.QuadPart;
}
BOOLEAN
__fastcall
SetBit(
__in PUCHAR BitBuf,
__in ULONG BitSize,
__in ULONGLONG Bit
)
{
ULONG ByteOffset = 0;
ULONG BitOffset = 0;
ByteOffset = (ULONG)(Bit / 8);
if (ByteOffset >= BitSize) {
return FALSE;
}
BitOffset = (ULONG)(Bit % 8);
BitBuf[ByteOffset] |= (UCHAR)(1 << BitOffset);
return TRUE;
}
BOOLEAN
__fastcall
ClearBit(
__in PUCHAR BitBuf,
__in ULONG BitSize,
__in ULONGLONG Bit
)
{
ULONG ByteOffset = 0;
ULONG BitOffset = 0;
ByteOffset = (ULONG)(Bit / 8);
if (ByteOffset >= BitSize) {
return FALSE;
}
BitOffset = (ULONG)(Bit % 8);
BitBuf[ByteOffset] &= (UCHAR)(~(1 << BitOffset));
return TRUE;
}
ULONG
__fastcall
GetBit(
__in PUCHAR BitBuf,
__in ULONG BitSize,
__in ULONGLONG Bit
)
{
ULONG ByteOffset = 0;
ULONG BitOffset = 0;
ByteOffset = (ULONG)(Bit / 8);
if (ByteOffset >= BitSize) {
return (ULONG)-1;
}
BitOffset = (ULONG)(Bit % 8);
return (BitBuf[ByteOffset] & (UCHAR)(1 << BitOffset)) != 0;
}
NTSTATUS
OpenMapping(
__in PWCHAR Name,
__out PHANDLE File,
__out PVOID *Buffer,
__out ULONG *BufferSize
)
{
NTSTATUS ns;
HANDLE FileHandle;
UNICODE_STRING FileName;
OBJECT_ATTRIBUTES oa;
IO_STATUS_BLOCK Iob;
LARGE_INTEGER MaxSize;
PVOID MapBuffer;
LARGE_INTEGER Offset = {0};
RtlInitUnicodeString(&FileName, Name);
InitializeObjectAttributes(&oa, &FileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
ns = ZwCreateFile(&FileHandle,
FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE,
&oa,
&Iob,
NULL,
0,
FILE_SHARE_READ,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_WRITE_THROUGH,
NULL,
0);
if (!NT_SUCCESS(ns)) {
return ns;
}
MaxSize.QuadPart = GetFileSize(FileHandle);
if (MaxSize.QuadPart == 0) {
ZwClose(FileHandle);
return STATUS_UNSUCCESSFUL;
}
MapBuffer = ExAllocatePoolWithTag(PagedPool, MaxSize.LowPart, 'bmp ');
if (MapBuffer == NULL) {
ZwClose(FileHandle);
return STATUS_INSUFFICIENT_RESOURCES;
}
ns = ZwReadFile(FileHandle, NULL, NULL, NULL, &Iob, MapBuffer, MaxSize.LowPart, &Offset, NULL);
if (!NT_SUCCESS(ns)) {
ExFreePoolWithTag(MapBuffer, 'bmp ');
ZwClose(FileHandle);
return ns;
}
*File = FileHandle;
*Buffer = MapBuffer;
*BufferSize = MaxSize.LowPart;
return ns;
}
VOID
CloseMapping(
__in HANDLE File,
__in PVOID Buffer
)
{
ExFreePoolWithTag(Buffer, 'bmp ');
ZwClose(File);
}
NTSTATUS
CreateSparseFile(
__out PHANDLE Handle,
__in PWCHAR FileName,
__in ULONGLONG FileSize,
__in BOOLEAN Restore
)
{
NTSTATUS ns;
HANDLE FileHandle;
UNICODE_STRING SparseFileName;
IO_STATUS_BLOCK Iob;
OBJECT_ATTRIBUTES oa;
FILE_END_OF_FILE_INFORMATION FileEndInfo = {0};
ULONG ExtFlag = 0;
if (!Restore) {
ExtFlag = FILE_RANDOM_ACCESS | FILE_NO_INTERMEDIATE_BUFFERING | FILE_WRITE_THROUGH;
}
RtlInitUnicodeString(&SparseFileName, FileName);
InitializeObjectAttributes(&oa,
&SparseFileName,
OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
NULL,
NULL);
ns = ZwCreateFile(
&FileHandle,
FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE | DELETE,
&oa,
&Iob,
NULL,
FILE_ATTRIBUTE_NORMAL,
0,
FILE_OPEN_IF,
FILE_SYNCHRONOUS_IO_NONALERT | ExtFlag,
NULL,
0);
if(!NT_SUCCESS(ns)) {
return ns;
}
if (Iob.Information == FILE_CREATED) {
ns = ZwFsControlFile(FileHandle,
NULL,
NULL,
NULL,
&Iob,
FSCTL_SET_SPARSE,
NULL,
0,
NULL,
0);
if(!NT_SUCCESS(ns)) {
ZwClose(FileHandle);
return ns;
}
FileEndInfo.EndOfFile.QuadPart = FileSize + 10*1024*1024;
ns = ZwSetInformationFile(FileHandle,
&Iob,
&FileEndInfo,
sizeof(FILE_END_OF_FILE_INFORMATION),
FileEndOfFileInformation);
if (!NT_SUCCESS(ns)) {
ZwClose(FileHandle);
return ns;
}
}
*Handle = FileHandle;
return ns;
}
NTSTATUS
AddDevice(
__in PDRIVER_OBJECT DriverObject,
__in PDEVICE_OBJECT PhysicalDeviceObject
)
{
NTSTATUS ns;
PDISK_FLT_DEVICE_EXT DevExt;
PDEVICE_OBJECT LowerDevObj;
PDEVICE_OBJECT FltDevObj;
ULONG RetLength;
HANDLE ThreadHandle;
UCHAR NameBuffer[1024 + sizeof(OBJECT_NAME_INFORMATION)];
POBJECT_NAME_INFORMATION DeviceNameInfo = (POBJECT_NAME_INFORMATION)NameBuffer;
DECLARE_CONST_UNICODE_STRING(Vol1, L"\\Device\\HarddiskVolume1");
ns = ObQueryNameString(PhysicalDeviceObject, DeviceNameInfo, 1024, &RetLength);
if (!NT_SUCCESS(ns)) {
return ns;
}
if (RtlCompareUnicodeString(&Vol1, &DeviceNameInfo->Name, TRUE) != 0) {
return STATUS_SUCCESS;
}
KdPrint(("Physical Device Dos Name : %wZ\n", &DeviceNameInfo->Name));
ns = IoCreateDevice(DriverObject,
sizeof(DISK_FLT_DEVICE_EXT),
NULL,
FILE_DEVICE_DISK,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&FltDevObj);
if (!NT_SUCCESS(ns)) {
return ns;
}
DevExt = FltDevObj->DeviceExtension;
RtlZeroMemory(DevExt,sizeof(DISK_FLT_DEVICE_EXT));
LowerDevObj = IoAttachDeviceToDeviceStack(FltDevObj,
PhysicalDeviceObject);
if (LowerDevObj == NULL) {
IoDeleteDevice(FltDevObj);
ns = STATUS_NO_SUCH_DEVICE;
return ns;
}
FltDevObj->Flags |= LowerDevObj->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE);
FltDevObj->Flags &= ~DO_DEVICE_INITIALIZING;
DevExt->DeviceType = DEVICE_TYPE_FILTER;
DevExt->FilterDeviceObject = FltDevObj;
DevExt->PhysicalDeviceObject = PhysicalDeviceObject;
DevExt->LowerDeviceObject = LowerDevObj;
InitializeListHead(&DevExt->ReqList);
KeInitializeSpinLock(&DevExt->ReqLock);
KeInitializeEvent(&DevExt->ReqEvent,
SynchronizationEvent,
FALSE);
DevExt->ThreadFlag = FALSE;
ns = PsCreateSystemThread(&ThreadHandle,
(ACCESS_MASK)0L,
NULL,
NULL,
NULL,
WriteWorkThread,
DevExt);
if (!NT_SUCCESS(ns)) {
IoDeleteDevice(FltDevObj);
return ns;
}
ns = ObReferenceObjectByHandle(ThreadHandle,
THREAD_ALL_ACCESS,
NULL,
KernelMode,
&DevExt->ThreadObject,
NULL);
ZwClose(ThreadHandle);
if (!NT_SUCCESS(ns)) {
DevExt->ThreadFlag = TRUE;
KeSetEvent(&DevExt->ReqEvent,
(KPRIORITY)0,
FALSE);
IoDeleteDevice(FltDevObj);
return ns;
}
ExInitializePagedLookasideList(&DevExt->WriteElemHeader,
NULL,
NULL,
0,
sizeof(WRITE_ELEMENT),
'welm',
0);
return ns;
}
VOID
Unload(
__in PDRIVER_OBJECT DriverObject
)
{
PDEVICE_OBJECT NextDevObj;
PDEVICE_OBJECT CurDevObj;
PDISK_FLT_DEVICE_EXT DevExt;
NextDevObj = DriverObject->DeviceObject;
while (NextDevObj != NULL) {
CurDevObj = NextDevObj;
DevExt = (PDISK_FLT_DEVICE_EXT)CurDevObj->DeviceExtension;
NextDevObj = CurDevObj->NextDevice;
if (DevExt->DeviceType == DEVICE_TYPE_FILTER) {
IoDetachDevice(DevExt->LowerDeviceObject);
if (DevExt->ThreadObject != NULL && DevExt->ThreadFlag != TRUE) {
DevExt->ThreadFlag = TRUE;
KeSetEvent(&DevExt->ReqEvent,
(KPRIORITY)0,
FALSE);
KeWaitForSingleObject(
DevExt->ThreadObject,
Executive,
KernelMode,
FALSE,
NULL
);
ObDereferenceObject(DevExt->ThreadObject);
DevExt->ThreadObject = NULL;
}
ExDeletePagedLookasideList(&DevExt->SectorBufHeader);
ExDeletePagedLookasideList(&DevExt->WriteElemHeader);
DevExt->LowerDeviceObject = NULL;
}
IoDeleteDevice(CurDevObj);
}
if (GlobalContext.FileHandle != NULL) {
CloseMapping(GlobalContext.FileHandle,
GlobalContext.MapBuffer);
GlobalContext.FileHandle = NULL;
}
if (GlobalContext.SparseFileHandle != NULL) {
ZwClose(GlobalContext.SparseFileHandle);
GlobalContext.SparseFileHandle = NULL;
}
return;
}
VOID
ReinitializationRoutine(
__in PDRIVER_OBJECT DriverObject,
__in PVOID Context,
__in ULONG Count
)
{
NTSTATUS ns;
PDEVICE_OBJECT FilterDevice;
PDISK_FLT_DEVICE_EXT DevExt;
BOOLEAN PrepareRestore = IsRestoreDisk();
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(Context);
UNREFERENCED_PARAMETER(Count);
ns = OpenMapping(L"\\??\\D:\\Bitmap.dat",
&GlobalContext.FileHandle,
&GlobalContext.MapBuffer,
&GlobalContext.MapSize);
if (!NT_SUCCESS(ns)) {
return;
}
ns = CreateSparseFile(&GlobalContext.SparseFileHandle,
L"\\??\\D:\\SpareFile.dat",
BootSec.ExBpb.TotalSectors * BootSec.Bpb.BytesPerSector, PrepareRestore);
if (!NT_SUCCESS(ns)) {
return;
}
if (PrepareRestore) {
FilterDevice = DriverObject->DeviceObject;
while (FilterDevice != NULL) {
DevExt = FilterDevice->DeviceExtension;
if (DevExt != NULL && DevExt->DeviceType == DEVICE_TYPE_FILTER) {
RestoreDisk(DevExt);
KdBreakPoint();
}
FilterDevice = FilterDevice->NextDevice;
}
}
InitFilter = TRUE;
return;
}
NTSTATUS
DriverEntry(
__in PDRIVER_OBJECT DriverObject,
__in PUNICODE_STRING RegistryPath
)
{
ULONG i;
UNREFERENCED_PARAMETER(RegistryPath);
KdBreakPoint();
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
DriverObject->MajorFunction[i] = DispatchPassThrough;
}
DriverObject->MajorFunction[IRP_MJ_POWER] = DispatchPower;
DriverObject->MajorFunction[IRP_MJ_PNP] = DispatchPnp;
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchReadWrite;
DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchReadWrite;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDeviceControl;
DriverObject->DriverExtension->AddDevice = AddDevice;
DriverObject->DriverUnload = Unload;
IoRegisterBootDriverReinitialization(DriverObject,
ReinitializationRoutine,
NULL);
return STATUS_SUCCESS;
} | C |
#ifndef INCLUDES_H
#define INCLUDES_H
// Application properties
#include "Properties.h"
/* Common includes for classes */
#include <QApplication>
#include <QObject>
#include <QDebug>
// GUI
/*#include <QSplashScreen>
#include <QLabel>
#include <QMessageBox>
#include <QCheckBox>
#include <QFileDialog>
#include <QIcon>
#include <QStyle>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QHeaderView>
#include <QComboBox>
#include <QScrollbar>
#include <QProgressBar>
#include <QPalette>
// Drag&Drop
#include <QMimeData>
#include <QDropEvent>
#include <QDragEnterEvent>*/
// String stuff
#include <QString>
#include <QStringList>
#include <QByteArray>
//#include <QRegExp>
//#include <QTextCodec>
// File access stuff
#include <QFile>
#include <QFileInfo>
#include <QDir>
/*#include <QTextStream>
#include <QUrl>*/
// Lists and maps
#include <QList>
#include <QHash>
#include <QMap>
// Settings
#include <QSettings>
#include <QIntValidator>
// Network
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QNetworkCookie>
#include <QNetworkCookieJar>
#include <QTcpServer>
#include <QTcpSocket>
// Images
#include <QImage>
#include <QPixmap>
// Misc
#include <QFlags>
#endif // INCLUDES_H
| C |
#include "Python.h"
#include "structmember.h"
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PyInt_FromSsize_t PyInt_FromLong
#define PyInt_AsSsize_t PyInt_AsLong
#endif
#ifndef Py_IS_FINITE
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
#endif
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#define DEFAULT_ENCODING "utf-8"
#define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
#define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
#define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
#define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
static PyTypeObject PyScannerType;
static PyTypeObject PyEncoderType;
typedef struct _PyScannerObject {
PyObject_HEAD
PyObject *encoding;
PyObject *strict;
PyObject *object_hook;
PyObject *parse_float;
PyObject *parse_int;
PyObject *parse_constant;
} PyScannerObject;
static PyMemberDef scanner_members[] = {
{"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
{"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
{"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
{"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
{"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
{"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
{NULL}
};
typedef struct _PyEncoderObject {
PyObject_HEAD
PyObject *markers;
PyObject *defaultfn;
PyObject *encoder;
PyObject *indent;
PyObject *key_separator;
PyObject *item_separator;
PyObject *sort_keys;
PyObject *skipkeys;
int fast_encode;
int allow_nan;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
{"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
{"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
{"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
{"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
{"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
{"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
{"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
{"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
{NULL}
};
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
static PyObject *
ascii_escape_unicode(PyObject *pystr);
static PyObject *
ascii_escape_str(PyObject *pystr);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
void init_speedups(void);
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
scanner_dealloc(PyObject *self);
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
encoder_dealloc(PyObject *self);
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
static PyObject *
_encoded_const(PyObject *const);
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj);
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj);
#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
#define MIN_EXPANSION 6
#ifdef Py_UNICODE_WIDE
#define MAX_EXPANSION (2 * MIN_EXPANSION)
#else
#define MAX_EXPANSION MIN_EXPANSION
#endif
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
{
/* PyObject to Py_ssize_t converter */
*size_ptr = PyInt_AsSsize_t(o);
if (*size_ptr == -1 && PyErr_Occurred());
return 1;
return 0;
}
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
{
/* Py_ssize_t to PyObject converter */
return PyInt_FromSsize_t(*size_ptr);
}
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
{
/* Escape unicode code point c to ASCII escape sequences
in char *output. output must have at least 12 bytes unused to
accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
output[chars++] = '\\';
switch (c) {
case '\\': output[chars++] = (char)c; break;
case '"': output[chars++] = (char)c; break;
case '\b': output[chars++] = 'b'; break;
case '\f': output[chars++] = 'f'; break;
case '\n': output[chars++] = 'n'; break;
case '\r': output[chars++] = 'r'; break;
case '\t': output[chars++] = 't'; break;
default:
#ifdef Py_UNICODE_WIDE
if (c >= 0x10000) {
/* UTF-16 surrogate pair */
Py_UNICODE v = c - 0x10000;
c = 0xd800 | ((v >> 10) & 0x3ff);
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
c = 0xdc00 | (v & 0x3ff);
output[chars++] = '\\';
}
#endif
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
}
return chars;
}
static PyObject *
ascii_escape_unicode(PyObject *pystr)
{
/* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t max_output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
Py_UNICODE *input_unicode;
input_chars = PyUnicode_GET_SIZE(pystr);
input_unicode = PyUnicode_AS_UNICODE(pystr);
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
max_output_size = 2 + (input_chars * MAX_EXPANSION);
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
chars = 0;
output[chars++] = '"';
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = input_unicode[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
if (output_size - chars < (1 + MAX_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
Py_ssize_t new_output_size = output_size * 2;
/* This is an upper bound */
if (new_output_size > max_output_size) {
new_output_size = max_output_size;
}
/* Make sure that the output size changed before resizing */
if (new_output_size != output_size) {
output_size = new_output_size;
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static PyObject *
ascii_escape_str(PyObject *pystr)
{
/* Take a PyString pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
char *input_str;
input_chars = PyString_GET_SIZE(pystr);
input_str = PyString_AS_STRING(pystr);
/* Fast path for a string that's already ASCII */
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (!S_CHAR(c)) {
/* If we have to escape something, scan the string for unicode */
Py_ssize_t j;
for (j = i; j < input_chars; j++) {
c = (Py_UNICODE)(unsigned char)input_str[j];
if (c > 0x7f) {
/* We hit a non-ASCII character, bail to unicode mode */
PyObject *uni;
uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
if (uni == NULL) {
return NULL;
}
rval = ascii_escape_unicode(uni);
Py_DECREF(uni);
return rval;
}
}
break;
}
}
if (i == input_chars) {
/* Input is already ASCII */
output_size = 2 + input_chars;
}
else {
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
}
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
output[0] = '"';
/* We know that everything up to i is ASCII already */
chars = i + 1;
memcpy(&output[1], input_str, i);
for (; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
/* An ASCII char can't possibly expand to a surrogate! */
if (output_size - chars < (1 + MIN_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
output_size *= 2;
if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
output_size = 2 + (input_chars * MIN_EXPANSION);
}
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
{
/* Use the Python function simplejson.decoder.errmsg to raise a nice
looking ValueError exception */
static PyObject *errmsg_fn = NULL;
PyObject *pymsg;
if (errmsg_fn == NULL) {
PyObject *decoder = PyImport_ImportModule("simplejson.decoder");
if (decoder == NULL)
return;
errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
Py_DECREF(decoder);
if (errmsg_fn == NULL)
return;
}
pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
if (pymsg) {
PyErr_SetObject(PyExc_ValueError, pymsg);
Py_DECREF(pymsg);
}
}
static PyObject *
join_list_unicode(PyObject *lst)
{
/* return u''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
join_list_string(PyObject *lst)
{
/* return ''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
PyObject *pyidx;
/*
steal a reference to rval, returns (rval, idx)
*/
if (rval == NULL) {
return NULL;
}
pyidx = PyInt_FromSsize_t(idx);
if (pyidx == NULL) {
Py_DECREF(rval);
return NULL;
}
tpl = PyTuple_New(2);
if (tpl == NULL) {
Py_DECREF(pyidx);
Py_DECREF(rval);
return NULL;
}
PyTuple_SET_ITEM(tpl, 0, rval);
PyTuple_SET_ITEM(tpl, 1, pyidx);
return tpl;
}
static PyObject *
scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyString pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyString (if ASCII-only) or PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyString_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
int has_unicode = 0;
char *buf = PyString_AS_STRING(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = (unsigned char)buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
else if (c > 0x7f) {
has_unicode = 1;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end);
if (strchunk == NULL) {
goto bail;
}
if (has_unicode) {
chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
Py_DECREF(strchunk);
if (chunk == NULL) {
goto bail;
}
}
else {
chunk = strchunk;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
if (c > 0x7f) {
has_unicode = 1;
}
if (has_unicode) {
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
}
else {
char c_char = Py_CHARMASK(c);
chunk = PyString_FromStringAndSize(&c_char, 1);
if (chunk == NULL) {
goto bail;
}
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_string(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
static PyObject *
scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyUnicode pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
chunk = PyUnicode_FromUnicode(&buf[end], next - end);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_DECREF(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
PyDoc_STRVAR(pydoc_scanstring,
"scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
"\n"
"Scan the string s for a JSON string. End is the index of the\n"
"character in s after the quote that started the JSON string.\n"
"Unescapes all valid JSON string escape sequences and raises ValueError\n"
"on attempt to decode an invalid string. If strict is False then literal\n"
"control characters are allowed in the string.\n"
"\n"
"Returns a tuple of the decoded string and the index of the character in s\n"
"after the end quote."
);
static PyObject *
py_scanstring(PyObject* self UNUSED, PyObject *args)
{
PyObject *pystr;
PyObject *rval;
Py_ssize_t end;
Py_ssize_t next_end = -1;
char *encoding = NULL;
int strict = 1;
if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
return NULL;
}
if (encoding == NULL) {
encoding = DEFAULT_ENCODING;
}
if (PyString_Check(pystr)) {
rval = scanstring_str(pystr, end, encoding, strict, &next_end);
}
else if (PyUnicode_Check(pystr)) {
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_end);
}
PyDoc_STRVAR(pydoc_encode_basestring_ascii,
"encode_basestring_ascii(basestring) -> str\n"
"\n"
"Return an ASCII-only JSON representation of a Python string"
);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
{
/* Return an ASCII-only JSON representation of a Python string */
/* METH_O */
if (PyString_Check(pystr)) {
return ascii_escape_str(pystr);
}
else if (PyUnicode_Check(pystr)) {
return ascii_escape_unicode(pystr);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
}
static void
scanner_dealloc(PyObject *self)
{
/* Deallocate scanner object */
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
self->ob_type->tp_free(self);
}
static PyObject *
_parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyString pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
PyObject *val = NULL;
char *encoding = PyString_AS_STRING(s->encoding);
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON data type */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyUnicode pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term and de-tuplefy the (rval, idx) */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON constant from PyString pystr.
constant is the constant string that was found
("NaN", "Infinity", "-Infinity").
idx is the index of the first character of the constant
*next_idx_ptr is a return-by-reference index to the first character after
the constant.
Returns the result of parse_constant
*/
PyObject *cstr;
PyObject *rval;
/* constant is "NaN", "Infinity", or "-Infinity" */
cstr = PyString_InternFromString(constant);
if (cstr == NULL)
return NULL;
/* rval = parse_constant(constant) */
rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
idx += PyString_GET_SIZE(cstr);
Py_DECREF(cstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyString pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
/* save the index of the 'e' or 'E' just in case we need to backtrack */
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyString_FromStringAndSize(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr)));
}
}
else {
/* parse as an int using a fast path if available, otherwise call user defined method */
if (s->parse_int != (PyObject *)&PyInt_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
else {
rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
}
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyUnicode pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyUnicode_FromUnicode(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromString(numstr, NULL);
}
}
else {
/* no fast path for unicode -> int, just call */
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyString pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_str(pystr, idx + 1,
PyString_AS_STRING(s->encoding),
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_str(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyUnicode pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_unicode(pystr, idx + 1,
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_unicode(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to scan_once_{str,unicode} */
PyObject *pystr;
PyObject *rval;
Py_ssize_t idx;
Py_ssize_t next_idx = -1;
static char *kwlist[] = {"string", "idx", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
return NULL;
if (PyString_Check(pystr)) {
rval = scan_once_str(s, pystr, idx, &next_idx);
}
else if (PyUnicode_Check(pystr)) {
rval = scan_once_unicode(s, pystr, idx, &next_idx);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_idx);
}
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Initialize Scanner object */
PyObject *ctx;
static char *kwlist[] = {"context", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
return -1;
s->encoding = NULL;
s->strict = NULL;
s->object_hook = NULL;
s->parse_float = NULL;
s->parse_int = NULL;
s->parse_constant = NULL;
/* PyString_AS_STRING is used on encoding */
s->encoding = PyObject_GetAttrString(ctx, "encoding");
if (s->encoding == Py_None) {
Py_DECREF(Py_None);
s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
}
else if (PyUnicode_Check(s->encoding)) {
PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
Py_DECREF(s->encoding);
s->encoding = tmp;
}
if (s->encoding == NULL || !PyString_Check(s->encoding))
goto bail;
/* All of these will fail "gracefully" so we don't need to verify them */
s->strict = PyObject_GetAttrString(ctx, "strict");
if (s->strict == NULL)
goto bail;
s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
if (s->object_hook == NULL)
goto bail;
s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
if (s->parse_float == NULL)
goto bail;
s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
if (s->parse_int == NULL)
goto bail;
s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
if (s->parse_constant == NULL)
goto bail;
return 0;
bail:
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return -1;
}
PyDoc_STRVAR(scanner_doc, "JSON scanner object");
static
PyTypeObject PyScannerType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Scanner", /* tp_name */
sizeof(PyScannerObject), /* tp_basicsize */
0, /* tp_itemsize */
scanner_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
scanner_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
scanner_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
scanner_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
scanner_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
PyEncoderObject *s;
PyObject *allow_nan;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
s->markers = NULL;
s->defaultfn = NULL;
s->encoder = NULL;
s->indent = NULL;
s->key_separator = NULL;
s->item_separator = NULL;
s->sort_keys = NULL;
s->skipkeys = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
&s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan))
return -1;
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
Py_INCREF(s->encoder);
Py_INCREF(s->indent);
Py_INCREF(s->key_separator);
Py_INCREF(s->item_separator);
Py_INCREF(s->sort_keys);
Py_INCREF(s->skipkeys);
s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
s->allow_nan = PyObject_IsTrue(allow_nan);
return 0;
}
static PyObject *
encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to encode_listencode_obj */
static char *kwlist[] = {"obj", "_current_indent_level", NULL};
PyObject *obj;
PyObject *rval;
Py_ssize_t indent_level;
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
&obj, _convertPyInt_AsSsize_t, &indent_level))
return NULL;
rval = PyList_New(0);
if (rval == NULL)
return NULL;
if (encoder_listencode_obj(s, rval, obj, indent_level)) {
Py_DECREF(rval);
return NULL;
}
return rval;
}
static PyObject *
_encoded_const(PyObject *obj)
{
/* Return the JSON string representation of None, True, False */
if (obj == Py_None) {
static PyObject *s_null = NULL;
if (s_null == NULL) {
s_null = PyString_InternFromString("null");
}
Py_INCREF(s_null);
return s_null;
}
else if (obj == Py_True) {
static PyObject *s_true = NULL;
if (s_true == NULL) {
s_true = PyString_InternFromString("true");
}
Py_INCREF(s_true);
return s_true;
}
else if (obj == Py_False) {
static PyObject *s_false = NULL;
if (s_false == NULL) {
s_false = PyString_InternFromString("false");
}
Py_INCREF(s_false);
return s_false;
}
else {
PyErr_SetString(PyExc_ValueError, "not a const");
return NULL;
}
}
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyString_FromString("Infinity");
}
else if (i < 0) {
return PyString_FromString("-Infinity");
}
else {
return PyString_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a string */
if (s->fast_encode)
return py_encode_basestring_ascii(NULL, obj);
else
return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
}
static int
_steal_list_append(PyObject *lst, PyObject *stolen)
{
/* Append stolen and then decrement its reference count */
int rval = PyList_Append(lst, stolen);
Py_DECREF(stolen);
return rval;
}
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
{
/* Encode Python object obj to a JSON term, rval is a PyList */
PyObject *newobj;
int rv;
if (obj == Py_None || obj == Py_True || obj == Py_False) {
PyObject *cstr = _encoded_const(obj);
if (cstr == NULL)
return -1;
return _steal_list_append(rval, cstr);
}
else if (PyString_Check(obj) || PyUnicode_Check(obj))
{
PyObject *encoded = encoder_encode_string(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyList_Check(obj) || PyTuple_Check(obj)) {
return encoder_listencode_list(s, rval, obj, indent_level);
}
else if (PyDict_Check(obj)) {
return encoder_listencode_dict(s, rval, obj, indent_level);
}
else {
PyObject *ident = NULL;
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(obj);
if (ident == NULL)
return -1;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
Py_DECREF(ident);
return -1;
}
if (PyDict_SetItem(s->markers, ident, obj)) {
Py_DECREF(ident);
return -1;
}
}
newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
if (newobj == NULL) {
Py_XDECREF(ident);
return -1;
}
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
return -1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident)) {
Py_XDECREF(ident);
return -1;
}
Py_XDECREF(ident);
}
return rv;
}
}
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
{
/* Encode Python dict dct a JSON term, rval is a PyList */
static PyObject *open_dict = NULL;
static PyObject *close_dict = NULL;
static PyObject *empty_dict = NULL;
PyObject *kstr = NULL;
PyObject *ident = NULL;
PyObject *key, *value;
Py_ssize_t pos;
int skipkeys;
Py_ssize_t idx;
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
open_dict = PyString_InternFromString("{");
close_dict = PyString_InternFromString("}");
empty_dict = PyString_InternFromString("{}");
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
return -1;
}
if (PyDict_Size(dct) == 0)
return PyList_Append(rval, empty_dict);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(dct);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, dct)) {
goto bail;
}
}
if (PyList_Append(rval, open_dict))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
/* TODO: C speedup not implemented for sort_keys */
pos = 0;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
while (PyDict_Next(dct, &pos, &key, &value)) {
PyObject *encoded;
if (PyString_Check(key) || PyUnicode_Check(key)) {
Py_INCREF(key);
kstr = key;
}
else if (PyFloat_Check(key)) {
kstr = encoder_encode_float(s, key);
if (kstr == NULL)
goto bail;
}
else if (PyInt_Check(key) || PyLong_Check(key)) {
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
}
else if (skipkeys) {
continue;
}
else {
/* TODO: include repr of key */
PyErr_SetString(PyExc_ValueError, "keys must be a string");
goto bail;
}
if (idx) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
encoded = encoder_encode_string(s, kstr);
Py_CLEAR(kstr);
if (encoded == NULL)
goto bail;
if (PyList_Append(rval, encoded)) {
Py_DECREF(encoded);
goto bail;
}
Py_DECREF(encoded);
if (PyList_Append(rval, s->key_separator))
goto bail;
if (encoder_listencode_obj(s, rval, value, indent_level))
goto bail;
idx += 1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_dict))
goto bail;
return 0;
bail:
Py_XDECREF(kstr);
Py_XDECREF(ident);
return -1;
}
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
{
/* Encode Python list seq to a JSON term, rval is a PyList */
static PyObject *open_array = NULL;
static PyObject *close_array = NULL;
static PyObject *empty_array = NULL;
PyObject *ident = NULL;
PyObject *s_fast = NULL;
Py_ssize_t num_items;
PyObject **seq_items;
Py_ssize_t i;
if (open_array == NULL || close_array == NULL || empty_array == NULL) {
open_array = PyString_InternFromString("[");
close_array = PyString_InternFromString("]");
empty_array = PyString_InternFromString("[]");
if (open_array == NULL || close_array == NULL || empty_array == NULL)
return -1;
}
ident = NULL;
s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
if (s_fast == NULL)
return -1;
num_items = PySequence_Fast_GET_SIZE(s_fast);
if (num_items == 0) {
Py_DECREF(s_fast);
return PyList_Append(rval, empty_array);
}
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(seq);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, seq)) {
goto bail;
}
}
seq_items = PySequence_Fast_ITEMS(s_fast);
if (PyList_Append(rval, open_array))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
for (i = 0; i < num_items; i++) {
PyObject *obj = seq_items[i];
if (i) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoder_listencode_obj(s, rval, obj, indent_level))
goto bail;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_array))
goto bail;
Py_DECREF(s_fast);
return 0;
bail:
Py_XDECREF(ident);
Py_DECREF(s_fast);
return -1;
}
static void
encoder_dealloc(PyObject *self)
{
/* Deallocate Encoder */
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_CLEAR(s->markers);
Py_CLEAR(s->defaultfn);
Py_CLEAR(s->encoder);
Py_CLEAR(s->indent);
Py_CLEAR(s->key_separator);
Py_CLEAR(s->item_separator);
Py_CLEAR(s->sort_keys);
Py_CLEAR(s->skipkeys);
self->ob_type->tp_free(self);
}
PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
static
PyTypeObject PyEncoderType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Encoder", /* tp_name */
sizeof(PyEncoderObject), /* tp_basicsize */
0, /* tp_itemsize */
encoder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
encoder_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
encoder_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
encoder_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
encoder_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static PyMethodDef speedups_methods[] = {
{"encode_basestring_ascii",
(PyCFunction)py_encode_basestring_ascii,
METH_O,
pydoc_encode_basestring_ascii},
{"scanstring",
(PyCFunction)py_scanstring,
METH_VARARGS,
pydoc_scanstring},
{NULL, NULL, 0, NULL}
};
PyDoc_STRVAR(module_doc,
"simplejson speedups\n");
void
init_speedups(void)
{
PyObject *m;
PyScannerType.tp_getattro = PyObject_GenericGetAttr;
PyScannerType.tp_setattro = PyObject_GenericSetAttr;
PyScannerType.tp_alloc = PyType_GenericAlloc;
PyScannerType.tp_new = PyType_GenericNew;
PyScannerType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyScannerType) < 0)
return;
PyEncoderType.tp_getattro = PyObject_GenericGetAttr;
PyEncoderType.tp_setattro = PyObject_GenericSetAttr;
PyEncoderType.tp_alloc = PyType_GenericAlloc;
PyEncoderType.tp_new = PyType_GenericNew;
PyEncoderType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyEncoderType) < 0)
return;
m = Py_InitModule3("_speedups", speedups_methods, module_doc);
Py_INCREF((PyObject*)&PyScannerType);
PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
Py_INCREF((PyObject*)&PyEncoderType);
PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
}
| C |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#define ATL_THUNK_APIHOOK
EXCEPTION_DISPOSITION
__cdecl
_except_handler(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef EXCEPTION_DISPOSITION
(__cdecl *_except_handler_type)(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef struct tagATL_THUNK_PATTERN
{
LPBYTE pattern;
int pattern_size;
(void)(*enumerator)(struct _CONTEXT *);
}ATL_THUNK_PATTERN;
void InstallAtlThunkEnumeration();
void UninstallAtlThunkEnumeration(); | C |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "npapi.h"
#include <npfunctions.h>
#include <prtypes.h>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <atlcom.h>
#include <atlctl.h>
#include <varargs.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
//#define NO_REGISTRY_AUTHORIZE
#define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__)
// For catch breakpoints.
HRESULT NotImpl();
#define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl())
void
log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...);
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved);
NPError NPP_Destroy(NPP instance, NPSavedData **save);
NPError NPP_SetWindow(NPP instance, NPWindow *window);
#define REGISTER_MANAGER | C |
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| C |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
struct ITypeInfo;
void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance);
void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance);
size_t VariantSize(VARTYPE vt);
HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest);
void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var); | C |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
// TODO: reference additional headers your program requires here
| C |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by npactivex.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| C |
#ifndef _HOOK_H_
#define _HOOK_H_
typedef struct _HOOKINFO_
{
PBYTE Stub;
DWORD CodeLength;
LPVOID FuncAddr;
LPVOID FakeAddr;
}HOOKINFO, *PHOOKINFO;
VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr);
BOOL HEStartHook(PHOOKINFO HookInfo);
BOOL HEStopHook(PHOOKINFO HookInfo);
#endif | C |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType); | C |
/*
* Copyright 2002 Damien Miller <djm@mindrot.org> 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 ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
#include "common.h"
#include "log.h"
#include "treetype.h"
#include "softflowd.h"
RCSID("$Id$");
/*
* This is the Cisco Netflow(tm) version 5 packet format
* Based on:
* http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm
*/
struct NF5_HEADER {
u_int16_t version, flows;
u_int32_t uptime_ms, time_sec, time_nanosec, flow_sequence;
u_int8_t engine_type, engine_id, reserved1, reserved2;
};
struct NF5_FLOW {
u_int32_t src_ip, dest_ip, nexthop_ip;
u_int16_t if_index_in, if_index_out;
u_int32_t flow_packets, flow_octets;
u_int32_t flow_start, flow_finish;
u_int16_t src_port, dest_port;
u_int8_t pad1;
u_int8_t tcp_flags, protocol, tos;
u_int16_t src_as, dest_as;
u_int8_t src_mask, dst_mask;
u_int16_t pad2;
};
#define NF5_MAXFLOWS 30
#define NF5_MAXPACKET_SIZE (sizeof(struct NF5_HEADER) + \
(NF5_MAXFLOWS * sizeof(struct NF5_FLOW)))
/*
* Given an array of expired flows, send netflow v5 report packets
* Returns number of packets sent or -1 on error
*/
int
send_netflow_v5(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx,
u_int64_t *flows_exported, struct timeval *system_boot_time,
int verbose_flag)
{
struct timeval now;
u_int32_t uptime_ms;
u_int8_t packet[NF5_MAXPACKET_SIZE]; /* Maximum allowed packet size (24 flows) */
struct NF5_HEADER *hdr = NULL;
struct NF5_FLOW *flw = NULL;
int i, j, offset, num_packets, err;
socklen_t errsz;
gettimeofday(&now, NULL);
uptime_ms = timeval_sub_ms(&now, system_boot_time);
hdr = (struct NF5_HEADER *)packet;
for (num_packets = offset = j = i = 0; i < num_flows; i++) {
if (j >= NF5_MAXFLOWS - 1) {
if (verbose_flag)
logit(LOG_DEBUG, "Sending flow packet len = %d", offset);
hdr->flows = htons(hdr->flows);
errsz = sizeof(err);
getsockopt(nfsock, SOL_SOCKET, SO_ERROR,
&err, &errsz); /* Clear ICMP errors */
if (send(nfsock, packet, (size_t)offset, 0) == -1)
return (-1);
*flows_exported += j;
j = 0;
num_packets++;
}
if (j == 0) {
memset(&packet, '\0', sizeof(packet));
hdr->version = htons(5);
hdr->flows = 0; /* Filled in as we go */
hdr->uptime_ms = htonl(uptime_ms);
hdr->time_sec = htonl(now.tv_sec);
hdr->time_nanosec = htonl(now.tv_usec * 1000);
hdr->flow_sequence = htonl(*flows_exported);
/* Other fields are left zero */
offset = sizeof(*hdr);
}
flw = (struct NF5_FLOW *)(packet + offset);
flw->if_index_in = flw->if_index_out = htons(ifidx);
/* NetFlow v.5 doesn't do IPv6 */
if (flows[i]->af != AF_INET)
continue;
if (flows[i]->octets[0] > 0) {
flw->src_ip = flows[i]->addr[0].v4.s_addr;
flw->dest_ip = flows[i]->addr[1].v4.s_addr;
flw->src_port = flows[i]->port[0];
flw->dest_port = flows[i]->port[1];
flw->flow_packets = htonl(flows[i]->packets[0]);
flw->flow_octets = htonl(flows[i]->octets[0]);
flw->flow_start =
htonl(timeval_sub_ms(&flows[i]->flow_start,
system_boot_time));
flw->flow_finish =
htonl(timeval_sub_ms(&flows[i]->flow_last,
system_boot_time));
flw->tcp_flags = flows[i]->tcp_flags[0];
flw->protocol = flows[i]->protocol;
offset += sizeof(*flw);
j++;
hdr->flows++;
}
flw = (struct NF5_FLOW *)(packet + offset);
flw->if_index_in = flw->if_index_out = htons(ifidx);
if (flows[i]->octets[1] > 0) {
flw->src_ip = flows[i]->addr[1].v4.s_addr;
flw->dest_ip = flows[i]->addr[0].v4.s_addr;
flw->src_port = flows[i]->port[1];
flw->dest_port = flows[i]->port[0];
flw->flow_packets = htonl(flows[i]->packets[1]);
flw->flow_octets = htonl(flows[i]->octets[1]);
flw->flow_start =
htonl(timeval_sub_ms(&flows[i]->flow_start,
system_boot_time));
flw->flow_finish =
htonl(timeval_sub_ms(&flows[i]->flow_last,
system_boot_time));
flw->tcp_flags = flows[i]->tcp_flags[1];
flw->protocol = flows[i]->protocol;
offset += sizeof(*flw);
j++;
hdr->flows++;
}
}
/* Send any leftovers */
if (j != 0) {
if (verbose_flag)
logit(LOG_DEBUG, "Sending v5 flow packet len = %d",
offset);
hdr->flows = htons(hdr->flows);
errsz = sizeof(err);
getsockopt(nfsock, SOL_SOCKET, SO_ERROR,
&err, &errsz); /* Clear ICMP errors */
if (send(nfsock, packet, (size_t)offset, 0) == -1)
return (-1);
num_packets++;
}
*flows_exported += j;
return (num_packets);
}
| C |
/*
* Copyright (c) 2007 Damien Miller. 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 ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "common.h"
#include "freelist.h"
#include "log.h"
#define FREELIST_MAX_ALLOC 0x1000000
#define FREELIST_ALLOC_ALIGN 16
#define FREELIST_INITIAL_ALLOC 16
#ifndef roundup
#define roundup(x, y) ((((x) + (y) - 1)/(y))*(y))
#endif /* roundup */
#undef FREELIST_DEBUG
#ifdef FREELIST_DEBUG
# define FLOGIT(a) logit a
#else
# define FLOGIT(a)
#endif
void
freelist_init(struct freelist *fl, size_t allocsz)
{
FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, allocsz));
bzero(fl, sizeof(fl));
fl->allocsz = roundup(allocsz, FREELIST_ALLOC_ALIGN);
fl->free_entries = NULL;
}
static int
freelist_grow(struct freelist *fl)
{
size_t i, oldnalloc, need;
void *p;
FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl));
FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->nalloc));
/* Sanity check */
if (fl->nalloc > FREELIST_MAX_ALLOC)
return -1;
oldnalloc = fl->nalloc;
if (fl->nalloc == 0)
fl->nalloc = FREELIST_INITIAL_ALLOC;
else
fl->nalloc <<= 1;
if (fl->nalloc > FREELIST_MAX_ALLOC)
fl->nalloc = FREELIST_MAX_ALLOC;
FLOGIT((LOG_DEBUG, "%s: nalloc now %zu", __func__, fl->nalloc));
/* Check for integer overflow */
if (SIZE_MAX / fl->nalloc < fl->allocsz ||
SIZE_MAX / fl->nalloc < sizeof(*fl->free_entries)) {
FLOGIT((LOG_DEBUG, "%s: integer overflow", __func__));
resize_fail:
fl->nalloc = oldnalloc;
return -1;
}
/* Allocate freelist - max size of nalloc */
need = fl->nalloc * sizeof(*fl->free_entries);
if ((p = realloc(fl->free_entries, need)) == NULL) {
FLOGIT((LOG_DEBUG, "%s: realloc(%zu) failed", __func__, need));
goto resize_fail;
}
/* Allocate the entries */
fl->free_entries = p;
need = (fl->nalloc - oldnalloc) * fl->allocsz;
if ((p = malloc(need)) == NULL) {
FLOGIT((LOG_DEBUG, "%s: malloc(%zu) failed", __func__, need));
goto resize_fail;
}
/*
* XXX store these malloc ranges in a tree or list, so we can
* validate them in _get/_put. Check that r_low <= addr < r_high, and
* (addr - r_low) % fl->allocsz == 0
*/
fl->navail = fl->nalloc - oldnalloc;
for (i = 0; i < fl->navail; i++)
fl->free_entries[i] = (u_char *)p + (i * fl->allocsz);
for (i = fl->navail; i < fl->nalloc; i++)
fl->free_entries[i] = NULL;
FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail));
return 0;
}
void *
freelist_get(struct freelist *fl)
{
void *r;
FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl));
FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail));
if (fl->navail == 0) {
if (freelist_grow(fl) == -1)
return NULL;
}
/* Sanity check */
if (fl->navail == 0 || fl->navail > FREELIST_MAX_ALLOC ||
fl->free_entries[fl->navail - 1] == NULL) {
logit(LOG_ERR, "%s: invalid navail", __func__);
raise(SIGSEGV);
}
fl->navail--;
r = fl->free_entries[fl->navail];
fl->free_entries[fl->navail] = NULL;
FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail));
return r;
}
void
freelist_put(struct freelist *fl, void *p)
{
FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, p));
FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail));
FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->navail));
/* Sanity check */
if (fl->navail >= fl->nalloc) {
logit(LOG_ERR, "%s: freelist navail >= nalloc", __func__);
raise(SIGSEGV);
}
if (fl->free_entries[fl->navail] != NULL) {
logit(LOG_ERR, "%s: free_entries[%lu] != NULL",
__func__, (unsigned long)fl->navail);
raise(SIGSEGV);
}
fl->free_entries[fl->navail] = p;
fl->navail++;
FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail));
}
| C |
C-Code-Large
C-Code-Large is a large-scale corpus of C programming language source code comprising more than 4 million code samples stored in .jsonl format. The dataset is designed to support research and development in large language model (LLM) pretraining, static analysis, systems programming, and software engineering automation for the C ecosystem.
By offering a high-volume, language-focused dataset, C-Code-Large enables targeted experimentation in low-level programming, memory-constrained environments, and performance-critical systems, where C continues to be a dominant language.
C-Code-Large addresses the lack of large, curated, C-specific datasets, making it possible to conduct focused research on procedural programming paradigms, manual memory management, and system-level abstractions.
1. Dataset Composition
Programming Language
C (ANSI C / C89 / C99 / C11 variants)
Total Size
4M+ C code samples
File Format
.jsonl (JSON Lines)
Each entry typically contains structured representations of:
- Source code snippets
- Full C source files
- Header files
2. Content Overview
The dataset captures a wide spectrum of C programming constructs, ranging from foundational syntax to advanced system-level patterns.
2.1 Core Language Features
- Functions and declarations
- Function pointers
- Recursion
- Macros and preprocessor directives (
#define,#ifdef, etc.) - Header inclusion patterns
- Inline functions (compiler-dependent)
- Typedef usage
- Enumeration types (
enum) - Structs and unions
- Bit fields
2.2 Procedural Programming Paradigm
Modular function design
Separation of interface and implementation via headers
Control flow constructs:
if,elseswitch- loops (
for,while,do-while)
Error handling via return codes and flags
2.3 Memory Management
- Manual memory allocation (
malloc,calloc,realloc,free) - Stack vs heap allocation patterns
- Pointer arithmetic
- Double pointers and multi-level indirection
- Memory safety patterns
- Buffer management techniques
- Common pitfalls (e.g., dangling pointers, leaks)
2.4 Data Structures
- Arrays (static and dynamic)
- Linked lists (singly, doubly)
- Stacks and queues
- Trees and graph representations
- Hash tables (custom implementations)
- Circular buffers
- Struct-based abstractions
3. Intended Research Applications
3.1 Pretraining
- Training C-specific foundation models
- Continued pretraining for code LLMs
- Tokenizer design for low-level languages
- Domain adaptation for systems programming
3.2 Fine-Tuning and Adaptation
- Code completion engines for C
- Intelligent IDE assistants
- Automated refactoring tools
- Conversational programming agents
- Static analysis enhancement models
3.3 Code Intelligence Tasks
- Code summarization
- Code-to-text generation
- Documentation generation
- Bug detection (e.g., null dereferences, memory leaks)
- Security vulnerability detection (e.g., buffer overflows)
- Clone detection
- Code similarity analysis
- Dead code detection
- Complexity estimation
- Pointer and memory flow analysis
4. Key Advantages
- Large-scale: Millions of real-world C code samples
- Language-specific: Focused purely on C (no cross-language noise)
- Diverse: Covers multiple domains and coding styles
- Research-ready: Suitable for ML pipelines and static analysis tools
Thanks to open source community for all the guidance & support!!
- Downloads last month
- 190