python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2018 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains pcre_exec(), the externally visible function that does
pattern matching using an NFA algorithm, trying to mimic Perl as closely as
possible. There are also some static supporting functions. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define NLBLOCK md /* Block containing newline information */
#define PSSTART start_subject /* Field containing processed string start */
#define PSEND end_subject /* Field containing processed string end */
#include "pcre_internal.h"
/* Undefine some potentially clashing cpp symbols */
#undef min
#undef max
/* The md->capture_last field uses the lower 16 bits for the last captured
substring (which can never be greater than 65535) and a bit in the top half
to mean "capture vector overflowed". This odd way of doing things was
implemented when it was realized that preserving and restoring the overflow bit
whenever the last capture number was saved/restored made for a neater
interface, and doing it this way saved on (a) another variable, which would
have increased the stack frame size (a big NO-NO in PCRE) and (b) another
separate set of save/restore instructions. The following defines are used in
implementing this. */
#define CAPLMASK 0x0000ffff /* The bits used for last_capture */
#define OVFLMASK 0xffff0000 /* The bits used for the overflow flag */
#define OVFLBIT 0x00010000 /* The bit that is set for overflow */
/* Values for setting in md->match_function_type to indicate two special types
of call to match(). We do it this way to save on using another stack variable,
as stack usage is to be discouraged. */
#define MATCH_CONDASSERT 1 /* Called to check a condition assertion */
#define MATCH_CBEGROUP 2 /* Could-be-empty unlimited repeat group */
/* Non-error returns from the match() function. Error returns are externally
defined PCRE_ERROR_xxx codes, which are all negative. */
#define MATCH_MATCH 1
#define MATCH_NOMATCH 0
/* Special internal returns from the match() function. Make them sufficiently
negative to avoid the external error codes. */
#define MATCH_ACCEPT (-999)
#define MATCH_KETRPOS (-998)
#define MATCH_ONCE (-997)
/* The next 5 must be kept together and in sequence so that a test that checks
for any one of them can use a range. */
#define MATCH_COMMIT (-996)
#define MATCH_PRUNE (-995)
#define MATCH_SKIP (-994)
#define MATCH_SKIP_ARG (-993)
#define MATCH_THEN (-992)
#define MATCH_BACKTRACK_MAX MATCH_THEN
#define MATCH_BACKTRACK_MIN MATCH_COMMIT
/* Maximum number of ints of offset to save on the stack for recursive calls.
If the offset vector is bigger, malloc is used. This should be a multiple of 3,
because the offset vector is always a multiple of 3 long. */
#define REC_STACK_SAVE_MAX 30
/* Min and max values for the common repeats; for the maxima, 0 => infinity */
static const char rep_min[] = { 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, };
static const char rep_max[] = { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, };
#ifdef PCRE_DEBUG
/*************************************************
* Debugging function to print chars *
*************************************************/
/* Print a sequence of chars in printable format, stopping at the end of the
subject if the requested.
Arguments:
p points to characters
length number to print
is_subject TRUE if printing from within md->start_subject
md pointer to matching data block, if is_subject is TRUE
Returns: nothing
*/
static void
pchars(const pcre_uchar *p, int length, BOOL is_subject, match_data *md)
{
pcre_uint32 c;
BOOL utf = md->utf;
if (is_subject && length > md->end_subject - p) length = md->end_subject - p;
while (length-- > 0)
if (isprint(c = UCHAR21INCTEST(p))) printf("%c", (char)c); else printf("\\x{%02x}", c);
}
#endif
/*************************************************
* Match a back-reference *
*************************************************/
/* Normally, if a back reference hasn't been set, the length that is passed is
negative, so the match always fails. However, in JavaScript compatibility mode,
the length passed is zero. Note that in caseless UTF-8 mode, the number of
subject bytes matched may be different to the number of reference bytes.
Arguments:
offset index into the offset vector
eptr pointer into the subject
length length of reference to be matched (number of bytes)
md points to match data block
caseless TRUE if caseless
Returns: >= 0 the number of subject bytes matched
-1 no match
-2 partial match; always given if at end subject
*/
static int
match_ref(int offset, register PCRE_PUCHAR eptr, int length, match_data *md,
BOOL caseless)
{
PCRE_PUCHAR eptr_start = eptr;
register PCRE_PUCHAR p = md->start_subject + md->offset_vector[offset];
#if defined SUPPORT_UTF && defined SUPPORT_UCP
BOOL utf = md->utf;
#endif
#ifdef PCRE_DEBUG
if (eptr >= md->end_subject)
printf("matching subject <null>");
else
{
printf("matching subject ");
pchars(eptr, length, TRUE, md);
}
printf(" against backref ");
pchars(p, length, FALSE, md);
printf("\n");
#endif
/* Always fail if reference not set (and not JavaScript compatible - in that
case the length is passed as zero). */
if (length < 0) return -1;
/* Separate the caseless case for speed. In UTF-8 mode we can only do this
properly if Unicode properties are supported. Otherwise, we can check only
ASCII characters. */
if (caseless)
{
#if defined SUPPORT_UTF && defined SUPPORT_UCP
if (utf)
{
/* Match characters up to the end of the reference. NOTE: the number of
data units matched may differ, because in UTF-8 there are some characters
whose upper and lower case versions code have different numbers of bytes.
For example, U+023A (2 bytes in UTF-8) is the upper case version of U+2C65
(3 bytes in UTF-8); a sequence of 3 of the former uses 6 bytes, as does a
sequence of two of the latter. It is important, therefore, to check the
length along the reference, not along the subject (earlier code did this
wrong). */
PCRE_PUCHAR endptr = p + length;
while (p < endptr)
{
pcre_uint32 c, d;
const ucd_record *ur;
if (eptr >= md->end_subject) return -2; /* Partial match */
GETCHARINC(c, eptr);
GETCHARINC(d, p);
ur = GET_UCD(d);
if (c != d && c != d + ur->other_case)
{
const pcre_uint32 *pp = PRIV(ucd_caseless_sets) + ur->caseset;
for (;;)
{
if (c < *pp) return -1;
if (c == *pp++) break;
}
}
}
}
else
#endif
/* The same code works when not in UTF-8 mode and in UTF-8 mode when there
is no UCP support. */
{
while (length-- > 0)
{
pcre_uint32 cc, cp;
if (eptr >= md->end_subject) return -2; /* Partial match */
cc = UCHAR21TEST(eptr);
cp = UCHAR21TEST(p);
if (TABLE_GET(cp, md->lcc, cp) != TABLE_GET(cc, md->lcc, cc)) return -1;
p++;
eptr++;
}
}
}
/* In the caseful case, we can just compare the bytes, whether or not we
are in UTF-8 mode. */
else
{
while (length-- > 0)
{
if (eptr >= md->end_subject) return -2; /* Partial match */
if (UCHAR21INCTEST(p) != UCHAR21INCTEST(eptr)) return -1;
}
}
return (int)(eptr - eptr_start);
}
/***************************************************************************
****************************************************************************
RECURSION IN THE match() FUNCTION
The match() function is highly recursive, though not every recursive call
increases the recursive depth. Nevertheless, some regular expressions can cause
it to recurse to a great depth. I was writing for Unix, so I just let it call
itself recursively. This uses the stack for saving everything that has to be
saved for a recursive call. On Unix, the stack can be large, and this works
fine.
It turns out that on some non-Unix-like systems there are problems with
programs that use a lot of stack. (This despite the fact that every last chip
has oodles of memory these days, and techniques for extending the stack have
been known for decades.) So....
There is a fudge, triggered by defining NO_RECURSE, which avoids recursive
calls by keeping local variables that need to be preserved in blocks of memory
obtained from malloc() instead instead of on the stack. Macros are used to
achieve this so that the actual code doesn't look very different to what it
always used to.
The original heap-recursive code used longjmp(). However, it seems that this
can be very slow on some operating systems. Following a suggestion from Stan
Switzer, the use of longjmp() has been abolished, at the cost of having to
provide a unique number for each call to RMATCH. There is no way of generating
a sequence of numbers at compile time in C. I have given them names, to make
them stand out more clearly.
Crude tests on x86 Linux show a small speedup of around 5-8%. However, on
FreeBSD, avoiding longjmp() more than halves the time taken to run the standard
tests. Furthermore, not using longjmp() means that local dynamic variables
don't have indeterminate values; this has meant that the frame size can be
reduced because the result can be "passed back" by straight setting of the
variable instead of being passed in the frame.
****************************************************************************
***************************************************************************/
/* Numbers for RMATCH calls. When this list is changed, the code at HEAP_RETURN
below must be updated in sync. */
enum { RM1=1, RM2, RM3, RM4, RM5, RM6, RM7, RM8, RM9, RM10,
RM11, RM12, RM13, RM14, RM15, RM16, RM17, RM18, RM19, RM20,
RM21, RM22, RM23, RM24, RM25, RM26, RM27, RM28, RM29, RM30,
RM31, RM32, RM33, RM34, RM35, RM36, RM37, RM38, RM39, RM40,
RM41, RM42, RM43, RM44, RM45, RM46, RM47, RM48, RM49, RM50,
RM51, RM52, RM53, RM54, RM55, RM56, RM57, RM58, RM59, RM60,
RM61, RM62, RM63, RM64, RM65, RM66, RM67 };
/* These versions of the macros use the stack, as normal. There are debugging
versions and production versions. Note that the "rw" argument of RMATCH isn't
actually used in this definition. */
#ifndef NO_RECURSE
#define REGISTER register
#ifdef PCRE_DEBUG
#define RMATCH(ra,rb,rc,rd,re,rw) \
{ \
printf("match() called in line %d\n", __LINE__); \
rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1); \
printf("to line %d\n", __LINE__); \
}
#define RRETURN(ra) \
{ \
printf("match() returned %d from line %d\n", ra, __LINE__); \
return ra; \
}
#else
#define RMATCH(ra,rb,rc,rd,re,rw) \
rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1)
#define RRETURN(ra) return ra
#endif
#else
/* These versions of the macros manage a private stack on the heap. Note that
the "rd" argument of RMATCH isn't actually used in this definition. It's the md
argument of match(), which never changes. */
#define REGISTER
#define RMATCH(ra,rb,rc,rd,re,rw)\
{\
heapframe *newframe = frame->Xnextframe;\
if (newframe == NULL)\
{\
newframe = (heapframe *)(PUBL(stack_malloc))(sizeof(heapframe));\
if (newframe == NULL) RRETURN(PCRE_ERROR_NOMEMORY);\
newframe->Xnextframe = NULL;\
frame->Xnextframe = newframe;\
}\
frame->Xwhere = rw;\
newframe->Xeptr = ra;\
newframe->Xecode = rb;\
newframe->Xmstart = mstart;\
newframe->Xoffset_top = rc;\
newframe->Xeptrb = re;\
newframe->Xrdepth = frame->Xrdepth + 1;\
newframe->Xprevframe = frame;\
frame = newframe;\
DPRINTF(("restarting from line %d\n", __LINE__));\
goto HEAP_RECURSE;\
L_##rw:\
DPRINTF(("jumped back to line %d\n", __LINE__));\
}
#define RRETURN(ra)\
{\
heapframe *oldframe = frame;\
frame = oldframe->Xprevframe;\
if (frame != NULL)\
{\
rrc = ra;\
goto HEAP_RETURN;\
}\
return ra;\
}
/* Structure for remembering the local variables in a private frame */
typedef struct heapframe {
struct heapframe *Xprevframe;
struct heapframe *Xnextframe;
/* Function arguments that may change */
PCRE_PUCHAR Xeptr;
const pcre_uchar *Xecode;
PCRE_PUCHAR Xmstart;
int Xoffset_top;
eptrblock *Xeptrb;
unsigned int Xrdepth;
/* Function local variables */
PCRE_PUCHAR Xcallpat;
#ifdef SUPPORT_UTF
PCRE_PUCHAR Xcharptr;
#endif
PCRE_PUCHAR Xdata;
PCRE_PUCHAR Xnext;
PCRE_PUCHAR Xpp;
PCRE_PUCHAR Xprev;
PCRE_PUCHAR Xsaved_eptr;
recursion_info Xnew_recursive;
BOOL Xcur_is_word;
BOOL Xcondition;
BOOL Xprev_is_word;
#ifdef SUPPORT_UCP
int Xprop_type;
unsigned int Xprop_value;
int Xprop_fail_result;
int Xoclength;
pcre_uchar Xocchars[6];
#endif
int Xcodelink;
int Xctype;
unsigned int Xfc;
int Xfi;
int Xlength;
int Xmax;
int Xmin;
unsigned int Xnumber;
int Xoffset;
unsigned int Xop;
pcre_int32 Xsave_capture_last;
int Xsave_offset1, Xsave_offset2, Xsave_offset3;
int Xstacksave[REC_STACK_SAVE_MAX];
eptrblock Xnewptrb;
/* Where to jump back to */
int Xwhere;
} heapframe;
#endif
/***************************************************************************
***************************************************************************/
/*************************************************
* Match from current position *
*************************************************/
/* This function is called recursively in many circumstances. Whenever it
returns a negative (error) response, the outer incarnation must also return the
same response. */
/* These macros pack up tests that are used for partial matching, and which
appear several times in the code. We set the "hit end" flag if the pointer is
at the end of the subject and also past the start of the subject (i.e.
something has been matched). For hard partial matching, we then return
immediately. The second one is used when we already know we are past the end of
the subject. */
#define CHECK_PARTIAL()\
if (md->partial != 0 && eptr >= md->end_subject && \
eptr > md->start_used_ptr) \
{ \
md->hitend = TRUE; \
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \
}
#define SCHECK_PARTIAL()\
if (md->partial != 0 && eptr > md->start_used_ptr) \
{ \
md->hitend = TRUE; \
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \
}
/* Performance note: It might be tempting to extract commonly used fields from
the md structure (e.g. utf, end_subject) into individual variables to improve
performance. Tests using gcc on a SPARC disproved this; in the first case, it
made performance worse.
Arguments:
eptr pointer to current character in subject
ecode pointer to current position in compiled code
mstart pointer to the current match start position (can be modified
by encountering \K)
offset_top current top pointer
md pointer to "static" info for the match
eptrb pointer to chain of blocks containing eptr at start of
brackets - for testing for empty matches
rdepth the recursion depth
Returns: MATCH_MATCH if matched ) these values are >= 0
MATCH_NOMATCH if failed to match )
a negative MATCH_xxx value for PRUNE, SKIP, etc
a negative PCRE_ERROR_xxx value if aborted by an error condition
(e.g. stopped by repeated call or recursion limit)
*/
static int
match(REGISTER PCRE_PUCHAR eptr, REGISTER const pcre_uchar *ecode,
PCRE_PUCHAR mstart, int offset_top, match_data *md, eptrblock *eptrb,
unsigned int rdepth)
{
/* These variables do not need to be preserved over recursion in this function,
so they can be ordinary variables in all cases. Mark some of them with
"register" because they are used a lot in loops. */
register int rrc; /* Returns from recursive calls */
register int i; /* Used for loops not involving calls to RMATCH() */
register pcre_uint32 c; /* Character values not kept over RMATCH() calls */
register BOOL utf; /* Local copy of UTF flag for speed */
BOOL minimize, possessive; /* Quantifier options */
BOOL caseless;
int condcode;
/* When recursion is not being used, all "local" variables that have to be
preserved over calls to RMATCH() are part of a "frame". We set up the top-level
frame on the stack here; subsequent instantiations are obtained from the heap
whenever RMATCH() does a "recursion". See the macro definitions above. Putting
the top-level on the stack rather than malloc-ing them all gives a performance
boost in many cases where there is not much "recursion". */
#ifdef NO_RECURSE
heapframe *frame = (heapframe *)md->match_frames_base;
/* Copy in the original argument variables */
frame->Xeptr = eptr;
frame->Xecode = ecode;
frame->Xmstart = mstart;
frame->Xoffset_top = offset_top;
frame->Xeptrb = eptrb;
frame->Xrdepth = rdepth;
/* This is where control jumps back to to effect "recursion" */
HEAP_RECURSE:
/* Macros make the argument variables come from the current frame */
#define eptr frame->Xeptr
#define ecode frame->Xecode
#define mstart frame->Xmstart
#define offset_top frame->Xoffset_top
#define eptrb frame->Xeptrb
#define rdepth frame->Xrdepth
/* Ditto for the local variables */
#ifdef SUPPORT_UTF
#define charptr frame->Xcharptr
#endif
#define callpat frame->Xcallpat
#define codelink frame->Xcodelink
#define data frame->Xdata
#define next frame->Xnext
#define pp frame->Xpp
#define prev frame->Xprev
#define saved_eptr frame->Xsaved_eptr
#define new_recursive frame->Xnew_recursive
#define cur_is_word frame->Xcur_is_word
#define condition frame->Xcondition
#define prev_is_word frame->Xprev_is_word
#ifdef SUPPORT_UCP
#define prop_type frame->Xprop_type
#define prop_value frame->Xprop_value
#define prop_fail_result frame->Xprop_fail_result
#define oclength frame->Xoclength
#define occhars frame->Xocchars
#endif
#define ctype frame->Xctype
#define fc frame->Xfc
#define fi frame->Xfi
#define length frame->Xlength
#define max frame->Xmax
#define min frame->Xmin
#define number frame->Xnumber
#define offset frame->Xoffset
#define op frame->Xop
#define save_capture_last frame->Xsave_capture_last
#define save_offset1 frame->Xsave_offset1
#define save_offset2 frame->Xsave_offset2
#define save_offset3 frame->Xsave_offset3
#define stacksave frame->Xstacksave
#define newptrb frame->Xnewptrb
/* When recursion is being used, local variables are allocated on the stack and
get preserved during recursion in the normal way. In this environment, fi and
i, and fc and c, can be the same variables. */
#else /* NO_RECURSE not defined */
#define fi i
#define fc c
/* Many of the following variables are used only in small blocks of the code.
My normal style of coding would have declared them within each of those blocks.
However, in order to accommodate the version of this code that uses an external
"stack" implemented on the heap, it is easier to declare them all here, so the
declarations can be cut out in a block. The only declarations within blocks
below are for variables that do not have to be preserved over a recursive call
to RMATCH(). */
#ifdef SUPPORT_UTF
const pcre_uchar *charptr;
#endif
const pcre_uchar *callpat;
const pcre_uchar *data;
const pcre_uchar *next;
PCRE_PUCHAR pp;
const pcre_uchar *prev;
PCRE_PUCHAR saved_eptr;
recursion_info new_recursive;
BOOL cur_is_word;
BOOL condition;
BOOL prev_is_word;
#ifdef SUPPORT_UCP
int prop_type;
unsigned int prop_value;
int prop_fail_result;
int oclength;
pcre_uchar occhars[6];
#endif
int codelink;
int ctype;
int length;
int max;
int min;
unsigned int number;
int offset;
unsigned int op;
pcre_int32 save_capture_last;
int save_offset1, save_offset2, save_offset3;
int stacksave[REC_STACK_SAVE_MAX];
eptrblock newptrb;
/* There is a special fudge for calling match() in a way that causes it to
measure the size of its basic stack frame when the stack is being used for
recursion. The second argument (ecode) being NULL triggers this behaviour. It
cannot normally ever be NULL. The return is the negated value of the frame
size. */
if (ecode == NULL)
{
if (rdepth == 0)
return match((PCRE_PUCHAR)&rdepth, NULL, NULL, 0, NULL, NULL, 1);
else
{
int len = (int)((char *)&rdepth - (char *)eptr);
return (len > 0)? -len : len;
}
}
#endif /* NO_RECURSE */
/* To save space on the stack and in the heap frame, I have doubled up on some
of the local variables that are used only in localised parts of the code, but
still need to be preserved over recursive calls of match(). These macros define
the alternative names that are used. */
#define allow_zero cur_is_word
#define cbegroup condition
#define code_offset codelink
#define condassert condition
#define matched_once prev_is_word
#define foc number
#define save_mark data
/* These statements are here to stop the compiler complaining about unitialized
variables. */
#ifdef SUPPORT_UCP
prop_value = 0;
prop_fail_result = 0;
#endif
/* This label is used for tail recursion, which is used in a few cases even
when NO_RECURSE is not defined, in order to reduce the amount of stack that is
used. Thanks to Ian Taylor for noticing this possibility and sending the
original patch. */
TAIL_RECURSE:
/* OK, now we can get on with the real code of the function. Recursive calls
are specified by the macro RMATCH and RRETURN is used to return. When
NO_RECURSE is *not* defined, these just turn into a recursive call to match()
and a "return", respectively (possibly with some debugging if PCRE_DEBUG is
defined). However, RMATCH isn't like a function call because it's quite a
complicated macro. It has to be used in one particular way. This shouldn't,
however, impact performance when true recursion is being used. */
#ifdef SUPPORT_UTF
utf = md->utf; /* Local copy of the flag */
#else
utf = FALSE;
#endif
/* First check that we haven't called match() too many times, or that we
haven't exceeded the recursive call limit. */
if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT);
if (rdepth >= md->match_limit_recursion) RRETURN(PCRE_ERROR_RECURSIONLIMIT);
/* At the start of a group with an unlimited repeat that may match an empty
string, the variable md->match_function_type is set to MATCH_CBEGROUP. It is
done this way to save having to use another function argument, which would take
up space on the stack. See also MATCH_CONDASSERT below.
When MATCH_CBEGROUP is set, add the current subject pointer to the chain of
such remembered pointers, to be checked when we hit the closing ket, in order
to break infinite loops that match no characters. When match() is called in
other circumstances, don't add to the chain. The MATCH_CBEGROUP feature must
NOT be used with tail recursion, because the memory block that is used is on
the stack, so a new one may be required for each match(). */
if (md->match_function_type == MATCH_CBEGROUP)
{
newptrb.epb_saved_eptr = eptr;
newptrb.epb_prev = eptrb;
eptrb = &newptrb;
md->match_function_type = 0;
}
/* Now start processing the opcodes. */
for (;;)
{
minimize = possessive = FALSE;
op = *ecode;
switch(op)
{
case OP_MARK:
md->nomatch_mark = ecode + 2;
md->mark = NULL; /* In case previously set by assertion */
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md,
eptrb, RM55);
if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) &&
md->mark == NULL) md->mark = ecode + 2;
/* A return of MATCH_SKIP_ARG means that matching failed at SKIP with an
argument, and we must check whether that argument matches this MARK's
argument. It is passed back in md->start_match_ptr (an overloading of that
variable). If it does match, we reset that variable to the current subject
position and return MATCH_SKIP. Otherwise, pass back the return code
unaltered. */
else if (rrc == MATCH_SKIP_ARG &&
STRCMP_UC_UC_TEST(ecode + 2, md->start_match_ptr) == 0)
{
md->start_match_ptr = eptr;
RRETURN(MATCH_SKIP);
}
RRETURN(rrc);
case OP_FAIL:
RRETURN(MATCH_NOMATCH);
case OP_COMMIT:
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM52);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
RRETURN(MATCH_COMMIT);
case OP_PRUNE:
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM51);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
RRETURN(MATCH_PRUNE);
case OP_PRUNE_ARG:
md->nomatch_mark = ecode + 2;
md->mark = NULL; /* In case previously set by assertion */
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md,
eptrb, RM56);
if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) &&
md->mark == NULL) md->mark = ecode + 2;
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
RRETURN(MATCH_PRUNE);
case OP_SKIP:
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM53);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->start_match_ptr = eptr; /* Pass back current position */
RRETURN(MATCH_SKIP);
/* Note that, for Perl compatibility, SKIP with an argument does NOT set
nomatch_mark. When a pattern match ends with a SKIP_ARG for which there was
not a matching mark, we have to re-run the match, ignoring the SKIP_ARG
that failed and any that precede it (either they also failed, or were not
triggered). To do this, we maintain a count of executed SKIP_ARGs. If a
SKIP_ARG gets to top level, the match is re-run with md->ignore_skip_arg
set to the count of the one that failed. */
case OP_SKIP_ARG:
md->skip_arg_count++;
if (md->skip_arg_count <= md->ignore_skip_arg)
{
ecode += PRIV(OP_lengths)[*ecode] + ecode[1];
break;
}
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md,
eptrb, RM57);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
/* Pass back the current skip name by overloading md->start_match_ptr and
returning the special MATCH_SKIP_ARG return code. This will either be
caught by a matching MARK, or get to the top, where it causes a rematch
with md->ignore_skip_arg set to the value of md->skip_arg_count. */
md->start_match_ptr = ecode + 2;
RRETURN(MATCH_SKIP_ARG);
/* For THEN (and THEN_ARG) we pass back the address of the opcode, so that
the branch in which it occurs can be determined. Overload the start of
match pointer to do this. */
case OP_THEN:
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM54);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->start_match_ptr = ecode;
RRETURN(MATCH_THEN);
case OP_THEN_ARG:
md->nomatch_mark = ecode + 2;
md->mark = NULL; /* In case previously set by assertion */
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top,
md, eptrb, RM58);
if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) &&
md->mark == NULL) md->mark = ecode + 2;
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->start_match_ptr = ecode;
RRETURN(MATCH_THEN);
/* Handle an atomic group that does not contain any capturing parentheses.
This can be handled like an assertion. Prior to 8.13, all atomic groups
were handled this way. In 8.13, the code was changed as below for ONCE, so
that backups pass through the group and thereby reset captured values.
However, this uses a lot more stack, so in 8.20, atomic groups that do not
contain any captures generate OP_ONCE_NC, which can be handled in the old,
less stack intensive way.
Check the alternative branches in turn - the matching won't pass the KET
for this kind of subpattern. If any one branch matches, we carry on as at
the end of a normal bracket, leaving the subject pointer, but resetting
the start-of-match value in case it was changed by \K. */
case OP_ONCE_NC:
prev = ecode;
saved_eptr = eptr;
save_mark = md->mark;
do
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM64);
if (rrc == MATCH_MATCH) /* Note: _not_ MATCH_ACCEPT */
{
mstart = md->start_match_ptr;
break;
}
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode += GET(ecode,1);
md->mark = save_mark;
}
while (*ecode == OP_ALT);
/* If hit the end of the group (which could be repeated), fail */
if (*ecode != OP_ONCE_NC && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH);
/* Continue as from after the group, updating the offsets high water
mark, since extracts may have been taken. */
do ecode += GET(ecode, 1); while (*ecode == OP_ALT);
offset_top = md->end_offset_top;
eptr = md->end_match_ptr;
/* For a non-repeating ket, just continue at this level. This also
happens for a repeating ket if no characters were matched in the group.
This is the forcible breaking of infinite loops as implemented in Perl
5.005. */
if (*ecode == OP_KET || eptr == saved_eptr)
{
ecode += 1+LINK_SIZE;
break;
}
/* The repeating kets try the rest of the pattern or restart from the
preceding bracket, in the appropriate order. The second "call" of match()
uses tail recursion, to avoid using another stack frame. */
if (*ecode == OP_KETRMIN)
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM65);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode = prev;
goto TAIL_RECURSE;
}
else /* OP_KETRMAX */
{
RMATCH(eptr, prev, offset_top, md, eptrb, RM66);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode += 1 + LINK_SIZE;
goto TAIL_RECURSE;
}
/* Control never gets here */
/* Handle a capturing bracket, other than those that are possessive with an
unlimited repeat. If there is space in the offset vector, save the current
subject position in the working slot at the top of the vector. We mustn't
change the current values of the data slot, because they may be set from a
previous iteration of this group, and be referred to by a reference inside
the group. A failure to match might occur after the group has succeeded,
if something later on doesn't match. For this reason, we need to restore
the working value and also the values of the final offsets, in case they
were set by a previous iteration of the same bracket.
If there isn't enough space in the offset vector, treat this as if it were
a non-capturing bracket. Don't worry about setting the flag for the error
case here; that is handled in the code for KET. */
case OP_CBRA:
case OP_SCBRA:
number = GET2(ecode, 1+LINK_SIZE);
offset = number << 1;
#ifdef PCRE_DEBUG
printf("start bracket %d\n", number);
printf("subject=");
pchars(eptr, 16, TRUE, md);
printf("\n");
#endif
if (offset < md->offset_max)
{
save_offset1 = md->offset_vector[offset];
save_offset2 = md->offset_vector[offset+1];
save_offset3 = md->offset_vector[md->offset_end - number];
save_capture_last = md->capture_last;
save_mark = md->mark;
DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3));
md->offset_vector[md->offset_end - number] =
(int)(eptr - md->start_subject);
for (;;)
{
if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP;
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM1);
if (rrc == MATCH_ONCE) break; /* Backing up through an atomic group */
/* If we backed up to a THEN, check whether it is within the current
branch by comparing the address of the THEN that is passed back with
the end of the branch. If it is within the current branch, and the
branch is one of two or more alternatives (it either starts or ends
with OP_ALT), we have reached the limit of THEN's action, so convert
the return code to NOMATCH, which will cause normal backtracking to
happen from now on. Otherwise, THEN is passed back to an outer
alternative. This implements Perl's treatment of parenthesized groups,
where a group not containing | does not affect the current alternative,
that is, (X) is NOT the same as (X|(*F)). */
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
/* Anything other than NOMATCH is passed back. */
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->capture_last = save_capture_last;
ecode += GET(ecode, 1);
md->mark = save_mark;
if (*ecode != OP_ALT) break;
}
DPRINTF(("bracket %d failed\n", number));
md->offset_vector[offset] = save_offset1;
md->offset_vector[offset+1] = save_offset2;
md->offset_vector[md->offset_end - number] = save_offset3;
/* At this point, rrc will be one of MATCH_ONCE or MATCH_NOMATCH. */
RRETURN(rrc);
}
/* FALL THROUGH ... Insufficient room for saving captured contents. Treat
as a non-capturing bracket. */
/* VVVVVVVVVVVVVVVVVVVVVVVVV */
/* VVVVVVVVVVVVVVVVVVVVVVVVV */
DPRINTF(("insufficient capture room: treat as non-capturing\n"));
/* VVVVVVVVVVVVVVVVVVVVVVVVV */
/* VVVVVVVVVVVVVVVVVVVVVVVVV */
/* Non-capturing or atomic group, except for possessive with unlimited
repeat and ONCE group with no captures. Loop for all the alternatives.
When we get to the final alternative within the brackets, we used to return
the result of a recursive call to match() whatever happened so it was
possible to reduce stack usage by turning this into a tail recursion,
except in the case of a possibly empty group. However, now that there is
the possiblity of (*THEN) occurring in the final alternative, this
optimization is no longer always possible.
We can optimize if we know there are no (*THEN)s in the pattern; at present
this is the best that can be done.
MATCH_ONCE is returned when the end of an atomic group is successfully
reached, but subsequent matching fails. It passes back up the tree (causing
captured values to be reset) until the original atomic group level is
reached. This is tested by comparing md->once_target with the start of the
group. At this point, the return is converted into MATCH_NOMATCH so that
previous backup points can be taken. */
case OP_ONCE:
case OP_BRA:
case OP_SBRA:
DPRINTF(("start non-capturing bracket\n"));
for (;;)
{
if (op >= OP_SBRA || op == OP_ONCE)
md->match_function_type = MATCH_CBEGROUP;
/* If this is not a possibly empty group, and there are no (*THEN)s in
the pattern, and this is the final alternative, optimize as described
above. */
else if (!md->hasthen && ecode[GET(ecode, 1)] != OP_ALT)
{
ecode += PRIV(OP_lengths)[*ecode];
goto TAIL_RECURSE;
}
/* In all other cases, we have to make another call to match(). */
save_mark = md->mark;
save_capture_last = md->capture_last;
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, eptrb,
RM2);
/* See comment in the code for capturing groups above about handling
THEN. */
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
if (rrc != MATCH_NOMATCH)
{
if (rrc == MATCH_ONCE)
{
const pcre_uchar *scode = ecode;
if (*scode != OP_ONCE) /* If not at start, find it */
{
while (*scode == OP_ALT) scode += GET(scode, 1);
scode -= GET(scode, 1);
}
if (md->once_target == scode) rrc = MATCH_NOMATCH;
}
RRETURN(rrc);
}
ecode += GET(ecode, 1);
md->mark = save_mark;
if (*ecode != OP_ALT) break;
md->capture_last = save_capture_last;
}
RRETURN(MATCH_NOMATCH);
/* Handle possessive capturing brackets with an unlimited repeat. We come
here from BRAZERO with allow_zero set TRUE. The offset_vector values are
handled similarly to the normal case above. However, the matching is
different. The end of these brackets will always be OP_KETRPOS, which
returns MATCH_KETRPOS without going further in the pattern. By this means
we can handle the group by iteration rather than recursion, thereby
reducing the amount of stack needed. */
case OP_CBRAPOS:
case OP_SCBRAPOS:
allow_zero = FALSE;
POSSESSIVE_CAPTURE:
number = GET2(ecode, 1+LINK_SIZE);
offset = number << 1;
#ifdef PCRE_DEBUG
printf("start possessive bracket %d\n", number);
printf("subject=");
pchars(eptr, 16, TRUE, md);
printf("\n");
#endif
if (offset >= md->offset_max) goto POSSESSIVE_NON_CAPTURE;
matched_once = FALSE;
code_offset = (int)(ecode - md->start_code);
save_offset1 = md->offset_vector[offset];
save_offset2 = md->offset_vector[offset+1];
save_offset3 = md->offset_vector[md->offset_end - number];
save_capture_last = md->capture_last;
DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3));
/* Each time round the loop, save the current subject position for use
when the group matches. For MATCH_MATCH, the group has matched, so we
restart it with a new subject starting position, remembering that we had
at least one match. For MATCH_NOMATCH, carry on with the alternatives, as
usual. If we haven't matched any alternatives in any iteration, check to
see if a previous iteration matched. If so, the group has matched;
continue from afterwards. Otherwise it has failed; restore the previous
capture values before returning NOMATCH. */
for (;;)
{
md->offset_vector[md->offset_end - number] =
(int)(eptr - md->start_subject);
if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP;
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM63);
if (rrc == MATCH_KETRPOS)
{
offset_top = md->end_offset_top;
ecode = md->start_code + code_offset;
save_capture_last = md->capture_last;
matched_once = TRUE;
mstart = md->start_match_ptr; /* In case \K changed it */
if (eptr == md->end_match_ptr) /* Matched an empty string */
{
do ecode += GET(ecode, 1); while (*ecode == OP_ALT);
break;
}
eptr = md->end_match_ptr;
continue;
}
/* See comment in the code for capturing groups above about handling
THEN. */
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->capture_last = save_capture_last;
ecode += GET(ecode, 1);
if (*ecode != OP_ALT) break;
}
if (!matched_once)
{
md->offset_vector[offset] = save_offset1;
md->offset_vector[offset+1] = save_offset2;
md->offset_vector[md->offset_end - number] = save_offset3;
}
if (allow_zero || matched_once)
{
ecode += 1 + LINK_SIZE;
break;
}
RRETURN(MATCH_NOMATCH);
/* Non-capturing possessive bracket with unlimited repeat. We come here
from BRAZERO with allow_zero = TRUE. The code is similar to the above,
without the capturing complication. It is written out separately for speed
and cleanliness. */
case OP_BRAPOS:
case OP_SBRAPOS:
allow_zero = FALSE;
POSSESSIVE_NON_CAPTURE:
matched_once = FALSE;
code_offset = (int)(ecode - md->start_code);
save_capture_last = md->capture_last;
for (;;)
{
if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP;
RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md,
eptrb, RM48);
if (rrc == MATCH_KETRPOS)
{
offset_top = md->end_offset_top;
ecode = md->start_code + code_offset;
matched_once = TRUE;
mstart = md->start_match_ptr; /* In case \K reset it */
if (eptr == md->end_match_ptr) /* Matched an empty string */
{
do ecode += GET(ecode, 1); while (*ecode == OP_ALT);
break;
}
eptr = md->end_match_ptr;
continue;
}
/* See comment in the code for capturing groups above about handling
THEN. */
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode += GET(ecode, 1);
if (*ecode != OP_ALT) break;
md->capture_last = save_capture_last;
}
if (matched_once || allow_zero)
{
ecode += 1 + LINK_SIZE;
break;
}
RRETURN(MATCH_NOMATCH);
/* Control never reaches here. */
/* Conditional group: compilation checked that there are no more than two
branches. If the condition is false, skipping the first branch takes us
past the end of the item if there is only one branch, but that's exactly
what we want. */
case OP_COND:
case OP_SCOND:
/* The variable codelink will be added to ecode when the condition is
false, to get to the second branch. Setting it to the offset to the ALT
or KET, then incrementing ecode achieves this effect. We now have ecode
pointing to the condition or callout. */
codelink = GET(ecode, 1); /* Offset to the second branch */
ecode += 1 + LINK_SIZE; /* From this opcode */
/* Because of the way auto-callout works during compile, a callout item is
inserted between OP_COND and an assertion condition. */
if (*ecode == OP_CALLOUT)
{
if (PUBL(callout) != NULL)
{
PUBL(callout_block) cb;
cb.version = 2; /* Version 1 of the callout block */
cb.callout_number = ecode[1];
cb.offset_vector = md->offset_vector;
#if defined COMPILE_PCRE8
cb.subject = (PCRE_SPTR)md->start_subject;
#elif defined COMPILE_PCRE16
cb.subject = (PCRE_SPTR16)md->start_subject;
#elif defined COMPILE_PCRE32
cb.subject = (PCRE_SPTR32)md->start_subject;
#endif
cb.subject_length = (int)(md->end_subject - md->start_subject);
cb.start_match = (int)(mstart - md->start_subject);
cb.current_position = (int)(eptr - md->start_subject);
cb.pattern_position = GET(ecode, 2);
cb.next_item_length = GET(ecode, 2 + LINK_SIZE);
cb.capture_top = offset_top/2;
cb.capture_last = md->capture_last & CAPLMASK;
/* Internal change requires this for API compatibility. */
if (cb.capture_last == 0) cb.capture_last = -1;
cb.callout_data = md->callout_data;
cb.mark = md->nomatch_mark;
if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH);
if (rrc < 0) RRETURN(rrc);
}
/* Advance ecode past the callout, so it now points to the condition. We
must adjust codelink so that the value of ecode+codelink is unchanged. */
ecode += PRIV(OP_lengths)[OP_CALLOUT];
codelink -= PRIV(OP_lengths)[OP_CALLOUT];
}
/* Test the various possible conditions */
condition = FALSE;
switch(condcode = *ecode)
{
case OP_RREF: /* Numbered group recursion test */
if (md->recursive != NULL) /* Not recursing => FALSE */
{
unsigned int recno = GET2(ecode, 1); /* Recursion group number*/
condition = (recno == RREF_ANY || recno == md->recursive->group_num);
}
break;
case OP_DNRREF: /* Duplicate named group recursion test */
if (md->recursive != NULL)
{
int count = GET2(ecode, 1 + IMM2_SIZE);
pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size;
while (count-- > 0)
{
unsigned int recno = GET2(slot, 0);
condition = recno == md->recursive->group_num;
if (condition) break;
slot += md->name_entry_size;
}
}
break;
case OP_CREF: /* Numbered group used test */
offset = GET2(ecode, 1) << 1; /* Doubled ref number */
condition = offset < offset_top && md->offset_vector[offset] >= 0;
break;
case OP_DNCREF: /* Duplicate named group used test */
{
int count = GET2(ecode, 1 + IMM2_SIZE);
pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size;
while (count-- > 0)
{
offset = GET2(slot, 0) << 1;
condition = offset < offset_top && md->offset_vector[offset] >= 0;
if (condition) break;
slot += md->name_entry_size;
}
}
break;
case OP_DEF: /* DEFINE - always false */
case OP_FAIL: /* From optimized (?!) condition */
break;
/* The condition is an assertion. Call match() to evaluate it - setting
md->match_function_type to MATCH_CONDASSERT causes it to stop at the end
of an assertion. */
default:
md->match_function_type = MATCH_CONDASSERT;
RMATCH(eptr, ecode, offset_top, md, NULL, RM3);
if (rrc == MATCH_MATCH)
{
if (md->end_offset_top > offset_top)
offset_top = md->end_offset_top; /* Captures may have happened */
condition = TRUE;
/* Advance ecode past the assertion to the start of the first branch,
but adjust it so that the general choosing code below works. If the
assertion has a quantifier that allows zero repeats we must skip over
the BRAZERO. This is a lunatic thing to do, but somebody did! */
if (*ecode == OP_BRAZERO) ecode++;
ecode += GET(ecode, 1);
while (*ecode == OP_ALT) ecode += GET(ecode, 1);
ecode += 1 + LINK_SIZE - PRIV(OP_lengths)[condcode];
}
/* PCRE doesn't allow the effect of (*THEN) to escape beyond an
assertion; it is therefore treated as NOMATCH. Any other return is an
error. */
else if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN)
{
RRETURN(rrc); /* Need braces because of following else */
}
break;
}
/* Choose branch according to the condition */
ecode += condition? PRIV(OP_lengths)[condcode] : codelink;
/* We are now at the branch that is to be obeyed. As there is only one, we
can use tail recursion to avoid using another stack frame, except when
there is unlimited repeat of a possibly empty group. In the latter case, a
recursive call to match() is always required, unless the second alternative
doesn't exist, in which case we can just plough on. Note that, for
compatibility with Perl, the | in a conditional group is NOT treated as
creating two alternatives. If a THEN is encountered in the branch, it
propagates out to the enclosing alternative (unless nested in a deeper set
of alternatives, of course). */
if (condition || ecode[-(1+LINK_SIZE)] == OP_ALT)
{
if (op != OP_SCOND)
{
goto TAIL_RECURSE;
}
md->match_function_type = MATCH_CBEGROUP;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM49);
RRETURN(rrc);
}
/* Condition false & no alternative; continue after the group. */
else
{
}
break;
/* Before OP_ACCEPT there may be any number of OP_CLOSE opcodes,
to close any currently open capturing brackets. */
case OP_CLOSE:
number = GET2(ecode, 1); /* Must be less than 65536 */
offset = number << 1;
#ifdef PCRE_DEBUG
printf("end bracket %d at *ACCEPT", number);
printf("\n");
#endif
md->capture_last = (md->capture_last & OVFLMASK) | number;
if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else
{
md->offset_vector[offset] =
md->offset_vector[md->offset_end - number];
md->offset_vector[offset+1] = (int)(eptr - md->start_subject);
/* If this group is at or above the current highwater mark, ensure that
any groups between the current high water mark and this group are marked
unset and then update the high water mark. */
if (offset >= offset_top)
{
register int *iptr = md->offset_vector + offset_top;
register int *iend = md->offset_vector + offset;
while (iptr < iend) *iptr++ = -1;
offset_top = offset + 2;
}
}
ecode += 1 + IMM2_SIZE;
break;
/* End of the pattern, either real or forced. */
case OP_END:
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
/* If we have matched an empty string, fail if not in an assertion and not
in a recursion if either PCRE_NOTEMPTY is set, or if PCRE_NOTEMPTY_ATSTART
is set and we have matched at the start of the subject. In both cases,
backtracking will then try other alternatives, if any. */
if (eptr == mstart && op != OP_ASSERT_ACCEPT &&
md->recursive == NULL &&
(md->notempty ||
(md->notempty_atstart &&
mstart == md->start_subject + md->start_offset)))
RRETURN(MATCH_NOMATCH);
/* Otherwise, we have a match. */
md->end_match_ptr = eptr; /* Record where we ended */
md->end_offset_top = offset_top; /* and how many extracts were taken */
md->start_match_ptr = mstart; /* and the start (\K can modify) */
/* For some reason, the macros don't work properly if an expression is
given as the argument to RRETURN when the heap is in use. */
rrc = (op == OP_END)? MATCH_MATCH : MATCH_ACCEPT;
RRETURN(rrc);
/* Assertion brackets. Check the alternative branches in turn - the
matching won't pass the KET for an assertion. If any one branch matches,
the assertion is true. Lookbehind assertions have an OP_REVERSE item at the
start of each branch to move the current point backwards, so the code at
this level is identical to the lookahead case. When the assertion is part
of a condition, we want to return immediately afterwards. The caller of
this incarnation of the match() function will have set MATCH_CONDASSERT in
md->match_function type, and one of these opcodes will be the first opcode
that is processed. We use a local variable that is preserved over calls to
match() to remember this case. */
case OP_ASSERT:
case OP_ASSERTBACK:
save_mark = md->mark;
if (md->match_function_type == MATCH_CONDASSERT)
{
condassert = TRUE;
md->match_function_type = 0;
}
else condassert = FALSE;
/* Loop for each branch */
do
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM4);
/* A match means that the assertion is true; break out of the loop
that matches its alternatives. */
if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT)
{
mstart = md->start_match_ptr; /* In case \K reset it */
break;
}
/* If not matched, restore the previous mark setting. */
md->mark = save_mark;
/* See comment in the code for capturing groups above about handling
THEN. */
if (rrc == MATCH_THEN)
{
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
rrc = MATCH_NOMATCH;
}
/* Anything other than NOMATCH causes the entire assertion to fail,
passing back the return code. This includes COMMIT, SKIP, PRUNE and an
uncaptured THEN, which means they take their normal effect. This
consistent approach does not always have exactly the same effect as in
Perl. */
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode += GET(ecode, 1);
}
while (*ecode == OP_ALT); /* Continue for next alternative */
/* If we have tried all the alternative branches, the assertion has
failed. If not, we broke out after a match. */
if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH);
/* If checking an assertion for a condition, return MATCH_MATCH. */
if (condassert) RRETURN(MATCH_MATCH);
/* Continue from after a successful assertion, updating the offsets high
water mark, since extracts may have been taken during the assertion. */
do ecode += GET(ecode,1); while (*ecode == OP_ALT);
ecode += 1 + LINK_SIZE;
offset_top = md->end_offset_top;
continue;
/* Negative assertion: all branches must fail to match for the assertion to
succeed. */
case OP_ASSERT_NOT:
case OP_ASSERTBACK_NOT:
save_mark = md->mark;
if (md->match_function_type == MATCH_CONDASSERT)
{
condassert = TRUE;
md->match_function_type = 0;
}
else condassert = FALSE;
/* Loop for each alternative branch. */
do
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM5);
md->mark = save_mark; /* Always restore the mark setting */
switch(rrc)
{
case MATCH_MATCH: /* A successful match means */
case MATCH_ACCEPT: /* the assertion has failed. */
RRETURN(MATCH_NOMATCH);
case MATCH_NOMATCH: /* Carry on with next branch */
break;
/* See comment in the code for capturing groups above about handling
THEN. */
case MATCH_THEN:
next = ecode + GET(ecode,1);
if (md->start_match_ptr < next &&
(*ecode == OP_ALT || *next == OP_ALT))
{
rrc = MATCH_NOMATCH;
break;
}
/* Otherwise fall through. */
/* COMMIT, SKIP, PRUNE, and an uncaptured THEN cause the whole
assertion to fail to match, without considering any more alternatives.
Failing to match means the assertion is true. This is a consistent
approach, but does not always have the same effect as in Perl. */
case MATCH_COMMIT:
case MATCH_SKIP:
case MATCH_SKIP_ARG:
case MATCH_PRUNE:
do ecode += GET(ecode,1); while (*ecode == OP_ALT);
goto NEG_ASSERT_TRUE; /* Break out of alternation loop */
/* Anything else is an error */
default:
RRETURN(rrc);
}
/* Continue with next branch */
ecode += GET(ecode,1);
}
while (*ecode == OP_ALT);
/* All branches in the assertion failed to match. */
NEG_ASSERT_TRUE:
if (condassert) RRETURN(MATCH_MATCH); /* Condition assertion */
ecode += 1 + LINK_SIZE; /* Continue with current branch */
continue;
/* Move the subject pointer back. This occurs only at the start of
each branch of a lookbehind assertion. If we are too close to the start to
move back, this match function fails. When working with UTF-8 we move
back a number of characters, not bytes. */
case OP_REVERSE:
#ifdef SUPPORT_UTF
if (utf)
{
i = GET(ecode, 1);
while (i-- > 0)
{
eptr--;
if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH);
BACKCHAR(eptr);
}
}
else
#endif
/* No UTF-8 support, or not in UTF-8 mode: count is byte count */
{
eptr -= GET(ecode, 1);
if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH);
}
/* Save the earliest consulted character, then skip to next op code */
if (eptr < md->start_used_ptr) md->start_used_ptr = eptr;
ecode += 1 + LINK_SIZE;
break;
/* The callout item calls an external function, if one is provided, passing
details of the match so far. This is mainly for debugging, though the
function is able to force a failure. */
case OP_CALLOUT:
if (PUBL(callout) != NULL)
{
PUBL(callout_block) cb;
cb.version = 2; /* Version 1 of the callout block */
cb.callout_number = ecode[1];
cb.offset_vector = md->offset_vector;
#if defined COMPILE_PCRE8
cb.subject = (PCRE_SPTR)md->start_subject;
#elif defined COMPILE_PCRE16
cb.subject = (PCRE_SPTR16)md->start_subject;
#elif defined COMPILE_PCRE32
cb.subject = (PCRE_SPTR32)md->start_subject;
#endif
cb.subject_length = (int)(md->end_subject - md->start_subject);
cb.start_match = (int)(mstart - md->start_subject);
cb.current_position = (int)(eptr - md->start_subject);
cb.pattern_position = GET(ecode, 2);
cb.next_item_length = GET(ecode, 2 + LINK_SIZE);
cb.capture_top = offset_top/2;
cb.capture_last = md->capture_last & CAPLMASK;
/* Internal change requires this for API compatibility. */
if (cb.capture_last == 0) cb.capture_last = -1;
cb.callout_data = md->callout_data;
cb.mark = md->nomatch_mark;
if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH);
if (rrc < 0) RRETURN(rrc);
}
ecode += 2 + 2*LINK_SIZE;
break;
/* Recursion either matches the current regex, or some subexpression. The
offset data is the offset to the starting bracket from the start of the
whole pattern. (This is so that it works from duplicated subpatterns.)
The state of the capturing groups is preserved over recursion, and
re-instated afterwards. We don't know how many are started and not yet
finished (offset_top records the completed total) so we just have to save
all the potential data. There may be up to 65535 such values, which is too
large to put on the stack, but using malloc for small numbers seems
expensive. As a compromise, the stack is used when there are no more than
REC_STACK_SAVE_MAX values to store; otherwise malloc is used.
There are also other values that have to be saved. We use a chained
sequence of blocks that actually live on the stack. Thanks to Robin Houston
for the original version of this logic. It has, however, been hacked around
a lot, so he is not to blame for the current way it works. */
case OP_RECURSE:
{
recursion_info *ri;
unsigned int recno;
callpat = md->start_code + GET(ecode, 1);
recno = (callpat == md->start_code)? 0 :
GET2(callpat, 1 + LINK_SIZE);
/* Check for repeating a recursion without advancing the subject pointer.
This should catch convoluted mutual recursions. (Some simple cases are
caught at compile time.) */
for (ri = md->recursive; ri != NULL; ri = ri->prevrec)
if (recno == ri->group_num && eptr == ri->subject_position)
RRETURN(PCRE_ERROR_RECURSELOOP);
/* Add to "recursing stack" */
new_recursive.group_num = recno;
new_recursive.saved_capture_last = md->capture_last;
new_recursive.subject_position = eptr;
new_recursive.prevrec = md->recursive;
md->recursive = &new_recursive;
/* Where to continue from afterwards */
ecode += 1 + LINK_SIZE;
/* Now save the offset data */
new_recursive.saved_max = md->offset_end;
if (new_recursive.saved_max <= REC_STACK_SAVE_MAX)
new_recursive.offset_save = stacksave;
else
{
new_recursive.offset_save =
(int *)(PUBL(malloc))(new_recursive.saved_max * sizeof(int));
if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY);
}
memcpy(new_recursive.offset_save, md->offset_vector,
new_recursive.saved_max * sizeof(int));
/* OK, now we can do the recursion. After processing each alternative,
restore the offset data and the last captured value. If there were nested
recursions, md->recursive might be changed, so reset it before looping.
*/
DPRINTF(("Recursing into group %d\n", new_recursive.group_num));
cbegroup = (*callpat >= OP_SBRA);
do
{
if (cbegroup) md->match_function_type = MATCH_CBEGROUP;
RMATCH(eptr, callpat + PRIV(OP_lengths)[*callpat], offset_top,
md, eptrb, RM6);
memcpy(md->offset_vector, new_recursive.offset_save,
new_recursive.saved_max * sizeof(int));
md->capture_last = new_recursive.saved_capture_last;
md->recursive = new_recursive.prevrec;
if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT)
{
DPRINTF(("Recursion matched\n"));
if (new_recursive.offset_save != stacksave)
(PUBL(free))(new_recursive.offset_save);
/* Set where we got to in the subject, and reset the start in case
it was changed by \K. This *is* propagated back out of a recursion,
for Perl compatibility. */
eptr = md->end_match_ptr;
mstart = md->start_match_ptr;
goto RECURSION_MATCHED; /* Exit loop; end processing */
}
/* PCRE does not allow THEN, SKIP, PRUNE or COMMIT to escape beyond a
recursion; they cause a NOMATCH for the entire recursion. These codes
are defined in a range that can be tested for. */
if (rrc >= MATCH_BACKTRACK_MIN && rrc <= MATCH_BACKTRACK_MAX)
{
if (new_recursive.offset_save != stacksave)
(PUBL(free))(new_recursive.offset_save);
RRETURN(MATCH_NOMATCH);
}
/* Any return code other than NOMATCH is an error. */
if (rrc != MATCH_NOMATCH)
{
DPRINTF(("Recursion gave error %d\n", rrc));
if (new_recursive.offset_save != stacksave)
(PUBL(free))(new_recursive.offset_save);
RRETURN(rrc);
}
md->recursive = &new_recursive;
callpat += GET(callpat, 1);
}
while (*callpat == OP_ALT);
DPRINTF(("Recursion didn't match\n"));
md->recursive = new_recursive.prevrec;
if (new_recursive.offset_save != stacksave)
(PUBL(free))(new_recursive.offset_save);
RRETURN(MATCH_NOMATCH);
}
RECURSION_MATCHED:
break;
/* An alternation is the end of a branch; scan along to find the end of the
bracketed group and go to there. */
case OP_ALT:
do ecode += GET(ecode,1); while (*ecode == OP_ALT);
break;
/* BRAZERO, BRAMINZERO and SKIPZERO occur just before a bracket group,
indicating that it may occur zero times. It may repeat infinitely, or not
at all - i.e. it could be ()* or ()? or even (){0} in the pattern. Brackets
with fixed upper repeat limits are compiled as a number of copies, with the
optional ones preceded by BRAZERO or BRAMINZERO. */
case OP_BRAZERO:
next = ecode + 1;
RMATCH(eptr, next, offset_top, md, eptrb, RM10);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
do next += GET(next, 1); while (*next == OP_ALT);
ecode = next + 1 + LINK_SIZE;
break;
case OP_BRAMINZERO:
next = ecode + 1;
do next += GET(next, 1); while (*next == OP_ALT);
RMATCH(eptr, next + 1+LINK_SIZE, offset_top, md, eptrb, RM11);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
ecode++;
break;
case OP_SKIPZERO:
next = ecode+1;
do next += GET(next,1); while (*next == OP_ALT);
ecode = next + 1 + LINK_SIZE;
break;
/* BRAPOSZERO occurs before a possessive bracket group. Don't do anything
here; just jump to the group, with allow_zero set TRUE. */
case OP_BRAPOSZERO:
op = *(++ecode);
allow_zero = TRUE;
if (op == OP_CBRAPOS || op == OP_SCBRAPOS) goto POSSESSIVE_CAPTURE;
goto POSSESSIVE_NON_CAPTURE;
/* End of a group, repeated or non-repeating. */
case OP_KET:
case OP_KETRMIN:
case OP_KETRMAX:
case OP_KETRPOS:
prev = ecode - GET(ecode, 1);
/* If this was a group that remembered the subject start, in order to break
infinite repeats of empty string matches, retrieve the subject start from
the chain. Otherwise, set it NULL. */
if (*prev >= OP_SBRA || *prev == OP_ONCE)
{
saved_eptr = eptrb->epb_saved_eptr; /* Value at start of group */
eptrb = eptrb->epb_prev; /* Backup to previous group */
}
else saved_eptr = NULL;
/* If we are at the end of an assertion group or a non-capturing atomic
group, stop matching and return MATCH_MATCH, but record the current high
water mark for use by positive assertions. We also need to record the match
start in case it was changed by \K. */
if ((*prev >= OP_ASSERT && *prev <= OP_ASSERTBACK_NOT) ||
*prev == OP_ONCE_NC)
{
md->end_match_ptr = eptr; /* For ONCE_NC */
md->end_offset_top = offset_top;
md->start_match_ptr = mstart;
RRETURN(MATCH_MATCH); /* Sets md->mark */
}
/* For capturing groups we have to check the group number back at the start
and if necessary complete handling an extraction by setting the offsets and
bumping the high water mark. Whole-pattern recursion is coded as a recurse
into group 0, so it won't be picked up here. Instead, we catch it when the
OP_END is reached. Other recursion is handled here. We just have to record
the current subject position and start match pointer and give a MATCH
return. */
if (*prev == OP_CBRA || *prev == OP_SCBRA ||
*prev == OP_CBRAPOS || *prev == OP_SCBRAPOS)
{
number = GET2(prev, 1+LINK_SIZE);
offset = number << 1;
#ifdef PCRE_DEBUG
printf("end bracket %d", number);
printf("\n");
#endif
/* Handle a recursively called group. */
if (md->recursive != NULL && md->recursive->group_num == number)
{
md->end_match_ptr = eptr;
md->start_match_ptr = mstart;
RRETURN(MATCH_MATCH);
}
/* Deal with capturing */
md->capture_last = (md->capture_last & OVFLMASK) | number;
if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else
{
/* If offset is greater than offset_top, it means that we are
"skipping" a capturing group, and that group's offsets must be marked
unset. In earlier versions of PCRE, all the offsets were unset at the
start of matching, but this doesn't work because atomic groups and
assertions can cause a value to be set that should later be unset.
Example: matching /(?>(a))b|(a)c/ against "ac". This sets group 1 as
part of the atomic group, but this is not on the final matching path,
so must be unset when 2 is set. (If there is no group 2, there is no
problem, because offset_top will then be 2, indicating no capture.) */
if (offset > offset_top)
{
register int *iptr = md->offset_vector + offset_top;
register int *iend = md->offset_vector + offset;
while (iptr < iend) *iptr++ = -1;
}
/* Now make the extraction */
md->offset_vector[offset] =
md->offset_vector[md->offset_end - number];
md->offset_vector[offset+1] = (int)(eptr - md->start_subject);
if (offset_top <= offset) offset_top = offset + 2;
}
}
/* OP_KETRPOS is a possessive repeating ket. Remember the current position,
and return the MATCH_KETRPOS. This makes it possible to do the repeats one
at a time from the outer level, thus saving stack. This must precede the
empty string test - in this case that test is done at the outer level. */
if (*ecode == OP_KETRPOS)
{
md->start_match_ptr = mstart; /* In case \K reset it */
md->end_match_ptr = eptr;
md->end_offset_top = offset_top;
RRETURN(MATCH_KETRPOS);
}
/* For an ordinary non-repeating ket, just continue at this level. This
also happens for a repeating ket if no characters were matched in the
group. This is the forcible breaking of infinite loops as implemented in
Perl 5.005. For a non-repeating atomic group that includes captures,
establish a backup point by processing the rest of the pattern at a lower
level. If this results in a NOMATCH return, pass MATCH_ONCE back to the
original OP_ONCE level, thereby bypassing intermediate backup points, but
resetting any captures that happened along the way. */
if (*ecode == OP_KET || eptr == saved_eptr)
{
if (*prev == OP_ONCE)
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM12);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */
RRETURN(MATCH_ONCE);
}
ecode += 1 + LINK_SIZE; /* Carry on at this level */
break;
}
/* The normal repeating kets try the rest of the pattern or restart from
the preceding bracket, in the appropriate order. In the second case, we can
use tail recursion to avoid using another stack frame, unless we have an
an atomic group or an unlimited repeat of a group that can match an empty
string. */
if (*ecode == OP_KETRMIN)
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM7);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (*prev == OP_ONCE)
{
RMATCH(eptr, prev, offset_top, md, eptrb, RM8);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */
RRETURN(MATCH_ONCE);
}
if (*prev >= OP_SBRA) /* Could match an empty string */
{
RMATCH(eptr, prev, offset_top, md, eptrb, RM50);
RRETURN(rrc);
}
ecode = prev;
goto TAIL_RECURSE;
}
else /* OP_KETRMAX */
{
RMATCH(eptr, prev, offset_top, md, eptrb, RM13);
if (rrc == MATCH_ONCE && md->once_target == prev) rrc = MATCH_NOMATCH;
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (*prev == OP_ONCE)
{
RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM9);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
md->once_target = prev;
RRETURN(MATCH_ONCE);
}
ecode += 1 + LINK_SIZE;
goto TAIL_RECURSE;
}
/* Control never gets here */
/* Not multiline mode: start of subject assertion, unless notbol. */
case OP_CIRC:
if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH);
/* Start of subject assertion */
case OP_SOD:
if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH);
ecode++;
break;
/* Multiline mode: start of subject unless notbol, or after any newline. */
case OP_CIRCM:
if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH);
if (eptr != md->start_subject &&
(eptr == md->end_subject || !WAS_NEWLINE(eptr)))
RRETURN(MATCH_NOMATCH);
ecode++;
break;
/* Start of match assertion */
case OP_SOM:
if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH);
ecode++;
break;
/* Reset the start of match point */
case OP_SET_SOM:
mstart = eptr;
ecode++;
break;
/* Multiline mode: assert before any newline, or before end of subject
unless noteol is set. */
case OP_DOLLM:
if (eptr < md->end_subject)
{
if (!IS_NEWLINE(eptr))
{
if (md->partial != 0 &&
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
UCHAR21TEST(eptr) == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
RRETURN(MATCH_NOMATCH);
}
}
else
{
if (md->noteol) RRETURN(MATCH_NOMATCH);
SCHECK_PARTIAL();
}
ecode++;
break;
/* Not multiline mode: assert before a terminating newline or before end of
subject unless noteol is set. */
case OP_DOLL:
if (md->noteol) RRETURN(MATCH_NOMATCH);
if (!md->endonly) goto ASSERT_NL_OR_EOS;
/* ... else fall through for endonly */
/* End of subject assertion (\z) */
case OP_EOD:
if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH);
SCHECK_PARTIAL();
ecode++;
break;
/* End of subject or ending \n assertion (\Z) */
case OP_EODN:
ASSERT_NL_OR_EOS:
if (eptr < md->end_subject &&
(!IS_NEWLINE(eptr) || eptr != md->end_subject - md->nllen))
{
if (md->partial != 0 &&
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
UCHAR21TEST(eptr) == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
RRETURN(MATCH_NOMATCH);
}
/* Either at end of string or \n before end. */
SCHECK_PARTIAL();
ecode++;
break;
/* Word boundary assertions */
case OP_NOT_WORD_BOUNDARY:
case OP_WORD_BOUNDARY:
{
/* Find out if the previous and current characters are "word" characters.
It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to
be "non-word" characters. Remember the earliest consulted character for
partial matching. */
#ifdef SUPPORT_UTF
if (utf)
{
/* Get status of previous character */
if (eptr == md->start_subject) prev_is_word = FALSE; else
{
PCRE_PUCHAR lastptr = eptr - 1;
BACKCHAR(lastptr);
if (lastptr < md->start_used_ptr) md->start_used_ptr = lastptr;
GETCHAR(c, lastptr);
#ifdef SUPPORT_UCP
if (md->use_ucp)
{
if (c == '_') prev_is_word = TRUE; else
{
int cat = UCD_CATEGORY(c);
prev_is_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0;
}
/* Get status of next character */
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
cur_is_word = FALSE;
}
else
{
GETCHAR(c, eptr);
#ifdef SUPPORT_UCP
if (md->use_ucp)
{
if (c == '_') cur_is_word = TRUE; else
{
int cat = UCD_CATEGORY(c);
cur_is_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0;
}
}
else
#endif
/* Not in UTF-8 mode, but we may still have PCRE_UCP set, and for
consistency with the behaviour of \w we do use it in this case. */
{
/* Get status of previous character */
if (eptr == md->start_subject) prev_is_word = FALSE; else
{
if (eptr <= md->start_used_ptr) md->start_used_ptr = eptr - 1;
#ifdef SUPPORT_UCP
if (md->use_ucp)
{
c = eptr[-1];
if (c == '_') prev_is_word = TRUE; else
{
int cat = UCD_CATEGORY(c);
prev_is_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
prev_is_word = MAX_255(eptr[-1])
&& ((md->ctypes[eptr[-1]] & ctype_word) != 0);
}
/* Get status of next character */
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
cur_is_word = FALSE;
}
else
#ifdef SUPPORT_UCP
if (md->use_ucp)
{
c = *eptr;
if (c == '_') cur_is_word = TRUE; else
{
int cat = UCD_CATEGORY(c);
cur_is_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
cur_is_word = MAX_255(*eptr)
&& ((md->ctypes[*eptr] & ctype_word) != 0);
}
/* Now see if the situation is what we want */
if ((*ecode++ == OP_WORD_BOUNDARY)?
cur_is_word == prev_is_word : cur_is_word != prev_is_word)
RRETURN(MATCH_NOMATCH);
}
break;
/* Match any single character type except newline; have to take care with
CRLF newlines and partial matching. */
case OP_ANY:
if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH);
if (md->partial != 0 &&
eptr == md->end_subject - 1 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
UCHAR21TEST(eptr) == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
/* Fall through */
/* Match any single character whatsoever. */
case OP_ALLANY:
if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */
{ /* not be updated before SCHECK_PARTIAL. */
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr++;
#ifdef SUPPORT_UTF
if (utf) ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
#endif
ecode++;
break;
/* Match a single byte, even in UTF-8 mode. This opcode really does match
any byte, even newline, independent of the setting of PCRE_DOTALL. */
case OP_ANYBYTE:
if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */
{ /* not be updated before SCHECK_PARTIAL. */
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr++;
ecode++;
break;
case OP_NOT_DIGIT:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c < 256 &&
#endif
(md->ctypes[c] & ctype_digit) != 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_DIGIT:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c > 255 ||
#endif
(md->ctypes[c] & ctype_digit) == 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_NOT_WHITESPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c < 256 &&
#endif
(md->ctypes[c] & ctype_space) != 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_WHITESPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c > 255 ||
#endif
(md->ctypes[c] & ctype_space) == 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_NOT_WORDCHAR:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c < 256 &&
#endif
(md->ctypes[c] & ctype_word) != 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_WORDCHAR:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (
#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8)
c > 255 ||
#endif
(md->ctypes[c] & ctype_word) == 0
)
RRETURN(MATCH_NOMATCH);
ecode++;
break;
case OP_ANYNL:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
case CHAR_CR:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
}
else if (UCHAR21TEST(eptr) == CHAR_LF) eptr++;
break;
case CHAR_LF:
break;
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH);
break;
}
ecode++;
break;
case OP_NOT_HSPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */
default: break;
}
ecode++;
break;
case OP_HSPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
HSPACE_CASES: break; /* Byte and multibyte cases */
default: RRETURN(MATCH_NOMATCH);
}
ecode++;
break;
case OP_NOT_VSPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
VSPACE_CASES: RRETURN(MATCH_NOMATCH);
default: break;
}
ecode++;
break;
case OP_VSPACE:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
VSPACE_CASES: break;
default: RRETURN(MATCH_NOMATCH);
}
ecode++;
break;
#ifdef SUPPORT_UCP
/* Check the next character by Unicode property. We will get here only
if the support is in the binary; otherwise a compile-time error occurs. */
case OP_PROP:
case OP_NOTPROP:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
{
const pcre_uint32 *cp;
const ucd_record *prop = GET_UCD(c);
switch(ecode[1])
{
case PT_ANY:
if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH);
break;
case PT_LAMP:
if ((prop->chartype == ucp_Lu ||
prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt) == (op == OP_NOTPROP))
RRETURN(MATCH_NOMATCH);
break;
case PT_GC:
if ((ecode[2] != PRIV(ucp_gentype)[prop->chartype]) == (op == OP_PROP))
RRETURN(MATCH_NOMATCH);
break;
case PT_PC:
if ((ecode[2] != prop->chartype) == (op == OP_PROP))
RRETURN(MATCH_NOMATCH);
break;
case PT_SC:
if ((ecode[2] != prop->script) == (op == OP_PROP))
RRETURN(MATCH_NOMATCH);
break;
/* These are specials */
case PT_ALNUM:
if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N) == (op == OP_NOTPROP))
RRETURN(MATCH_NOMATCH);
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH);
break;
default:
if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) ==
(op == OP_NOTPROP)) RRETURN(MATCH_NOMATCH);
break;
}
break;
case PT_WORD:
if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
c == CHAR_UNDERSCORE) == (op == OP_NOTPROP))
RRETURN(MATCH_NOMATCH);
break;
case PT_CLIST:
cp = PRIV(ucd_caseless_sets) + ecode[2];
for (;;)
{
if (c < *cp)
{ if (op == OP_PROP) { RRETURN(MATCH_NOMATCH); } else break; }
if (c == *cp++)
{ if (op == OP_PROP) break; else { RRETURN(MATCH_NOMATCH); } }
}
break;
case PT_UCNC:
if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000) == (op == OP_NOTPROP))
RRETURN(MATCH_NOMATCH);
break;
/* This should never occur */
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
ecode += 3;
}
break;
/* Match an extended Unicode sequence. We will get here only if the support
is in the binary; otherwise a compile-time error occurs. */
case OP_EXTUNI:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
else
{
int lgb, rgb;
GETCHARINCTEST(c, eptr);
lgb = UCD_GRAPHBREAK(c);
while (eptr < md->end_subject)
{
int len = 1;
if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); }
rgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
lgb = rgb;
eptr += len;
}
}
CHECK_PARTIAL();
ecode++;
break;
#endif /* SUPPORT_UCP */
/* Match a back reference, possibly repeatedly. Look past the end of the
item to see if there is repeat information following. The code is similar
to that for character classes, but repeated for efficiency. Then obey
similar code to character type repeats - written out again for speed.
However, if the referenced string is the empty string, always treat
it as matched, any number of times (otherwise there could be infinite
loops). If the reference is unset, there are two possibilities:
(a) In the default, Perl-compatible state, set the length negative;
this ensures that every attempt at a match fails. We can't just fail
here, because of the possibility of quantifiers with zero minima.
(b) If the JavaScript compatibility flag is set, set the length to zero
so that the back reference matches an empty string.
Otherwise, set the length to the length of what was matched by the
referenced subpattern.
The OP_REF and OP_REFI opcodes are used for a reference to a numbered group
or to a non-duplicated named group. For a duplicated named group, OP_DNREF
and OP_DNREFI are used. In this case we must scan the list of groups to
which the name refers, and use the first one that is set. */
case OP_DNREF:
case OP_DNREFI:
caseless = op == OP_DNREFI;
{
int count = GET2(ecode, 1+IMM2_SIZE);
pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size;
ecode += 1 + 2*IMM2_SIZE;
/* Setting the default length first and initializing 'offset' avoids
compiler warnings in the REF_REPEAT code. */
length = (md->jscript_compat)? 0 : -1;
offset = 0;
while (count-- > 0)
{
offset = GET2(slot, 0) << 1;
if (offset < offset_top && md->offset_vector[offset] >= 0)
{
length = md->offset_vector[offset+1] - md->offset_vector[offset];
break;
}
slot += md->name_entry_size;
}
}
goto REF_REPEAT;
case OP_REF:
case OP_REFI:
caseless = op == OP_REFI;
offset = GET2(ecode, 1) << 1; /* Doubled ref number */
ecode += 1 + IMM2_SIZE;
if (offset >= offset_top || md->offset_vector[offset] < 0)
length = (md->jscript_compat)? 0 : -1;
else
length = md->offset_vector[offset+1] - md->offset_vector[offset];
/* Set up for repetition, or handle the non-repeated case */
REF_REPEAT:
switch (*ecode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRQUERY:
case OP_CRMINQUERY:
c = *ecode++ - OP_CRSTAR;
minimize = (c & 1) != 0;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
minimize = (*ecode == OP_CRMINRANGE);
min = GET2(ecode, 1);
max = GET2(ecode, 1 + IMM2_SIZE);
if (max == 0) max = INT_MAX;
ecode += 1 + 2 * IMM2_SIZE;
break;
default: /* No repeat follows */
if ((length = match_ref(offset, eptr, length, md, caseless)) < 0)
{
if (length == -2) eptr = md->end_subject; /* Partial match */
CHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr += length;
continue; /* With the main loop */
}
/* Handle repeated back references. If the length of the reference is
zero, just continue with the main loop. If the length is negative, it
means the reference is unset in non-Java-compatible mode. If the minimum is
zero, we can continue at the same level without recursion. For any other
minimum, carrying on will result in NOMATCH. */
if (length == 0) continue;
if (length < 0 && min == 0) continue;
/* First, ensure the minimum number of matches are present. We get back
the length of the reference string explicitly rather than passing the
address of eptr, so that eptr can be a register variable. */
for (i = 1; i <= min; i++)
{
int slength;
if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0)
{
if (slength == -2) eptr = md->end_subject; /* Partial match */
CHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr += slength;
}
/* If min = max, continue at the same level without recursion.
They are not both allowed to be zero. */
if (min == max) continue;
/* If minimizing, keep trying and advancing the pointer */
if (minimize)
{
for (fi = min;; fi++)
{
int slength;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM14);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0)
{
if (slength == -2) eptr = md->end_subject; /* Partial match */
CHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr += slength;
}
/* Control never gets here */
}
/* If maximizing, find the longest string and work backwards */
else
{
pp = eptr;
for (i = min; i < max; i++)
{
int slength;
if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0)
{
/* Can't use CHECK_PARTIAL because we don't want to update eptr in
the soft partial matching case. */
if (slength == -2 && md->partial != 0 &&
md->end_subject > md->start_used_ptr)
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
break;
}
eptr += slength;
}
while (eptr >= pp)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM15);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr -= length;
}
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
/* Match a bit-mapped character class, possibly repeatedly. This op code is
used when all the characters in the class have values in the range 0-255,
and either the matching is caseful, or the characters are in the range
0-127 when UTF-8 processing is enabled. The only difference between
OP_CLASS and OP_NCLASS occurs when a data character outside the range is
encountered.
First, look past the end of the item to see if there is repeat information
following. Then obey similar code to character type repeats - written out
again for speed. */
case OP_NCLASS:
case OP_CLASS:
{
/* The data variable is saved across frames, so the byte map needs to
be stored there. */
#define BYTE_MAP ((pcre_uint8 *)data)
data = ecode + 1; /* Save for matching */
ecode += 1 + (32 / sizeof(pcre_uchar)); /* Advance past the item */
switch (*ecode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSSTAR:
case OP_CRPOSPLUS:
case OP_CRPOSQUERY:
c = *ecode++ - OP_CRSTAR;
if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0;
else possessive = TRUE;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
minimize = (*ecode == OP_CRMINRANGE);
possessive = (*ecode == OP_CRPOSRANGE);
min = GET2(ecode, 1);
max = GET2(ecode, 1 + IMM2_SIZE);
if (max == 0) max = INT_MAX;
ecode += 1 + 2 * IMM2_SIZE;
break;
default: /* No repeat follows */
min = max = 1;
break;
}
/* First, ensure the minimum number of matches are present. */
#ifdef SUPPORT_UTF
if (utf)
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
if (c > 255)
{
if (op == OP_CLASS) RRETURN(MATCH_NOMATCH);
}
else
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH);
}
}
else
#endif
/* Not UTF mode */
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
c = *eptr++;
#ifndef COMPILE_PCRE8
if (c > 255)
{
if (op == OP_CLASS) RRETURN(MATCH_NOMATCH);
}
else
#endif
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH);
}
}
/* If max == min we can continue with the main loop without the
need to recurse. */
if (min == max) continue;
/* If minimizing, keep testing the rest of the expression and advancing
the pointer while it matches the class. */
if (minimize)
{
#ifdef SUPPORT_UTF
if (utf)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM16);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
if (c > 255)
{
if (op == OP_CLASS) RRETURN(MATCH_NOMATCH);
}
else
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH);
}
}
else
#endif
/* Not UTF mode */
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM17);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
c = *eptr++;
#ifndef COMPILE_PCRE8
if (c > 255)
{
if (op == OP_CLASS) RRETURN(MATCH_NOMATCH);
}
else
#endif
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH);
}
}
/* Control never gets here */
}
/* If maximizing, find the longest possible run, then work backwards. */
else
{
pp = eptr;
#ifdef SUPPORT_UTF
if (utf)
{
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c > 255)
{
if (op == OP_CLASS) break;
}
else
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break;
eptr += len;
}
if (possessive) continue; /* No backtracking */
for (;;)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM18);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (eptr-- <= pp) break; /* Stop if tried at original pos */
BACKCHAR(eptr);
}
}
else
#endif
/* Not UTF mode */
{
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
c = *eptr;
#ifndef COMPILE_PCRE8
if (c > 255)
{
if (op == OP_CLASS) break;
}
else
#endif
if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break;
eptr++;
}
if (possessive) continue; /* No backtracking */
while (eptr >= pp)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM19);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
}
}
RRETURN(MATCH_NOMATCH);
}
#undef BYTE_MAP
}
/* Control never gets here */
/* Match an extended character class. In the 8-bit library, this opcode is
encountered only when UTF-8 mode mode is supported. In the 16-bit and
32-bit libraries, codepoints greater than 255 may be encountered even when
UTF is not supported. */
#if defined SUPPORT_UTF || !defined COMPILE_PCRE8
case OP_XCLASS:
{
data = ecode + 1 + LINK_SIZE; /* Save for matching */
ecode += GET(ecode, 1); /* Advance past the item */
switch (*ecode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSSTAR:
case OP_CRPOSPLUS:
case OP_CRPOSQUERY:
c = *ecode++ - OP_CRSTAR;
if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0;
else possessive = TRUE;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
minimize = (*ecode == OP_CRMINRANGE);
possessive = (*ecode == OP_CRPOSRANGE);
min = GET2(ecode, 1);
max = GET2(ecode, 1 + IMM2_SIZE);
if (max == 0) max = INT_MAX;
ecode += 1 + 2 * IMM2_SIZE;
break;
default: /* No repeat follows */
min = max = 1;
break;
}
/* First, ensure the minimum number of matches are present. */
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH);
}
/* If max == min we can continue with the main loop without the
need to recurse. */
if (min == max) continue;
/* If minimizing, keep testing the rest of the expression and advancing
the pointer while it matches the class. */
if (minimize)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM20);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
}
/* If maximizing, find the longest possible run, then work backwards. */
else
{
pp = eptr;
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
#ifdef SUPPORT_UTF
GETCHARLENTEST(c, eptr, len);
#else
c = *eptr;
#endif
if (!PRIV(xclass)(c, data, utf)) break;
eptr += len;
}
if (possessive) continue; /* No backtracking */
for(;;)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM21);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (eptr-- <= pp) break; /* Stop if tried at original pos */
#ifdef SUPPORT_UTF
if (utf) BACKCHAR(eptr);
#endif
}
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
}
#endif /* End of XCLASS */
/* Match a single character, casefully */
case OP_CHAR:
#ifdef SUPPORT_UTF
if (utf)
{
length = 1;
ecode++;
GETCHARLEN(fc, ecode, length);
if (length > md->end_subject - eptr)
{
CHECK_PARTIAL(); /* Not SCHECK_PARTIAL() */
RRETURN(MATCH_NOMATCH);
}
while (length-- > 0) if (*ecode++ != UCHAR21INC(eptr)) RRETURN(MATCH_NOMATCH);
}
else
#endif
/* Not UTF mode */
{
if (md->end_subject - eptr < 1)
{
SCHECK_PARTIAL(); /* This one can use SCHECK_PARTIAL() */
RRETURN(MATCH_NOMATCH);
}
if (ecode[1] != *eptr++) RRETURN(MATCH_NOMATCH);
ecode += 2;
}
break;
/* Match a single character, caselessly. If we are at the end of the
subject, give up immediately. */
case OP_CHARI:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
#ifdef SUPPORT_UTF
if (utf)
{
length = 1;
ecode++;
GETCHARLEN(fc, ecode, length);
/* If the pattern character's value is < 128, we have only one byte, and
we know that its other case must also be one byte long, so we can use the
fast lookup table. We know that there is at least one byte left in the
subject. */
if (fc < 128)
{
pcre_uint32 cc = UCHAR21(eptr);
if (md->lcc[fc] != TABLE_GET(cc, md->lcc, cc)) RRETURN(MATCH_NOMATCH);
ecode++;
eptr++;
}
/* Otherwise we must pick up the subject character. Note that we cannot
use the value of "length" to check for sufficient bytes left, because the
other case of the character may have more or fewer bytes. */
else
{
pcre_uint32 dc;
GETCHARINC(dc, eptr);
ecode += length;
/* If we have Unicode property support, we can use it to test the other
case of the character, if there is one. */
if (fc != dc)
{
#ifdef SUPPORT_UCP
if (dc != UCD_OTHERCASE(fc))
#endif
RRETURN(MATCH_NOMATCH);
}
}
}
else
#endif /* SUPPORT_UTF */
/* Not UTF mode */
{
if (TABLE_GET(ecode[1], md->lcc, ecode[1])
!= TABLE_GET(*eptr, md->lcc, *eptr)) RRETURN(MATCH_NOMATCH);
eptr++;
ecode += 2;
}
break;
/* Match a single character repeatedly. */
case OP_EXACT:
case OP_EXACTI:
min = max = GET2(ecode, 1);
ecode += 1 + IMM2_SIZE;
goto REPEATCHAR;
case OP_POSUPTO:
case OP_POSUPTOI:
possessive = TRUE;
/* Fall through */
case OP_UPTO:
case OP_UPTOI:
case OP_MINUPTO:
case OP_MINUPTOI:
min = 0;
max = GET2(ecode, 1);
minimize = *ecode == OP_MINUPTO || *ecode == OP_MINUPTOI;
ecode += 1 + IMM2_SIZE;
goto REPEATCHAR;
case OP_POSSTAR:
case OP_POSSTARI:
possessive = TRUE;
min = 0;
max = INT_MAX;
ecode++;
goto REPEATCHAR;
case OP_POSPLUS:
case OP_POSPLUSI:
possessive = TRUE;
min = 1;
max = INT_MAX;
ecode++;
goto REPEATCHAR;
case OP_POSQUERY:
case OP_POSQUERYI:
possessive = TRUE;
min = 0;
max = 1;
ecode++;
goto REPEATCHAR;
case OP_STAR:
case OP_STARI:
case OP_MINSTAR:
case OP_MINSTARI:
case OP_PLUS:
case OP_PLUSI:
case OP_MINPLUS:
case OP_MINPLUSI:
case OP_QUERY:
case OP_QUERYI:
case OP_MINQUERY:
case OP_MINQUERYI:
c = *ecode++ - ((op < OP_STARI)? OP_STAR : OP_STARI);
minimize = (c & 1) != 0;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
/* Common code for all repeated single-character matches. We first check
for the minimum number of characters. If the minimum equals the maximum, we
are done. Otherwise, if minimizing, check the rest of the pattern for a
match; if there isn't one, advance up to the maximum, one character at a
time.
If maximizing, advance up to the maximum number of matching characters,
until eptr is past the end of the maximum run. If possessive, we are
then done (no backing up). Otherwise, match at this position; anything
other than no match is immediately returned. For nomatch, back up one
character, unless we are matching \R and the last thing matched was
\r\n, in which case, back up two bytes. When we reach the first optional
character position, we can save stack by doing a tail recurse.
The various UTF/non-UTF and caseful/caseless cases are handled separately,
for speed. */
REPEATCHAR:
#ifdef SUPPORT_UTF
if (utf)
{
length = 1;
charptr = ecode;
GETCHARLEN(fc, ecode, length);
ecode += length;
/* Handle multibyte character matching specially here. There is
support for caseless matching if UCP support is present. */
if (length > 1)
{
#ifdef SUPPORT_UCP
pcre_uint32 othercase;
if (op >= OP_STARI && /* Caseless */
(othercase = UCD_OTHERCASE(fc)) != fc)
oclength = PRIV(ord2utf)(othercase, occhars);
else oclength = 0;
#endif /* SUPPORT_UCP */
for (i = 1; i <= min; i++)
{
if (eptr <= md->end_subject - length &&
memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length;
#ifdef SUPPORT_UCP
else if (oclength > 0 &&
eptr <= md->end_subject - oclength &&
memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength;
#endif /* SUPPORT_UCP */
else
{
CHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
}
if (min == max) continue;
if (minimize)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM22);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr <= md->end_subject - length &&
memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length;
#ifdef SUPPORT_UCP
else if (oclength > 0 &&
eptr <= md->end_subject - oclength &&
memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength;
#endif /* SUPPORT_UCP */
else
{
CHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
}
/* Control never gets here */
}
else /* Maximize */
{
pp = eptr;
for (i = min; i < max; i++)
{
if (eptr <= md->end_subject - length &&
memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length;
#ifdef SUPPORT_UCP
else if (oclength > 0 &&
eptr <= md->end_subject - oclength &&
memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength;
#endif /* SUPPORT_UCP */
else
{
CHECK_PARTIAL();
break;
}
}
if (possessive) continue; /* No backtracking */
for(;;)
{
if (eptr <= pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM23);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
#ifdef SUPPORT_UCP
eptr--;
BACKCHAR(eptr);
#else /* without SUPPORT_UCP */
eptr -= length;
#endif /* SUPPORT_UCP */
}
}
/* Control never gets here */
}
/* If the length of a UTF-8 character is 1, we fall through here, and
obey the code as for non-UTF-8 characters below, though in this case the
value of fc will always be < 128. */
}
else
#endif /* SUPPORT_UTF */
/* When not in UTF-8 mode, load a single-byte character. */
fc = *ecode++;
/* The value of fc at this point is always one character, though we may
or may not be in UTF mode. The code is duplicated for the caseless and
caseful cases, for speed, since matching characters is likely to be quite
common. First, ensure the minimum number of matches are present. If min =
max, continue at the same level without recursing. Otherwise, if
minimizing, keep trying the rest of the expression and advancing one
matching character if failing, up to the maximum. Alternatively, if
maximizing, find the maximum number of characters and work backwards. */
DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max,
max, (char *)eptr));
if (op >= OP_STARI) /* Caseless */
{
#ifdef COMPILE_PCRE8
/* fc must be < 128 if UTF is enabled. */
foc = md->fcc[fc];
#else
#ifdef SUPPORT_UTF
#ifdef SUPPORT_UCP
if (utf && fc > 127)
foc = UCD_OTHERCASE(fc);
#else
if (utf && fc > 127)
foc = fc;
#endif /* SUPPORT_UCP */
else
#endif /* SUPPORT_UTF */
foc = TABLE_GET(fc, md->fcc, fc);
#endif /* COMPILE_PCRE8 */
for (i = 1; i <= min; i++)
{
pcre_uint32 cc; /* Faster than pcre_uchar */
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21TEST(eptr);
if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH);
eptr++;
}
if (min == max) continue;
if (minimize)
{
for (fi = min;; fi++)
{
pcre_uint32 cc; /* Faster than pcre_uchar */
RMATCH(eptr, ecode, offset_top, md, eptrb, RM24);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21TEST(eptr);
if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH);
eptr++;
}
/* Control never gets here */
}
else /* Maximize */
{
pp = eptr;
for (i = min; i < max; i++)
{
pcre_uint32 cc; /* Faster than pcre_uchar */
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
cc = UCHAR21TEST(eptr);
if (fc != cc && foc != cc) break;
eptr++;
}
if (possessive) continue; /* No backtracking */
for (;;)
{
if (eptr == pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM25);
eptr--;
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
}
/* Control never gets here */
}
}
/* Caseful comparisons (includes all multi-byte characters) */
else
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH);
}
if (min == max) continue;
if (minimize)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM26);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
}
else /* Maximize */
{
pp = eptr;
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (fc != UCHAR21TEST(eptr)) break;
eptr++;
}
if (possessive) continue; /* No backtracking */
for (;;)
{
if (eptr == pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM27);
eptr--;
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
}
/* Control never gets here */
}
}
/* Control never gets here */
/* Match a negated single one-byte character. The character we are
checking can be multibyte. */
case OP_NOT:
case OP_NOTI:
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 ch, och;
ecode++;
GETCHARINC(ch, ecode);
GETCHARINC(c, eptr);
if (op == OP_NOT)
{
if (ch == c) RRETURN(MATCH_NOMATCH);
}
else
{
#ifdef SUPPORT_UCP
if (ch > 127)
och = UCD_OTHERCASE(ch);
#else
if (ch > 127)
och = ch;
#endif /* SUPPORT_UCP */
else
och = TABLE_GET(ch, md->fcc, ch);
if (ch == c || och == c) RRETURN(MATCH_NOMATCH);
}
}
else
#endif
{
register pcre_uint32 ch = ecode[1];
c = *eptr++;
if (ch == c || (op == OP_NOTI && TABLE_GET(ch, md->fcc, ch) == c))
RRETURN(MATCH_NOMATCH);
ecode += 2;
}
break;
/* Match a negated single one-byte character repeatedly. This is almost a
repeat of the code for a repeated single character, but I haven't found a
nice way of commoning these up that doesn't require a test of the
positive/negative option for each character match. Maybe that wouldn't add
very much to the time taken, but character matching *is* what this is all
about... */
case OP_NOTEXACT:
case OP_NOTEXACTI:
min = max = GET2(ecode, 1);
ecode += 1 + IMM2_SIZE;
goto REPEATNOTCHAR;
case OP_NOTUPTO:
case OP_NOTUPTOI:
case OP_NOTMINUPTO:
case OP_NOTMINUPTOI:
min = 0;
max = GET2(ecode, 1);
minimize = *ecode == OP_NOTMINUPTO || *ecode == OP_NOTMINUPTOI;
ecode += 1 + IMM2_SIZE;
goto REPEATNOTCHAR;
case OP_NOTPOSSTAR:
case OP_NOTPOSSTARI:
possessive = TRUE;
min = 0;
max = INT_MAX;
ecode++;
goto REPEATNOTCHAR;
case OP_NOTPOSPLUS:
case OP_NOTPOSPLUSI:
possessive = TRUE;
min = 1;
max = INT_MAX;
ecode++;
goto REPEATNOTCHAR;
case OP_NOTPOSQUERY:
case OP_NOTPOSQUERYI:
possessive = TRUE;
min = 0;
max = 1;
ecode++;
goto REPEATNOTCHAR;
case OP_NOTPOSUPTO:
case OP_NOTPOSUPTOI:
possessive = TRUE;
min = 0;
max = GET2(ecode, 1);
ecode += 1 + IMM2_SIZE;
goto REPEATNOTCHAR;
case OP_NOTSTAR:
case OP_NOTSTARI:
case OP_NOTMINSTAR:
case OP_NOTMINSTARI:
case OP_NOTPLUS:
case OP_NOTPLUSI:
case OP_NOTMINPLUS:
case OP_NOTMINPLUSI:
case OP_NOTQUERY:
case OP_NOTQUERYI:
case OP_NOTMINQUERY:
case OP_NOTMINQUERYI:
c = *ecode++ - ((op >= OP_NOTSTARI)? OP_NOTSTARI: OP_NOTSTAR);
minimize = (c & 1) != 0;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
/* Common code for all repeated single-byte matches. */
REPEATNOTCHAR:
GETCHARINCTEST(fc, ecode);
/* The code is duplicated for the caseless and caseful cases, for speed,
since matching characters is likely to be quite common. First, ensure the
minimum number of matches are present. If min = max, continue at the same
level without recursing. Otherwise, if minimizing, keep trying the rest of
the expression and advancing one matching character if failing, up to the
maximum. Alternatively, if maximizing, find the maximum number of
characters and work backwards. */
DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max,
max, (char *)eptr));
if (op >= OP_NOTSTARI) /* Caseless */
{
#ifdef SUPPORT_UTF
#ifdef SUPPORT_UCP
if (utf && fc > 127)
foc = UCD_OTHERCASE(fc);
#else
if (utf && fc > 127)
foc = fc;
#endif /* SUPPORT_UCP */
else
#endif /* SUPPORT_UTF */
foc = TABLE_GET(fc, md->fcc, fc);
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(d, eptr);
if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH);
}
}
else
#endif /* SUPPORT_UTF */
/* Not UTF mode */
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH);
eptr++;
}
}
if (min == max) continue;
if (minimize)
{
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM28);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(d, eptr);
if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH);
}
}
else
#endif /*SUPPORT_UTF */
/* Not UTF mode */
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM29);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH);
eptr++;
}
}
/* Control never gets here */
}
/* Maximize case */
else
{
pp = eptr;
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(d, eptr, len);
if (fc == d || (unsigned int)foc == d) break;
eptr += len;
}
if (possessive) continue; /* No backtracking */
for(;;)
{
if (eptr <= pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM30);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
BACKCHAR(eptr);
}
}
else
#endif /* SUPPORT_UTF */
/* Not UTF mode */
{
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (fc == *eptr || foc == *eptr) break;
eptr++;
}
if (possessive) continue; /* No backtracking */
for (;;)
{
if (eptr == pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM31);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
}
}
/* Control never gets here */
}
}
/* Caseful comparisons */
else
{
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(d, eptr);
if (fc == d) RRETURN(MATCH_NOMATCH);
}
}
else
#endif
/* Not UTF mode */
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc == *eptr++) RRETURN(MATCH_NOMATCH);
}
}
if (min == max) continue;
if (minimize)
{
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM32);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(d, eptr);
if (fc == d) RRETURN(MATCH_NOMATCH);
}
}
else
#endif
/* Not UTF mode */
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM33);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (fc == *eptr++) RRETURN(MATCH_NOMATCH);
}
}
/* Control never gets here */
}
/* Maximize case */
else
{
pp = eptr;
#ifdef SUPPORT_UTF
if (utf)
{
register pcre_uint32 d;
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(d, eptr, len);
if (fc == d) break;
eptr += len;
}
if (possessive) continue; /* No backtracking */
for(;;)
{
if (eptr <= pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM34);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
BACKCHAR(eptr);
}
}
else
#endif
/* Not UTF mode */
{
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (fc == *eptr) break;
eptr++;
}
if (possessive) continue; /* No backtracking */
for (;;)
{
if (eptr == pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM35);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
}
}
/* Control never gets here */
}
}
/* Control never gets here */
/* Match a single character type repeatedly; several different opcodes
share code. This is very similar to the code for single characters, but we
repeat it in the interests of efficiency. */
case OP_TYPEEXACT:
min = max = GET2(ecode, 1);
minimize = TRUE;
ecode += 1 + IMM2_SIZE;
goto REPEATTYPE;
case OP_TYPEUPTO:
case OP_TYPEMINUPTO:
min = 0;
max = GET2(ecode, 1);
minimize = *ecode == OP_TYPEMINUPTO;
ecode += 1 + IMM2_SIZE;
goto REPEATTYPE;
case OP_TYPEPOSSTAR:
possessive = TRUE;
min = 0;
max = INT_MAX;
ecode++;
goto REPEATTYPE;
case OP_TYPEPOSPLUS:
possessive = TRUE;
min = 1;
max = INT_MAX;
ecode++;
goto REPEATTYPE;
case OP_TYPEPOSQUERY:
possessive = TRUE;
min = 0;
max = 1;
ecode++;
goto REPEATTYPE;
case OP_TYPEPOSUPTO:
possessive = TRUE;
min = 0;
max = GET2(ecode, 1);
ecode += 1 + IMM2_SIZE;
goto REPEATTYPE;
case OP_TYPESTAR:
case OP_TYPEMINSTAR:
case OP_TYPEPLUS:
case OP_TYPEMINPLUS:
case OP_TYPEQUERY:
case OP_TYPEMINQUERY:
c = *ecode++ - OP_TYPESTAR;
minimize = (c & 1) != 0;
min = rep_min[c]; /* Pick up values from tables; */
max = rep_max[c]; /* zero for max => infinity */
if (max == 0) max = INT_MAX;
/* Common code for all repeated single character type matches. Note that
in UTF-8 mode, '.' matches a character of any length, but for the other
character types, the valid characters are all one-byte long. */
REPEATTYPE:
ctype = *ecode++; /* Code for the character type */
#ifdef SUPPORT_UCP
if (ctype == OP_PROP || ctype == OP_NOTPROP)
{
prop_fail_result = ctype == OP_NOTPROP;
prop_type = *ecode++;
prop_value = *ecode++;
}
else prop_type = -1;
#endif
/* First, ensure the minimum number of matches are present. Use inline
code for maximizing the speed, and do the type test once at the start
(i.e. keep it out of the loop). Separate the UTF-8 code completely as that
is tidier. Also separate the UCP code, which can be the same for both UTF-8
and single-bytes. */
if (min > 0)
{
#ifdef SUPPORT_UCP
if (prop_type >= 0)
{
switch(prop_type)
{
case PT_ANY:
if (prop_fail_result) RRETURN(MATCH_NOMATCH);
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
}
break;
case PT_LAMP:
for (i = 1; i <= min; i++)
{
int chartype;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
chartype = UCD_CHARTYPE(c);
if ((chartype == ucp_Lu ||
chartype == ucp_Ll ||
chartype == ucp_Lt) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
case PT_GC:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
case PT_PC:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
case PT_SC:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
case PT_ALNUM:
for (i = 1; i <= min; i++)
{
int category;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
category = UCD_CATEGORY(c);
if ((category == ucp_L || category == ucp_N) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
if (prop_fail_result) RRETURN(MATCH_NOMATCH);
break;
default:
if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
break;
}
}
break;
case PT_WORD:
for (i = 1; i <= min; i++)
{
int category;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
category = UCD_CATEGORY(c);
if ((category == ucp_L || category == ucp_N || c == CHAR_UNDERSCORE)
== prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
case PT_CLIST:
for (i = 1; i <= min; i++)
{
const pcre_uint32 *cp;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
cp = PRIV(ucd_caseless_sets) + prop_value;
for (;;)
{
if (c < *cp)
{ if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } }
if (c == *cp++)
{ if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; }
}
}
break;
case PT_UCNC:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
break;
/* This should not occur */
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
}
/* Match extended Unicode sequences. We will get here only if the
support is in the binary; otherwise a compile-time error occurs. */
else if (ctype == OP_EXTUNI)
{
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
else
{
int lgb, rgb;
GETCHARINCTEST(c, eptr);
lgb = UCD_GRAPHBREAK(c);
while (eptr < md->end_subject)
{
int len = 1;
if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); }
rgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
lgb = rgb;
eptr += len;
}
}
CHECK_PARTIAL();
}
}
else
#endif /* SUPPORT_UCP */
/* Handle all other cases when the coding is UTF-8 */
#ifdef SUPPORT_UTF
if (utf) switch(ctype)
{
case OP_ANY:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH);
if (md->partial != 0 &&
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
UCHAR21(eptr) == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
break;
case OP_ALLANY:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
break;
case OP_ANYBYTE:
if (eptr > md->end_subject - min) RRETURN(MATCH_NOMATCH);
eptr += min;
break;
case OP_ANYNL:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
case CHAR_CR:
if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++;
break;
case CHAR_LF:
break;
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH);
break;
}
}
break;
case OP_NOT_HSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
switch(c)
{
HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */
default: break;
}
}
break;
case OP_HSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
switch(c)
{
HSPACE_CASES: break; /* Byte and multibyte cases */
default: RRETURN(MATCH_NOMATCH);
}
}
break;
case OP_NOT_VSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
switch(c)
{
VSPACE_CASES: RRETURN(MATCH_NOMATCH);
default: break;
}
}
break;
case OP_VSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
switch(c)
{
VSPACE_CASES: break;
default: RRETURN(MATCH_NOMATCH);
}
}
break;
case OP_NOT_DIGIT:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINC(c, eptr);
if (c < 128 && (md->ctypes[c] & ctype_digit) != 0)
RRETURN(MATCH_NOMATCH);
}
break;
case OP_DIGIT:
for (i = 1; i <= min; i++)
{
pcre_uint32 cc;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21(eptr);
if (cc >= 128 || (md->ctypes[cc] & ctype_digit) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
/* No need to skip more bytes - we know it's a 1-byte character */
}
break;
case OP_NOT_WHITESPACE:
for (i = 1; i <= min; i++)
{
pcre_uint32 cc;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21(eptr);
if (cc < 128 && (md->ctypes[cc] & ctype_space) != 0)
RRETURN(MATCH_NOMATCH);
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
break;
case OP_WHITESPACE:
for (i = 1; i <= min; i++)
{
pcre_uint32 cc;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21(eptr);
if (cc >= 128 || (md->ctypes[cc] & ctype_space) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
/* No need to skip more bytes - we know it's a 1-byte character */
}
break;
case OP_NOT_WORDCHAR:
for (i = 1; i <= min; i++)
{
pcre_uint32 cc;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21(eptr);
if (cc < 128 && (md->ctypes[cc] & ctype_word) != 0)
RRETURN(MATCH_NOMATCH);
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
break;
case OP_WORDCHAR:
for (i = 1; i <= min; i++)
{
pcre_uint32 cc;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
cc = UCHAR21(eptr);
if (cc >= 128 || (md->ctypes[cc] & ctype_word) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
/* No need to skip more bytes - we know it's a 1-byte character */
}
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
} /* End switch(ctype) */
else
#endif /* SUPPORT_UTF */
/* Code for the non-UTF-8 case for minimum matching of operators other
than OP_PROP and OP_NOTPROP. */
switch(ctype)
{
case OP_ANY:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH);
if (md->partial != 0 &&
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
*eptr == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
eptr++;
}
break;
case OP_ALLANY:
if (eptr > md->end_subject - min)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr += min;
break;
case OP_ANYBYTE:
if (eptr > md->end_subject - min)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
eptr += min;
break;
case OP_ANYNL:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
switch(*eptr++)
{
default: RRETURN(MATCH_NOMATCH);
case CHAR_CR:
if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++;
break;
case CHAR_LF:
break;
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
case 0x2028:
case 0x2029:
#endif
if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH);
break;
}
}
break;
case OP_NOT_HSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
switch(*eptr++)
{
default: break;
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
RRETURN(MATCH_NOMATCH);
}
}
break;
case OP_HSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
switch(*eptr++)
{
default: RRETURN(MATCH_NOMATCH);
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
break;
}
}
break;
case OP_NOT_VSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
switch(*eptr++)
{
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
RRETURN(MATCH_NOMATCH);
default: break;
}
}
break;
case OP_VSPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
switch(*eptr++)
{
default: RRETURN(MATCH_NOMATCH);
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
break;
}
}
break;
case OP_NOT_DIGIT:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
case OP_DIGIT:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
case OP_NOT_WHITESPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
case OP_WHITESPACE:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
case OP_NOT_WORDCHAR:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
case OP_WORDCHAR:
for (i = 1; i <= min; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0)
RRETURN(MATCH_NOMATCH);
eptr++;
}
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
}
/* If min = max, continue at the same level without recursing */
if (min == max) continue;
/* If minimizing, we have to test the rest of the pattern before each
subsequent match. Again, separate the UTF-8 case for speed, and also
separate the UCP cases. */
if (minimize)
{
#ifdef SUPPORT_UCP
if (prop_type >= 0)
{
switch(prop_type)
{
case PT_ANY:
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM36);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if (prop_fail_result) RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_LAMP:
for (fi = min;; fi++)
{
int chartype;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM37);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
chartype = UCD_CHARTYPE(c);
if ((chartype == ucp_Lu ||
chartype == ucp_Ll ||
chartype == ucp_Lt) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_GC:
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM38);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_PC:
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM39);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_SC:
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM40);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_ALNUM:
for (fi = min;; fi++)
{
int category;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM59);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
category = UCD_CATEGORY(c);
if ((category == ucp_L || category == ucp_N) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM61);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
if (prop_fail_result) RRETURN(MATCH_NOMATCH);
break;
default:
if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
break;
}
}
/* Control never gets here */
case PT_WORD:
for (fi = min;; fi++)
{
int category;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM62);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
category = UCD_CATEGORY(c);
if ((category == ucp_L ||
category == ucp_N ||
c == CHAR_UNDERSCORE)
== prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
case PT_CLIST:
for (fi = min;; fi++)
{
const pcre_uint32 *cp;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM67);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
cp = PRIV(ucd_caseless_sets) + prop_value;
for (;;)
{
if (c < *cp)
{ if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } }
if (c == *cp++)
{ if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; }
}
}
/* Control never gets here */
case PT_UCNC:
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM60);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
GETCHARINCTEST(c, eptr);
if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000) == prop_fail_result)
RRETURN(MATCH_NOMATCH);
}
/* Control never gets here */
/* This should never occur */
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
}
/* Match extended Unicode sequences. We will get here only if the
support is in the binary; otherwise a compile-time error occurs. */
else if (ctype == OP_EXTUNI)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM41);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
else
{
int lgb, rgb;
GETCHARINCTEST(c, eptr);
lgb = UCD_GRAPHBREAK(c);
while (eptr < md->end_subject)
{
int len = 1;
if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); }
rgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
lgb = rgb;
eptr += len;
}
}
CHECK_PARTIAL();
}
}
else
#endif /* SUPPORT_UCP */
#ifdef SUPPORT_UTF
if (utf)
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM42);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (ctype == OP_ANY && IS_NEWLINE(eptr))
RRETURN(MATCH_NOMATCH);
GETCHARINC(c, eptr);
switch(ctype)
{
case OP_ANY: /* This is the non-NL case */
if (md->partial != 0 && /* Take care with CRLF partial */
eptr >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
break;
case OP_ALLANY:
case OP_ANYBYTE:
break;
case OP_ANYNL:
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
case CHAR_CR:
if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++;
break;
case CHAR_LF:
break;
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH);
break;
}
break;
case OP_NOT_HSPACE:
switch(c)
{
HSPACE_CASES: RRETURN(MATCH_NOMATCH);
default: break;
}
break;
case OP_HSPACE:
switch(c)
{
HSPACE_CASES: break;
default: RRETURN(MATCH_NOMATCH);
}
break;
case OP_NOT_VSPACE:
switch(c)
{
VSPACE_CASES: RRETURN(MATCH_NOMATCH);
default: break;
}
break;
case OP_VSPACE:
switch(c)
{
VSPACE_CASES: break;
default: RRETURN(MATCH_NOMATCH);
}
break;
case OP_NOT_DIGIT:
if (c < 256 && (md->ctypes[c] & ctype_digit) != 0)
RRETURN(MATCH_NOMATCH);
break;
case OP_DIGIT:
if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0)
RRETURN(MATCH_NOMATCH);
break;
case OP_NOT_WHITESPACE:
if (c < 256 && (md->ctypes[c] & ctype_space) != 0)
RRETURN(MATCH_NOMATCH);
break;
case OP_WHITESPACE:
if (c >= 256 || (md->ctypes[c] & ctype_space) == 0)
RRETURN(MATCH_NOMATCH);
break;
case OP_NOT_WORDCHAR:
if (c < 256 && (md->ctypes[c] & ctype_word) != 0)
RRETURN(MATCH_NOMATCH);
break;
case OP_WORDCHAR:
if (c >= 256 || (md->ctypes[c] & ctype_word) == 0)
RRETURN(MATCH_NOMATCH);
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
}
}
else
#endif
/* Not UTF mode */
{
for (fi = min;; fi++)
{
RMATCH(eptr, ecode, offset_top, md, eptrb, RM43);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
if (fi >= max) RRETURN(MATCH_NOMATCH);
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
RRETURN(MATCH_NOMATCH);
}
if (ctype == OP_ANY && IS_NEWLINE(eptr))
RRETURN(MATCH_NOMATCH);
c = *eptr++;
switch(ctype)
{
case OP_ANY: /* This is the non-NL case */
if (md->partial != 0 && /* Take care with CRLF partial */
eptr >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
break;
case OP_ALLANY:
case OP_ANYBYTE:
break;
case OP_ANYNL:
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
case CHAR_CR:
if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++;
break;
case CHAR_LF:
break;
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
case 0x2028:
case 0x2029:
#endif
if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH);
break;
}
break;
case OP_NOT_HSPACE:
switch(c)
{
default: break;
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
RRETURN(MATCH_NOMATCH);
}
break;
case OP_HSPACE:
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
break;
}
break;
case OP_NOT_VSPACE:
switch(c)
{
default: break;
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
RRETURN(MATCH_NOMATCH);
}
break;
case OP_VSPACE:
switch(c)
{
default: RRETURN(MATCH_NOMATCH);
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
break;
}
break;
case OP_NOT_DIGIT:
if (MAX_255(c) && (md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH);
break;
case OP_DIGIT:
if (!MAX_255(c) || (md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH);
break;
case OP_NOT_WHITESPACE:
if (MAX_255(c) && (md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH);
break;
case OP_WHITESPACE:
if (!MAX_255(c) || (md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH);
break;
case OP_NOT_WORDCHAR:
if (MAX_255(c) && (md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH);
break;
case OP_WORDCHAR:
if (!MAX_255(c) || (md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH);
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
}
}
/* Control never gets here */
}
/* If maximizing, it is worth using inline code for speed, doing the type
test once at the start (i.e. keep it out of the loop). Again, keep the
UTF-8 and UCP stuff separate. */
else
{
pp = eptr; /* Remember where we started */
#ifdef SUPPORT_UCP
if (prop_type >= 0)
{
switch(prop_type)
{
case PT_ANY:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
if (prop_fail_result) break;
eptr+= len;
}
break;
case PT_LAMP:
for (i = min; i < max; i++)
{
int chartype;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
chartype = UCD_CHARTYPE(c);
if ((chartype == ucp_Lu ||
chartype == ucp_Ll ||
chartype == ucp_Lt) == prop_fail_result)
break;
eptr+= len;
}
break;
case PT_GC:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) break;
eptr+= len;
}
break;
case PT_PC:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) break;
eptr+= len;
}
break;
case PT_SC:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) break;
eptr+= len;
}
break;
case PT_ALNUM:
for (i = min; i < max; i++)
{
int category;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
category = UCD_CATEGORY(c);
if ((category == ucp_L || category == ucp_N) == prop_fail_result)
break;
eptr+= len;
}
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
if (prop_fail_result) goto ENDLOOP99; /* Break the loop */
break;
default:
if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result)
goto ENDLOOP99; /* Break the loop */
break;
}
eptr+= len;
}
ENDLOOP99:
break;
case PT_WORD:
for (i = min; i < max; i++)
{
int category;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
category = UCD_CATEGORY(c);
if ((category == ucp_L || category == ucp_N ||
c == CHAR_UNDERSCORE) == prop_fail_result)
break;
eptr+= len;
}
break;
case PT_CLIST:
for (i = min; i < max; i++)
{
const pcre_uint32 *cp;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
cp = PRIV(ucd_caseless_sets) + prop_value;
for (;;)
{
if (c < *cp)
{ if (prop_fail_result) break; else goto GOT_MAX; }
if (c == *cp++)
{ if (prop_fail_result) goto GOT_MAX; else break; }
}
eptr += len;
}
GOT_MAX:
break;
case PT_UCNC:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLENTEST(c, eptr, len);
if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000) == prop_fail_result)
break;
eptr += len;
}
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
/* eptr is now past the end of the maximum run */
if (possessive) continue; /* No backtracking */
for(;;)
{
if (eptr <= pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM44);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
if (utf) BACKCHAR(eptr);
}
}
/* Match extended Unicode grapheme clusters. We will get here only if the
support is in the binary; otherwise a compile-time error occurs. */
else if (ctype == OP_EXTUNI)
{
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
else
{
int lgb, rgb;
GETCHARINCTEST(c, eptr);
lgb = UCD_GRAPHBREAK(c);
while (eptr < md->end_subject)
{
int len = 1;
if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); }
rgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
lgb = rgb;
eptr += len;
}
}
CHECK_PARTIAL();
}
/* eptr is now past the end of the maximum run */
if (possessive) continue; /* No backtracking */
/* We use <= pp rather than == pp to detect the start of the run while
backtracking because the use of \C in UTF mode can cause BACKCHAR to
move back past pp. This is just palliative; the use of \C in UTF mode
is fraught with danger. */
for(;;)
{
int lgb, rgb;
PCRE_PUCHAR fptr;
if (eptr <= pp) goto TAIL_RECURSE; /* At start of char run */
RMATCH(eptr, ecode, offset_top, md, eptrb, RM45);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
/* Backtracking over an extended grapheme cluster involves inspecting
the previous two characters (if present) to see if a break is
permitted between them. */
eptr--;
if (!utf) c = *eptr; else
{
BACKCHAR(eptr);
GETCHAR(c, eptr);
}
rgb = UCD_GRAPHBREAK(c);
for (;;)
{
if (eptr <= pp) goto TAIL_RECURSE; /* At start of char run */
fptr = eptr - 1;
if (!utf) c = *fptr; else
{
BACKCHAR(fptr);
GETCHAR(c, fptr);
}
lgb = UCD_GRAPHBREAK(c);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
eptr = fptr;
rgb = lgb;
}
}
}
else
#endif /* SUPPORT_UCP */
#ifdef SUPPORT_UTF
if (utf)
{
switch(ctype)
{
case OP_ANY:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (IS_NEWLINE(eptr)) break;
if (md->partial != 0 && /* Take care with CRLF partial */
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
UCHAR21(eptr) == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
break;
case OP_ALLANY:
if (max < INT_MAX)
{
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
eptr++;
ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++);
}
}
else
{
eptr = md->end_subject; /* Unlimited UTF-8 repeat */
SCHECK_PARTIAL();
}
break;
/* The byte case is the same as non-UTF8 */
case OP_ANYBYTE:
c = max - min;
if (c > (unsigned int)(md->end_subject - eptr))
{
eptr = md->end_subject;
SCHECK_PARTIAL();
}
else eptr += c;
break;
case OP_ANYNL:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c == CHAR_CR)
{
if (++eptr >= md->end_subject) break;
if (UCHAR21(eptr) == CHAR_LF) eptr++;
}
else
{
if (c != CHAR_LF &&
(md->bsr_anycrlf ||
(c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL
#ifndef EBCDIC
&& c != 0x2028 && c != 0x2029
#endif /* Not EBCDIC */
)))
break;
eptr += len;
}
}
break;
case OP_NOT_HSPACE:
case OP_HSPACE:
for (i = min; i < max; i++)
{
BOOL gotspace;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
switch(c)
{
HSPACE_CASES: gotspace = TRUE; break;
default: gotspace = FALSE; break;
}
if (gotspace == (ctype == OP_NOT_HSPACE)) break;
eptr += len;
}
break;
case OP_NOT_VSPACE:
case OP_VSPACE:
for (i = min; i < max; i++)
{
BOOL gotspace;
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
switch(c)
{
VSPACE_CASES: gotspace = TRUE; break;
default: gotspace = FALSE; break;
}
if (gotspace == (ctype == OP_NOT_VSPACE)) break;
eptr += len;
}
break;
case OP_NOT_DIGIT:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break;
eptr+= len;
}
break;
case OP_DIGIT:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break;
eptr+= len;
}
break;
case OP_NOT_WHITESPACE:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break;
eptr+= len;
}
break;
case OP_WHITESPACE:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break;
eptr+= len;
}
break;
case OP_NOT_WORDCHAR:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break;
eptr+= len;
}
break;
case OP_WORDCHAR:
for (i = min; i < max; i++)
{
int len = 1;
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
GETCHARLEN(c, eptr, len);
if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break;
eptr+= len;
}
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
if (possessive) continue; /* No backtracking */
for(;;)
{
if (eptr <= pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM46);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
BACKCHAR(eptr);
if (ctype == OP_ANYNL && eptr > pp && UCHAR21(eptr) == CHAR_NL &&
UCHAR21(eptr - 1) == CHAR_CR) eptr--;
}
}
else
#endif /* SUPPORT_UTF */
/* Not UTF mode */
{
switch(ctype)
{
case OP_ANY:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (IS_NEWLINE(eptr)) break;
if (md->partial != 0 && /* Take care with CRLF partial */
eptr + 1 >= md->end_subject &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
*eptr == NLBLOCK->nl[0])
{
md->hitend = TRUE;
if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL);
}
eptr++;
}
break;
case OP_ALLANY:
case OP_ANYBYTE:
c = max - min;
if (c > (unsigned int)(md->end_subject - eptr))
{
eptr = md->end_subject;
SCHECK_PARTIAL();
}
else eptr += c;
break;
case OP_ANYNL:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
c = *eptr;
if (c == CHAR_CR)
{
if (++eptr >= md->end_subject) break;
if (*eptr == CHAR_LF) eptr++;
}
else
{
if (c != CHAR_LF && (md->bsr_anycrlf ||
(c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
&& c != 0x2028 && c != 0x2029
#endif
))) break;
eptr++;
}
}
break;
case OP_NOT_HSPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
switch(*eptr)
{
default: eptr++; break;
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
goto ENDLOOP00;
}
}
ENDLOOP00:
break;
case OP_HSPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
switch(*eptr)
{
default: goto ENDLOOP01;
HSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
HSPACE_MULTIBYTE_CASES:
#endif
eptr++; break;
}
}
ENDLOOP01:
break;
case OP_NOT_VSPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
switch(*eptr)
{
default: eptr++; break;
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
goto ENDLOOP02;
}
}
ENDLOOP02:
break;
case OP_VSPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
switch(*eptr)
{
default: goto ENDLOOP03;
VSPACE_BYTE_CASES:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
VSPACE_MULTIBYTE_CASES:
#endif
eptr++; break;
}
}
ENDLOOP03:
break;
case OP_NOT_DIGIT:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0) break;
eptr++;
}
break;
case OP_DIGIT:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0) break;
eptr++;
}
break;
case OP_NOT_WHITESPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0) break;
eptr++;
}
break;
case OP_WHITESPACE:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0) break;
eptr++;
}
break;
case OP_NOT_WORDCHAR:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0) break;
eptr++;
}
break;
case OP_WORDCHAR:
for (i = min; i < max; i++)
{
if (eptr >= md->end_subject)
{
SCHECK_PARTIAL();
break;
}
if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0) break;
eptr++;
}
break;
default:
RRETURN(PCRE_ERROR_INTERNAL);
}
if (possessive) continue; /* No backtracking */
for (;;)
{
if (eptr == pp) goto TAIL_RECURSE;
RMATCH(eptr, ecode, offset_top, md, eptrb, RM47);
if (rrc != MATCH_NOMATCH) RRETURN(rrc);
eptr--;
if (ctype == OP_ANYNL && eptr > pp && *eptr == CHAR_LF &&
eptr[-1] == CHAR_CR) eptr--;
}
}
/* Control never gets here */
}
/* There's been some horrible disaster. Arrival here can only mean there is
something seriously wrong in the code above or the OP_xxx definitions. */
default:
DPRINTF(("Unknown opcode %d\n", *ecode));
RRETURN(PCRE_ERROR_UNKNOWN_OPCODE);
}
/* Do not stick any code in here without much thought; it is assumed
that "continue" in the code above comes out to here to repeat the main
loop. */
} /* End of main loop */
/* Control never reaches here */
/* When compiling to use the heap rather than the stack for recursive calls to
match(), the RRETURN() macro jumps here. The number that is saved in
frame->Xwhere indicates which label we actually want to return to. */
#ifdef NO_RECURSE
#define LBL(val) case val: goto L_RM##val;
HEAP_RETURN:
switch (frame->Xwhere)
{
LBL( 1) LBL( 2) LBL( 3) LBL( 4) LBL( 5) LBL( 6) LBL( 7) LBL( 8)
LBL( 9) LBL(10) LBL(11) LBL(12) LBL(13) LBL(14) LBL(15) LBL(17)
LBL(19) LBL(24) LBL(25) LBL(26) LBL(27) LBL(29) LBL(31) LBL(33)
LBL(35) LBL(43) LBL(47) LBL(48) LBL(49) LBL(50) LBL(51) LBL(52)
LBL(53) LBL(54) LBL(55) LBL(56) LBL(57) LBL(58) LBL(63) LBL(64)
LBL(65) LBL(66)
#if defined SUPPORT_UTF || !defined COMPILE_PCRE8
LBL(20) LBL(21)
#endif
#ifdef SUPPORT_UTF
LBL(16) LBL(18)
LBL(22) LBL(23) LBL(28) LBL(30)
LBL(32) LBL(34) LBL(42) LBL(46)
#ifdef SUPPORT_UCP
LBL(36) LBL(37) LBL(38) LBL(39) LBL(40) LBL(41) LBL(44) LBL(45)
LBL(59) LBL(60) LBL(61) LBL(62) LBL(67)
#endif /* SUPPORT_UCP */
#endif /* SUPPORT_UTF */
default:
DPRINTF(("jump error in pcre match: label %d non-existent\n", frame->Xwhere));
return PCRE_ERROR_INTERNAL;
}
#undef LBL
#endif /* NO_RECURSE */
}
/***************************************************************************
****************************************************************************
RECURSION IN THE match() FUNCTION
Undefine all the macros that were defined above to handle this. */
#ifdef NO_RECURSE
#undef eptr
#undef ecode
#undef mstart
#undef offset_top
#undef eptrb
#undef flags
#undef callpat
#undef charptr
#undef data
#undef next
#undef pp
#undef prev
#undef saved_eptr
#undef new_recursive
#undef cur_is_word
#undef condition
#undef prev_is_word
#undef ctype
#undef length
#undef max
#undef min
#undef number
#undef offset
#undef op
#undef save_capture_last
#undef save_offset1
#undef save_offset2
#undef save_offset3
#undef stacksave
#undef newptrb
#endif
/* These two are defined as macros in both cases */
#undef fc
#undef fi
/***************************************************************************
***************************************************************************/
#ifdef NO_RECURSE
/*************************************************
* Release allocated heap frames *
*************************************************/
/* This function releases all the allocated frames. The base frame is on the
machine stack, and so must not be freed.
Argument: the address of the base frame
Returns: nothing
*/
static void
release_match_heapframes (heapframe *frame_base)
{
heapframe *nextframe = frame_base->Xnextframe;
while (nextframe != NULL)
{
heapframe *oldframe = nextframe;
nextframe = nextframe->Xnextframe;
(PUBL(stack_free))(oldframe);
}
}
#endif
/*************************************************
* Execute a Regular Expression *
*************************************************/
/* This function applies a compiled re to a subject string and picks out
portions of the string if it matches. Two elements in the vector are set for
each substring: the offsets to the start and end of the substring.
Arguments:
argument_re points to the compiled expression
extra_data points to extra data or is NULL
subject points to the subject string
length length of subject string (may contain binary zeros)
start_offset where to start in the subject string
options option bits
offsets points to a vector of ints to be filled in with offsets
offsetcount the number of elements in the vector
Returns: > 0 => success; value is the number of elements filled in
= 0 => success, but offsets is not big enough
-1 => failed to match
< -1 => some kind of unexpected problem
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_exec(const pcre *argument_re, const pcre_extra *extra_data,
PCRE_SPTR subject, int length, int start_offset, int options, int *offsets,
int offsetcount)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre16_exec(const pcre16 *argument_re, const pcre16_extra *extra_data,
PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets,
int offsetcount)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre32_exec(const pcre32 *argument_re, const pcre32_extra *extra_data,
PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets,
int offsetcount)
#endif
{
int rc, ocount, arg_offset_max;
int newline;
BOOL using_temporary_offsets = FALSE;
BOOL anchored;
BOOL startline;
BOOL firstline;
BOOL utf;
BOOL has_first_char = FALSE;
BOOL has_req_char = FALSE;
pcre_uchar first_char = 0;
pcre_uchar first_char2 = 0;
pcre_uchar req_char = 0;
pcre_uchar req_char2 = 0;
match_data match_block;
match_data *md = &match_block;
const pcre_uint8 *tables;
const pcre_uint8 *start_bits = NULL;
PCRE_PUCHAR start_match = (PCRE_PUCHAR)subject + start_offset;
PCRE_PUCHAR end_subject;
PCRE_PUCHAR start_partial = NULL;
PCRE_PUCHAR match_partial = NULL;
PCRE_PUCHAR req_char_ptr = start_match - 1;
const pcre_study_data *study;
const REAL_PCRE *re = (const REAL_PCRE *)argument_re;
#ifdef NO_RECURSE
heapframe frame_zero;
frame_zero.Xprevframe = NULL; /* Marks the top level */
frame_zero.Xnextframe = NULL; /* None are allocated yet */
md->match_frames_base = &frame_zero;
#endif
/* Check for the special magic call that measures the size of the stack used
per recursive call of match(). Without the funny casting for sizeof, a Windows
compiler gave this error: "unary minus operator applied to unsigned type,
result still unsigned". Hopefully the cast fixes that. */
if (re == NULL && extra_data == NULL && subject == NULL && length == -999 &&
start_offset == -999)
#ifdef NO_RECURSE
return -((int)sizeof(heapframe));
#else
return match(NULL, NULL, NULL, 0, NULL, NULL, 0);
#endif
/* Plausibility checks */
if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION;
if (re == NULL || subject == NULL || (offsets == NULL && offsetcount > 0))
return PCRE_ERROR_NULL;
if (offsetcount < 0) return PCRE_ERROR_BADCOUNT;
if (length < 0) return PCRE_ERROR_BADLENGTH;
if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET;
/* Check that the first field in the block is the magic number. If it is not,
return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to
REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which
means that the pattern is likely compiled with different endianness. */
if (re->magic_number != MAGIC_NUMBER)
return re->magic_number == REVERSED_MAGIC_NUMBER?
PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC;
if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE;
/* These two settings are used in the code for checking a UTF-8 string that
follows immediately afterwards. Other values in the md block are used only
during "normal" pcre_exec() processing, not when the JIT support is in use,
so they are set up later. */
/* PCRE_UTF16 has the same value as PCRE_UTF8. */
utf = md->utf = (re->options & PCRE_UTF8) != 0;
md->partial = ((options & PCRE_PARTIAL_HARD) != 0)? 2 :
((options & PCRE_PARTIAL_SOFT) != 0)? 1 : 0;
/* Check a UTF-8 string if required. Pass back the character offset and error
code for an invalid string if a results vector is available. */
#ifdef SUPPORT_UTF
if (utf && (options & PCRE_NO_UTF8_CHECK) == 0)
{
int erroroffset;
int errorcode = PRIV(valid_utf)((PCRE_PUCHAR)subject, length, &erroroffset);
if (errorcode != 0)
{
if (offsetcount >= 2)
{
offsets[0] = erroroffset;
offsets[1] = errorcode;
}
#if defined COMPILE_PCRE8
return (errorcode <= PCRE_UTF8_ERR5 && md->partial > 1)?
PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8;
#elif defined COMPILE_PCRE16
return (errorcode <= PCRE_UTF16_ERR1 && md->partial > 1)?
PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16;
#elif defined COMPILE_PCRE32
return PCRE_ERROR_BADUTF32;
#endif
}
#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16
/* Check that a start_offset points to the start of a UTF character. */
if (start_offset > 0 && start_offset < length &&
NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset]))
return PCRE_ERROR_BADUTF8_OFFSET;
#endif
}
#endif
/* If the pattern was successfully studied with JIT support, run the JIT
executable instead of the rest of this function. Most options must be set at
compile time for the JIT code to be usable. Fallback to the normal code path if
an unsupported flag is set. */
#ifdef SUPPORT_JIT
if (extra_data != NULL
&& (extra_data->flags & (PCRE_EXTRA_EXECUTABLE_JIT |
PCRE_EXTRA_TABLES)) == PCRE_EXTRA_EXECUTABLE_JIT
&& extra_data->executable_jit != NULL
&& (options & ~PUBLIC_JIT_EXEC_OPTIONS) == 0)
{
rc = PRIV(jit_exec)(extra_data, (const pcre_uchar *)subject, length,
start_offset, options, offsets, offsetcount);
/* PCRE_ERROR_NULL means that the selected normal or partial matching
mode is not compiled. In this case we simply fallback to interpreter. */
if (rc != PCRE_ERROR_JIT_BADOPTION) return rc;
}
#endif
/* Carry on with non-JIT matching. This information is for finding all the
numbers associated with a given name, for condition testing. */
md->name_table = (pcre_uchar *)re + re->name_table_offset;
md->name_count = re->name_count;
md->name_entry_size = re->name_entry_size;
/* Fish out the optional data from the extra_data structure, first setting
the default values. */
study = NULL;
md->match_limit = MATCH_LIMIT;
md->match_limit_recursion = MATCH_LIMIT_RECURSION;
md->callout_data = NULL;
/* The table pointer is always in native byte order. */
tables = re->tables;
/* The two limit values override the defaults, whatever their value. */
if (extra_data != NULL)
{
unsigned long int flags = extra_data->flags;
if ((flags & PCRE_EXTRA_STUDY_DATA) != 0)
study = (const pcre_study_data *)extra_data->study_data;
if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0)
md->match_limit = extra_data->match_limit;
if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0)
md->match_limit_recursion = extra_data->match_limit_recursion;
if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0)
md->callout_data = extra_data->callout_data;
if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables;
}
/* Limits in the regex override only if they are smaller. */
if ((re->flags & PCRE_MLSET) != 0 && re->limit_match < md->match_limit)
md->match_limit = re->limit_match;
if ((re->flags & PCRE_RLSET) != 0 &&
re->limit_recursion < md->match_limit_recursion)
md->match_limit_recursion = re->limit_recursion;
/* If the exec call supplied NULL for tables, use the inbuilt ones. This
is a feature that makes it possible to save compiled regex and re-use them
in other programs later. */
if (tables == NULL) tables = PRIV(default_tables);
/* Set up other data */
anchored = ((re->options | options) & PCRE_ANCHORED) != 0;
startline = (re->flags & PCRE_STARTLINE) != 0;
firstline = (re->options & PCRE_FIRSTLINE) != 0;
/* The code starts after the real_pcre block and the capture name table. */
md->start_code = (const pcre_uchar *)re + re->name_table_offset +
re->name_count * re->name_entry_size;
md->start_subject = (PCRE_PUCHAR)subject;
md->start_offset = start_offset;
md->end_subject = md->start_subject + length;
end_subject = md->end_subject;
md->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0;
md->use_ucp = (re->options & PCRE_UCP) != 0;
md->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0;
md->ignore_skip_arg = 0;
/* Some options are unpacked into BOOL variables in the hope that testing
them will be faster than individual option bits. */
md->notbol = (options & PCRE_NOTBOL) != 0;
md->noteol = (options & PCRE_NOTEOL) != 0;
md->notempty = (options & PCRE_NOTEMPTY) != 0;
md->notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0;
md->hitend = FALSE;
md->mark = md->nomatch_mark = NULL; /* In case never set */
md->recursive = NULL; /* No recursion at top level */
md->hasthen = (re->flags & PCRE_HASTHEN) != 0;
md->lcc = tables + lcc_offset;
md->fcc = tables + fcc_offset;
md->ctypes = tables + ctypes_offset;
/* Handle different \R options. */
switch (options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE))
{
case 0:
if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0)
md->bsr_anycrlf = (re->options & PCRE_BSR_ANYCRLF) != 0;
else
#ifdef BSR_ANYCRLF
md->bsr_anycrlf = TRUE;
#else
md->bsr_anycrlf = FALSE;
#endif
break;
case PCRE_BSR_ANYCRLF:
md->bsr_anycrlf = TRUE;
break;
case PCRE_BSR_UNICODE:
md->bsr_anycrlf = FALSE;
break;
default: return PCRE_ERROR_BADNEWLINE;
}
/* Handle different types of newline. The three bits give eight cases. If
nothing is set at run time, whatever was used at compile time applies. */
switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options :
(pcre_uint32)options) & PCRE_NEWLINE_BITS)
{
case 0: newline = NEWLINE; break; /* Compile-time default */
case PCRE_NEWLINE_CR: newline = CHAR_CR; break;
case PCRE_NEWLINE_LF: newline = CHAR_NL; break;
case PCRE_NEWLINE_CR+
PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break;
case PCRE_NEWLINE_ANY: newline = -1; break;
case PCRE_NEWLINE_ANYCRLF: newline = -2; break;
default: return PCRE_ERROR_BADNEWLINE;
}
if (newline == -2)
{
md->nltype = NLTYPE_ANYCRLF;
}
else if (newline < 0)
{
md->nltype = NLTYPE_ANY;
}
else
{
md->nltype = NLTYPE_FIXED;
if (newline > 255)
{
md->nllen = 2;
md->nl[0] = (newline >> 8) & 255;
md->nl[1] = newline & 255;
}
else
{
md->nllen = 1;
md->nl[0] = newline;
}
}
/* Partial matching was originally supported only for a restricted set of
regexes; from release 8.00 there are no restrictions, but the bits are still
defined (though never set). So there's no harm in leaving this code. */
if (md->partial && (re->flags & PCRE_NOPARTIAL) != 0)
return PCRE_ERROR_BADPARTIAL;
/* If the expression has got more back references than the offsets supplied can
hold, we get a temporary chunk of working store to use during the matching.
Otherwise, we can use the vector supplied, rounding down its size to a multiple
of 3. */
ocount = offsetcount - (offsetcount % 3);
arg_offset_max = (2*ocount)/3;
if (re->top_backref > 0 && re->top_backref >= ocount/3)
{
ocount = re->top_backref * 3 + 3;
md->offset_vector = (int *)(PUBL(malloc))(ocount * sizeof(int));
if (md->offset_vector == NULL) return PCRE_ERROR_NOMEMORY;
using_temporary_offsets = TRUE;
DPRINTF(("Got memory to hold back references\n"));
}
else md->offset_vector = offsets;
md->offset_end = ocount;
md->offset_max = (2*ocount)/3;
md->capture_last = 0;
/* Reset the working variable associated with each extraction. These should
never be used unless previously set, but they get saved and restored, and so we
initialize them to avoid reading uninitialized locations. Also, unset the
offsets for the matched string. This is really just for tidiness with callouts,
in case they inspect these fields. */
if (md->offset_vector != NULL)
{
register int *iptr = md->offset_vector + ocount;
register int *iend = iptr - re->top_bracket;
if (iend < md->offset_vector + 2) iend = md->offset_vector + 2;
while (--iptr >= iend) *iptr = -1;
if (offsetcount > 0) md->offset_vector[0] = -1;
if (offsetcount > 1) md->offset_vector[1] = -1;
}
/* Set up the first character to match, if available. The first_char value is
never set for an anchored regular expression, but the anchoring may be forced
at run time, so we have to test for anchoring. The first char may be unset for
an unanchored pattern, of course. If there's no first char and the pattern was
studied, there may be a bitmap of possible first characters. */
if (!anchored)
{
if ((re->flags & PCRE_FIRSTSET) != 0)
{
has_first_char = TRUE;
first_char = first_char2 = (pcre_uchar)(re->first_char);
if ((re->flags & PCRE_FCH_CASELESS) != 0)
{
first_char2 = TABLE_GET(first_char, md->fcc, first_char);
#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
if (utf && first_char > 127)
first_char2 = UCD_OTHERCASE(first_char);
#endif
}
}
else
if (!startline && study != NULL &&
(study->flags & PCRE_STUDY_MAPPED) != 0)
start_bits = study->start_bits;
}
/* For anchored or unanchored matches, there may be a "last known required
character" set. */
if ((re->flags & PCRE_REQCHSET) != 0)
{
has_req_char = TRUE;
req_char = req_char2 = (pcre_uchar)(re->req_char);
if ((re->flags & PCRE_RCH_CASELESS) != 0)
{
req_char2 = TABLE_GET(req_char, md->fcc, req_char);
#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
if (utf && req_char > 127)
req_char2 = UCD_OTHERCASE(req_char);
#endif
}
}
/* ==========================================================================*/
/* Loop for handling unanchored repeated matching attempts; for anchored regexs
the loop runs just once. */
for(;;)
{
PCRE_PUCHAR save_end_subject = end_subject;
PCRE_PUCHAR new_start_match;
/* If firstline is TRUE, the start of the match is constrained to the first
line of a multiline string. That is, the match must be before or at the first
newline. Implement this by temporarily adjusting end_subject so that we stop
scanning at a newline. If the match fails at the newline, later code breaks
this loop. */
if (firstline)
{
PCRE_PUCHAR t = start_match;
#ifdef SUPPORT_UTF
if (utf)
{
while (t < md->end_subject && !IS_NEWLINE(t))
{
t++;
ACROSSCHAR(t < end_subject, *t, t++);
}
}
else
#endif
while (t < md->end_subject && !IS_NEWLINE(t)) t++;
end_subject = t;
}
/* There are some optimizations that avoid running the match if a known
starting point is not found, or if a known later character is not present.
However, there is an option that disables these, for testing and for ensuring
that all callouts do actually occur. The option can be set in the regex by
(*NO_START_OPT) or passed in match-time options. */
if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0)
{
/* Advance to a unique first char if there is one. */
if (has_first_char)
{
pcre_uchar smc;
if (first_char != first_char2)
while (start_match < end_subject &&
(smc = UCHAR21TEST(start_match)) != first_char && smc != first_char2)
start_match++;
else
while (start_match < end_subject && UCHAR21TEST(start_match) != first_char)
start_match++;
}
/* Or to just after a linebreak for a multiline match */
else if (startline)
{
if (start_match > md->start_subject + start_offset)
{
#ifdef SUPPORT_UTF
if (utf)
{
while (start_match < end_subject && !WAS_NEWLINE(start_match))
{
start_match++;
ACROSSCHAR(start_match < end_subject, *start_match,
start_match++);
}
}
else
#endif
while (start_match < end_subject && !WAS_NEWLINE(start_match))
start_match++;
/* If we have just passed a CR and the newline option is ANY or ANYCRLF,
and we are now at a LF, advance the match position by one more character.
*/
if (start_match[-1] == CHAR_CR &&
(md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) &&
start_match < end_subject &&
UCHAR21TEST(start_match) == CHAR_NL)
start_match++;
}
}
/* Or to a non-unique first byte after study */
else if (start_bits != NULL)
{
while (start_match < end_subject)
{
register pcre_uint32 c = UCHAR21TEST(start_match);
#ifndef COMPILE_PCRE8
if (c > 255) c = 255;
#endif
if ((start_bits[c/8] & (1 << (c&7))) != 0) break;
start_match++;
}
}
} /* Starting optimizations */
/* Restore fudged end_subject */
end_subject = save_end_subject;
/* The following two optimizations are disabled for partial matching or if
disabling is explicitly requested. */
if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 && !md->partial)
{
/* If the pattern was studied, a minimum subject length may be set. This is
a lower bound; no actual string of that length may actually match the
pattern. Although the value is, strictly, in characters, we treat it as
bytes to avoid spending too much time in this optimization. */
if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 &&
(pcre_uint32)(end_subject - start_match) < study->minlength)
{
rc = MATCH_NOMATCH;
break;
}
/* If req_char is set, we know that that character must appear in the
subject for the match to succeed. If the first character is set, req_char
must be later in the subject; otherwise the test starts at the match point.
This optimization can save a huge amount of backtracking in patterns with
nested unlimited repeats that aren't going to match. Writing separate code
for cased/caseless versions makes it go faster, as does using an
autoincrement and backing off on a match.
HOWEVER: when the subject string is very, very long, searching to its end
can take a long time, and give bad performance on quite ordinary patterns.
This showed up when somebody was matching something like /^\d+C/ on a
32-megabyte string... so we don't do this when the string is sufficiently
long. */
if (has_req_char && end_subject - start_match < REQ_BYTE_MAX)
{
register PCRE_PUCHAR p = start_match + (has_first_char? 1:0);
/* We don't need to repeat the search if we haven't yet reached the
place we found it at last time. */
if (p > req_char_ptr)
{
if (req_char != req_char2)
{
while (p < end_subject)
{
register pcre_uint32 pp = UCHAR21INCTEST(p);
if (pp == req_char || pp == req_char2) { p--; break; }
}
}
else
{
while (p < end_subject)
{
if (UCHAR21INCTEST(p) == req_char) { p--; break; }
}
}
/* If we can't find the required character, break the matching loop,
forcing a match failure. */
if (p >= end_subject)
{
rc = MATCH_NOMATCH;
break;
}
/* If we have found the required character, save the point where we
found it, so that we don't search again next time round the loop if
the start hasn't passed this character yet. */
req_char_ptr = p;
}
}
}
#ifdef PCRE_DEBUG /* Sigh. Some compilers never learn. */
printf(">>>> Match against: ");
pchars(start_match, end_subject - start_match, TRUE, md);
printf("\n");
#endif
/* OK, we can now run the match. If "hitend" is set afterwards, remember the
first starting point for which a partial match was found. */
md->start_match_ptr = start_match;
md->start_used_ptr = start_match;
md->match_call_count = 0;
md->match_function_type = 0;
md->end_offset_top = 0;
md->skip_arg_count = 0;
rc = match(start_match, md->start_code, start_match, 2, md, NULL, 0);
if (md->hitend && start_partial == NULL)
{
start_partial = md->start_used_ptr;
match_partial = start_match;
}
switch(rc)
{
/* If MATCH_SKIP_ARG reaches this level it means that a MARK that matched
the SKIP's arg was not found. In this circumstance, Perl ignores the SKIP
entirely. The only way we can do that is to re-do the match at the same
point, with a flag to force SKIP with an argument to be ignored. Just
treating this case as NOMATCH does not work because it does not check other
alternatives in patterns such as A(*SKIP:A)B|AC when the subject is AC. */
case MATCH_SKIP_ARG:
new_start_match = start_match;
md->ignore_skip_arg = md->skip_arg_count;
break;
/* SKIP passes back the next starting point explicitly, but if it is no
greater than the match we have just done, treat it as NOMATCH. */
case MATCH_SKIP:
if (md->start_match_ptr > start_match)
{
new_start_match = md->start_match_ptr;
break;
}
/* Fall through */
/* NOMATCH and PRUNE advance by one character. THEN at this level acts
exactly like PRUNE. Unset ignore SKIP-with-argument. */
case MATCH_NOMATCH:
case MATCH_PRUNE:
case MATCH_THEN:
md->ignore_skip_arg = 0;
new_start_match = start_match + 1;
#ifdef SUPPORT_UTF
if (utf)
ACROSSCHAR(new_start_match < end_subject, *new_start_match,
new_start_match++);
#endif
break;
/* COMMIT disables the bumpalong, but otherwise behaves as NOMATCH. */
case MATCH_COMMIT:
rc = MATCH_NOMATCH;
goto ENDLOOP;
/* Any other return is either a match, or some kind of error. */
default:
goto ENDLOOP;
}
/* Control reaches here for the various types of "no match at this point"
result. Reset the code to MATCH_NOMATCH for subsequent checking. */
rc = MATCH_NOMATCH;
/* If PCRE_FIRSTLINE is set, the match must happen before or at the first
newline in the subject (though it may continue over the newline). Therefore,
if we have just failed to match, starting at a newline, do not continue. */
if (firstline && IS_NEWLINE(start_match)) break;
/* Advance to new matching position */
start_match = new_start_match;
/* Break the loop if the pattern is anchored or if we have passed the end of
the subject. */
if (anchored || start_match > end_subject) break;
/* If we have just passed a CR and we are now at a LF, and the pattern does
not contain any explicit matches for \r or \n, and the newline option is CRLF
or ANY or ANYCRLF, advance the match position by one more character. In
normal matching start_match will aways be greater than the first position at
this stage, but a failed *SKIP can cause a return at the same point, which is
why the first test exists. */
if (start_match > (PCRE_PUCHAR)subject + start_offset &&
start_match[-1] == CHAR_CR &&
start_match < end_subject &&
*start_match == CHAR_NL &&
(re->flags & PCRE_HASCRORLF) == 0 &&
(md->nltype == NLTYPE_ANY ||
md->nltype == NLTYPE_ANYCRLF ||
md->nllen == 2))
start_match++;
md->mark = NULL; /* Reset for start of next match attempt */
} /* End of for(;;) "bumpalong" loop */
/* ==========================================================================*/
/* We reach here when rc is not MATCH_NOMATCH, or if one of the stopping
conditions is true:
(1) The pattern is anchored or the match was failed by (*COMMIT);
(2) We are past the end of the subject;
(3) PCRE_FIRSTLINE is set and we have failed to match at a newline, because
this option requests that a match occur at or before the first newline in
the subject.
When we have a match and the offset vector is big enough to deal with any
backreferences, captured substring offsets will already be set up. In the case
where we had to get some local store to hold offsets for backreference
processing, copy those that we can. In this case there need not be overflow if
certain parts of the pattern were not used, even though there are more
capturing parentheses than vector slots. */
ENDLOOP:
if (rc == MATCH_MATCH || rc == MATCH_ACCEPT)
{
if (using_temporary_offsets)
{
if (arg_offset_max >= 4)
{
memcpy(offsets + 2, md->offset_vector + 2,
(arg_offset_max - 2) * sizeof(int));
DPRINTF(("Copied offsets from temporary memory\n"));
}
if (md->end_offset_top > arg_offset_max) md->capture_last |= OVFLBIT;
DPRINTF(("Freeing temporary memory\n"));
(PUBL(free))(md->offset_vector);
}
/* Set the return code to the number of captured strings, or 0 if there were
too many to fit into the vector. */
rc = ((md->capture_last & OVFLBIT) != 0 &&
md->end_offset_top >= arg_offset_max)?
0 : md->end_offset_top/2;
/* If there is space in the offset vector, set any unused pairs at the end of
the pattern to -1 for backwards compatibility. It is documented that this
happens. In earlier versions, the whole set of potential capturing offsets
was set to -1 each time round the loop, but this is handled differently now.
"Gaps" are set to -1 dynamically instead (this fixes a bug). Thus, it is only
those at the end that need unsetting here. We can't just unset them all at
the start of the whole thing because they may get set in one branch that is
not the final matching branch. */
if (md->end_offset_top/2 <= re->top_bracket && offsets != NULL)
{
register int *iptr, *iend;
int resetcount = 2 + re->top_bracket * 2;
if (resetcount > offsetcount) resetcount = offsetcount;
iptr = offsets + md->end_offset_top;
iend = offsets + resetcount;
while (iptr < iend) *iptr++ = -1;
}
/* If there is space, set up the whole thing as substring 0. The value of
md->start_match_ptr might be modified if \K was encountered on the success
matching path. */
if (offsetcount < 2) rc = 0; else
{
offsets[0] = (int)(md->start_match_ptr - md->start_subject);
offsets[1] = (int)(md->end_match_ptr - md->start_subject);
}
/* Return MARK data if requested */
if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0)
*(extra_data->mark) = (pcre_uchar *)md->mark;
DPRINTF((">>>> returning %d\n", rc));
#ifdef NO_RECURSE
release_match_heapframes(&frame_zero);
#endif
return rc;
}
/* Control gets here if there has been an error, or if the overall match
attempt has failed at all permitted starting positions. */
if (using_temporary_offsets)
{
DPRINTF(("Freeing temporary memory\n"));
(PUBL(free))(md->offset_vector);
}
/* For anything other than nomatch or partial match, just return the code. */
if (rc != MATCH_NOMATCH && rc != PCRE_ERROR_PARTIAL)
{
DPRINTF((">>>> error: returning %d\n", rc));
#ifdef NO_RECURSE
release_match_heapframes(&frame_zero);
#endif
return rc;
}
/* Handle partial matches - disable any mark data */
if (match_partial != NULL)
{
DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n"));
md->mark = NULL;
if (offsetcount > 1)
{
offsets[0] = (int)(start_partial - (PCRE_PUCHAR)subject);
offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject);
if (offsetcount > 2)
offsets[2] = (int)(match_partial - (PCRE_PUCHAR)subject);
}
rc = PCRE_ERROR_PARTIAL;
}
/* This is the classic nomatch case */
else
{
DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n"));
rc = PCRE_ERROR_NOMATCH;
}
/* Return the MARK data if it has been requested. */
if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0)
*(extra_data->mark) = (pcre_uchar *)md->nomatch_mark;
#ifdef NO_RECURSE
release_match_heapframes(&frame_zero);
#endif
return rc;
}
/* End of pcre_exec.c */
| libgit2-main | deps/pcre/pcre_exec.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2017 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
#ifndef PCRE_INCLUDED
/* This module contains some fixed tables that are used by more than one of the
PCRE code modules. The tables are also #included by the pcretest program, which
uses macros to change their names from _pcre_xxx to xxxx, thereby avoiding name
clashes with the library. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#endif /* PCRE_INCLUDED */
/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that
the definition is next to the definition of the opcodes in pcre_internal.h. */
const pcre_uint8 PRIV(OP_lengths)[] = { OP_LENGTHS };
/* Tables of horizontal and vertical whitespace characters, suitable for
adding to classes. */
const pcre_uint32 PRIV(hspace_list)[] = { HSPACE_LIST };
const pcre_uint32 PRIV(vspace_list)[] = { VSPACE_LIST };
/*************************************************
* Tables for UTF-8 support *
*************************************************/
/* These are the breakpoints for different numbers of bytes in a UTF-8
character. */
#if (defined SUPPORT_UTF && defined COMPILE_PCRE8) \
|| (defined PCRE_INCLUDED && (defined SUPPORT_PCRE16 || defined SUPPORT_PCRE32))
/* These tables are also required by pcretest in 16- or 32-bit mode. */
const int PRIV(utf8_table1)[] =
{ 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff};
const int PRIV(utf8_table1_size) = sizeof(PRIV(utf8_table1)) / sizeof(int);
/* These are the indicator bits and the mask for the data bits to set in the
first byte of a character, indexed by the number of additional bytes. */
const int PRIV(utf8_table2)[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc};
const int PRIV(utf8_table3)[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
/* Table of the number of extra bytes, indexed by the first byte masked with
0x3f. The highest number for a valid UTF-8 first byte is in fact 0x3d. */
const pcre_uint8 PRIV(utf8_table4)[] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
#endif /* (SUPPORT_UTF && COMPILE_PCRE8) || (PCRE_INCLUDED && SUPPORT_PCRE[16|32])*/
#ifdef SUPPORT_UTF
/* Table to translate from particular type value to the general value. */
const pcre_uint32 PRIV(ucp_gentype)[] = {
ucp_C, ucp_C, ucp_C, ucp_C, ucp_C, /* Cc, Cf, Cn, Co, Cs */
ucp_L, ucp_L, ucp_L, ucp_L, ucp_L, /* Ll, Lu, Lm, Lo, Lt */
ucp_M, ucp_M, ucp_M, /* Mc, Me, Mn */
ucp_N, ucp_N, ucp_N, /* Nd, Nl, No */
ucp_P, ucp_P, ucp_P, ucp_P, ucp_P, /* Pc, Pd, Pe, Pf, Pi */
ucp_P, ucp_P, /* Ps, Po */
ucp_S, ucp_S, ucp_S, ucp_S, /* Sc, Sk, Sm, So */
ucp_Z, ucp_Z, ucp_Z /* Zl, Zp, Zs */
};
/* This table encodes the rules for finding the end of an extended grapheme
cluster. Every code point has a grapheme break property which is one of the
ucp_gbXX values defined in ucp.h. The 2-dimensional table is indexed by the
properties of two adjacent code points. The left property selects a word from
the table, and the right property selects a bit from that word like this:
ucp_gbtable[left-property] & (1 << right-property)
The value is non-zero if a grapheme break is NOT permitted between the relevant
two code points. The breaking rules are as follows:
1. Break at the start and end of text (pretty obviously).
2. Do not break between a CR and LF; otherwise, break before and after
controls.
3. Do not break Hangul syllable sequences, the rules for which are:
L may be followed by L, V, LV or LVT
LV or V may be followed by V or T
LVT or T may be followed by T
4. Do not break before extending characters.
The next two rules are only for extended grapheme clusters (but that's what we
are implementing).
5. Do not break before SpacingMarks.
6. Do not break after Prepend characters.
7. Otherwise, break everywhere.
*/
const pcre_uint32 PRIV(ucp_gbtable[]) = {
(1<<ucp_gbLF), /* 0 CR */
0, /* 1 LF */
0, /* 2 Control */
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark), /* 3 Extend */
(1<<ucp_gbExtend)|(1<<ucp_gbPrepend)| /* 4 Prepend */
(1<<ucp_gbSpacingMark)|(1<<ucp_gbL)|
(1<<ucp_gbV)|(1<<ucp_gbT)|(1<<ucp_gbLV)|
(1<<ucp_gbLVT)|(1<<ucp_gbOther),
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark), /* 5 SpacingMark */
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbL)| /* 6 L */
(1<<ucp_gbV)|(1<<ucp_gbLV)|(1<<ucp_gbLVT),
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbV)| /* 7 V */
(1<<ucp_gbT),
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbT), /* 8 T */
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbV)| /* 9 LV */
(1<<ucp_gbT),
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark)|(1<<ucp_gbT), /* 10 LVT */
(1<<ucp_gbRegionalIndicator), /* 11 RegionalIndicator */
(1<<ucp_gbExtend)|(1<<ucp_gbSpacingMark) /* 12 Other */
};
#ifdef SUPPORT_JIT
/* This table reverses PRIV(ucp_gentype). We can save the cost
of a memory load. */
const int PRIV(ucp_typerange)[] = {
ucp_Cc, ucp_Cs,
ucp_Ll, ucp_Lu,
ucp_Mc, ucp_Mn,
ucp_Nd, ucp_No,
ucp_Pc, ucp_Ps,
ucp_Sc, ucp_So,
ucp_Zl, ucp_Zs,
};
#endif /* SUPPORT_JIT */
/* The pcre_utt[] table below translates Unicode property names into type and
code values. It is searched by binary chop, so must be in collating sequence of
name. Originally, the table contained pointers to the name strings in the first
field of each entry. However, that leads to a large number of relocations when
a shared library is dynamically loaded. A significant reduction is made by
putting all the names into a single, large string and then using offsets in the
table itself. Maintenance is more error-prone, but frequent changes to this
data are unlikely.
July 2008: There is now a script called maint/GenerateUtt.py that can be used
to generate this data automatically instead of maintaining it by hand.
The script was updated in March 2009 to generate a new EBCDIC-compliant
version. Like all other character and string literals that are compared against
the regular expression pattern, we must use STR_ macros instead of literal
strings to make sure that UTF-8 support works on EBCDIC platforms. */
#define STRING_Any0 STR_A STR_n STR_y "\0"
#define STRING_Arabic0 STR_A STR_r STR_a STR_b STR_i STR_c "\0"
#define STRING_Armenian0 STR_A STR_r STR_m STR_e STR_n STR_i STR_a STR_n "\0"
#define STRING_Avestan0 STR_A STR_v STR_e STR_s STR_t STR_a STR_n "\0"
#define STRING_Balinese0 STR_B STR_a STR_l STR_i STR_n STR_e STR_s STR_e "\0"
#define STRING_Bamum0 STR_B STR_a STR_m STR_u STR_m "\0"
#define STRING_Bassa_Vah0 STR_B STR_a STR_s STR_s STR_a STR_UNDERSCORE STR_V STR_a STR_h "\0"
#define STRING_Batak0 STR_B STR_a STR_t STR_a STR_k "\0"
#define STRING_Bengali0 STR_B STR_e STR_n STR_g STR_a STR_l STR_i "\0"
#define STRING_Bopomofo0 STR_B STR_o STR_p STR_o STR_m STR_o STR_f STR_o "\0"
#define STRING_Brahmi0 STR_B STR_r STR_a STR_h STR_m STR_i "\0"
#define STRING_Braille0 STR_B STR_r STR_a STR_i STR_l STR_l STR_e "\0"
#define STRING_Buginese0 STR_B STR_u STR_g STR_i STR_n STR_e STR_s STR_e "\0"
#define STRING_Buhid0 STR_B STR_u STR_h STR_i STR_d "\0"
#define STRING_C0 STR_C "\0"
#define STRING_Canadian_Aboriginal0 STR_C STR_a STR_n STR_a STR_d STR_i STR_a STR_n STR_UNDERSCORE STR_A STR_b STR_o STR_r STR_i STR_g STR_i STR_n STR_a STR_l "\0"
#define STRING_Carian0 STR_C STR_a STR_r STR_i STR_a STR_n "\0"
#define STRING_Caucasian_Albanian0 STR_C STR_a STR_u STR_c STR_a STR_s STR_i STR_a STR_n STR_UNDERSCORE STR_A STR_l STR_b STR_a STR_n STR_i STR_a STR_n "\0"
#define STRING_Cc0 STR_C STR_c "\0"
#define STRING_Cf0 STR_C STR_f "\0"
#define STRING_Chakma0 STR_C STR_h STR_a STR_k STR_m STR_a "\0"
#define STRING_Cham0 STR_C STR_h STR_a STR_m "\0"
#define STRING_Cherokee0 STR_C STR_h STR_e STR_r STR_o STR_k STR_e STR_e "\0"
#define STRING_Cn0 STR_C STR_n "\0"
#define STRING_Co0 STR_C STR_o "\0"
#define STRING_Common0 STR_C STR_o STR_m STR_m STR_o STR_n "\0"
#define STRING_Coptic0 STR_C STR_o STR_p STR_t STR_i STR_c "\0"
#define STRING_Cs0 STR_C STR_s "\0"
#define STRING_Cuneiform0 STR_C STR_u STR_n STR_e STR_i STR_f STR_o STR_r STR_m "\0"
#define STRING_Cypriot0 STR_C STR_y STR_p STR_r STR_i STR_o STR_t "\0"
#define STRING_Cyrillic0 STR_C STR_y STR_r STR_i STR_l STR_l STR_i STR_c "\0"
#define STRING_Deseret0 STR_D STR_e STR_s STR_e STR_r STR_e STR_t "\0"
#define STRING_Devanagari0 STR_D STR_e STR_v STR_a STR_n STR_a STR_g STR_a STR_r STR_i "\0"
#define STRING_Duployan0 STR_D STR_u STR_p STR_l STR_o STR_y STR_a STR_n "\0"
#define STRING_Egyptian_Hieroglyphs0 STR_E STR_g STR_y STR_p STR_t STR_i STR_a STR_n STR_UNDERSCORE STR_H STR_i STR_e STR_r STR_o STR_g STR_l STR_y STR_p STR_h STR_s "\0"
#define STRING_Elbasan0 STR_E STR_l STR_b STR_a STR_s STR_a STR_n "\0"
#define STRING_Ethiopic0 STR_E STR_t STR_h STR_i STR_o STR_p STR_i STR_c "\0"
#define STRING_Georgian0 STR_G STR_e STR_o STR_r STR_g STR_i STR_a STR_n "\0"
#define STRING_Glagolitic0 STR_G STR_l STR_a STR_g STR_o STR_l STR_i STR_t STR_i STR_c "\0"
#define STRING_Gothic0 STR_G STR_o STR_t STR_h STR_i STR_c "\0"
#define STRING_Grantha0 STR_G STR_r STR_a STR_n STR_t STR_h STR_a "\0"
#define STRING_Greek0 STR_G STR_r STR_e STR_e STR_k "\0"
#define STRING_Gujarati0 STR_G STR_u STR_j STR_a STR_r STR_a STR_t STR_i "\0"
#define STRING_Gurmukhi0 STR_G STR_u STR_r STR_m STR_u STR_k STR_h STR_i "\0"
#define STRING_Han0 STR_H STR_a STR_n "\0"
#define STRING_Hangul0 STR_H STR_a STR_n STR_g STR_u STR_l "\0"
#define STRING_Hanunoo0 STR_H STR_a STR_n STR_u STR_n STR_o STR_o "\0"
#define STRING_Hebrew0 STR_H STR_e STR_b STR_r STR_e STR_w "\0"
#define STRING_Hiragana0 STR_H STR_i STR_r STR_a STR_g STR_a STR_n STR_a "\0"
#define STRING_Imperial_Aramaic0 STR_I STR_m STR_p STR_e STR_r STR_i STR_a STR_l STR_UNDERSCORE STR_A STR_r STR_a STR_m STR_a STR_i STR_c "\0"
#define STRING_Inherited0 STR_I STR_n STR_h STR_e STR_r STR_i STR_t STR_e STR_d "\0"
#define STRING_Inscriptional_Pahlavi0 STR_I STR_n STR_s STR_c STR_r STR_i STR_p STR_t STR_i STR_o STR_n STR_a STR_l STR_UNDERSCORE STR_P STR_a STR_h STR_l STR_a STR_v STR_i "\0"
#define STRING_Inscriptional_Parthian0 STR_I STR_n STR_s STR_c STR_r STR_i STR_p STR_t STR_i STR_o STR_n STR_a STR_l STR_UNDERSCORE STR_P STR_a STR_r STR_t STR_h STR_i STR_a STR_n "\0"
#define STRING_Javanese0 STR_J STR_a STR_v STR_a STR_n STR_e STR_s STR_e "\0"
#define STRING_Kaithi0 STR_K STR_a STR_i STR_t STR_h STR_i "\0"
#define STRING_Kannada0 STR_K STR_a STR_n STR_n STR_a STR_d STR_a "\0"
#define STRING_Katakana0 STR_K STR_a STR_t STR_a STR_k STR_a STR_n STR_a "\0"
#define STRING_Kayah_Li0 STR_K STR_a STR_y STR_a STR_h STR_UNDERSCORE STR_L STR_i "\0"
#define STRING_Kharoshthi0 STR_K STR_h STR_a STR_r STR_o STR_s STR_h STR_t STR_h STR_i "\0"
#define STRING_Khmer0 STR_K STR_h STR_m STR_e STR_r "\0"
#define STRING_Khojki0 STR_K STR_h STR_o STR_j STR_k STR_i "\0"
#define STRING_Khudawadi0 STR_K STR_h STR_u STR_d STR_a STR_w STR_a STR_d STR_i "\0"
#define STRING_L0 STR_L "\0"
#define STRING_L_AMPERSAND0 STR_L STR_AMPERSAND "\0"
#define STRING_Lao0 STR_L STR_a STR_o "\0"
#define STRING_Latin0 STR_L STR_a STR_t STR_i STR_n "\0"
#define STRING_Lepcha0 STR_L STR_e STR_p STR_c STR_h STR_a "\0"
#define STRING_Limbu0 STR_L STR_i STR_m STR_b STR_u "\0"
#define STRING_Linear_A0 STR_L STR_i STR_n STR_e STR_a STR_r STR_UNDERSCORE STR_A "\0"
#define STRING_Linear_B0 STR_L STR_i STR_n STR_e STR_a STR_r STR_UNDERSCORE STR_B "\0"
#define STRING_Lisu0 STR_L STR_i STR_s STR_u "\0"
#define STRING_Ll0 STR_L STR_l "\0"
#define STRING_Lm0 STR_L STR_m "\0"
#define STRING_Lo0 STR_L STR_o "\0"
#define STRING_Lt0 STR_L STR_t "\0"
#define STRING_Lu0 STR_L STR_u "\0"
#define STRING_Lycian0 STR_L STR_y STR_c STR_i STR_a STR_n "\0"
#define STRING_Lydian0 STR_L STR_y STR_d STR_i STR_a STR_n "\0"
#define STRING_M0 STR_M "\0"
#define STRING_Mahajani0 STR_M STR_a STR_h STR_a STR_j STR_a STR_n STR_i "\0"
#define STRING_Malayalam0 STR_M STR_a STR_l STR_a STR_y STR_a STR_l STR_a STR_m "\0"
#define STRING_Mandaic0 STR_M STR_a STR_n STR_d STR_a STR_i STR_c "\0"
#define STRING_Manichaean0 STR_M STR_a STR_n STR_i STR_c STR_h STR_a STR_e STR_a STR_n "\0"
#define STRING_Mc0 STR_M STR_c "\0"
#define STRING_Me0 STR_M STR_e "\0"
#define STRING_Meetei_Mayek0 STR_M STR_e STR_e STR_t STR_e STR_i STR_UNDERSCORE STR_M STR_a STR_y STR_e STR_k "\0"
#define STRING_Mende_Kikakui0 STR_M STR_e STR_n STR_d STR_e STR_UNDERSCORE STR_K STR_i STR_k STR_a STR_k STR_u STR_i "\0"
#define STRING_Meroitic_Cursive0 STR_M STR_e STR_r STR_o STR_i STR_t STR_i STR_c STR_UNDERSCORE STR_C STR_u STR_r STR_s STR_i STR_v STR_e "\0"
#define STRING_Meroitic_Hieroglyphs0 STR_M STR_e STR_r STR_o STR_i STR_t STR_i STR_c STR_UNDERSCORE STR_H STR_i STR_e STR_r STR_o STR_g STR_l STR_y STR_p STR_h STR_s "\0"
#define STRING_Miao0 STR_M STR_i STR_a STR_o "\0"
#define STRING_Mn0 STR_M STR_n "\0"
#define STRING_Modi0 STR_M STR_o STR_d STR_i "\0"
#define STRING_Mongolian0 STR_M STR_o STR_n STR_g STR_o STR_l STR_i STR_a STR_n "\0"
#define STRING_Mro0 STR_M STR_r STR_o "\0"
#define STRING_Myanmar0 STR_M STR_y STR_a STR_n STR_m STR_a STR_r "\0"
#define STRING_N0 STR_N "\0"
#define STRING_Nabataean0 STR_N STR_a STR_b STR_a STR_t STR_a STR_e STR_a STR_n "\0"
#define STRING_Nd0 STR_N STR_d "\0"
#define STRING_New_Tai_Lue0 STR_N STR_e STR_w STR_UNDERSCORE STR_T STR_a STR_i STR_UNDERSCORE STR_L STR_u STR_e "\0"
#define STRING_Nko0 STR_N STR_k STR_o "\0"
#define STRING_Nl0 STR_N STR_l "\0"
#define STRING_No0 STR_N STR_o "\0"
#define STRING_Ogham0 STR_O STR_g STR_h STR_a STR_m "\0"
#define STRING_Ol_Chiki0 STR_O STR_l STR_UNDERSCORE STR_C STR_h STR_i STR_k STR_i "\0"
#define STRING_Old_Italic0 STR_O STR_l STR_d STR_UNDERSCORE STR_I STR_t STR_a STR_l STR_i STR_c "\0"
#define STRING_Old_North_Arabian0 STR_O STR_l STR_d STR_UNDERSCORE STR_N STR_o STR_r STR_t STR_h STR_UNDERSCORE STR_A STR_r STR_a STR_b STR_i STR_a STR_n "\0"
#define STRING_Old_Permic0 STR_O STR_l STR_d STR_UNDERSCORE STR_P STR_e STR_r STR_m STR_i STR_c "\0"
#define STRING_Old_Persian0 STR_O STR_l STR_d STR_UNDERSCORE STR_P STR_e STR_r STR_s STR_i STR_a STR_n "\0"
#define STRING_Old_South_Arabian0 STR_O STR_l STR_d STR_UNDERSCORE STR_S STR_o STR_u STR_t STR_h STR_UNDERSCORE STR_A STR_r STR_a STR_b STR_i STR_a STR_n "\0"
#define STRING_Old_Turkic0 STR_O STR_l STR_d STR_UNDERSCORE STR_T STR_u STR_r STR_k STR_i STR_c "\0"
#define STRING_Oriya0 STR_O STR_r STR_i STR_y STR_a "\0"
#define STRING_Osmanya0 STR_O STR_s STR_m STR_a STR_n STR_y STR_a "\0"
#define STRING_P0 STR_P "\0"
#define STRING_Pahawh_Hmong0 STR_P STR_a STR_h STR_a STR_w STR_h STR_UNDERSCORE STR_H STR_m STR_o STR_n STR_g "\0"
#define STRING_Palmyrene0 STR_P STR_a STR_l STR_m STR_y STR_r STR_e STR_n STR_e "\0"
#define STRING_Pau_Cin_Hau0 STR_P STR_a STR_u STR_UNDERSCORE STR_C STR_i STR_n STR_UNDERSCORE STR_H STR_a STR_u "\0"
#define STRING_Pc0 STR_P STR_c "\0"
#define STRING_Pd0 STR_P STR_d "\0"
#define STRING_Pe0 STR_P STR_e "\0"
#define STRING_Pf0 STR_P STR_f "\0"
#define STRING_Phags_Pa0 STR_P STR_h STR_a STR_g STR_s STR_UNDERSCORE STR_P STR_a "\0"
#define STRING_Phoenician0 STR_P STR_h STR_o STR_e STR_n STR_i STR_c STR_i STR_a STR_n "\0"
#define STRING_Pi0 STR_P STR_i "\0"
#define STRING_Po0 STR_P STR_o "\0"
#define STRING_Ps0 STR_P STR_s "\0"
#define STRING_Psalter_Pahlavi0 STR_P STR_s STR_a STR_l STR_t STR_e STR_r STR_UNDERSCORE STR_P STR_a STR_h STR_l STR_a STR_v STR_i "\0"
#define STRING_Rejang0 STR_R STR_e STR_j STR_a STR_n STR_g "\0"
#define STRING_Runic0 STR_R STR_u STR_n STR_i STR_c "\0"
#define STRING_S0 STR_S "\0"
#define STRING_Samaritan0 STR_S STR_a STR_m STR_a STR_r STR_i STR_t STR_a STR_n "\0"
#define STRING_Saurashtra0 STR_S STR_a STR_u STR_r STR_a STR_s STR_h STR_t STR_r STR_a "\0"
#define STRING_Sc0 STR_S STR_c "\0"
#define STRING_Sharada0 STR_S STR_h STR_a STR_r STR_a STR_d STR_a "\0"
#define STRING_Shavian0 STR_S STR_h STR_a STR_v STR_i STR_a STR_n "\0"
#define STRING_Siddham0 STR_S STR_i STR_d STR_d STR_h STR_a STR_m "\0"
#define STRING_Sinhala0 STR_S STR_i STR_n STR_h STR_a STR_l STR_a "\0"
#define STRING_Sk0 STR_S STR_k "\0"
#define STRING_Sm0 STR_S STR_m "\0"
#define STRING_So0 STR_S STR_o "\0"
#define STRING_Sora_Sompeng0 STR_S STR_o STR_r STR_a STR_UNDERSCORE STR_S STR_o STR_m STR_p STR_e STR_n STR_g "\0"
#define STRING_Sundanese0 STR_S STR_u STR_n STR_d STR_a STR_n STR_e STR_s STR_e "\0"
#define STRING_Syloti_Nagri0 STR_S STR_y STR_l STR_o STR_t STR_i STR_UNDERSCORE STR_N STR_a STR_g STR_r STR_i "\0"
#define STRING_Syriac0 STR_S STR_y STR_r STR_i STR_a STR_c "\0"
#define STRING_Tagalog0 STR_T STR_a STR_g STR_a STR_l STR_o STR_g "\0"
#define STRING_Tagbanwa0 STR_T STR_a STR_g STR_b STR_a STR_n STR_w STR_a "\0"
#define STRING_Tai_Le0 STR_T STR_a STR_i STR_UNDERSCORE STR_L STR_e "\0"
#define STRING_Tai_Tham0 STR_T STR_a STR_i STR_UNDERSCORE STR_T STR_h STR_a STR_m "\0"
#define STRING_Tai_Viet0 STR_T STR_a STR_i STR_UNDERSCORE STR_V STR_i STR_e STR_t "\0"
#define STRING_Takri0 STR_T STR_a STR_k STR_r STR_i "\0"
#define STRING_Tamil0 STR_T STR_a STR_m STR_i STR_l "\0"
#define STRING_Telugu0 STR_T STR_e STR_l STR_u STR_g STR_u "\0"
#define STRING_Thaana0 STR_T STR_h STR_a STR_a STR_n STR_a "\0"
#define STRING_Thai0 STR_T STR_h STR_a STR_i "\0"
#define STRING_Tibetan0 STR_T STR_i STR_b STR_e STR_t STR_a STR_n "\0"
#define STRING_Tifinagh0 STR_T STR_i STR_f STR_i STR_n STR_a STR_g STR_h "\0"
#define STRING_Tirhuta0 STR_T STR_i STR_r STR_h STR_u STR_t STR_a "\0"
#define STRING_Ugaritic0 STR_U STR_g STR_a STR_r STR_i STR_t STR_i STR_c "\0"
#define STRING_Vai0 STR_V STR_a STR_i "\0"
#define STRING_Warang_Citi0 STR_W STR_a STR_r STR_a STR_n STR_g STR_UNDERSCORE STR_C STR_i STR_t STR_i "\0"
#define STRING_Xan0 STR_X STR_a STR_n "\0"
#define STRING_Xps0 STR_X STR_p STR_s "\0"
#define STRING_Xsp0 STR_X STR_s STR_p "\0"
#define STRING_Xuc0 STR_X STR_u STR_c "\0"
#define STRING_Xwd0 STR_X STR_w STR_d "\0"
#define STRING_Yi0 STR_Y STR_i "\0"
#define STRING_Z0 STR_Z "\0"
#define STRING_Zl0 STR_Z STR_l "\0"
#define STRING_Zp0 STR_Z STR_p "\0"
#define STRING_Zs0 STR_Z STR_s "\0"
const char PRIV(utt_names)[] =
STRING_Any0
STRING_Arabic0
STRING_Armenian0
STRING_Avestan0
STRING_Balinese0
STRING_Bamum0
STRING_Bassa_Vah0
STRING_Batak0
STRING_Bengali0
STRING_Bopomofo0
STRING_Brahmi0
STRING_Braille0
STRING_Buginese0
STRING_Buhid0
STRING_C0
STRING_Canadian_Aboriginal0
STRING_Carian0
STRING_Caucasian_Albanian0
STRING_Cc0
STRING_Cf0
STRING_Chakma0
STRING_Cham0
STRING_Cherokee0
STRING_Cn0
STRING_Co0
STRING_Common0
STRING_Coptic0
STRING_Cs0
STRING_Cuneiform0
STRING_Cypriot0
STRING_Cyrillic0
STRING_Deseret0
STRING_Devanagari0
STRING_Duployan0
STRING_Egyptian_Hieroglyphs0
STRING_Elbasan0
STRING_Ethiopic0
STRING_Georgian0
STRING_Glagolitic0
STRING_Gothic0
STRING_Grantha0
STRING_Greek0
STRING_Gujarati0
STRING_Gurmukhi0
STRING_Han0
STRING_Hangul0
STRING_Hanunoo0
STRING_Hebrew0
STRING_Hiragana0
STRING_Imperial_Aramaic0
STRING_Inherited0
STRING_Inscriptional_Pahlavi0
STRING_Inscriptional_Parthian0
STRING_Javanese0
STRING_Kaithi0
STRING_Kannada0
STRING_Katakana0
STRING_Kayah_Li0
STRING_Kharoshthi0
STRING_Khmer0
STRING_Khojki0
STRING_Khudawadi0
STRING_L0
STRING_L_AMPERSAND0
STRING_Lao0
STRING_Latin0
STRING_Lepcha0
STRING_Limbu0
STRING_Linear_A0
STRING_Linear_B0
STRING_Lisu0
STRING_Ll0
STRING_Lm0
STRING_Lo0
STRING_Lt0
STRING_Lu0
STRING_Lycian0
STRING_Lydian0
STRING_M0
STRING_Mahajani0
STRING_Malayalam0
STRING_Mandaic0
STRING_Manichaean0
STRING_Mc0
STRING_Me0
STRING_Meetei_Mayek0
STRING_Mende_Kikakui0
STRING_Meroitic_Cursive0
STRING_Meroitic_Hieroglyphs0
STRING_Miao0
STRING_Mn0
STRING_Modi0
STRING_Mongolian0
STRING_Mro0
STRING_Myanmar0
STRING_N0
STRING_Nabataean0
STRING_Nd0
STRING_New_Tai_Lue0
STRING_Nko0
STRING_Nl0
STRING_No0
STRING_Ogham0
STRING_Ol_Chiki0
STRING_Old_Italic0
STRING_Old_North_Arabian0
STRING_Old_Permic0
STRING_Old_Persian0
STRING_Old_South_Arabian0
STRING_Old_Turkic0
STRING_Oriya0
STRING_Osmanya0
STRING_P0
STRING_Pahawh_Hmong0
STRING_Palmyrene0
STRING_Pau_Cin_Hau0
STRING_Pc0
STRING_Pd0
STRING_Pe0
STRING_Pf0
STRING_Phags_Pa0
STRING_Phoenician0
STRING_Pi0
STRING_Po0
STRING_Ps0
STRING_Psalter_Pahlavi0
STRING_Rejang0
STRING_Runic0
STRING_S0
STRING_Samaritan0
STRING_Saurashtra0
STRING_Sc0
STRING_Sharada0
STRING_Shavian0
STRING_Siddham0
STRING_Sinhala0
STRING_Sk0
STRING_Sm0
STRING_So0
STRING_Sora_Sompeng0
STRING_Sundanese0
STRING_Syloti_Nagri0
STRING_Syriac0
STRING_Tagalog0
STRING_Tagbanwa0
STRING_Tai_Le0
STRING_Tai_Tham0
STRING_Tai_Viet0
STRING_Takri0
STRING_Tamil0
STRING_Telugu0
STRING_Thaana0
STRING_Thai0
STRING_Tibetan0
STRING_Tifinagh0
STRING_Tirhuta0
STRING_Ugaritic0
STRING_Vai0
STRING_Warang_Citi0
STRING_Xan0
STRING_Xps0
STRING_Xsp0
STRING_Xuc0
STRING_Xwd0
STRING_Yi0
STRING_Z0
STRING_Zl0
STRING_Zp0
STRING_Zs0;
const ucp_type_table PRIV(utt)[] = {
{ 0, PT_ANY, 0 },
{ 4, PT_SC, ucp_Arabic },
{ 11, PT_SC, ucp_Armenian },
{ 20, PT_SC, ucp_Avestan },
{ 28, PT_SC, ucp_Balinese },
{ 37, PT_SC, ucp_Bamum },
{ 43, PT_SC, ucp_Bassa_Vah },
{ 53, PT_SC, ucp_Batak },
{ 59, PT_SC, ucp_Bengali },
{ 67, PT_SC, ucp_Bopomofo },
{ 76, PT_SC, ucp_Brahmi },
{ 83, PT_SC, ucp_Braille },
{ 91, PT_SC, ucp_Buginese },
{ 100, PT_SC, ucp_Buhid },
{ 106, PT_GC, ucp_C },
{ 108, PT_SC, ucp_Canadian_Aboriginal },
{ 128, PT_SC, ucp_Carian },
{ 135, PT_SC, ucp_Caucasian_Albanian },
{ 154, PT_PC, ucp_Cc },
{ 157, PT_PC, ucp_Cf },
{ 160, PT_SC, ucp_Chakma },
{ 167, PT_SC, ucp_Cham },
{ 172, PT_SC, ucp_Cherokee },
{ 181, PT_PC, ucp_Cn },
{ 184, PT_PC, ucp_Co },
{ 187, PT_SC, ucp_Common },
{ 194, PT_SC, ucp_Coptic },
{ 201, PT_PC, ucp_Cs },
{ 204, PT_SC, ucp_Cuneiform },
{ 214, PT_SC, ucp_Cypriot },
{ 222, PT_SC, ucp_Cyrillic },
{ 231, PT_SC, ucp_Deseret },
{ 239, PT_SC, ucp_Devanagari },
{ 250, PT_SC, ucp_Duployan },
{ 259, PT_SC, ucp_Egyptian_Hieroglyphs },
{ 280, PT_SC, ucp_Elbasan },
{ 288, PT_SC, ucp_Ethiopic },
{ 297, PT_SC, ucp_Georgian },
{ 306, PT_SC, ucp_Glagolitic },
{ 317, PT_SC, ucp_Gothic },
{ 324, PT_SC, ucp_Grantha },
{ 332, PT_SC, ucp_Greek },
{ 338, PT_SC, ucp_Gujarati },
{ 347, PT_SC, ucp_Gurmukhi },
{ 356, PT_SC, ucp_Han },
{ 360, PT_SC, ucp_Hangul },
{ 367, PT_SC, ucp_Hanunoo },
{ 375, PT_SC, ucp_Hebrew },
{ 382, PT_SC, ucp_Hiragana },
{ 391, PT_SC, ucp_Imperial_Aramaic },
{ 408, PT_SC, ucp_Inherited },
{ 418, PT_SC, ucp_Inscriptional_Pahlavi },
{ 440, PT_SC, ucp_Inscriptional_Parthian },
{ 463, PT_SC, ucp_Javanese },
{ 472, PT_SC, ucp_Kaithi },
{ 479, PT_SC, ucp_Kannada },
{ 487, PT_SC, ucp_Katakana },
{ 496, PT_SC, ucp_Kayah_Li },
{ 505, PT_SC, ucp_Kharoshthi },
{ 516, PT_SC, ucp_Khmer },
{ 522, PT_SC, ucp_Khojki },
{ 529, PT_SC, ucp_Khudawadi },
{ 539, PT_GC, ucp_L },
{ 541, PT_LAMP, 0 },
{ 544, PT_SC, ucp_Lao },
{ 548, PT_SC, ucp_Latin },
{ 554, PT_SC, ucp_Lepcha },
{ 561, PT_SC, ucp_Limbu },
{ 567, PT_SC, ucp_Linear_A },
{ 576, PT_SC, ucp_Linear_B },
{ 585, PT_SC, ucp_Lisu },
{ 590, PT_PC, ucp_Ll },
{ 593, PT_PC, ucp_Lm },
{ 596, PT_PC, ucp_Lo },
{ 599, PT_PC, ucp_Lt },
{ 602, PT_PC, ucp_Lu },
{ 605, PT_SC, ucp_Lycian },
{ 612, PT_SC, ucp_Lydian },
{ 619, PT_GC, ucp_M },
{ 621, PT_SC, ucp_Mahajani },
{ 630, PT_SC, ucp_Malayalam },
{ 640, PT_SC, ucp_Mandaic },
{ 648, PT_SC, ucp_Manichaean },
{ 659, PT_PC, ucp_Mc },
{ 662, PT_PC, ucp_Me },
{ 665, PT_SC, ucp_Meetei_Mayek },
{ 678, PT_SC, ucp_Mende_Kikakui },
{ 692, PT_SC, ucp_Meroitic_Cursive },
{ 709, PT_SC, ucp_Meroitic_Hieroglyphs },
{ 730, PT_SC, ucp_Miao },
{ 735, PT_PC, ucp_Mn },
{ 738, PT_SC, ucp_Modi },
{ 743, PT_SC, ucp_Mongolian },
{ 753, PT_SC, ucp_Mro },
{ 757, PT_SC, ucp_Myanmar },
{ 765, PT_GC, ucp_N },
{ 767, PT_SC, ucp_Nabataean },
{ 777, PT_PC, ucp_Nd },
{ 780, PT_SC, ucp_New_Tai_Lue },
{ 792, PT_SC, ucp_Nko },
{ 796, PT_PC, ucp_Nl },
{ 799, PT_PC, ucp_No },
{ 802, PT_SC, ucp_Ogham },
{ 808, PT_SC, ucp_Ol_Chiki },
{ 817, PT_SC, ucp_Old_Italic },
{ 828, PT_SC, ucp_Old_North_Arabian },
{ 846, PT_SC, ucp_Old_Permic },
{ 857, PT_SC, ucp_Old_Persian },
{ 869, PT_SC, ucp_Old_South_Arabian },
{ 887, PT_SC, ucp_Old_Turkic },
{ 898, PT_SC, ucp_Oriya },
{ 904, PT_SC, ucp_Osmanya },
{ 912, PT_GC, ucp_P },
{ 914, PT_SC, ucp_Pahawh_Hmong },
{ 927, PT_SC, ucp_Palmyrene },
{ 937, PT_SC, ucp_Pau_Cin_Hau },
{ 949, PT_PC, ucp_Pc },
{ 952, PT_PC, ucp_Pd },
{ 955, PT_PC, ucp_Pe },
{ 958, PT_PC, ucp_Pf },
{ 961, PT_SC, ucp_Phags_Pa },
{ 970, PT_SC, ucp_Phoenician },
{ 981, PT_PC, ucp_Pi },
{ 984, PT_PC, ucp_Po },
{ 987, PT_PC, ucp_Ps },
{ 990, PT_SC, ucp_Psalter_Pahlavi },
{ 1006, PT_SC, ucp_Rejang },
{ 1013, PT_SC, ucp_Runic },
{ 1019, PT_GC, ucp_S },
{ 1021, PT_SC, ucp_Samaritan },
{ 1031, PT_SC, ucp_Saurashtra },
{ 1042, PT_PC, ucp_Sc },
{ 1045, PT_SC, ucp_Sharada },
{ 1053, PT_SC, ucp_Shavian },
{ 1061, PT_SC, ucp_Siddham },
{ 1069, PT_SC, ucp_Sinhala },
{ 1077, PT_PC, ucp_Sk },
{ 1080, PT_PC, ucp_Sm },
{ 1083, PT_PC, ucp_So },
{ 1086, PT_SC, ucp_Sora_Sompeng },
{ 1099, PT_SC, ucp_Sundanese },
{ 1109, PT_SC, ucp_Syloti_Nagri },
{ 1122, PT_SC, ucp_Syriac },
{ 1129, PT_SC, ucp_Tagalog },
{ 1137, PT_SC, ucp_Tagbanwa },
{ 1146, PT_SC, ucp_Tai_Le },
{ 1153, PT_SC, ucp_Tai_Tham },
{ 1162, PT_SC, ucp_Tai_Viet },
{ 1171, PT_SC, ucp_Takri },
{ 1177, PT_SC, ucp_Tamil },
{ 1183, PT_SC, ucp_Telugu },
{ 1190, PT_SC, ucp_Thaana },
{ 1197, PT_SC, ucp_Thai },
{ 1202, PT_SC, ucp_Tibetan },
{ 1210, PT_SC, ucp_Tifinagh },
{ 1219, PT_SC, ucp_Tirhuta },
{ 1227, PT_SC, ucp_Ugaritic },
{ 1236, PT_SC, ucp_Vai },
{ 1240, PT_SC, ucp_Warang_Citi },
{ 1252, PT_ALNUM, 0 },
{ 1256, PT_PXSPACE, 0 },
{ 1260, PT_SPACE, 0 },
{ 1264, PT_UCNC, 0 },
{ 1268, PT_WORD, 0 },
{ 1272, PT_SC, ucp_Yi },
{ 1275, PT_GC, ucp_Z },
{ 1277, PT_PC, ucp_Zl },
{ 1280, PT_PC, ucp_Zp },
{ 1283, PT_PC, ucp_Zs }
};
const int PRIV(utt_size) = sizeof(PRIV(utt)) / sizeof(ucp_type_table);
#endif /* SUPPORT_UTF */
/* End of pcre_tables.c */
| libgit2-main | deps/pcre/pcre_tables.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2014 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains internal functions for comparing and finding the length
of strings for different data item sizes. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#ifndef COMPILE_PCRE8
/*************************************************
* Compare string utilities *
*************************************************/
/* The following two functions compares two strings. Basically a strcmp
for non 8 bit characters.
Arguments:
str1 first string
str2 second string
Returns: 0 if both string are equal (like strcmp), 1 otherwise
*/
int
PRIV(strcmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2)
{
pcre_uchar c1;
pcre_uchar c2;
while (*str1 != '\0' || *str2 != '\0')
{
c1 = *str1++;
c2 = *str2++;
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
#ifdef COMPILE_PCRE32
int
PRIV(strcmp_uc_uc_utf)(const pcre_uchar *str1, const pcre_uchar *str2)
{
pcre_uchar c1;
pcre_uchar c2;
while (*str1 != '\0' || *str2 != '\0')
{
c1 = UCHAR21INC(str1);
c2 = UCHAR21INC(str2);
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
#endif /* COMPILE_PCRE32 */
int
PRIV(strcmp_uc_c8)(const pcre_uchar *str1, const char *str2)
{
const pcre_uint8 *ustr2 = (pcre_uint8 *)str2;
pcre_uchar c1;
pcre_uchar c2;
while (*str1 != '\0' || *ustr2 != '\0')
{
c1 = *str1++;
c2 = (pcre_uchar)*ustr2++;
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
#ifdef COMPILE_PCRE32
int
PRIV(strcmp_uc_c8_utf)(const pcre_uchar *str1, const char *str2)
{
const pcre_uint8 *ustr2 = (pcre_uint8 *)str2;
pcre_uchar c1;
pcre_uchar c2;
while (*str1 != '\0' || *ustr2 != '\0')
{
c1 = UCHAR21INC(str1);
c2 = (pcre_uchar)*ustr2++;
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
#endif /* COMPILE_PCRE32 */
/* The following two functions compares two, fixed length
strings. Basically an strncmp for non 8 bit characters.
Arguments:
str1 first string
str2 second string
num size of the string
Returns: 0 if both string are equal (like strcmp), 1 otherwise
*/
int
PRIV(strncmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2, unsigned int num)
{
pcre_uchar c1;
pcre_uchar c2;
while (num-- > 0)
{
c1 = *str1++;
c2 = *str2++;
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
int
PRIV(strncmp_uc_c8)(const pcre_uchar *str1, const char *str2, unsigned int num)
{
const pcre_uint8 *ustr2 = (pcre_uint8 *)str2;
pcre_uchar c1;
pcre_uchar c2;
while (num-- > 0)
{
c1 = *str1++;
c2 = (pcre_uchar)*ustr2++;
if (c1 != c2)
return ((c1 > c2) << 1) - 1;
}
/* Both length and characters must be equal. */
return 0;
}
/* The following function returns with the length of
a zero terminated string. Basically an strlen for non 8 bit characters.
Arguments:
str string
Returns: length of the string
*/
unsigned int
PRIV(strlen_uc)(const pcre_uchar *str)
{
unsigned int len = 0;
while (*str++ != 0)
len++;
return len;
}
#endif /* !COMPILE_PCRE8 */
/* End of pcre_string_utils.c */
| libgit2-main | deps/pcre/pcre_string_utils.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2020 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module is a wrapper that provides a POSIX API to the underlying PCRE
functions. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* We include pcre.h before pcre_internal.h so that the PCRE library functions
are declared as "import" for Windows by defining PCRE_EXP_DECL as "import".
This is needed even though pcre_internal.h itself includes pcre.h, because it
does so after it has set PCRE_EXP_DECL to "export" if it is not already set. */
#include "pcre.h"
#include "pcre_internal.h"
#include "pcreposix.h"
/* Table to translate PCRE compile time error codes into POSIX error codes. */
static const int eint[] = {
0, /* no error */
PCRE_REG_EESCAPE, /* \ at end of pattern */
PCRE_REG_EESCAPE, /* \c at end of pattern */
PCRE_REG_EESCAPE, /* unrecognized character follows \ */
PCRE_REG_BADBR, /* numbers out of order in {} quantifier */
/* 5 */
PCRE_REG_BADBR, /* number too big in {} quantifier */
PCRE_REG_EBRACK, /* missing terminating ] for character class */
PCRE_REG_ECTYPE, /* invalid escape sequence in character class */
PCRE_REG_ERANGE, /* range out of order in character class */
PCRE_REG_BADRPT, /* nothing to repeat */
/* 10 */
PCRE_REG_BADRPT, /* operand of unlimited repeat could match the empty string */
PCRE_REG_ASSERT, /* internal error: unexpected repeat */
PCRE_REG_BADPAT, /* unrecognized character after (? */
PCRE_REG_BADPAT, /* POSIX named classes are supported only within a class */
PCRE_REG_EPAREN, /* missing ) */
/* 15 */
PCRE_REG_ESUBREG, /* reference to non-existent subpattern */
PCRE_REG_INVARG, /* erroffset passed as NULL */
PCRE_REG_INVARG, /* unknown option bit(s) set */
PCRE_REG_EPAREN, /* missing ) after comment */
PCRE_REG_ESIZE, /* parentheses nested too deeply */
/* 20 */
PCRE_REG_ESIZE, /* regular expression too large */
PCRE_REG_ESPACE, /* failed to get memory */
PCRE_REG_EPAREN, /* unmatched parentheses */
PCRE_REG_ASSERT, /* internal error: code overflow */
PCRE_REG_BADPAT, /* unrecognized character after (?< */
/* 25 */
PCRE_REG_BADPAT, /* lookbehind assertion is not fixed length */
PCRE_REG_BADPAT, /* malformed number or name after (?( */
PCRE_REG_BADPAT, /* conditional group contains more than two branches */
PCRE_REG_BADPAT, /* assertion expected after (?( */
PCRE_REG_BADPAT, /* (?R or (?[+-]digits must be followed by ) */
/* 30 */
PCRE_REG_ECTYPE, /* unknown POSIX class name */
PCRE_REG_BADPAT, /* POSIX collating elements are not supported */
PCRE_REG_INVARG, /* this version of PCRE is not compiled with PCRE_UTF8 support */
PCRE_REG_BADPAT, /* spare error */
PCRE_REG_BADPAT, /* character value in \x{} or \o{} is too large */
/* 35 */
PCRE_REG_BADPAT, /* invalid condition (?(0) */
PCRE_REG_BADPAT, /* \C not allowed in lookbehind assertion */
PCRE_REG_EESCAPE, /* PCRE does not support \L, \l, \N, \U, or \u */
PCRE_REG_BADPAT, /* number after (?C is > 255 */
PCRE_REG_BADPAT, /* closing ) for (?C expected */
/* 40 */
PCRE_REG_BADPAT, /* recursive call could loop indefinitely */
PCRE_REG_BADPAT, /* unrecognized character after (?P */
PCRE_REG_BADPAT, /* syntax error in subpattern name (missing terminator) */
PCRE_REG_BADPAT, /* two named subpatterns have the same name */
PCRE_REG_BADPAT, /* invalid UTF-8 string */
/* 45 */
PCRE_REG_BADPAT, /* support for \P, \p, and \X has not been compiled */
PCRE_REG_BADPAT, /* malformed \P or \p sequence */
PCRE_REG_BADPAT, /* unknown property name after \P or \p */
PCRE_REG_BADPAT, /* subpattern name is too long (maximum 32 characters) */
PCRE_REG_BADPAT, /* too many named subpatterns (maximum 10,000) */
/* 50 */
PCRE_REG_BADPAT, /* repeated subpattern is too long */
PCRE_REG_BADPAT, /* octal value is greater than \377 (not in UTF-8 mode) */
PCRE_REG_BADPAT, /* internal error: overran compiling workspace */
PCRE_REG_BADPAT, /* internal error: previously-checked referenced subpattern not found */
PCRE_REG_BADPAT, /* DEFINE group contains more than one branch */
/* 55 */
PCRE_REG_BADPAT, /* repeating a DEFINE group is not allowed */
PCRE_REG_INVARG, /* inconsistent NEWLINE options */
PCRE_REG_BADPAT, /* \g is not followed followed by an (optionally braced) non-zero number */
PCRE_REG_BADPAT, /* a numbered reference must not be zero */
PCRE_REG_BADPAT, /* an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT) */
/* 60 */
PCRE_REG_BADPAT, /* (*VERB) not recognized */
PCRE_REG_BADPAT, /* number is too big */
PCRE_REG_BADPAT, /* subpattern name expected */
PCRE_REG_BADPAT, /* digit expected after (?+ */
PCRE_REG_BADPAT, /* ] is an invalid data character in JavaScript compatibility mode */
/* 65 */
PCRE_REG_BADPAT, /* different names for subpatterns of the same number are not allowed */
PCRE_REG_BADPAT, /* (*MARK) must have an argument */
PCRE_REG_INVARG, /* this version of PCRE is not compiled with PCRE_UCP support */
PCRE_REG_BADPAT, /* \c must be followed by an ASCII character */
PCRE_REG_BADPAT, /* \k is not followed by a braced, angle-bracketed, or quoted name */
/* 70 */
PCRE_REG_BADPAT, /* internal error: unknown opcode in find_fixedlength() */
PCRE_REG_BADPAT, /* \N is not supported in a class */
PCRE_REG_BADPAT, /* too many forward references */
PCRE_REG_BADPAT, /* disallowed UTF-8/16/32 code point (>= 0xd800 && <= 0xdfff) */
PCRE_REG_BADPAT, /* invalid UTF-16 string (should not occur) */
/* 75 */
PCRE_REG_BADPAT, /* overlong MARK name */
PCRE_REG_BADPAT, /* character value in \u.... sequence is too large */
PCRE_REG_BADPAT, /* invalid UTF-32 string (should not occur) */
PCRE_REG_BADPAT, /* setting UTF is disabled by the application */
PCRE_REG_BADPAT, /* non-hex character in \\x{} (closing brace missing?) */
/* 80 */
PCRE_REG_BADPAT, /* non-octal character in \o{} (closing brace missing?) */
PCRE_REG_BADPAT, /* missing opening brace after \o */
PCRE_REG_BADPAT, /* parentheses too deeply nested */
PCRE_REG_BADPAT, /* invalid range in character class */
PCRE_REG_BADPAT, /* group name must start with a non-digit */
/* 85 */
PCRE_REG_BADPAT, /* parentheses too deeply nested (stack check) */
PCRE_REG_BADPAT, /* missing digits in \x{} or \o{} */
PCRE_REG_BADPAT /* pattern too complicated */
};
/* Table of texts corresponding to POSIX error codes */
static const char *const pstring[] = {
"", /* Dummy for value 0 */
"internal error", /* REG_ASSERT */
"invalid repeat counts in {}", /* BADBR */
"pattern error", /* BADPAT */
"? * + invalid", /* BADRPT */
"unbalanced {}", /* EBRACE */
"unbalanced []", /* EBRACK */
"collation error - not relevant", /* ECOLLATE */
"bad class", /* ECTYPE */
"bad escape sequence", /* EESCAPE */
"empty expression", /* EMPTY */
"unbalanced ()", /* EPAREN */
"bad range inside []", /* ERANGE */
"expression too big", /* ESIZE */
"failed to get memory", /* ESPACE */
"bad back reference", /* ESUBREG */
"bad argument", /* INVARG */
"match failed" /* NOMATCH */
};
/*************************************************
* Translate error code to string *
*************************************************/
PCREPOSIX_EXP_DEFN size_t PCRE_CALL_CONVENTION
pcre_regerror(int errcode, const pcre_regex_t *preg, char *errbuf, size_t errbuf_size)
{
const char *message, *addmessage;
size_t length, addlength;
message = (errcode >= (int)(sizeof(pstring)/sizeof(char *)))?
"unknown error code" : pstring[errcode];
length = strlen(message) + 1;
addmessage = " at offset ";
addlength = (preg != NULL && (int)preg->re_erroffset != -1)?
strlen(addmessage) + 6 : 0;
if (errbuf_size > 0)
{
if (addlength > 0 && errbuf_size >= length + addlength)
sprintf(errbuf, "%s%s%-6d", message, addmessage, (int)preg->re_erroffset);
else
{
strncpy(errbuf, message, errbuf_size - 1);
errbuf[errbuf_size-1] = 0;
}
}
return length + addlength;
}
/*************************************************
* Free store held by a regex *
*************************************************/
PCREPOSIX_EXP_DEFN void PCRE_CALL_CONVENTION
pcre_regfree(pcre_regex_t *preg)
{
(PUBL(free))(preg->re_pcre);
}
/*************************************************
* Compile a regular expression *
*************************************************/
/*
Arguments:
preg points to a structure for recording the compiled expression
pattern the pattern to compile
cflags compilation flags
Returns: 0 on success
various non-zero codes on failure
*/
PCREPOSIX_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_regcomp(pcre_regex_t *preg, const char *pattern, int cflags)
{
const char *errorptr;
int erroffset;
int errorcode;
int options = 0;
int re_nsub = 0;
if ((cflags & PCRE_REG_ICASE) != 0) options |= PCRE_CASELESS;
if ((cflags & PCRE_REG_NEWLINE) != 0) options |= PCRE_MULTILINE;
if ((cflags & PCRE_REG_DOTALL) != 0) options |= PCRE_DOTALL;
if ((cflags & PCRE_REG_NOSUB) != 0) options |= PCRE_NO_AUTO_CAPTURE;
if ((cflags & PCRE_REG_UTF8) != 0) options |= PCRE_UTF8;
if ((cflags & PCRE_REG_UCP) != 0) options |= PCRE_UCP;
if ((cflags & PCRE_REG_UNGREEDY) != 0) options |= PCRE_UNGREEDY;
preg->re_pcre = pcre_compile2(pattern, options, &errorcode, &errorptr,
&erroffset, NULL);
preg->re_erroffset = erroffset;
/* Safety: if the error code is too big for the translation vector (which
should not happen, but we all make mistakes), return REG_BADPAT. */
if (preg->re_pcre == NULL)
{
return (errorcode < (int)(sizeof(eint)/sizeof(const int)))?
eint[errorcode] : PCRE_REG_BADPAT;
}
(void)pcre_fullinfo((const pcre *)preg->re_pcre, NULL, PCRE_INFO_CAPTURECOUNT,
&re_nsub);
preg->re_nsub = (size_t)re_nsub;
preg->re_erroffset = (size_t)(-1); /* No meaning after successful compile */
return 0;
}
/*************************************************
* Match a regular expression *
*************************************************/
/* Unfortunately, PCRE requires 3 ints of working space for each captured
substring, so we have to get and release working store instead of just using
the POSIX structures as was done in earlier releases when PCRE needed only 2
ints. However, if the number of possible capturing brackets is small, use a
block of store on the stack, to reduce the use of malloc/free. The threshold is
in a macro that can be changed at configure time.
If REG_NOSUB was specified at compile time, the PCRE_NO_AUTO_CAPTURE flag will
be set. When this is the case, the nmatch and pmatch arguments are ignored, and
the only result is yes/no/error. */
PCREPOSIX_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_regexec(const pcre_regex_t *preg, const char *string, size_t nmatch,
pcre_regmatch_t pmatch[], int eflags)
{
int rc, so, eo;
int options = 0;
int *ovector = NULL;
int small_ovector[POSIX_MALLOC_THRESHOLD * 3];
BOOL allocated_ovector = FALSE;
BOOL nosub =
(REAL_PCRE_OPTIONS((const pcre *)preg->re_pcre) & PCRE_NO_AUTO_CAPTURE) != 0;
if ((eflags & PCRE_REG_NOTBOL) != 0) options |= PCRE_NOTBOL;
if ((eflags & PCRE_REG_NOTEOL) != 0) options |= PCRE_NOTEOL;
if ((eflags & PCRE_REG_NOTEMPTY) != 0) options |= PCRE_NOTEMPTY;
/* When no string data is being returned, or no vector has been passed in which
to put it, ensure that nmatch is zero. Otherwise, ensure the vector for holding
the return data is large enough. */
if (nosub || pmatch == NULL) nmatch = 0;
else if (nmatch > 0)
{
if (nmatch <= POSIX_MALLOC_THRESHOLD)
{
ovector = &(small_ovector[0]);
}
else
{
if (nmatch > INT_MAX/(sizeof(int) * 3)) return PCRE_REG_ESPACE;
ovector = (int *)malloc(sizeof(int) * nmatch * 3);
if (ovector == NULL) return PCRE_REG_ESPACE;
allocated_ovector = TRUE;
}
}
/* REG_STARTEND is a BSD extension, to allow for non-NUL-terminated strings.
The man page from OS X says "REG_STARTEND affects only the location of the
string, not how it is matched". That is why the "so" value is used to bump the
start location rather than being passed as a PCRE "starting offset". */
if ((eflags & PCRE_REG_STARTEND) != 0)
{
if (pmatch == NULL) return PCRE_REG_INVARG;
so = pmatch[0].rm_so;
eo = pmatch[0].rm_eo;
}
else
{
so = 0;
eo = (int)strlen(string);
}
rc = pcre_exec((const pcre *)preg->re_pcre, NULL, string + so, (eo - so),
0, options, ovector, (int)(nmatch * 3));
if (rc == 0) rc = (int)nmatch; /* All captured slots were filled in */
/* Successful match */
if (rc >= 0)
{
size_t i;
if (!nosub)
{
for (i = 0; i < (size_t)rc; i++)
{
pmatch[i].rm_so = (ovector[i*2] < 0)? -1 : ovector[i*2] + so;
pmatch[i].rm_eo = (ovector[i*2+1] < 0)? -1: ovector[i*2+1] + so;
}
if (allocated_ovector) free(ovector);
for (; i < nmatch; i++) pmatch[i].rm_so = pmatch[i].rm_eo = -1;
}
return 0;
}
/* Unsuccessful match */
if (allocated_ovector) free(ovector);
switch(rc)
{
/* ========================================================================== */
/* These cases are never obeyed. This is a fudge that causes a compile-time
error if the vector eint, which is indexed by compile-time error number, is
not the correct length. It seems to be the only way to do such a check at
compile time, as the sizeof() operator does not work in the C preprocessor.
As all the PCRE_ERROR_xxx values are negative, we can use 0 and 1. */
case 0:
case (sizeof(eint)/sizeof(int) == ERRCOUNT):
return PCRE_REG_ASSERT;
/* ========================================================================== */
case PCRE_ERROR_NOMATCH: return PCRE_REG_NOMATCH;
case PCRE_ERROR_NULL: return PCRE_REG_INVARG;
case PCRE_ERROR_BADOPTION: return PCRE_REG_INVARG;
case PCRE_ERROR_BADMAGIC: return PCRE_REG_INVARG;
case PCRE_ERROR_UNKNOWN_NODE: return PCRE_REG_ASSERT;
case PCRE_ERROR_NOMEMORY: return PCRE_REG_ESPACE;
case PCRE_ERROR_MATCHLIMIT: return PCRE_REG_ESPACE;
case PCRE_ERROR_BADUTF8: return PCRE_REG_INVARG;
case PCRE_ERROR_BADUTF8_OFFSET: return PCRE_REG_INVARG;
case PCRE_ERROR_BADMODE: return PCRE_REG_INVARG;
default: return PCRE_REG_ASSERT;
}
}
/* End of pcreposix.c */
| libgit2-main | deps/pcre/pcreposix.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_version(), which returns a
string that identifies the PCRE version that is in use. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Return version string *
*************************************************/
/* These macros are the standard way of turning unquoted text into C strings.
They allow macros like PCRE_MAJOR to be defined without quotes, which is
convenient for user programs that want to test its value. */
#define STRING(a) # a
#define XSTRING(s) STRING(s)
/* A problem turned up with PCRE_PRERELEASE, which is defined empty for
production releases. Originally, it was used naively in this code:
return XSTRING(PCRE_MAJOR)
"." XSTRING(PCRE_MINOR)
XSTRING(PCRE_PRERELEASE)
" " XSTRING(PCRE_DATE);
However, when PCRE_PRERELEASE is empty, this leads to an attempted expansion of
STRING(). The C standard states: "If (before argument substitution) any
argument consists of no preprocessing tokens, the behavior is undefined." It
turns out the gcc treats this case as a single empty string - which is what we
really want - but Visual C grumbles about the lack of an argument for the
macro. Unfortunately, both are within their rights. To cope with both ways of
handling this, I had resort to some messy hackery that does a test at run time.
I could find no way of detecting that a macro is defined as an empty string at
pre-processor time. This hack uses a standard trick for avoiding calling
the STRING macro with an empty argument when doing the test. */
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION
pcre_version(void)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION
pcre16_version(void)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION
pcre32_version(void)
#endif
{
return (XSTRING(Z PCRE_PRERELEASE)[1] == 0)?
XSTRING(PCRE_MAJOR.PCRE_MINOR PCRE_DATE) :
XSTRING(PCRE_MAJOR.PCRE_MINOR) XSTRING(PCRE_PRERELEASE PCRE_DATE);
}
/* End of pcre_version.c */
| libgit2-main | deps/pcre/pcre_version.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_study(), along with local
supporting functions. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#define SET_BIT(c) start_bits[c/8] |= (1 << (c&7))
/* Returns from set_start_bits() */
enum { SSB_FAIL, SSB_DONE, SSB_CONTINUE, SSB_UNKNOWN };
/*************************************************
* Find the minimum subject length for a group *
*************************************************/
/* Scan a parenthesized group and compute the minimum length of subject that
is needed to match it. This is a lower bound; it does not mean there is a
string of that length that matches. In UTF8 mode, the result is in characters
rather than bytes.
Arguments:
re compiled pattern block
code pointer to start of group (the bracket)
startcode pointer to start of the whole pattern's code
options the compiling options
recurses chain of recurse_check to catch mutual recursion
countptr pointer to call count (to catch over complexity)
Returns: the minimum length
-1 if \C in UTF-8 mode or (*ACCEPT) was encountered
-2 internal error (missing capturing bracket)
-3 internal error (opcode not listed)
*/
static int
find_minlength(const REAL_PCRE *re, const pcre_uchar *code,
const pcre_uchar *startcode, int options, recurse_check *recurses,
int *countptr)
{
int length = -1;
/* PCRE_UTF16 has the same value as PCRE_UTF8. */
BOOL utf = (options & PCRE_UTF8) != 0;
BOOL had_recurse = FALSE;
recurse_check this_recurse;
register int branchlength = 0;
register pcre_uchar *cc = (pcre_uchar *)code + 1 + LINK_SIZE;
if ((*countptr)++ > 1000) return -1; /* too complex */
if (*code == OP_CBRA || *code == OP_SCBRA ||
*code == OP_CBRAPOS || *code == OP_SCBRAPOS) cc += IMM2_SIZE;
/* Scan along the opcodes for this branch. If we get to the end of the
branch, check the length against that of the other branches. */
for (;;)
{
int d, min;
pcre_uchar *cs, *ce;
register pcre_uchar op = *cc;
switch (op)
{
case OP_COND:
case OP_SCOND:
/* If there is only one branch in a condition, the implied branch has zero
length, so we don't add anything. This covers the DEFINE "condition"
automatically. */
cs = cc + GET(cc, 1);
if (*cs != OP_ALT)
{
cc = cs + 1 + LINK_SIZE;
break;
}
/* Otherwise we can fall through and treat it the same as any other
subpattern. */
case OP_CBRA:
case OP_SCBRA:
case OP_BRA:
case OP_SBRA:
case OP_CBRAPOS:
case OP_SCBRAPOS:
case OP_BRAPOS:
case OP_SBRAPOS:
case OP_ONCE:
case OP_ONCE_NC:
d = find_minlength(re, cc, startcode, options, recurses, countptr);
if (d < 0) return d;
branchlength += d;
do cc += GET(cc, 1); while (*cc == OP_ALT);
cc += 1 + LINK_SIZE;
break;
/* ACCEPT makes things far too complicated; we have to give up. */
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
return -1;
/* Reached end of a branch; if it's a ket it is the end of a nested
call. If it's ALT it is an alternation in a nested call. If it is END it's
the end of the outer call. All can be handled by the same code. If an
ACCEPT was previously encountered, use the length that was in force at that
time, and pass back the shortest ACCEPT length. */
case OP_ALT:
case OP_KET:
case OP_KETRMAX:
case OP_KETRMIN:
case OP_KETRPOS:
case OP_END:
if (length < 0 || (!had_recurse && branchlength < length))
length = branchlength;
if (op != OP_ALT) return length;
cc += 1 + LINK_SIZE;
branchlength = 0;
had_recurse = FALSE;
break;
/* Skip over assertive subpatterns */
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
do cc += GET(cc, 1); while (*cc == OP_ALT);
/* Fall through */
/* Skip over things that don't match chars */
case OP_REVERSE:
case OP_CREF:
case OP_DNCREF:
case OP_RREF:
case OP_DNRREF:
case OP_DEF:
case OP_CALLOUT:
case OP_SOD:
case OP_SOM:
case OP_EOD:
case OP_EODN:
case OP_CIRC:
case OP_CIRCM:
case OP_DOLL:
case OP_DOLLM:
case OP_NOT_WORD_BOUNDARY:
case OP_WORD_BOUNDARY:
cc += PRIV(OP_lengths)[*cc];
break;
/* Skip over a subpattern that has a {0} or {0,x} quantifier */
case OP_BRAZERO:
case OP_BRAMINZERO:
case OP_BRAPOSZERO:
case OP_SKIPZERO:
cc += PRIV(OP_lengths)[*cc];
do cc += GET(cc, 1); while (*cc == OP_ALT);
cc += 1 + LINK_SIZE;
break;
/* Handle literal characters and + repetitions */
case OP_CHAR:
case OP_CHARI:
case OP_NOT:
case OP_NOTI:
case OP_PLUS:
case OP_PLUSI:
case OP_MINPLUS:
case OP_MINPLUSI:
case OP_POSPLUS:
case OP_POSPLUSI:
case OP_NOTPLUS:
case OP_NOTPLUSI:
case OP_NOTMINPLUS:
case OP_NOTMINPLUSI:
case OP_NOTPOSPLUS:
case OP_NOTPOSPLUSI:
branchlength++;
cc += 2;
#ifdef SUPPORT_UTF
if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
case OP_TYPEPLUS:
case OP_TYPEMINPLUS:
case OP_TYPEPOSPLUS:
branchlength++;
cc += (cc[1] == OP_PROP || cc[1] == OP_NOTPROP)? 4 : 2;
break;
/* Handle exact repetitions. The count is already in characters, but we
need to skip over a multibyte character in UTF8 mode. */
case OP_EXACT:
case OP_EXACTI:
case OP_NOTEXACT:
case OP_NOTEXACTI:
branchlength += GET2(cc,1);
cc += 2 + IMM2_SIZE;
#ifdef SUPPORT_UTF
if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
case OP_TYPEEXACT:
branchlength += GET2(cc,1);
cc += 2 + IMM2_SIZE + ((cc[1 + IMM2_SIZE] == OP_PROP
|| cc[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0);
break;
/* Handle single-char non-literal matchers */
case OP_PROP:
case OP_NOTPROP:
cc += 2;
/* Fall through */
case OP_NOT_DIGIT:
case OP_DIGIT:
case OP_NOT_WHITESPACE:
case OP_WHITESPACE:
case OP_NOT_WORDCHAR:
case OP_WORDCHAR:
case OP_ANY:
case OP_ALLANY:
case OP_EXTUNI:
case OP_HSPACE:
case OP_NOT_HSPACE:
case OP_VSPACE:
case OP_NOT_VSPACE:
branchlength++;
cc++;
break;
/* "Any newline" might match two characters, but it also might match just
one. */
case OP_ANYNL:
branchlength += 1;
cc++;
break;
/* The single-byte matcher means we can't proceed in UTF-8 mode. (In
non-UTF-8 mode \C will actually be turned into OP_ALLANY, so won't ever
appear, but leave the code, just in case.) */
case OP_ANYBYTE:
#ifdef SUPPORT_UTF
if (utf) return -1;
#endif
branchlength++;
cc++;
break;
/* For repeated character types, we have to test for \p and \P, which have
an extra two bytes of parameters. */
case OP_TYPESTAR:
case OP_TYPEMINSTAR:
case OP_TYPEQUERY:
case OP_TYPEMINQUERY:
case OP_TYPEPOSSTAR:
case OP_TYPEPOSQUERY:
if (cc[1] == OP_PROP || cc[1] == OP_NOTPROP) cc += 2;
cc += PRIV(OP_lengths)[op];
break;
case OP_TYPEUPTO:
case OP_TYPEMINUPTO:
case OP_TYPEPOSUPTO:
if (cc[1 + IMM2_SIZE] == OP_PROP
|| cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2;
cc += PRIV(OP_lengths)[op];
break;
/* Check a class for variable quantification */
case OP_CLASS:
case OP_NCLASS:
#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32
case OP_XCLASS:
/* The original code caused an unsigned overflow in 64 bit systems,
so now we use a conditional statement. */
if (op == OP_XCLASS)
cc += GET(cc, 1);
else
cc += PRIV(OP_lengths)[OP_CLASS];
#else
cc += PRIV(OP_lengths)[OP_CLASS];
#endif
switch (*cc)
{
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRPOSPLUS:
branchlength++;
/* Fall through */
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSSTAR:
case OP_CRPOSQUERY:
cc++;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
branchlength += GET2(cc,1);
cc += 1 + 2 * IMM2_SIZE;
break;
default:
branchlength++;
break;
}
break;
/* Backreferences and subroutine calls are treated in the same way: we find
the minimum length for the subpattern. A recursion, however, causes an
a flag to be set that causes the length of this branch to be ignored. The
logic is that a recursion can only make sense if there is another
alternation that stops the recursing. That will provide the minimum length
(when no recursion happens). A backreference within the group that it is
referencing behaves in the same way.
If PCRE_JAVASCRIPT_COMPAT is set, a backreference to an unset bracket
matches an empty string (by default it causes a matching failure), so in
that case we must set the minimum length to zero. */
case OP_DNREF: /* Duplicate named pattern back reference */
case OP_DNREFI:
if ((options & PCRE_JAVASCRIPT_COMPAT) == 0)
{
int count = GET2(cc, 1+IMM2_SIZE);
pcre_uchar *slot = (pcre_uchar *)re +
re->name_table_offset + GET2(cc, 1) * re->name_entry_size;
d = INT_MAX;
while (count-- > 0)
{
ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(slot, 0));
if (cs == NULL) return -2;
do ce += GET(ce, 1); while (*ce == OP_ALT);
if (cc > cs && cc < ce) /* Simple recursion */
{
d = 0;
had_recurse = TRUE;
break;
}
else
{
recurse_check *r = recurses;
for (r = recurses; r != NULL; r = r->prev) if (r->group == cs) break;
if (r != NULL) /* Mutual recursion */
{
d = 0;
had_recurse = TRUE;
break;
}
else
{
int dd;
this_recurse.prev = recurses;
this_recurse.group = cs;
dd = find_minlength(re, cs, startcode, options, &this_recurse,
countptr);
if (dd < d) d = dd;
}
}
slot += re->name_entry_size;
}
}
else d = 0;
cc += 1 + 2*IMM2_SIZE;
goto REPEAT_BACK_REFERENCE;
case OP_REF: /* Single back reference */
case OP_REFI:
if ((options & PCRE_JAVASCRIPT_COMPAT) == 0)
{
ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(cc, 1));
if (cs == NULL) return -2;
do ce += GET(ce, 1); while (*ce == OP_ALT);
if (cc > cs && cc < ce) /* Simple recursion */
{
d = 0;
had_recurse = TRUE;
}
else
{
recurse_check *r = recurses;
for (r = recurses; r != NULL; r = r->prev) if (r->group == cs) break;
if (r != NULL) /* Mutual recursion */
{
d = 0;
had_recurse = TRUE;
}
else
{
this_recurse.prev = recurses;
this_recurse.group = cs;
d = find_minlength(re, cs, startcode, options, &this_recurse,
countptr);
}
}
}
else d = 0;
cc += 1 + IMM2_SIZE;
/* Handle repeated back references */
REPEAT_BACK_REFERENCE:
switch (*cc)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSSTAR:
case OP_CRPOSQUERY:
min = 0;
cc++;
break;
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRPOSPLUS:
min = 1;
cc++;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
min = GET2(cc, 1);
cc += 1 + 2 * IMM2_SIZE;
break;
default:
min = 1;
break;
}
branchlength += min * d;
break;
/* We can easily detect direct recursion, but not mutual recursion. This is
caught by a recursion depth count. */
case OP_RECURSE:
cs = ce = (pcre_uchar *)startcode + GET(cc, 1);
do ce += GET(ce, 1); while (*ce == OP_ALT);
if (cc > cs && cc < ce) /* Simple recursion */
had_recurse = TRUE;
else
{
recurse_check *r = recurses;
for (r = recurses; r != NULL; r = r->prev) if (r->group == cs) break;
if (r != NULL) /* Mutual recursion */
had_recurse = TRUE;
else
{
this_recurse.prev = recurses;
this_recurse.group = cs;
branchlength += find_minlength(re, cs, startcode, options,
&this_recurse, countptr);
}
}
cc += 1 + LINK_SIZE;
break;
/* Anything else does not or need not match a character. We can get the
item's length from the table, but for those that can match zero occurrences
of a character, we must take special action for UTF-8 characters. As it
happens, the "NOT" versions of these opcodes are used at present only for
ASCII characters, so they could be omitted from this list. However, in
future that may change, so we include them here so as not to leave a
gotcha for a future maintainer. */
case OP_UPTO:
case OP_UPTOI:
case OP_NOTUPTO:
case OP_NOTUPTOI:
case OP_MINUPTO:
case OP_MINUPTOI:
case OP_NOTMINUPTO:
case OP_NOTMINUPTOI:
case OP_POSUPTO:
case OP_POSUPTOI:
case OP_NOTPOSUPTO:
case OP_NOTPOSUPTOI:
case OP_STAR:
case OP_STARI:
case OP_NOTSTAR:
case OP_NOTSTARI:
case OP_MINSTAR:
case OP_MINSTARI:
case OP_NOTMINSTAR:
case OP_NOTMINSTARI:
case OP_POSSTAR:
case OP_POSSTARI:
case OP_NOTPOSSTAR:
case OP_NOTPOSSTARI:
case OP_QUERY:
case OP_QUERYI:
case OP_NOTQUERY:
case OP_NOTQUERYI:
case OP_MINQUERY:
case OP_MINQUERYI:
case OP_NOTMINQUERY:
case OP_NOTMINQUERYI:
case OP_POSQUERY:
case OP_POSQUERYI:
case OP_NOTPOSQUERY:
case OP_NOTPOSQUERYI:
cc += PRIV(OP_lengths)[op];
#ifdef SUPPORT_UTF
if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
/* Skip these, but we need to add in the name length. */
case OP_MARK:
case OP_PRUNE_ARG:
case OP_SKIP_ARG:
case OP_THEN_ARG:
cc += PRIV(OP_lengths)[op] + cc[1];
break;
/* The remaining opcodes are just skipped over. */
case OP_CLOSE:
case OP_COMMIT:
case OP_FAIL:
case OP_PRUNE:
case OP_SET_SOM:
case OP_SKIP:
case OP_THEN:
cc += PRIV(OP_lengths)[op];
break;
/* This should not occur: we list all opcodes explicitly so that when
new ones get added they are properly considered. */
default:
return -3;
}
}
/* Control never gets here */
}
/*************************************************
* Set a bit and maybe its alternate case *
*************************************************/
/* Given a character, set its first byte's bit in the table, and also the
corresponding bit for the other version of a letter if we are caseless. In
UTF-8 mode, for characters greater than 127, we can only do the caseless thing
when Unicode property support is available.
Arguments:
start_bits points to the bit map
p points to the character
caseless the caseless flag
cd the block with char table pointers
utf TRUE for UTF-8 / UTF-16 / UTF-32 mode
Returns: pointer after the character
*/
static const pcre_uchar *
set_table_bit(pcre_uint8 *start_bits, const pcre_uchar *p, BOOL caseless,
compile_data *cd, BOOL utf)
{
pcre_uint32 c = *p;
#ifdef COMPILE_PCRE8
SET_BIT(c);
#ifdef SUPPORT_UTF
if (utf && c > 127)
{
GETCHARINC(c, p);
#ifdef SUPPORT_UCP
if (caseless)
{
pcre_uchar buff[6];
c = UCD_OTHERCASE(c);
(void)PRIV(ord2utf)(c, buff);
SET_BIT(buff[0]);
}
#endif /* Not SUPPORT_UCP */
return p;
}
#else /* Not SUPPORT_UTF */
(void)(utf); /* Stops warning for unused parameter */
#endif /* SUPPORT_UTF */
/* Not UTF-8 mode, or character is less than 127. */
if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]);
return p + 1;
#endif /* COMPILE_PCRE8 */
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
if (c > 0xff)
{
c = 0xff;
caseless = FALSE;
}
SET_BIT(c);
#ifdef SUPPORT_UTF
if (utf && c > 127)
{
GETCHARINC(c, p);
#ifdef SUPPORT_UCP
if (caseless)
{
c = UCD_OTHERCASE(c);
if (c > 0xff)
c = 0xff;
SET_BIT(c);
}
#endif /* SUPPORT_UCP */
return p;
}
#else /* Not SUPPORT_UTF */
(void)(utf); /* Stops warning for unused parameter */
#endif /* SUPPORT_UTF */
if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]);
return p + 1;
#endif
}
/*************************************************
* Set bits for a positive character type *
*************************************************/
/* This function sets starting bits for a character type. In UTF-8 mode, we can
only do a direct setting for bytes less than 128, as otherwise there can be
confusion with bytes in the middle of UTF-8 characters. In a "traditional"
environment, the tables will only recognize ASCII characters anyway, but in at
least one Windows environment, some higher bytes bits were set in the tables.
So we deal with that case by considering the UTF-8 encoding.
Arguments:
start_bits the starting bitmap
cbit type the type of character wanted
table_limit 32 for non-UTF-8; 16 for UTF-8
cd the block with char table pointers
Returns: nothing
*/
static void
set_type_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit,
compile_data *cd)
{
register pcre_uint32 c;
for (c = 0; c < table_limit; c++) start_bits[c] |= cd->cbits[c+cbit_type];
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
if (table_limit == 32) return;
for (c = 128; c < 256; c++)
{
if ((cd->cbits[c/8] & (1 << (c&7))) != 0)
{
pcre_uchar buff[6];
(void)PRIV(ord2utf)(c, buff);
SET_BIT(buff[0]);
}
}
#endif
}
/*************************************************
* Set bits for a negative character type *
*************************************************/
/* This function sets starting bits for a negative character type such as \D.
In UTF-8 mode, we can only do a direct setting for bytes less than 128, as
otherwise there can be confusion with bytes in the middle of UTF-8 characters.
Unlike in the positive case, where we can set appropriate starting bits for
specific high-valued UTF-8 characters, in this case we have to set the bits for
all high-valued characters. The lowest is 0xc2, but we overkill by starting at
0xc0 (192) for simplicity.
Arguments:
start_bits the starting bitmap
cbit type the type of character wanted
table_limit 32 for non-UTF-8; 16 for UTF-8
cd the block with char table pointers
Returns: nothing
*/
static void
set_nottype_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit,
compile_data *cd)
{
register pcre_uint32 c;
for (c = 0; c < table_limit; c++) start_bits[c] |= ~cd->cbits[c+cbit_type];
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
if (table_limit != 32) for (c = 24; c < 32; c++) start_bits[c] = 0xff;
#endif
}
/*************************************************
* Create bitmap of starting bytes *
*************************************************/
/* This function scans a compiled unanchored expression recursively and
attempts to build a bitmap of the set of possible starting bytes. As time goes
by, we may be able to get more clever at doing this. The SSB_CONTINUE return is
useful for parenthesized groups in patterns such as (a*)b where the group
provides some optional starting bytes but scanning must continue at the outer
level to find at least one mandatory byte. At the outermost level, this
function fails unless the result is SSB_DONE.
Arguments:
code points to an expression
start_bits points to a 32-byte table, initialized to 0
utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode
cd the block with char table pointers
Returns: SSB_FAIL => Failed to find any starting bytes
SSB_DONE => Found mandatory starting bytes
SSB_CONTINUE => Found optional starting bytes
SSB_UNKNOWN => Hit an unrecognized opcode
*/
static int
set_start_bits(const pcre_uchar *code, pcre_uint8 *start_bits, BOOL utf,
compile_data *cd)
{
register pcre_uint32 c;
int yield = SSB_DONE;
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
int table_limit = utf? 16:32;
#else
int table_limit = 32;
#endif
#if 0
/* ========================================================================= */
/* The following comment and code was inserted in January 1999. In May 2006,
when it was observed to cause compiler warnings about unused values, I took it
out again. If anybody is still using OS/2, they will have to put it back
manually. */
/* This next statement and the later reference to dummy are here in order to
trick the optimizer of the IBM C compiler for OS/2 into generating correct
code. Apparently IBM isn't going to fix the problem, and we would rather not
disable optimization (in this module it actually makes a big difference, and
the pcre module can use all the optimization it can get). */
volatile int dummy;
/* ========================================================================= */
#endif
do
{
BOOL try_next = TRUE;
const pcre_uchar *tcode = code + 1 + LINK_SIZE;
if (*code == OP_CBRA || *code == OP_SCBRA ||
*code == OP_CBRAPOS || *code == OP_SCBRAPOS) tcode += IMM2_SIZE;
while (try_next) /* Loop for items in this branch */
{
int rc;
switch(*tcode)
{
/* If we reach something we don't understand, it means a new opcode has
been created that hasn't been added to this code. Hopefully this problem
will be discovered during testing. */
default:
return SSB_UNKNOWN;
/* Fail for a valid opcode that implies no starting bits. */
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
case OP_ALLANY:
case OP_ANY:
case OP_ANYBYTE:
case OP_CIRC:
case OP_CIRCM:
case OP_CLOSE:
case OP_COMMIT:
case OP_COND:
case OP_CREF:
case OP_DEF:
case OP_DNCREF:
case OP_DNREF:
case OP_DNREFI:
case OP_DNRREF:
case OP_DOLL:
case OP_DOLLM:
case OP_END:
case OP_EOD:
case OP_EODN:
case OP_EXTUNI:
case OP_FAIL:
case OP_MARK:
case OP_NOT:
case OP_NOTEXACT:
case OP_NOTEXACTI:
case OP_NOTI:
case OP_NOTMINPLUS:
case OP_NOTMINPLUSI:
case OP_NOTMINQUERY:
case OP_NOTMINQUERYI:
case OP_NOTMINSTAR:
case OP_NOTMINSTARI:
case OP_NOTMINUPTO:
case OP_NOTMINUPTOI:
case OP_NOTPLUS:
case OP_NOTPLUSI:
case OP_NOTPOSPLUS:
case OP_NOTPOSPLUSI:
case OP_NOTPOSQUERY:
case OP_NOTPOSQUERYI:
case OP_NOTPOSSTAR:
case OP_NOTPOSSTARI:
case OP_NOTPOSUPTO:
case OP_NOTPOSUPTOI:
case OP_NOTPROP:
case OP_NOTQUERY:
case OP_NOTQUERYI:
case OP_NOTSTAR:
case OP_NOTSTARI:
case OP_NOTUPTO:
case OP_NOTUPTOI:
case OP_NOT_HSPACE:
case OP_NOT_VSPACE:
case OP_PRUNE:
case OP_PRUNE_ARG:
case OP_RECURSE:
case OP_REF:
case OP_REFI:
case OP_REVERSE:
case OP_RREF:
case OP_SCOND:
case OP_SET_SOM:
case OP_SKIP:
case OP_SKIP_ARG:
case OP_SOD:
case OP_SOM:
case OP_THEN:
case OP_THEN_ARG:
return SSB_FAIL;
/* A "real" property test implies no starting bits, but the fake property
PT_CLIST identifies a list of characters. These lists are short, as they
are used for characters with more than one "other case", so there is no
point in recognizing them for OP_NOTPROP. */
case OP_PROP:
if (tcode[1] != PT_CLIST) return SSB_FAIL;
{
const pcre_uint32 *p = PRIV(ucd_caseless_sets) + tcode[2];
while ((c = *p++) < NOTACHAR)
{
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
if (utf)
{
pcre_uchar buff[6];
(void)PRIV(ord2utf)(c, buff);
c = buff[0];
}
#endif
if (c > 0xff) SET_BIT(0xff); else SET_BIT(c);
}
}
try_next = FALSE;
break;
/* We can ignore word boundary tests. */
case OP_WORD_BOUNDARY:
case OP_NOT_WORD_BOUNDARY:
tcode++;
break;
/* If we hit a bracket or a positive lookahead assertion, recurse to set
bits from within the subpattern. If it can't find anything, we have to
give up. If it finds some mandatory character(s), we are done for this
branch. Otherwise, carry on scanning after the subpattern. */
case OP_BRA:
case OP_SBRA:
case OP_CBRA:
case OP_SCBRA:
case OP_BRAPOS:
case OP_SBRAPOS:
case OP_CBRAPOS:
case OP_SCBRAPOS:
case OP_ONCE:
case OP_ONCE_NC:
case OP_ASSERT:
rc = set_start_bits(tcode, start_bits, utf, cd);
if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc;
if (rc == SSB_DONE) try_next = FALSE; else
{
do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
}
break;
/* If we hit ALT or KET, it means we haven't found anything mandatory in
this branch, though we might have found something optional. For ALT, we
continue with the next alternative, but we have to arrange that the final
result from subpattern is SSB_CONTINUE rather than SSB_DONE. For KET,
return SSB_CONTINUE: if this is the top level, that indicates failure,
but after a nested subpattern, it causes scanning to continue. */
case OP_ALT:
yield = SSB_CONTINUE;
try_next = FALSE;
break;
case OP_KET:
case OP_KETRMAX:
case OP_KETRMIN:
case OP_KETRPOS:
return SSB_CONTINUE;
/* Skip over callout */
case OP_CALLOUT:
tcode += 2 + 2*LINK_SIZE;
break;
/* Skip over lookbehind and negative lookahead assertions */
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
break;
/* BRAZERO does the bracket, but carries on. */
case OP_BRAZERO:
case OP_BRAMINZERO:
case OP_BRAPOSZERO:
rc = set_start_bits(++tcode, start_bits, utf, cd);
if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc;
/* =========================================================================
See the comment at the head of this function concerning the next line,
which was an old fudge for the benefit of OS/2.
dummy = 1;
========================================================================= */
do tcode += GET(tcode,1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
break;
/* SKIPZERO skips the bracket. */
case OP_SKIPZERO:
tcode++;
do tcode += GET(tcode,1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
break;
/* Single-char * or ? sets the bit and tries the next item */
case OP_STAR:
case OP_MINSTAR:
case OP_POSSTAR:
case OP_QUERY:
case OP_MINQUERY:
case OP_POSQUERY:
tcode = set_table_bit(start_bits, tcode + 1, FALSE, cd, utf);
break;
case OP_STARI:
case OP_MINSTARI:
case OP_POSSTARI:
case OP_QUERYI:
case OP_MINQUERYI:
case OP_POSQUERYI:
tcode = set_table_bit(start_bits, tcode + 1, TRUE, cd, utf);
break;
/* Single-char upto sets the bit and tries the next */
case OP_UPTO:
case OP_MINUPTO:
case OP_POSUPTO:
tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, FALSE, cd, utf);
break;
case OP_UPTOI:
case OP_MINUPTOI:
case OP_POSUPTOI:
tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, TRUE, cd, utf);
break;
/* At least one single char sets the bit and stops */
case OP_EXACT:
tcode += IMM2_SIZE;
/* Fall through */
case OP_CHAR:
case OP_PLUS:
case OP_MINPLUS:
case OP_POSPLUS:
(void)set_table_bit(start_bits, tcode + 1, FALSE, cd, utf);
try_next = FALSE;
break;
case OP_EXACTI:
tcode += IMM2_SIZE;
/* Fall through */
case OP_CHARI:
case OP_PLUSI:
case OP_MINPLUSI:
case OP_POSPLUSI:
(void)set_table_bit(start_bits, tcode + 1, TRUE, cd, utf);
try_next = FALSE;
break;
/* Special spacing and line-terminating items. These recognize specific
lists of characters. The difference between VSPACE and ANYNL is that the
latter can match the two-character CRLF sequence, but that is not
relevant for finding the first character, so their code here is
identical. */
case OP_HSPACE:
SET_BIT(CHAR_HT);
SET_BIT(CHAR_SPACE);
#ifdef SUPPORT_UTF
if (utf)
{
#ifdef COMPILE_PCRE8
SET_BIT(0xC2); /* For U+00A0 */
SET_BIT(0xE1); /* For U+1680, U+180E */
SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */
SET_BIT(0xE3); /* For U+3000 */
#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(0xA0);
SET_BIT(0xFF); /* For characters > 255 */
#endif /* COMPILE_PCRE[8|16|32] */
}
else
#endif /* SUPPORT_UTF */
{
#ifndef EBCDIC
SET_BIT(0xA0);
#endif /* Not EBCDIC */
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(0xFF); /* For characters > 255 */
#endif /* COMPILE_PCRE[16|32] */
}
try_next = FALSE;
break;
case OP_ANYNL:
case OP_VSPACE:
SET_BIT(CHAR_LF);
SET_BIT(CHAR_VT);
SET_BIT(CHAR_FF);
SET_BIT(CHAR_CR);
#ifdef SUPPORT_UTF
if (utf)
{
#ifdef COMPILE_PCRE8
SET_BIT(0xC2); /* For U+0085 */
SET_BIT(0xE2); /* For U+2028, U+2029 */
#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(CHAR_NEL);
SET_BIT(0xFF); /* For characters > 255 */
#endif /* COMPILE_PCRE[8|16|32] */
}
else
#endif /* SUPPORT_UTF */
{
SET_BIT(CHAR_NEL);
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(0xFF); /* For characters > 255 */
#endif
}
try_next = FALSE;
break;
/* Single character types set the bits and stop. Note that if PCRE_UCP
is set, we do not see these op codes because \d etc are converted to
properties. Therefore, these apply in the case when only characters less
than 256 are recognized to match the types. */
case OP_NOT_DIGIT:
set_nottype_bits(start_bits, cbit_digit, table_limit, cd);
try_next = FALSE;
break;
case OP_DIGIT:
set_type_bits(start_bits, cbit_digit, table_limit, cd);
try_next = FALSE;
break;
/* The cbit_space table has vertical tab as whitespace; we no longer
have to play fancy tricks because Perl added VT to its whitespace at
release 5.18. PCRE added it at release 8.34. */
case OP_NOT_WHITESPACE:
set_nottype_bits(start_bits, cbit_space, table_limit, cd);
try_next = FALSE;
break;
case OP_WHITESPACE:
set_type_bits(start_bits, cbit_space, table_limit, cd);
try_next = FALSE;
break;
case OP_NOT_WORDCHAR:
set_nottype_bits(start_bits, cbit_word, table_limit, cd);
try_next = FALSE;
break;
case OP_WORDCHAR:
set_type_bits(start_bits, cbit_word, table_limit, cd);
try_next = FALSE;
break;
/* One or more character type fudges the pointer and restarts, knowing
it will hit a single character type and stop there. */
case OP_TYPEPLUS:
case OP_TYPEMINPLUS:
case OP_TYPEPOSPLUS:
tcode++;
break;
case OP_TYPEEXACT:
tcode += 1 + IMM2_SIZE;
break;
/* Zero or more repeats of character types set the bits and then
try again. */
case OP_TYPEUPTO:
case OP_TYPEMINUPTO:
case OP_TYPEPOSUPTO:
tcode += IMM2_SIZE; /* Fall through */
case OP_TYPESTAR:
case OP_TYPEMINSTAR:
case OP_TYPEPOSSTAR:
case OP_TYPEQUERY:
case OP_TYPEMINQUERY:
case OP_TYPEPOSQUERY:
switch(tcode[1])
{
default:
case OP_ANY:
case OP_ALLANY:
return SSB_FAIL;
case OP_HSPACE:
SET_BIT(CHAR_HT);
SET_BIT(CHAR_SPACE);
#ifdef SUPPORT_UTF
if (utf)
{
#ifdef COMPILE_PCRE8
SET_BIT(0xC2); /* For U+00A0 */
SET_BIT(0xE1); /* For U+1680, U+180E */
SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */
SET_BIT(0xE3); /* For U+3000 */
#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(0xA0);
SET_BIT(0xFF); /* For characters > 255 */
#endif /* COMPILE_PCRE[8|16|32] */
}
else
#endif /* SUPPORT_UTF */
#ifndef EBCDIC
SET_BIT(0xA0);
#endif /* Not EBCDIC */
break;
case OP_ANYNL:
case OP_VSPACE:
SET_BIT(CHAR_LF);
SET_BIT(CHAR_VT);
SET_BIT(CHAR_FF);
SET_BIT(CHAR_CR);
#ifdef SUPPORT_UTF
if (utf)
{
#ifdef COMPILE_PCRE8
SET_BIT(0xC2); /* For U+0085 */
SET_BIT(0xE2); /* For U+2028, U+2029 */
#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(CHAR_NEL);
SET_BIT(0xFF); /* For characters > 255 */
#endif /* COMPILE_PCRE16 */
}
else
#endif /* SUPPORT_UTF */
SET_BIT(CHAR_NEL);
break;
case OP_NOT_DIGIT:
set_nottype_bits(start_bits, cbit_digit, table_limit, cd);
break;
case OP_DIGIT:
set_type_bits(start_bits, cbit_digit, table_limit, cd);
break;
/* The cbit_space table has vertical tab as whitespace; we no longer
have to play fancy tricks because Perl added VT to its whitespace at
release 5.18. PCRE added it at release 8.34. */
case OP_NOT_WHITESPACE:
set_nottype_bits(start_bits, cbit_space, table_limit, cd);
break;
case OP_WHITESPACE:
set_type_bits(start_bits, cbit_space, table_limit, cd);
break;
case OP_NOT_WORDCHAR:
set_nottype_bits(start_bits, cbit_word, table_limit, cd);
break;
case OP_WORDCHAR:
set_type_bits(start_bits, cbit_word, table_limit, cd);
break;
}
tcode += 2;
break;
/* Character class where all the information is in a bit map: set the
bits and either carry on or not, according to the repeat count. If it was
a negative class, and we are operating with UTF-8 characters, any byte
with a value >= 0xc4 is a potentially valid starter because it starts a
character with a value > 255. */
#if defined SUPPORT_UTF || !defined COMPILE_PCRE8
case OP_XCLASS:
if ((tcode[1 + LINK_SIZE] & XCL_HASPROP) != 0)
return SSB_FAIL;
/* All bits are set. */
if ((tcode[1 + LINK_SIZE] & XCL_MAP) == 0 && (tcode[1 + LINK_SIZE] & XCL_NOT) != 0)
return SSB_FAIL;
#endif
/* Fall through */
case OP_NCLASS:
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
if (utf)
{
start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */
memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */
}
#endif
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
SET_BIT(0xFF); /* For characters > 255 */
#endif
/* Fall through */
case OP_CLASS:
{
pcre_uint8 *map;
#if defined SUPPORT_UTF || !defined COMPILE_PCRE8
map = NULL;
if (*tcode == OP_XCLASS)
{
if ((tcode[1 + LINK_SIZE] & XCL_MAP) != 0)
map = (pcre_uint8 *)(tcode + 1 + LINK_SIZE + 1);
tcode += GET(tcode, 1);
}
else
#endif
{
tcode++;
map = (pcre_uint8 *)tcode;
tcode += 32 / sizeof(pcre_uchar);
}
/* In UTF-8 mode, the bits in a bit map correspond to character
values, not to byte values. However, the bit map we are constructing is
for byte values. So we have to do a conversion for characters whose
value is > 127. In fact, there are only two possible starting bytes for
characters in the range 128 - 255. */
#if defined SUPPORT_UTF || !defined COMPILE_PCRE8
if (map != NULL)
#endif
{
#if defined SUPPORT_UTF && defined COMPILE_PCRE8
if (utf)
{
for (c = 0; c < 16; c++) start_bits[c] |= map[c];
for (c = 128; c < 256; c++)
{
if ((map[c/8] & (1 << (c&7))) != 0)
{
int d = (c >> 6) | 0xc0; /* Set bit for this starter */
start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */
c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */
}
}
}
else
#endif
{
/* In non-UTF-8 mode, the two bit maps are completely compatible. */
for (c = 0; c < 32; c++) start_bits[c] |= map[c];
}
}
/* Advance past the bit map, and act on what follows. For a zero
minimum repeat, continue; otherwise stop processing. */
switch (*tcode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSSTAR:
case OP_CRPOSQUERY:
tcode++;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
if (GET2(tcode, 1) == 0) tcode += 1 + 2 * IMM2_SIZE;
else try_next = FALSE;
break;
default:
try_next = FALSE;
break;
}
}
break; /* End of bitmap class handling */
} /* End of switch */
} /* End of try_next loop */
code += GET(code, 1); /* Advance to next branch */
}
while (*code == OP_ALT);
return yield;
}
/*************************************************
* Study a compiled expression *
*************************************************/
/* This function is handed a compiled expression that it must study to produce
information that will speed up the matching. It returns a pcre[16]_extra block
which then gets handed back to pcre_exec().
Arguments:
re points to the compiled expression
options contains option bits
errorptr points to where to place error messages;
set NULL unless error
Returns: pointer to a pcre[16]_extra block, with study_data filled in and
the appropriate flags set;
NULL on error or if no optimization possible
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN pcre_extra * PCRE_CALL_CONVENTION
pcre_study(const pcre *external_re, int options, const char **errorptr)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN pcre16_extra * PCRE_CALL_CONVENTION
pcre16_study(const pcre16 *external_re, int options, const char **errorptr)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN pcre32_extra * PCRE_CALL_CONVENTION
pcre32_study(const pcre32 *external_re, int options, const char **errorptr)
#endif
{
int min;
int count = 0;
BOOL bits_set = FALSE;
pcre_uint8 start_bits[32];
PUBL(extra) *extra = NULL;
pcre_study_data *study;
const pcre_uint8 *tables;
pcre_uchar *code;
compile_data compile_block;
const REAL_PCRE *re = (const REAL_PCRE *)external_re;
*errorptr = NULL;
if (re == NULL || re->magic_number != MAGIC_NUMBER)
{
*errorptr = "argument is not a compiled regular expression";
return NULL;
}
if ((re->flags & PCRE_MODE) == 0)
{
#if defined COMPILE_PCRE8
*errorptr = "argument not compiled in 8 bit mode";
#elif defined COMPILE_PCRE16
*errorptr = "argument not compiled in 16 bit mode";
#elif defined COMPILE_PCRE32
*errorptr = "argument not compiled in 32 bit mode";
#endif
return NULL;
}
if ((options & ~PUBLIC_STUDY_OPTIONS) != 0)
{
*errorptr = "unknown or incorrect option bit(s) set";
return NULL;
}
code = (pcre_uchar *)re + re->name_table_offset +
(re->name_count * re->name_entry_size);
/* For an anchored pattern, or an unanchored pattern that has a first char, or
a multiline pattern that matches only at "line starts", there is no point in
seeking a list of starting bytes. */
if ((re->options & PCRE_ANCHORED) == 0 &&
(re->flags & (PCRE_FIRSTSET|PCRE_STARTLINE)) == 0)
{
int rc;
/* Set the character tables in the block that is passed around */
tables = re->tables;
#if defined COMPILE_PCRE8
if (tables == NULL)
(void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES,
(void *)(&tables));
#elif defined COMPILE_PCRE16
if (tables == NULL)
(void)pcre16_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES,
(void *)(&tables));
#elif defined COMPILE_PCRE32
if (tables == NULL)
(void)pcre32_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES,
(void *)(&tables));
#endif
compile_block.lcc = tables + lcc_offset;
compile_block.fcc = tables + fcc_offset;
compile_block.cbits = tables + cbits_offset;
compile_block.ctypes = tables + ctypes_offset;
/* See if we can find a fixed set of initial characters for the pattern. */
memset(start_bits, 0, 32 * sizeof(pcre_uint8));
rc = set_start_bits(code, start_bits, (re->options & PCRE_UTF8) != 0,
&compile_block);
bits_set = rc == SSB_DONE;
if (rc == SSB_UNKNOWN)
{
*errorptr = "internal error: opcode not recognized";
return NULL;
}
}
/* Find the minimum length of subject string. */
switch(min = find_minlength(re, code, code, re->options, NULL, &count))
{
case -2: *errorptr = "internal error: missing capturing bracket"; return NULL;
case -3: *errorptr = "internal error: opcode not recognized"; return NULL;
default: break;
}
/* If a set of starting bytes has been identified, or if the minimum length is
greater than zero, or if JIT optimization has been requested, or if
PCRE_STUDY_EXTRA_NEEDED is set, get a pcre[16]_extra block and a
pcre_study_data block. The study data is put in the latter, which is pointed to
by the former, which may also get additional data set later by the calling
program. At the moment, the size of pcre_study_data is fixed. We nevertheless
save it in a field for returning via the pcre_fullinfo() function so that if it
becomes variable in the future, we don't have to change that code. */
if (bits_set || min > 0 || (options & (
#ifdef SUPPORT_JIT
PCRE_STUDY_JIT_COMPILE | PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE |
PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE |
#endif
PCRE_STUDY_EXTRA_NEEDED)) != 0)
{
extra = (PUBL(extra) *)(PUBL(malloc))
(sizeof(PUBL(extra)) + sizeof(pcre_study_data));
if (extra == NULL)
{
*errorptr = "failed to get memory";
return NULL;
}
study = (pcre_study_data *)((char *)extra + sizeof(PUBL(extra)));
extra->flags = PCRE_EXTRA_STUDY_DATA;
extra->study_data = study;
study->size = sizeof(pcre_study_data);
study->flags = 0;
/* Set the start bits always, to avoid unset memory errors if the
study data is written to a file, but set the flag only if any of the bits
are set, to save time looking when none are. */
if (bits_set)
{
study->flags |= PCRE_STUDY_MAPPED;
memcpy(study->start_bits, start_bits, sizeof(start_bits));
}
else memset(study->start_bits, 0, 32 * sizeof(pcre_uint8));
#ifdef PCRE_DEBUG
if (bits_set)
{
pcre_uint8 *ptr = start_bits;
int i;
printf("Start bits:\n");
for (i = 0; i < 32; i++)
printf("%3d: %02x%s", i * 8, *ptr++, ((i + 1) & 0x7) != 0? " " : "\n");
}
#endif
/* Always set the minlength value in the block, because the JIT compiler
makes use of it. However, don't set the bit unless the length is greater than
zero - the interpretive pcre_exec() and pcre_dfa_exec() needn't waste time
checking the zero case. */
if (min > 0)
{
study->flags |= PCRE_STUDY_MINLEN;
study->minlength = min;
}
else study->minlength = 0;
/* If JIT support was compiled and requested, attempt the JIT compilation.
If no starting bytes were found, and the minimum length is zero, and JIT
compilation fails, abandon the extra block and return NULL, unless
PCRE_STUDY_EXTRA_NEEDED is set. */
#ifdef SUPPORT_JIT
extra->executable_jit = NULL;
if ((options & PCRE_STUDY_JIT_COMPILE) != 0)
PRIV(jit_compile)(re, extra, JIT_COMPILE);
if ((options & PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE) != 0)
PRIV(jit_compile)(re, extra, JIT_PARTIAL_SOFT_COMPILE);
if ((options & PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE) != 0)
PRIV(jit_compile)(re, extra, JIT_PARTIAL_HARD_COMPILE);
if (study->flags == 0 && (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) == 0 &&
(options & PCRE_STUDY_EXTRA_NEEDED) == 0)
{
#if defined COMPILE_PCRE8
pcre_free_study(extra);
#elif defined COMPILE_PCRE16
pcre16_free_study(extra);
#elif defined COMPILE_PCRE32
pcre32_free_study(extra);
#endif
extra = NULL;
}
#endif
}
return extra;
}
/*************************************************
* Free the study data *
*************************************************/
/* This function frees the memory that was obtained by pcre_study().
Argument: a pointer to the pcre[16]_extra block
Returns: nothing
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN void
pcre_free_study(pcre_extra *extra)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN void
pcre16_free_study(pcre16_extra *extra)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN void
pcre32_free_study(pcre32_extra *extra)
#endif
{
if (extra == NULL)
return;
#ifdef SUPPORT_JIT
if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 &&
extra->executable_jit != NULL)
PRIV(jit_free)(extra->executable_jit);
#endif
PUBL(free)(extra);
}
/* End of pcre_study.c */
| libgit2-main | deps/pcre/pcre_study.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains internal functions for testing newlines when more than
one kind of newline is to be recognized. When a newline is found, its length is
returned. In principle, we could implement several newline "types", each
referring to a different set of newline characters. At present, PCRE supports
only NLTYPE_FIXED, which gets handled without these functions, NLTYPE_ANYCRLF,
and NLTYPE_ANY. The full list of Unicode newline characters is taken from
http://unicode.org/unicode/reports/tr18/. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Check for newline at given position *
*************************************************/
/* It is guaranteed that the initial value of ptr is less than the end of the
string that is being processed.
Arguments:
ptr pointer to possible newline
type the newline type
endptr pointer to the end of the string
lenptr where to return the length
utf TRUE if in utf mode
Returns: TRUE or FALSE
*/
BOOL
PRIV(is_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR endptr, int *lenptr,
BOOL utf)
{
pcre_uint32 c;
(void)utf;
#ifdef SUPPORT_UTF
if (utf)
{
GETCHAR(c, ptr);
}
else
#endif /* SUPPORT_UTF */
c = *ptr;
/* Note that this function is called only for ANY or ANYCRLF. */
if (type == NLTYPE_ANYCRLF) switch(c)
{
case CHAR_LF: *lenptr = 1; return TRUE;
case CHAR_CR: *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1;
return TRUE;
default: return FALSE;
}
/* NLTYPE_ANY */
else switch(c)
{
#ifdef EBCDIC
case CHAR_NEL:
#endif
case CHAR_LF:
case CHAR_VT:
case CHAR_FF: *lenptr = 1; return TRUE;
case CHAR_CR:
*lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1;
return TRUE;
#ifndef EBCDIC
#ifdef COMPILE_PCRE8
case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE;
case 0x2028: /* LS */
case 0x2029: *lenptr = 3; return TRUE; /* PS */
#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */
case CHAR_NEL:
case 0x2028: /* LS */
case 0x2029: *lenptr = 1; return TRUE; /* PS */
#endif /* COMPILE_PCRE8 */
#endif /* Not EBCDIC */
default: return FALSE;
}
}
/*************************************************
* Check for newline at previous position *
*************************************************/
/* It is guaranteed that the initial value of ptr is greater than the start of
the string that is being processed.
Arguments:
ptr pointer to possible newline
type the newline type
startptr pointer to the start of the string
lenptr where to return the length
utf TRUE if in utf mode
Returns: TRUE or FALSE
*/
BOOL
PRIV(was_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR startptr, int *lenptr,
BOOL utf)
{
pcre_uint32 c;
(void)utf;
ptr--;
#ifdef SUPPORT_UTF
if (utf)
{
BACKCHAR(ptr);
GETCHAR(c, ptr);
}
else
#endif /* SUPPORT_UTF */
c = *ptr;
/* Note that this function is called only for ANY or ANYCRLF. */
if (type == NLTYPE_ANYCRLF) switch(c)
{
case CHAR_LF:
*lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1;
return TRUE;
case CHAR_CR: *lenptr = 1; return TRUE;
default: return FALSE;
}
/* NLTYPE_ANY */
else switch(c)
{
case CHAR_LF:
*lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1;
return TRUE;
#ifdef EBCDIC
case CHAR_NEL:
#endif
case CHAR_VT:
case CHAR_FF:
case CHAR_CR: *lenptr = 1; return TRUE;
#ifndef EBCDIC
#ifdef COMPILE_PCRE8
case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE;
case 0x2028: /* LS */
case 0x2029: *lenptr = 3; return TRUE; /* PS */
#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */
case CHAR_NEL:
case 0x2028: /* LS */
case 0x2029: *lenptr = 1; return TRUE; /* PS */
#endif /* COMPILE_PCRE8 */
#endif /* NotEBCDIC */
default: return FALSE;
}
}
/* End of pcre_newline.c */
| libgit2-main | deps/pcre/pcre_newline.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_refcount(), which is an
auxiliary function that can be used to maintain a reference count in a compiled
pattern data block. This might be helpful in applications where the block is
shared by different users. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Maintain reference count *
*************************************************/
/* The reference count is a 16-bit field, initialized to zero. It is not
possible to transfer a non-zero count from one host to a different host that
has a different byte order - though I can't see why anyone in their right mind
would ever want to do that!
Arguments:
argument_re points to compiled code
adjust value to add to the count
Returns: the (possibly updated) count value (a non-negative number), or
a negative error number
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_refcount(pcre *argument_re, int adjust)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre16_refcount(pcre16 *argument_re, int adjust)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre32_refcount(pcre32 *argument_re, int adjust)
#endif
{
REAL_PCRE *re = (REAL_PCRE *)argument_re;
if (re == NULL) return PCRE_ERROR_NULL;
if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC;
if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE;
re->ref_count = (-adjust > re->ref_count)? 0 :
(adjust + re->ref_count > 65535)? 65535 :
re->ref_count + adjust;
return re->ref_count;
}
/* End of pcre_refcount.c */
| libgit2-main | deps/pcre/pcre_refcount.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_maketables(), which builds
character tables for PCRE in the current locale. The file is compiled on its
own as part of the PCRE library. However, it is also included in the
compilation of dftables.c, in which case the macro DFTABLES is defined. */
#ifndef DFTABLES
# ifdef HAVE_CONFIG_H
# include "config.h"
# endif
# include "pcre_internal.h"
#endif
/*************************************************
* Create PCRE character tables *
*************************************************/
/* This function builds a set of character tables for use by PCRE and returns
a pointer to them. They are build using the ctype functions, and consequently
their contents will depend upon the current locale setting. When compiled as
part of the library, the store is obtained via PUBL(malloc)(), but when
compiled inside dftables, use malloc().
Arguments: none
Returns: pointer to the contiguous block of data
*/
#if defined COMPILE_PCRE8
const unsigned char *
pcre_maketables(void)
#elif defined COMPILE_PCRE16
const unsigned char *
pcre16_maketables(void)
#elif defined COMPILE_PCRE32
const unsigned char *
pcre32_maketables(void)
#endif
{
unsigned char *yield, *p;
int i;
#ifndef DFTABLES
yield = (unsigned char*)(PUBL(malloc))(tables_length);
#else
yield = (unsigned char*)malloc(tables_length);
#endif
if (yield == NULL) return NULL;
p = yield;
/* First comes the lower casing table */
for (i = 0; i < 256; i++) *p++ = tolower(i);
/* Next the case-flipping table */
for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i);
/* Then the character class tables. Don't try to be clever and save effort on
exclusive ones - in some locales things may be different.
Note that the table for "space" includes everything "isspace" gives, including
VT in the default locale. This makes it work for the POSIX class [:space:].
From release 8.34 is is also correct for Perl space, because Perl added VT at
release 5.18.
Note also that it is possible for a character to be alnum or alpha without
being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the
fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must
test for alnum specially. */
memset(p, 0, cbit_length);
for (i = 0; i < 256; i++)
{
if (isdigit(i)) p[cbit_digit + i/8] |= 1 << (i&7);
if (isupper(i)) p[cbit_upper + i/8] |= 1 << (i&7);
if (islower(i)) p[cbit_lower + i/8] |= 1 << (i&7);
if (isalnum(i)) p[cbit_word + i/8] |= 1 << (i&7);
if (i == '_') p[cbit_word + i/8] |= 1 << (i&7);
if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7);
if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7);
if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7);
if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7);
if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7);
if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7);
}
p += cbit_length;
/* Finally, the character type table. In this, we used to exclude VT from the
white space chars, because Perl didn't recognize it as such for \s and for
comments within regexes. However, Perl changed at release 5.18, so PCRE changed
at release 8.34. */
for (i = 0; i < 256; i++)
{
int x = 0;
if (isspace(i)) x += ctype_space;
if (isalpha(i)) x += ctype_letter;
if (isdigit(i)) x += ctype_digit;
if (isxdigit(i)) x += ctype_xdigit;
if (isalnum(i) || i == '_') x += ctype_word;
/* Note: strchr includes the terminating zero in the characters it considers.
In this instance, that is ok because we want binary zero to be flagged as a
meta-character, which in this sense is any character that terminates a run
of data characters. */
if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta;
*p++ = x;
}
return yield;
}
/* End of pcre_maketables.c */
| libgit2-main | deps/pcre/pcre_maketables.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_config(). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* Keep the original link size. */
static int real_link_size = LINK_SIZE;
#include "pcre_internal.h"
/*************************************************
* Return info about what features are configured *
*************************************************/
/* This function has an extensible interface so that additional items can be
added compatibly.
Arguments:
what what information is required
where where to put the information
Returns: 0 if data returned, negative on error
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_config(int what, void *where)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre16_config(int what, void *where)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre32_config(int what, void *where)
#endif
{
switch (what)
{
case PCRE_CONFIG_UTF8:
#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32
*((int *)where) = 0;
return PCRE_ERROR_BADOPTION;
#else
#if defined SUPPORT_UTF
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
#endif
case PCRE_CONFIG_UTF16:
#if defined COMPILE_PCRE8 || defined COMPILE_PCRE32
*((int *)where) = 0;
return PCRE_ERROR_BADOPTION;
#else
#if defined SUPPORT_UTF
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
#endif
case PCRE_CONFIG_UTF32:
#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16
*((int *)where) = 0;
return PCRE_ERROR_BADOPTION;
#else
#if defined SUPPORT_UTF
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
#endif
case PCRE_CONFIG_UNICODE_PROPERTIES:
#ifdef SUPPORT_UCP
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_JIT:
#ifdef SUPPORT_JIT
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_JITTARGET:
#ifdef SUPPORT_JIT
*((const char **)where) = PRIV(jit_get_target)();
#else
*((const char **)where) = NULL;
#endif
break;
case PCRE_CONFIG_NEWLINE:
*((int *)where) = NEWLINE;
break;
case PCRE_CONFIG_BSR:
#ifdef BSR_ANYCRLF
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_LINK_SIZE:
*((int *)where) = real_link_size;
break;
case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD:
*((int *)where) = POSIX_MALLOC_THRESHOLD;
break;
case PCRE_CONFIG_PARENS_LIMIT:
*((unsigned long int *)where) = PARENS_NEST_LIMIT;
break;
case PCRE_CONFIG_MATCH_LIMIT:
*((unsigned long int *)where) = MATCH_LIMIT;
break;
case PCRE_CONFIG_MATCH_LIMIT_RECURSION:
*((unsigned long int *)where) = MATCH_LIMIT_RECURSION;
break;
case PCRE_CONFIG_STACKRECURSE:
#ifdef NO_RECURSE
*((int *)where) = 0;
#else
*((int *)where) = 1;
#endif
break;
default: return PCRE_ERROR_BADOPTION;
}
return 0;
}
/* End of pcre_config.c */
| libgit2-main | deps/pcre/pcre_config.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2013 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_fullinfo(), which returns
information about a compiled pattern. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Return info about compiled pattern *
*************************************************/
/* This is a newer "info" function which has an extensible interface so
that additional items can be added compatibly.
Arguments:
argument_re points to compiled code
extra_data points extra data, or NULL
what what information is required
where where to put the information
Returns: 0 if data returned, negative on error
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data,
int what, void *where)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre16_fullinfo(const pcre16 *argument_re, const pcre16_extra *extra_data,
int what, void *where)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre32_fullinfo(const pcre32 *argument_re, const pcre32_extra *extra_data,
int what, void *where)
#endif
{
const REAL_PCRE *re = (const REAL_PCRE *)argument_re;
const pcre_study_data *study = NULL;
if (re == NULL || where == NULL) return PCRE_ERROR_NULL;
if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0)
study = (const pcre_study_data *)extra_data->study_data;
/* Check that the first field in the block is the magic number. If it is not,
return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to
REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which
means that the pattern is likely compiled with different endianness. */
if (re->magic_number != MAGIC_NUMBER)
return re->magic_number == REVERSED_MAGIC_NUMBER?
PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC;
/* Check that this pattern was compiled in the correct bit mode */
if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE;
switch (what)
{
case PCRE_INFO_OPTIONS:
*((unsigned long int *)where) = re->options & PUBLIC_COMPILE_OPTIONS;
break;
case PCRE_INFO_SIZE:
*((size_t *)where) = re->size;
break;
case PCRE_INFO_STUDYSIZE:
*((size_t *)where) = (study == NULL)? 0 : study->size;
break;
case PCRE_INFO_JITSIZE:
#ifdef SUPPORT_JIT
*((size_t *)where) =
(extra_data != NULL &&
(extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 &&
extra_data->executable_jit != NULL)?
PRIV(jit_get_size)(extra_data->executable_jit) : 0;
#else
*((size_t *)where) = 0;
#endif
break;
case PCRE_INFO_CAPTURECOUNT:
*((int *)where) = re->top_bracket;
break;
case PCRE_INFO_BACKREFMAX:
*((int *)where) = re->top_backref;
break;
case PCRE_INFO_FIRSTBYTE:
*((int *)where) =
((re->flags & PCRE_FIRSTSET) != 0)? (int)re->first_char :
((re->flags & PCRE_STARTLINE) != 0)? -1 : -2;
break;
case PCRE_INFO_FIRSTCHARACTER:
*((pcre_uint32 *)where) =
(re->flags & PCRE_FIRSTSET) != 0 ? re->first_char : 0;
break;
case PCRE_INFO_FIRSTCHARACTERFLAGS:
*((int *)where) =
((re->flags & PCRE_FIRSTSET) != 0) ? 1 :
((re->flags & PCRE_STARTLINE) != 0) ? 2 : 0;
break;
/* Make sure we pass back the pointer to the bit vector in the external
block, not the internal copy (with flipped integer fields). */
case PCRE_INFO_FIRSTTABLE:
*((const pcre_uint8 **)where) =
(study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0)?
((const pcre_study_data *)extra_data->study_data)->start_bits : NULL;
break;
case PCRE_INFO_MINLENGTH:
*((int *)where) =
(study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0)?
(int)(study->minlength) : -1;
break;
case PCRE_INFO_JIT:
*((int *)where) = extra_data != NULL &&
(extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 &&
extra_data->executable_jit != NULL;
break;
case PCRE_INFO_LASTLITERAL:
*((int *)where) =
((re->flags & PCRE_REQCHSET) != 0)? (int)re->req_char : -1;
break;
case PCRE_INFO_REQUIREDCHAR:
*((pcre_uint32 *)where) =
((re->flags & PCRE_REQCHSET) != 0) ? re->req_char : 0;
break;
case PCRE_INFO_REQUIREDCHARFLAGS:
*((int *)where) =
((re->flags & PCRE_REQCHSET) != 0);
break;
case PCRE_INFO_NAMEENTRYSIZE:
*((int *)where) = re->name_entry_size;
break;
case PCRE_INFO_NAMECOUNT:
*((int *)where) = re->name_count;
break;
case PCRE_INFO_NAMETABLE:
*((const pcre_uchar **)where) = (const pcre_uchar *)re + re->name_table_offset;
break;
case PCRE_INFO_DEFAULT_TABLES:
*((const pcre_uint8 **)where) = (const pcre_uint8 *)(PRIV(default_tables));
break;
/* From release 8.00 this will always return TRUE because NOPARTIAL is
no longer ever set (the restrictions have been removed). */
case PCRE_INFO_OKPARTIAL:
*((int *)where) = (re->flags & PCRE_NOPARTIAL) == 0;
break;
case PCRE_INFO_JCHANGED:
*((int *)where) = (re->flags & PCRE_JCHANGED) != 0;
break;
case PCRE_INFO_HASCRORLF:
*((int *)where) = (re->flags & PCRE_HASCRORLF) != 0;
break;
case PCRE_INFO_MAXLOOKBEHIND:
*((int *)where) = re->max_lookbehind;
break;
case PCRE_INFO_MATCHLIMIT:
if ((re->flags & PCRE_MLSET) == 0) return PCRE_ERROR_UNSET;
*((pcre_uint32 *)where) = re->limit_match;
break;
case PCRE_INFO_RECURSIONLIMIT:
if ((re->flags & PCRE_RLSET) == 0) return PCRE_ERROR_UNSET;
*((pcre_uint32 *)where) = re->limit_recursion;
break;
case PCRE_INFO_MATCH_EMPTY:
*((int *)where) = (re->flags & PCRE_MATCH_EMPTY) != 0;
break;
default: return PCRE_ERROR_BADOPTION;
}
return 0;
}
/* End of pcre_fullinfo.c */
| libgit2-main | deps/pcre/pcre_fullinfo.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language (but see
below for why this module is different).
Written by Philip Hazel
Copyright (c) 1997-2017 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_dfa_exec(), which is an
alternative matching function that uses a sort of DFA algorithm (not a true
FSM). This is NOT Perl-compatible, but it has advantages in certain
applications. */
/* NOTE ABOUT PERFORMANCE: A user of this function sent some code that improved
the performance of his patterns greatly. I could not use it as it stood, as it
was not thread safe, and made assumptions about pattern sizes. Also, it caused
test 7 to loop, and test 9 to crash with a segfault.
The issue is the check for duplicate states, which is done by a simple linear
search up the state list. (Grep for "duplicate" below to find the code.) For
many patterns, there will never be many states active at one time, so a simple
linear search is fine. In patterns that have many active states, it might be a
bottleneck. The suggested code used an indexing scheme to remember which states
had previously been used for each character, and avoided the linear search when
it knew there was no chance of a duplicate. This was implemented when adding
states to the state lists.
I wrote some thread-safe, not-limited code to try something similar at the time
of checking for duplicates (instead of when adding states), using index vectors
on the stack. It did give a 13% improvement with one specially constructed
pattern for certain subject strings, but on other strings and on many of the
simpler patterns in the test suite it did worse. The major problem, I think,
was the extra time to initialize the index. This had to be done for each call
of internal_dfa_exec(). (The supplied patch used a static vector, initialized
only once - I suspect this was the cause of the problems with the tests.)
Overall, I concluded that the gains in some cases did not outweigh the losses
in others, so I abandoned this code. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define NLBLOCK md /* Block containing newline information */
#define PSSTART start_subject /* Field containing processed string start */
#define PSEND end_subject /* Field containing processed string end */
#include "pcre_internal.h"
/* For use to indent debugging output */
#define SP " "
/*************************************************
* Code parameters and static tables *
*************************************************/
/* These are offsets that are used to turn the OP_TYPESTAR and friends opcodes
into others, under special conditions. A gap of 20 between the blocks should be
enough. The resulting opcodes don't have to be less than 256 because they are
never stored, so we push them well clear of the normal opcodes. */
#define OP_PROP_EXTRA 300
#define OP_EXTUNI_EXTRA 320
#define OP_ANYNL_EXTRA 340
#define OP_HSPACE_EXTRA 360
#define OP_VSPACE_EXTRA 380
/* This table identifies those opcodes that are followed immediately by a
character that is to be tested in some way. This makes it possible to
centralize the loading of these characters. In the case of Type * etc, the
"character" is the opcode for \D, \d, \S, \s, \W, or \w, which will always be a
small value. Non-zero values in the table are the offsets from the opcode where
the character is to be found. ***NOTE*** If the start of this table is
modified, the three tables that follow must also be modified. */
static const pcre_uint8 coptable[] = {
0, /* End */
0, 0, 0, 0, 0, /* \A, \G, \K, \B, \b */
0, 0, 0, 0, 0, 0, /* \D, \d, \S, \s, \W, \w */
0, 0, 0, /* Any, AllAny, Anybyte */
0, 0, /* \P, \p */
0, 0, 0, 0, 0, /* \R, \H, \h, \V, \v */
0, /* \X */
0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */
1, /* Char */
1, /* Chari */
1, /* not */
1, /* noti */
/* Positive single-char repeats */
1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */
1+IMM2_SIZE, 1+IMM2_SIZE, /* upto, minupto */
1+IMM2_SIZE, /* exact */
1, 1, 1, 1+IMM2_SIZE, /* *+, ++, ?+, upto+ */
1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */
1+IMM2_SIZE, 1+IMM2_SIZE, /* upto I, minupto I */
1+IMM2_SIZE, /* exact I */
1, 1, 1, 1+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */
/* Negative single-char repeats - only for chars < 256 */
1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */
1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto, minupto */
1+IMM2_SIZE, /* NOT exact */
1, 1, 1, 1+IMM2_SIZE, /* NOT *+, ++, ?+, upto+ */
1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */
1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto I, minupto I */
1+IMM2_SIZE, /* NOT exact I */
1, 1, 1, 1+IMM2_SIZE, /* NOT *+I, ++I, ?+I, upto+I */
/* Positive type repeats */
1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */
1+IMM2_SIZE, 1+IMM2_SIZE, /* Type upto, minupto */
1+IMM2_SIZE, /* Type exact */
1, 1, 1, 1+IMM2_SIZE, /* Type *+, ++, ?+, upto+ */
/* Character class & ref repeats */
0, 0, 0, 0, 0, 0, /* *, *?, +, +?, ?, ?? */
0, 0, /* CRRANGE, CRMINRANGE */
0, 0, 0, 0, /* Possessive *+, ++, ?+, CRPOSRANGE */
0, /* CLASS */
0, /* NCLASS */
0, /* XCLASS - variable length */
0, /* REF */
0, /* REFI */
0, /* DNREF */
0, /* DNREFI */
0, /* RECURSE */
0, /* CALLOUT */
0, /* Alt */
0, /* Ket */
0, /* KetRmax */
0, /* KetRmin */
0, /* KetRpos */
0, /* Reverse */
0, /* Assert */
0, /* Assert not */
0, /* Assert behind */
0, /* Assert behind not */
0, 0, /* ONCE, ONCE_NC */
0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */
0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */
0, 0, /* CREF, DNCREF */
0, 0, /* RREF, DNRREF */
0, /* DEF */
0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */
0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */
0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */
0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */
0, 0 /* CLOSE, SKIPZERO */
};
/* This table identifies those opcodes that inspect a character. It is used to
remember the fact that a character could have been inspected when the end of
the subject is reached. ***NOTE*** If the start of this table is modified, the
two tables that follow must also be modified. */
static const pcre_uint8 poptable[] = {
0, /* End */
0, 0, 0, 1, 1, /* \A, \G, \K, \B, \b */
1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */
1, 1, 1, /* Any, AllAny, Anybyte */
1, 1, /* \P, \p */
1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */
1, /* \X */
0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */
1, /* Char */
1, /* Chari */
1, /* not */
1, /* noti */
/* Positive single-char repeats */
1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */
1, 1, 1, /* upto, minupto, exact */
1, 1, 1, 1, /* *+, ++, ?+, upto+ */
1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */
1, 1, 1, /* upto I, minupto I, exact I */
1, 1, 1, 1, /* *+I, ++I, ?+I, upto+I */
/* Negative single-char repeats - only for chars < 256 */
1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */
1, 1, 1, /* NOT upto, minupto, exact */
1, 1, 1, 1, /* NOT *+, ++, ?+, upto+ */
1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */
1, 1, 1, /* NOT upto I, minupto I, exact I */
1, 1, 1, 1, /* NOT *+I, ++I, ?+I, upto+I */
/* Positive type repeats */
1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */
1, 1, 1, /* Type upto, minupto, exact */
1, 1, 1, 1, /* Type *+, ++, ?+, upto+ */
/* Character class & ref repeats */
1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */
1, 1, /* CRRANGE, CRMINRANGE */
1, 1, 1, 1, /* Possessive *+, ++, ?+, CRPOSRANGE */
1, /* CLASS */
1, /* NCLASS */
1, /* XCLASS - variable length */
0, /* REF */
0, /* REFI */
0, /* DNREF */
0, /* DNREFI */
0, /* RECURSE */
0, /* CALLOUT */
0, /* Alt */
0, /* Ket */
0, /* KetRmax */
0, /* KetRmin */
0, /* KetRpos */
0, /* Reverse */
0, /* Assert */
0, /* Assert not */
0, /* Assert behind */
0, /* Assert behind not */
0, 0, /* ONCE, ONCE_NC */
0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */
0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */
0, 0, /* CREF, DNCREF */
0, 0, /* RREF, DNRREF */
0, /* DEF */
0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */
0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */
0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */
0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */
0, 0 /* CLOSE, SKIPZERO */
};
/* These 2 tables allow for compact code for testing for \D, \d, \S, \s, \W,
and \w */
static const pcre_uint8 toptable1[] = {
0, 0, 0, 0, 0, 0,
ctype_digit, ctype_digit,
ctype_space, ctype_space,
ctype_word, ctype_word,
0, 0 /* OP_ANY, OP_ALLANY */
};
static const pcre_uint8 toptable2[] = {
0, 0, 0, 0, 0, 0,
ctype_digit, 0,
ctype_space, 0,
ctype_word, 0,
1, 1 /* OP_ANY, OP_ALLANY */
};
/* Structure for holding data about a particular state, which is in effect the
current data for an active path through the match tree. It must consist
entirely of ints because the working vector we are passed, and which we put
these structures in, is a vector of ints. */
typedef struct stateblock {
int offset; /* Offset to opcode */
int count; /* Count for repeats */
int data; /* Some use extra data */
} stateblock;
#define INTS_PER_STATEBLOCK (int)(sizeof(stateblock)/sizeof(int))
#ifdef PCRE_DEBUG
/*************************************************
* Print character string *
*************************************************/
/* Character string printing function for debugging.
Arguments:
p points to string
length number of bytes
f where to print
Returns: nothing
*/
static void
pchars(const pcre_uchar *p, int length, FILE *f)
{
pcre_uint32 c;
while (length-- > 0)
{
if (isprint(c = *(p++)))
fprintf(f, "%c", c);
else
fprintf(f, "\\x{%02x}", c);
}
}
#endif
/*************************************************
* Execute a Regular Expression - DFA engine *
*************************************************/
/* This internal function applies a compiled pattern to a subject string,
starting at a given point, using a DFA engine. This function is called from the
external one, possibly multiple times if the pattern is not anchored. The
function calls itself recursively for some kinds of subpattern.
Arguments:
md the match_data block with fixed information
this_start_code the opening bracket of this subexpression's code
current_subject where we currently are in the subject string
start_offset start offset in the subject string
offsets vector to contain the matching string offsets
offsetcount size of same
workspace vector of workspace
wscount size of same
rlevel function call recursion level
Returns: > 0 => number of match offset pairs placed in offsets
= 0 => offsets overflowed; longest matches are present
-1 => failed to match
< -1 => some kind of unexpected problem
The following macros are used for adding states to the two state vectors (one
for the current character, one for the following character). */
#define ADD_ACTIVE(x,y) \
if (active_count++ < wscount) \
{ \
next_active_state->offset = (x); \
next_active_state->count = (y); \
next_active_state++; \
DPRINTF(("%.*sADD_ACTIVE(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \
} \
else return PCRE_ERROR_DFA_WSSIZE
#define ADD_ACTIVE_DATA(x,y,z) \
if (active_count++ < wscount) \
{ \
next_active_state->offset = (x); \
next_active_state->count = (y); \
next_active_state->data = (z); \
next_active_state++; \
DPRINTF(("%.*sADD_ACTIVE_DATA(%d,%d,%d)\n", rlevel*2-2, SP, (x), (y), (z))); \
} \
else return PCRE_ERROR_DFA_WSSIZE
#define ADD_NEW(x,y) \
if (new_count++ < wscount) \
{ \
next_new_state->offset = (x); \
next_new_state->count = (y); \
next_new_state++; \
DPRINTF(("%.*sADD_NEW(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \
} \
else return PCRE_ERROR_DFA_WSSIZE
#define ADD_NEW_DATA(x,y,z) \
if (new_count++ < wscount) \
{ \
next_new_state->offset = (x); \
next_new_state->count = (y); \
next_new_state->data = (z); \
next_new_state++; \
DPRINTF(("%.*sADD_NEW_DATA(%d,%d,%d) line %d\n", rlevel*2-2, SP, \
(x), (y), (z), __LINE__)); \
} \
else return PCRE_ERROR_DFA_WSSIZE
/* And now, here is the code */
static int
internal_dfa_exec(
dfa_match_data *md,
const pcre_uchar *this_start_code,
const pcre_uchar *current_subject,
int start_offset,
int *offsets,
int offsetcount,
int *workspace,
int wscount,
int rlevel)
{
stateblock *active_states, *new_states, *temp_states;
stateblock *next_active_state, *next_new_state;
const pcre_uint8 *ctypes, *lcc, *fcc;
const pcre_uchar *ptr;
const pcre_uchar *end_code, *first_op;
dfa_recursion_info new_recursive;
int active_count, new_count, match_count;
/* Some fields in the md block are frequently referenced, so we load them into
independent variables in the hope that this will perform better. */
const pcre_uchar *start_subject = md->start_subject;
const pcre_uchar *end_subject = md->end_subject;
const pcre_uchar *start_code = md->start_code;
#ifdef SUPPORT_UTF
BOOL utf = (md->poptions & PCRE_UTF8) != 0;
#else
BOOL utf = FALSE;
#endif
BOOL reset_could_continue = FALSE;
rlevel++;
offsetcount &= (-2);
wscount -= 2;
wscount = (wscount - (wscount % (INTS_PER_STATEBLOCK * 2))) /
(2 * INTS_PER_STATEBLOCK);
DPRINTF(("\n%.*s---------------------\n"
"%.*sCall to internal_dfa_exec f=%d\n",
rlevel*2-2, SP, rlevel*2-2, SP, rlevel));
ctypes = md->tables + ctypes_offset;
lcc = md->tables + lcc_offset;
fcc = md->tables + fcc_offset;
match_count = PCRE_ERROR_NOMATCH; /* A negative number */
active_states = (stateblock *)(workspace + 2);
next_new_state = new_states = active_states + wscount;
new_count = 0;
first_op = this_start_code + 1 + LINK_SIZE +
((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA ||
*this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS)
? IMM2_SIZE:0);
/* The first thing in any (sub) pattern is a bracket of some sort. Push all
the alternative states onto the list, and find out where the end is. This
makes is possible to use this function recursively, when we want to stop at a
matching internal ket rather than at the end.
If the first opcode in the first alternative is OP_REVERSE, we are dealing with
a backward assertion. In that case, we have to find out the maximum amount to
move back, and set up each alternative appropriately. */
if (*first_op == OP_REVERSE)
{
int max_back = 0;
int gone_back;
end_code = this_start_code;
do
{
int back = GET(end_code, 2+LINK_SIZE);
if (back > max_back) max_back = back;
end_code += GET(end_code, 1);
}
while (*end_code == OP_ALT);
/* If we can't go back the amount required for the longest lookbehind
pattern, go back as far as we can; some alternatives may still be viable. */
#ifdef SUPPORT_UTF
/* In character mode we have to step back character by character */
if (utf)
{
for (gone_back = 0; gone_back < max_back; gone_back++)
{
if (current_subject <= start_subject) break;
current_subject--;
ACROSSCHAR(current_subject > start_subject, *current_subject, current_subject--);
}
}
else
#endif
/* In byte-mode we can do this quickly. */
{
gone_back = (current_subject - max_back < start_subject)?
(int)(current_subject - start_subject) : max_back;
current_subject -= gone_back;
}
/* Save the earliest consulted character */
if (current_subject < md->start_used_ptr)
md->start_used_ptr = current_subject;
/* Now we can process the individual branches. */
end_code = this_start_code;
do
{
int back = GET(end_code, 2+LINK_SIZE);
if (back <= gone_back)
{
int bstate = (int)(end_code - start_code + 2 + 2*LINK_SIZE);
ADD_NEW_DATA(-bstate, 0, gone_back - back);
}
end_code += GET(end_code, 1);
}
while (*end_code == OP_ALT);
}
/* This is the code for a "normal" subpattern (not a backward assertion). The
start of a whole pattern is always one of these. If we are at the top level,
we may be asked to restart matching from the same point that we reached for a
previous partial match. We still have to scan through the top-level branches to
find the end state. */
else
{
end_code = this_start_code;
/* Restarting */
if (rlevel == 1 && (md->moptions & PCRE_DFA_RESTART) != 0)
{
do { end_code += GET(end_code, 1); } while (*end_code == OP_ALT);
new_count = workspace[1];
if (!workspace[0])
memcpy(new_states, active_states, new_count * sizeof(stateblock));
}
/* Not restarting */
else
{
int length = 1 + LINK_SIZE +
((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA ||
*this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS)
? IMM2_SIZE:0);
do
{
ADD_NEW((int)(end_code - start_code + length), 0);
end_code += GET(end_code, 1);
length = 1 + LINK_SIZE;
}
while (*end_code == OP_ALT);
}
}
workspace[0] = 0; /* Bit indicating which vector is current */
DPRINTF(("%.*sEnd state = %d\n", rlevel*2-2, SP, (int)(end_code - start_code)));
/* Loop for scanning the subject */
ptr = current_subject;
for (;;)
{
int i, j;
int clen, dlen;
pcre_uint32 c, d;
int forced_fail = 0;
BOOL partial_newline = FALSE;
BOOL could_continue = reset_could_continue;
reset_could_continue = FALSE;
/* Make the new state list into the active state list and empty the
new state list. */
temp_states = active_states;
active_states = new_states;
new_states = temp_states;
active_count = new_count;
new_count = 0;
workspace[0] ^= 1; /* Remember for the restarting feature */
workspace[1] = active_count;
#ifdef PCRE_DEBUG
printf("%.*sNext character: rest of subject = \"", rlevel*2-2, SP);
pchars(ptr, STRLEN_UC(ptr), stdout);
printf("\"\n");
printf("%.*sActive states: ", rlevel*2-2, SP);
for (i = 0; i < active_count; i++)
printf("%d/%d ", active_states[i].offset, active_states[i].count);
printf("\n");
#endif
/* Set the pointers for adding new states */
next_active_state = active_states + active_count;
next_new_state = new_states;
/* Load the current character from the subject outside the loop, as many
different states may want to look at it, and we assume that at least one
will. */
if (ptr < end_subject)
{
clen = 1; /* Number of data items in the character */
#ifdef SUPPORT_UTF
GETCHARLENTEST(c, ptr, clen);
#else
c = *ptr;
#endif /* SUPPORT_UTF */
}
else
{
clen = 0; /* This indicates the end of the subject */
c = NOTACHAR; /* This value should never actually be used */
}
/* Scan up the active states and act on each one. The result of an action
may be to add more states to the currently active list (e.g. on hitting a
parenthesis) or it may be to put states on the new list, for considering
when we move the character pointer on. */
for (i = 0; i < active_count; i++)
{
stateblock *current_state = active_states + i;
BOOL caseless = FALSE;
const pcre_uchar *code;
int state_offset = current_state->offset;
int codevalue, rrc;
int count;
#ifdef PCRE_DEBUG
printf ("%.*sProcessing state %d c=", rlevel*2-2, SP, state_offset);
if (clen == 0) printf("EOL\n");
else if (c > 32 && c < 127) printf("'%c'\n", c);
else printf("0x%02x\n", c);
#endif
/* A negative offset is a special case meaning "hold off going to this
(negated) state until the number of characters in the data field have
been skipped". If the could_continue flag was passed over from a previous
state, arrange for it to passed on. */
if (state_offset < 0)
{
if (current_state->data > 0)
{
DPRINTF(("%.*sSkipping this character\n", rlevel*2-2, SP));
ADD_NEW_DATA(state_offset, current_state->count,
current_state->data - 1);
if (could_continue) reset_could_continue = TRUE;
continue;
}
else
{
current_state->offset = state_offset = -state_offset;
}
}
/* Check for a duplicate state with the same count, and skip if found.
See the note at the head of this module about the possibility of improving
performance here. */
for (j = 0; j < i; j++)
{
if (active_states[j].offset == state_offset &&
active_states[j].count == current_state->count)
{
DPRINTF(("%.*sDuplicate state: skipped\n", rlevel*2-2, SP));
goto NEXT_ACTIVE_STATE;
}
}
/* The state offset is the offset to the opcode */
code = start_code + state_offset;
codevalue = *code;
/* If this opcode inspects a character, but we are at the end of the
subject, remember the fact for use when testing for a partial match. */
if (clen == 0 && poptable[codevalue] != 0)
could_continue = TRUE;
/* If this opcode is followed by an inline character, load it. It is
tempting to test for the presence of a subject character here, but that
is wrong, because sometimes zero repetitions of the subject are
permitted.
We also use this mechanism for opcodes such as OP_TYPEPLUS that take an
argument that is not a data character - but is always one byte long because
the values are small. We have to take special action to deal with \P, \p,
\H, \h, \V, \v and \X in this case. To keep the other cases fast, convert
these ones to new opcodes. */
if (coptable[codevalue] > 0)
{
dlen = 1;
#ifdef SUPPORT_UTF
if (utf) { GETCHARLEN(d, (code + coptable[codevalue]), dlen); } else
#endif /* SUPPORT_UTF */
d = code[coptable[codevalue]];
if (codevalue >= OP_TYPESTAR)
{
switch(d)
{
case OP_ANYBYTE: return PCRE_ERROR_DFA_UITEM;
case OP_NOTPROP:
case OP_PROP: codevalue += OP_PROP_EXTRA; break;
case OP_ANYNL: codevalue += OP_ANYNL_EXTRA; break;
case OP_EXTUNI: codevalue += OP_EXTUNI_EXTRA; break;
case OP_NOT_HSPACE:
case OP_HSPACE: codevalue += OP_HSPACE_EXTRA; break;
case OP_NOT_VSPACE:
case OP_VSPACE: codevalue += OP_VSPACE_EXTRA; break;
default: break;
}
}
}
else
{
dlen = 0; /* Not strictly necessary, but compilers moan */
d = NOTACHAR; /* if these variables are not set. */
}
/* Now process the individual opcodes */
switch (codevalue)
{
/* ========================================================================== */
/* These cases are never obeyed. This is a fudge that causes a compile-
time error if the vectors coptable or poptable, which are indexed by
opcode, are not the correct length. It seems to be the only way to do
such a check at compile time, as the sizeof() operator does not work
in the C preprocessor. */
case OP_TABLE_LENGTH:
case OP_TABLE_LENGTH +
((sizeof(coptable) == OP_TABLE_LENGTH) &&
(sizeof(poptable) == OP_TABLE_LENGTH)):
break;
/* ========================================================================== */
/* Reached a closing bracket. If not at the end of the pattern, carry
on with the next opcode. For repeating opcodes, also add the repeat
state. Note that KETRPOS will always be encountered at the end of the
subpattern, because the possessive subpattern repeats are always handled
using recursive calls. Thus, it never adds any new states.
At the end of the (sub)pattern, unless we have an empty string and
PCRE_NOTEMPTY is set, or PCRE_NOTEMPTY_ATSTART is set and we are at the
start of the subject, save the match data, shifting up all previous
matches so we always have the longest first. */
case OP_KET:
case OP_KETRMIN:
case OP_KETRMAX:
case OP_KETRPOS:
if (code != end_code)
{
ADD_ACTIVE(state_offset + 1 + LINK_SIZE, 0);
if (codevalue != OP_KET)
{
ADD_ACTIVE(state_offset - GET(code, 1), 0);
}
}
else
{
if (ptr > current_subject ||
((md->moptions & PCRE_NOTEMPTY) == 0 &&
((md->moptions & PCRE_NOTEMPTY_ATSTART) == 0 ||
current_subject > start_subject + md->start_offset)))
{
if (match_count < 0) match_count = (offsetcount >= 2)? 1 : 0;
else if (match_count > 0 && ++match_count * 2 > offsetcount)
match_count = 0;
count = ((match_count == 0)? offsetcount : match_count * 2) - 2;
if (count > 0) memmove(offsets + 2, offsets, count * sizeof(int));
if (offsetcount >= 2)
{
offsets[0] = (int)(current_subject - start_subject);
offsets[1] = (int)(ptr - start_subject);
DPRINTF(("%.*sSet matched string = \"%.*s\"\n", rlevel*2-2, SP,
offsets[1] - offsets[0], (char *)current_subject));
}
if ((md->moptions & PCRE_DFA_SHORTEST) != 0)
{
DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n"
"%.*s---------------------\n\n", rlevel*2-2, SP, rlevel,
match_count, rlevel*2-2, SP));
return match_count;
}
}
}
break;
/* ========================================================================== */
/* These opcodes add to the current list of states without looking
at the current character. */
/*-----------------------------------------------------------------*/
case OP_ALT:
do { code += GET(code, 1); } while (*code == OP_ALT);
ADD_ACTIVE((int)(code - start_code), 0);
break;
/*-----------------------------------------------------------------*/
case OP_BRA:
case OP_SBRA:
do
{
ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0);
code += GET(code, 1);
}
while (*code == OP_ALT);
break;
/*-----------------------------------------------------------------*/
case OP_CBRA:
case OP_SCBRA:
ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE + IMM2_SIZE), 0);
code += GET(code, 1);
while (*code == OP_ALT)
{
ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0);
code += GET(code, 1);
}
break;
/*-----------------------------------------------------------------*/
case OP_BRAZERO:
case OP_BRAMINZERO:
ADD_ACTIVE(state_offset + 1, 0);
code += 1 + GET(code, 2);
while (*code == OP_ALT) code += GET(code, 1);
ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0);
break;
/*-----------------------------------------------------------------*/
case OP_SKIPZERO:
code += 1 + GET(code, 2);
while (*code == OP_ALT) code += GET(code, 1);
ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0);
break;
/*-----------------------------------------------------------------*/
case OP_CIRC:
if (ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0)
{ ADD_ACTIVE(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_CIRCM:
if ((ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0) ||
(ptr != end_subject && WAS_NEWLINE(ptr)))
{ ADD_ACTIVE(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_EOD:
if (ptr >= end_subject)
{
if ((md->moptions & PCRE_PARTIAL_HARD) != 0)
could_continue = TRUE;
else { ADD_ACTIVE(state_offset + 1, 0); }
}
break;
/*-----------------------------------------------------------------*/
case OP_SOD:
if (ptr == start_subject) { ADD_ACTIVE(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_SOM:
if (ptr == start_subject + start_offset) { ADD_ACTIVE(state_offset + 1, 0); }
break;
/* ========================================================================== */
/* These opcodes inspect the next subject character, and sometimes
the previous one as well, but do not have an argument. The variable
clen contains the length of the current character and is zero if we are
at the end of the subject. */
/*-----------------------------------------------------------------*/
case OP_ANY:
if (clen > 0 && !IS_NEWLINE(ptr))
{
if (ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else
{
ADD_NEW(state_offset + 1, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_ALLANY:
if (clen > 0)
{ ADD_NEW(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_EODN:
if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0)
could_continue = TRUE;
else if (clen == 0 || (IS_NEWLINE(ptr) && ptr == end_subject - md->nllen))
{ ADD_ACTIVE(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_DOLL:
if ((md->moptions & PCRE_NOTEOL) == 0)
{
if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0)
could_continue = TRUE;
else if (clen == 0 ||
((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr) &&
(ptr == end_subject - md->nllen)
))
{ ADD_ACTIVE(state_offset + 1, 0); }
else if (ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
if ((md->moptions & PCRE_PARTIAL_HARD) != 0)
{
reset_could_continue = TRUE;
ADD_NEW_DATA(-(state_offset + 1), 0, 1);
}
else could_continue = partial_newline = TRUE;
}
}
break;
/*-----------------------------------------------------------------*/
case OP_DOLLM:
if ((md->moptions & PCRE_NOTEOL) == 0)
{
if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0)
could_continue = TRUE;
else if (clen == 0 ||
((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr)))
{ ADD_ACTIVE(state_offset + 1, 0); }
else if (ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
if ((md->moptions & PCRE_PARTIAL_HARD) != 0)
{
reset_could_continue = TRUE;
ADD_NEW_DATA(-(state_offset + 1), 0, 1);
}
else could_continue = partial_newline = TRUE;
}
}
else if (IS_NEWLINE(ptr))
{ ADD_ACTIVE(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_DIGIT:
case OP_WHITESPACE:
case OP_WORDCHAR:
if (clen > 0 && c < 256 &&
((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0)
{ ADD_NEW(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_NOT_DIGIT:
case OP_NOT_WHITESPACE:
case OP_NOT_WORDCHAR:
if (clen > 0 && (c >= 256 ||
((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0))
{ ADD_NEW(state_offset + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_WORD_BOUNDARY:
case OP_NOT_WORD_BOUNDARY:
{
int left_word, right_word;
if (ptr > start_subject)
{
const pcre_uchar *temp = ptr - 1;
if (temp < md->start_used_ptr) md->start_used_ptr = temp;
#if defined SUPPORT_UTF && !defined COMPILE_PCRE32
if (utf) { BACKCHAR(temp); }
#endif
GETCHARTEST(d, temp);
#ifdef SUPPORT_UCP
if ((md->poptions & PCRE_UCP) != 0)
{
if (d == '_') left_word = TRUE; else
{
int cat = UCD_CATEGORY(d);
left_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
left_word = d < 256 && (ctypes[d] & ctype_word) != 0;
}
else left_word = FALSE;
if (clen > 0)
{
#ifdef SUPPORT_UCP
if ((md->poptions & PCRE_UCP) != 0)
{
if (c == '_') right_word = TRUE; else
{
int cat = UCD_CATEGORY(c);
right_word = (cat == ucp_L || cat == ucp_N);
}
}
else
#endif
right_word = c < 256 && (ctypes[c] & ctype_word) != 0;
}
else right_word = FALSE;
if ((left_word == right_word) == (codevalue == OP_NOT_WORD_BOUNDARY))
{ ADD_ACTIVE(state_offset + 1, 0); }
}
break;
/*-----------------------------------------------------------------*/
/* Check the next character by Unicode property. We will get here only
if the support is in the binary; otherwise a compile-time error occurs.
*/
#ifdef SUPPORT_UCP
case OP_PROP:
case OP_NOTPROP:
if (clen > 0)
{
BOOL OK;
const pcre_uint32 *cp;
const ucd_record * prop = GET_UCD(c);
switch(code[1])
{
case PT_ANY:
OK = TRUE;
break;
case PT_LAMP:
OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt;
break;
case PT_GC:
OK = PRIV(ucp_gentype)[prop->chartype] == code[2];
break;
case PT_PC:
OK = prop->chartype == code[2];
break;
case PT_SC:
OK = prop->script == code[2];
break;
/* These are specials for combination cases. */
case PT_ALNUM:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N;
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z;
break;
}
break;
case PT_WORD:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
c == CHAR_UNDERSCORE;
break;
case PT_CLIST:
cp = PRIV(ucd_caseless_sets) + code[2];
for (;;)
{
if (c < *cp) { OK = FALSE; break; }
if (c == *cp++) { OK = TRUE; break; }
}
break;
case PT_UCNC:
OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000;
break;
/* Should never occur, but keep compilers from grumbling. */
default:
OK = codevalue != OP_PROP;
break;
}
if (OK == (codevalue == OP_PROP)) { ADD_NEW(state_offset + 3, 0); }
}
break;
#endif
/* ========================================================================== */
/* These opcodes likewise inspect the subject character, but have an
argument that is not a data character. It is one of these opcodes:
OP_ANY, OP_ALLANY, OP_DIGIT, OP_NOT_DIGIT, OP_WHITESPACE, OP_NOT_SPACE,
OP_WORDCHAR, OP_NOT_WORDCHAR. The value is loaded into d. */
case OP_TYPEPLUS:
case OP_TYPEMINPLUS:
case OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); }
if (clen > 0)
{
if (d == OP_ANY && ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) ||
(c < 256 &&
(d != OP_ANY || !IS_NEWLINE(ptr)) &&
((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0))
{
if (count > 0 && codevalue == OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW(state_offset, count);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_TYPEQUERY:
case OP_TYPEMINQUERY:
case OP_TYPEPOSQUERY:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
if (d == OP_ANY && ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) ||
(c < 256 &&
(d != OP_ANY || !IS_NEWLINE(ptr)) &&
((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0))
{
if (codevalue == OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset + 2, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_TYPESTAR:
case OP_TYPEMINSTAR:
case OP_TYPEPOSSTAR:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
if (d == OP_ANY && ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) ||
(c < 256 &&
(d != OP_ANY || !IS_NEWLINE(ptr)) &&
((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0))
{
if (codevalue == OP_TYPEPOSSTAR)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_TYPEEXACT:
count = current_state->count; /* Number already matched */
if (clen > 0)
{
if (d == OP_ANY && ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) ||
(c < 256 &&
(d != OP_ANY || !IS_NEWLINE(ptr)) &&
((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0))
{
if (++count >= (int)GET2(code, 1))
{ ADD_NEW(state_offset + 1 + IMM2_SIZE + 1, 0); }
else
{ ADD_NEW(state_offset, count); }
}
}
break;
/*-----------------------------------------------------------------*/
case OP_TYPEUPTO:
case OP_TYPEMINUPTO:
case OP_TYPEPOSUPTO:
ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0);
count = current_state->count; /* Number already matched */
if (clen > 0)
{
if (d == OP_ANY && ptr + 1 >= md->end_subject &&
(md->moptions & (PCRE_PARTIAL_HARD)) != 0 &&
NLBLOCK->nltype == NLTYPE_FIXED &&
NLBLOCK->nllen == 2 &&
c == NLBLOCK->nl[0])
{
could_continue = partial_newline = TRUE;
}
else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) ||
(c < 256 &&
(d != OP_ANY || !IS_NEWLINE(ptr)) &&
((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0))
{
if (codevalue == OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW(state_offset + 2 + IMM2_SIZE, 0); }
else
{ ADD_NEW(state_offset, count); }
}
}
break;
/* ========================================================================== */
/* These are virtual opcodes that are used when something like
OP_TYPEPLUS has OP_PROP, OP_NOTPROP, OP_ANYNL, or OP_EXTUNI as its
argument. It keeps the code above fast for the other cases. The argument
is in the d variable. */
#ifdef SUPPORT_UCP
case OP_PROP_EXTRA + OP_TYPEPLUS:
case OP_PROP_EXTRA + OP_TYPEMINPLUS:
case OP_PROP_EXTRA + OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 4, 0); }
if (clen > 0)
{
BOOL OK;
const pcre_uint32 *cp;
const ucd_record * prop = GET_UCD(c);
switch(code[2])
{
case PT_ANY:
OK = TRUE;
break;
case PT_LAMP:
OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt;
break;
case PT_GC:
OK = PRIV(ucp_gentype)[prop->chartype] == code[3];
break;
case PT_PC:
OK = prop->chartype == code[3];
break;
case PT_SC:
OK = prop->script == code[3];
break;
/* These are specials for combination cases. */
case PT_ALNUM:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N;
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z;
break;
}
break;
case PT_WORD:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
c == CHAR_UNDERSCORE;
break;
case PT_CLIST:
cp = PRIV(ucd_caseless_sets) + code[3];
for (;;)
{
if (c < *cp) { OK = FALSE; break; }
if (c == *cp++) { OK = TRUE; break; }
}
break;
case PT_UCNC:
OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000;
break;
/* Should never occur, but keep compilers from grumbling. */
default:
OK = codevalue != OP_PROP;
break;
}
if (OK == (d == OP_PROP))
{
if (count > 0 && codevalue == OP_PROP_EXTRA + OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW(state_offset, count);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_EXTUNI_EXTRA + OP_TYPEPLUS:
case OP_EXTUNI_EXTRA + OP_TYPEMINPLUS:
case OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); }
if (clen > 0)
{
int lgb, rgb;
const pcre_uchar *nptr = ptr + clen;
int ncount = 0;
if (count > 0 && codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
lgb = UCD_GRAPHBREAK(c);
while (nptr < end_subject)
{
dlen = 1;
if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); }
rgb = UCD_GRAPHBREAK(d);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
ncount++;
lgb = rgb;
nptr += dlen;
}
count++;
ADD_NEW_DATA(-state_offset, count, ncount);
}
break;
#endif
/*-----------------------------------------------------------------*/
case OP_ANYNL_EXTRA + OP_TYPEPLUS:
case OP_ANYNL_EXTRA + OP_TYPEMINPLUS:
case OP_ANYNL_EXTRA + OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); }
if (clen > 0)
{
int ncount = 0;
switch (c)
{
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break;
goto ANYNL01;
case CHAR_CR:
if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1;
/* Fall through */
ANYNL01:
case CHAR_LF:
if (count > 0 && codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW_DATA(-state_offset, count, ncount);
break;
default:
break;
}
}
break;
/*-----------------------------------------------------------------*/
case OP_VSPACE_EXTRA + OP_TYPEPLUS:
case OP_VSPACE_EXTRA + OP_TYPEMINPLUS:
case OP_VSPACE_EXTRA + OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); }
if (clen > 0)
{
BOOL OK;
switch (c)
{
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
break;
}
if (OK == (d == OP_VSPACE))
{
if (count > 0 && codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW_DATA(-state_offset, count, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_HSPACE_EXTRA + OP_TYPEPLUS:
case OP_HSPACE_EXTRA + OP_TYPEMINPLUS:
case OP_HSPACE_EXTRA + OP_TYPEPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); }
if (clen > 0)
{
BOOL OK;
switch (c)
{
HSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
break;
}
if (OK == (d == OP_HSPACE))
{
if (count > 0 && codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW_DATA(-state_offset, count, 0);
}
}
break;
/*-----------------------------------------------------------------*/
#ifdef SUPPORT_UCP
case OP_PROP_EXTRA + OP_TYPEQUERY:
case OP_PROP_EXTRA + OP_TYPEMINQUERY:
case OP_PROP_EXTRA + OP_TYPEPOSQUERY:
count = 4;
goto QS1;
case OP_PROP_EXTRA + OP_TYPESTAR:
case OP_PROP_EXTRA + OP_TYPEMINSTAR:
case OP_PROP_EXTRA + OP_TYPEPOSSTAR:
count = 0;
QS1:
ADD_ACTIVE(state_offset + 4, 0);
if (clen > 0)
{
BOOL OK;
const pcre_uint32 *cp;
const ucd_record * prop = GET_UCD(c);
switch(code[2])
{
case PT_ANY:
OK = TRUE;
break;
case PT_LAMP:
OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt;
break;
case PT_GC:
OK = PRIV(ucp_gentype)[prop->chartype] == code[3];
break;
case PT_PC:
OK = prop->chartype == code[3];
break;
case PT_SC:
OK = prop->script == code[3];
break;
/* These are specials for combination cases. */
case PT_ALNUM:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N;
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z;
break;
}
break;
case PT_WORD:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
c == CHAR_UNDERSCORE;
break;
case PT_CLIST:
cp = PRIV(ucd_caseless_sets) + code[3];
for (;;)
{
if (c < *cp) { OK = FALSE; break; }
if (c == *cp++) { OK = TRUE; break; }
}
break;
case PT_UCNC:
OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000;
break;
/* Should never occur, but keep compilers from grumbling. */
default:
OK = codevalue != OP_PROP;
break;
}
if (OK == (d == OP_PROP))
{
if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSSTAR ||
codevalue == OP_PROP_EXTRA + OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset + count, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_EXTUNI_EXTRA + OP_TYPEQUERY:
case OP_EXTUNI_EXTRA + OP_TYPEMINQUERY:
case OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY:
count = 2;
goto QS2;
case OP_EXTUNI_EXTRA + OP_TYPESTAR:
case OP_EXTUNI_EXTRA + OP_TYPEMINSTAR:
case OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR:
count = 0;
QS2:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
int lgb, rgb;
const pcre_uchar *nptr = ptr + clen;
int ncount = 0;
if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR ||
codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
lgb = UCD_GRAPHBREAK(c);
while (nptr < end_subject)
{
dlen = 1;
if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); }
rgb = UCD_GRAPHBREAK(d);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
ncount++;
lgb = rgb;
nptr += dlen;
}
ADD_NEW_DATA(-(state_offset + count), 0, ncount);
}
break;
#endif
/*-----------------------------------------------------------------*/
case OP_ANYNL_EXTRA + OP_TYPEQUERY:
case OP_ANYNL_EXTRA + OP_TYPEMINQUERY:
case OP_ANYNL_EXTRA + OP_TYPEPOSQUERY:
count = 2;
goto QS3;
case OP_ANYNL_EXTRA + OP_TYPESTAR:
case OP_ANYNL_EXTRA + OP_TYPEMINSTAR:
case OP_ANYNL_EXTRA + OP_TYPEPOSSTAR:
count = 0;
QS3:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
int ncount = 0;
switch (c)
{
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break;
goto ANYNL02;
case CHAR_CR:
if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1;
/* Fall through */
ANYNL02:
case CHAR_LF:
if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSSTAR ||
codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW_DATA(-(state_offset + (int)count), 0, ncount);
break;
default:
break;
}
}
break;
/*-----------------------------------------------------------------*/
case OP_VSPACE_EXTRA + OP_TYPEQUERY:
case OP_VSPACE_EXTRA + OP_TYPEMINQUERY:
case OP_VSPACE_EXTRA + OP_TYPEPOSQUERY:
count = 2;
goto QS4;
case OP_VSPACE_EXTRA + OP_TYPESTAR:
case OP_VSPACE_EXTRA + OP_TYPEMINSTAR:
case OP_VSPACE_EXTRA + OP_TYPEPOSSTAR:
count = 0;
QS4:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
BOOL OK;
switch (c)
{
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
break;
}
if (OK == (d == OP_VSPACE))
{
if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSSTAR ||
codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW_DATA(-(state_offset + (int)count), 0, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_HSPACE_EXTRA + OP_TYPEQUERY:
case OP_HSPACE_EXTRA + OP_TYPEMINQUERY:
case OP_HSPACE_EXTRA + OP_TYPEPOSQUERY:
count = 2;
goto QS5;
case OP_HSPACE_EXTRA + OP_TYPESTAR:
case OP_HSPACE_EXTRA + OP_TYPEMINSTAR:
case OP_HSPACE_EXTRA + OP_TYPEPOSSTAR:
count = 0;
QS5:
ADD_ACTIVE(state_offset + 2, 0);
if (clen > 0)
{
BOOL OK;
switch (c)
{
HSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
break;
}
if (OK == (d == OP_HSPACE))
{
if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSSTAR ||
codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW_DATA(-(state_offset + (int)count), 0, 0);
}
}
break;
/*-----------------------------------------------------------------*/
#ifdef SUPPORT_UCP
case OP_PROP_EXTRA + OP_TYPEEXACT:
case OP_PROP_EXTRA + OP_TYPEUPTO:
case OP_PROP_EXTRA + OP_TYPEMINUPTO:
case OP_PROP_EXTRA + OP_TYPEPOSUPTO:
if (codevalue != OP_PROP_EXTRA + OP_TYPEEXACT)
{ ADD_ACTIVE(state_offset + 1 + IMM2_SIZE + 3, 0); }
count = current_state->count; /* Number already matched */
if (clen > 0)
{
BOOL OK;
const pcre_uint32 *cp;
const ucd_record * prop = GET_UCD(c);
switch(code[1 + IMM2_SIZE + 1])
{
case PT_ANY:
OK = TRUE;
break;
case PT_LAMP:
OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll ||
prop->chartype == ucp_Lt;
break;
case PT_GC:
OK = PRIV(ucp_gentype)[prop->chartype] == code[1 + IMM2_SIZE + 2];
break;
case PT_PC:
OK = prop->chartype == code[1 + IMM2_SIZE + 2];
break;
case PT_SC:
OK = prop->script == code[1 + IMM2_SIZE + 2];
break;
/* These are specials for combination cases. */
case PT_ALNUM:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N;
break;
/* Perl space used to exclude VT, but from Perl 5.18 it is included,
which means that Perl space and POSIX space are now identical. PCRE
was changed at release 8.34. */
case PT_SPACE: /* Perl space */
case PT_PXSPACE: /* POSIX space */
switch(c)
{
HSPACE_CASES:
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z;
break;
}
break;
case PT_WORD:
OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L ||
PRIV(ucp_gentype)[prop->chartype] == ucp_N ||
c == CHAR_UNDERSCORE;
break;
case PT_CLIST:
cp = PRIV(ucd_caseless_sets) + code[1 + IMM2_SIZE + 2];
for (;;)
{
if (c < *cp) { OK = FALSE; break; }
if (c == *cp++) { OK = TRUE; break; }
}
break;
case PT_UCNC:
OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT ||
c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) ||
c >= 0xe000;
break;
/* Should never occur, but keep compilers from grumbling. */
default:
OK = codevalue != OP_PROP;
break;
}
if (OK == (d == OP_PROP))
{
if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW(state_offset + 1 + IMM2_SIZE + 3, 0); }
else
{ ADD_NEW(state_offset, count); }
}
}
break;
/*-----------------------------------------------------------------*/
case OP_EXTUNI_EXTRA + OP_TYPEEXACT:
case OP_EXTUNI_EXTRA + OP_TYPEUPTO:
case OP_EXTUNI_EXTRA + OP_TYPEMINUPTO:
case OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO:
if (codevalue != OP_EXTUNI_EXTRA + OP_TYPEEXACT)
{ ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); }
count = current_state->count; /* Number already matched */
if (clen > 0)
{
int lgb, rgb;
const pcre_uchar *nptr = ptr + clen;
int ncount = 0;
if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
lgb = UCD_GRAPHBREAK(c);
while (nptr < end_subject)
{
dlen = 1;
if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); }
rgb = UCD_GRAPHBREAK(d);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
ncount++;
lgb = rgb;
nptr += dlen;
}
if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0)
reset_could_continue = TRUE;
if (++count >= (int)GET2(code, 1))
{ ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); }
else
{ ADD_NEW_DATA(-state_offset, count, ncount); }
}
break;
#endif
/*-----------------------------------------------------------------*/
case OP_ANYNL_EXTRA + OP_TYPEEXACT:
case OP_ANYNL_EXTRA + OP_TYPEUPTO:
case OP_ANYNL_EXTRA + OP_TYPEMINUPTO:
case OP_ANYNL_EXTRA + OP_TYPEPOSUPTO:
if (codevalue != OP_ANYNL_EXTRA + OP_TYPEEXACT)
{ ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); }
count = current_state->count; /* Number already matched */
if (clen > 0)
{
int ncount = 0;
switch (c)
{
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break;
goto ANYNL03;
case CHAR_CR:
if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1;
/* Fall through */
ANYNL03:
case CHAR_LF:
if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); }
else
{ ADD_NEW_DATA(-state_offset, count, ncount); }
break;
default:
break;
}
}
break;
/*-----------------------------------------------------------------*/
case OP_VSPACE_EXTRA + OP_TYPEEXACT:
case OP_VSPACE_EXTRA + OP_TYPEUPTO:
case OP_VSPACE_EXTRA + OP_TYPEMINUPTO:
case OP_VSPACE_EXTRA + OP_TYPEPOSUPTO:
if (codevalue != OP_VSPACE_EXTRA + OP_TYPEEXACT)
{ ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); }
count = current_state->count; /* Number already matched */
if (clen > 0)
{
BOOL OK;
switch (c)
{
VSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
}
if (OK == (d == OP_VSPACE))
{
if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); }
else
{ ADD_NEW_DATA(-state_offset, count, 0); }
}
}
break;
/*-----------------------------------------------------------------*/
case OP_HSPACE_EXTRA + OP_TYPEEXACT:
case OP_HSPACE_EXTRA + OP_TYPEUPTO:
case OP_HSPACE_EXTRA + OP_TYPEMINUPTO:
case OP_HSPACE_EXTRA + OP_TYPEPOSUPTO:
if (codevalue != OP_HSPACE_EXTRA + OP_TYPEEXACT)
{ ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); }
count = current_state->count; /* Number already matched */
if (clen > 0)
{
BOOL OK;
switch (c)
{
HSPACE_CASES:
OK = TRUE;
break;
default:
OK = FALSE;
break;
}
if (OK == (d == OP_HSPACE))
{
if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); }
else
{ ADD_NEW_DATA(-state_offset, count, 0); }
}
}
break;
/* ========================================================================== */
/* These opcodes are followed by a character that is usually compared
to the current subject character; it is loaded into d. We still get
here even if there is no subject character, because in some cases zero
repetitions are permitted. */
/*-----------------------------------------------------------------*/
case OP_CHAR:
if (clen > 0 && c == d) { ADD_NEW(state_offset + dlen + 1, 0); }
break;
/*-----------------------------------------------------------------*/
case OP_CHARI:
if (clen == 0) break;
#ifdef SUPPORT_UTF
if (utf)
{
if (c == d) { ADD_NEW(state_offset + dlen + 1, 0); } else
{
unsigned int othercase;
if (c < 128)
othercase = fcc[c];
else
/* If we have Unicode property support, we can use it to test the
other case of the character. */
#ifdef SUPPORT_UCP
othercase = UCD_OTHERCASE(c);
#else
othercase = NOTACHAR;
#endif
if (d == othercase) { ADD_NEW(state_offset + dlen + 1, 0); }
}
}
else
#endif /* SUPPORT_UTF */
/* Not UTF mode */
{
if (TABLE_GET(c, lcc, c) == TABLE_GET(d, lcc, d))
{ ADD_NEW(state_offset + 2, 0); }
}
break;
#ifdef SUPPORT_UCP
/*-----------------------------------------------------------------*/
/* This is a tricky one because it can match more than one character.
Find out how many characters to skip, and then set up a negative state
to wait for them to pass before continuing. */
case OP_EXTUNI:
if (clen > 0)
{
int lgb, rgb;
const pcre_uchar *nptr = ptr + clen;
int ncount = 0;
lgb = UCD_GRAPHBREAK(c);
while (nptr < end_subject)
{
dlen = 1;
if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); }
rgb = UCD_GRAPHBREAK(d);
if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break;
ncount++;
lgb = rgb;
nptr += dlen;
}
if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0)
reset_could_continue = TRUE;
ADD_NEW_DATA(-(state_offset + 1), 0, ncount);
}
break;
#endif
/*-----------------------------------------------------------------*/
/* This is a tricky like EXTUNI because it too can match more than one
character (when CR is followed by LF). In this case, set up a negative
state to wait for one character to pass before continuing. */
case OP_ANYNL:
if (clen > 0) switch(c)
{
case CHAR_VT:
case CHAR_FF:
case CHAR_NEL:
#ifndef EBCDIC
case 0x2028:
case 0x2029:
#endif /* Not EBCDIC */
if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break;
case CHAR_LF:
ADD_NEW(state_offset + 1, 0);
break;
case CHAR_CR:
if (ptr + 1 >= end_subject)
{
ADD_NEW(state_offset + 1, 0);
if ((md->moptions & PCRE_PARTIAL_HARD) != 0)
reset_could_continue = TRUE;
}
else if (UCHAR21TEST(ptr + 1) == CHAR_LF)
{
ADD_NEW_DATA(-(state_offset + 1), 0, 1);
}
else
{
ADD_NEW(state_offset + 1, 0);
}
break;
}
break;
/*-----------------------------------------------------------------*/
case OP_NOT_VSPACE:
if (clen > 0) switch(c)
{
VSPACE_CASES:
break;
default:
ADD_NEW(state_offset + 1, 0);
break;
}
break;
/*-----------------------------------------------------------------*/
case OP_VSPACE:
if (clen > 0) switch(c)
{
VSPACE_CASES:
ADD_NEW(state_offset + 1, 0);
break;
default:
break;
}
break;
/*-----------------------------------------------------------------*/
case OP_NOT_HSPACE:
if (clen > 0) switch(c)
{
HSPACE_CASES:
break;
default:
ADD_NEW(state_offset + 1, 0);
break;
}
break;
/*-----------------------------------------------------------------*/
case OP_HSPACE:
if (clen > 0) switch(c)
{
HSPACE_CASES:
ADD_NEW(state_offset + 1, 0);
break;
default:
break;
}
break;
/*-----------------------------------------------------------------*/
/* Match a negated single character casefully. */
case OP_NOT:
if (clen > 0 && c != d) { ADD_NEW(state_offset + dlen + 1, 0); }
break;
/*-----------------------------------------------------------------*/
/* Match a negated single character caselessly. */
case OP_NOTI:
if (clen > 0)
{
pcre_uint32 otherd;
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#else
otherd = d;
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
if (c != d && c != otherd)
{ ADD_NEW(state_offset + dlen + 1, 0); }
}
break;
/*-----------------------------------------------------------------*/
case OP_PLUSI:
case OP_MINPLUSI:
case OP_POSPLUSI:
case OP_NOTPLUSI:
case OP_NOTMINPLUSI:
case OP_NOTPOSPLUSI:
caseless = TRUE;
codevalue -= OP_STARI - OP_STAR;
/* Fall through */
case OP_PLUS:
case OP_MINPLUS:
case OP_POSPLUS:
case OP_NOTPLUS:
case OP_NOTMINPLUS:
case OP_NOTPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(state_offset + dlen + 1, 0); }
if (clen > 0)
{
pcre_uint32 otherd = NOTACHAR;
if (caseless)
{
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
}
if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR))
{
if (count > 0 &&
(codevalue == OP_POSPLUS || codevalue == OP_NOTPOSPLUS))
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW(state_offset, count);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_QUERYI:
case OP_MINQUERYI:
case OP_POSQUERYI:
case OP_NOTQUERYI:
case OP_NOTMINQUERYI:
case OP_NOTPOSQUERYI:
caseless = TRUE;
codevalue -= OP_STARI - OP_STAR;
/* Fall through */
case OP_QUERY:
case OP_MINQUERY:
case OP_POSQUERY:
case OP_NOTQUERY:
case OP_NOTMINQUERY:
case OP_NOTPOSQUERY:
ADD_ACTIVE(state_offset + dlen + 1, 0);
if (clen > 0)
{
pcre_uint32 otherd = NOTACHAR;
if (caseless)
{
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
}
if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR))
{
if (codevalue == OP_POSQUERY || codevalue == OP_NOTPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset + dlen + 1, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_STARI:
case OP_MINSTARI:
case OP_POSSTARI:
case OP_NOTSTARI:
case OP_NOTMINSTARI:
case OP_NOTPOSSTARI:
caseless = TRUE;
codevalue -= OP_STARI - OP_STAR;
/* Fall through */
case OP_STAR:
case OP_MINSTAR:
case OP_POSSTAR:
case OP_NOTSTAR:
case OP_NOTMINSTAR:
case OP_NOTPOSSTAR:
ADD_ACTIVE(state_offset + dlen + 1, 0);
if (clen > 0)
{
pcre_uint32 otherd = NOTACHAR;
if (caseless)
{
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
}
if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR))
{
if (codevalue == OP_POSSTAR || codevalue == OP_NOTPOSSTAR)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset, 0);
}
}
break;
/*-----------------------------------------------------------------*/
case OP_EXACTI:
case OP_NOTEXACTI:
caseless = TRUE;
codevalue -= OP_STARI - OP_STAR;
/* Fall through */
case OP_EXACT:
case OP_NOTEXACT:
count = current_state->count; /* Number already matched */
if (clen > 0)
{
pcre_uint32 otherd = NOTACHAR;
if (caseless)
{
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
}
if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR))
{
if (++count >= (int)GET2(code, 1))
{ ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); }
else
{ ADD_NEW(state_offset, count); }
}
}
break;
/*-----------------------------------------------------------------*/
case OP_UPTOI:
case OP_MINUPTOI:
case OP_POSUPTOI:
case OP_NOTUPTOI:
case OP_NOTMINUPTOI:
case OP_NOTPOSUPTOI:
caseless = TRUE;
codevalue -= OP_STARI - OP_STAR;
/* Fall through */
case OP_UPTO:
case OP_MINUPTO:
case OP_POSUPTO:
case OP_NOTUPTO:
case OP_NOTMINUPTO:
case OP_NOTPOSUPTO:
ADD_ACTIVE(state_offset + dlen + 1 + IMM2_SIZE, 0);
count = current_state->count; /* Number already matched */
if (clen > 0)
{
pcre_uint32 otherd = NOTACHAR;
if (caseless)
{
#ifdef SUPPORT_UTF
if (utf && d >= 128)
{
#ifdef SUPPORT_UCP
otherd = UCD_OTHERCASE(d);
#endif /* SUPPORT_UCP */
}
else
#endif /* SUPPORT_UTF */
otherd = TABLE_GET(d, fcc, d);
}
if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR))
{
if (codevalue == OP_POSUPTO || codevalue == OP_NOTPOSUPTO)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= (int)GET2(code, 1))
{ ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); }
else
{ ADD_NEW(state_offset, count); }
}
}
break;
/* ========================================================================== */
/* These are the class-handling opcodes */
case OP_CLASS:
case OP_NCLASS:
case OP_XCLASS:
{
BOOL isinclass = FALSE;
int next_state_offset;
const pcre_uchar *ecode;
/* For a simple class, there is always just a 32-byte table, and we
can set isinclass from it. */
if (codevalue != OP_XCLASS)
{
ecode = code + 1 + (32 / sizeof(pcre_uchar));
if (clen > 0)
{
isinclass = (c > 255)? (codevalue == OP_NCLASS) :
((((pcre_uint8 *)(code + 1))[c/8] & (1 << (c&7))) != 0);
}
}
/* An extended class may have a table or a list of single characters,
ranges, or both, and it may be positive or negative. There's a
function that sorts all this out. */
else
{
ecode = code + GET(code, 1);
if (clen > 0) isinclass = PRIV(xclass)(c, code + 1 + LINK_SIZE, utf);
}
/* At this point, isinclass is set for all kinds of class, and ecode
points to the byte after the end of the class. If there is a
quantifier, this is where it will be. */
next_state_offset = (int)(ecode - start_code);
switch (*ecode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPOSSTAR:
ADD_ACTIVE(next_state_offset + 1, 0);
if (isinclass)
{
if (*ecode == OP_CRPOSSTAR)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(state_offset, 0);
}
break;
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRPOSPLUS:
count = current_state->count; /* Already matched */
if (count > 0) { ADD_ACTIVE(next_state_offset + 1, 0); }
if (isinclass)
{
if (count > 0 && *ecode == OP_CRPOSPLUS)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
count++;
ADD_NEW(state_offset, count);
}
break;
case OP_CRQUERY:
case OP_CRMINQUERY:
case OP_CRPOSQUERY:
ADD_ACTIVE(next_state_offset + 1, 0);
if (isinclass)
{
if (*ecode == OP_CRPOSQUERY)
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
ADD_NEW(next_state_offset + 1, 0);
}
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
case OP_CRPOSRANGE:
count = current_state->count; /* Already matched */
if (count >= (int)GET2(ecode, 1))
{ ADD_ACTIVE(next_state_offset + 1 + 2 * IMM2_SIZE, 0); }
if (isinclass)
{
int max = (int)GET2(ecode, 1 + IMM2_SIZE);
if (*ecode == OP_CRPOSRANGE && count >= (int)GET2(ecode, 1))
{
active_count--; /* Remove non-match possibility */
next_active_state--;
}
if (++count >= max && max != 0) /* Max 0 => no limit */
{ ADD_NEW(next_state_offset + 1 + 2 * IMM2_SIZE, 0); }
else
{ ADD_NEW(state_offset, count); }
}
break;
default:
if (isinclass) { ADD_NEW(next_state_offset, 0); }
break;
}
}
break;
/* ========================================================================== */
/* These are the opcodes for fancy brackets of various kinds. We have
to use recursion in order to handle them. The "always failing" assertion
(?!) is optimised to OP_FAIL when compiling, so we have to support that,
though the other "backtracking verbs" are not supported. */
case OP_FAIL:
forced_fail++; /* Count FAILs for multiple states */
break;
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
{
int rc;
int local_offsets[2];
int local_workspace[1000];
const pcre_uchar *endasscode = code + GET(code, 1);
while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1);
rc = internal_dfa_exec(
md, /* static match data */
code, /* this subexpression's code */
ptr, /* where we currently are */
(int)(ptr - start_subject), /* start offset */
local_offsets, /* offset vector */
sizeof(local_offsets)/sizeof(int), /* size of same */
local_workspace, /* workspace vector */
sizeof(local_workspace)/sizeof(int), /* size of same */
rlevel); /* function recursion level */
if (rc == PCRE_ERROR_DFA_UITEM) return rc;
if ((rc >= 0) == (codevalue == OP_ASSERT || codevalue == OP_ASSERTBACK))
{ ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); }
}
break;
/*-----------------------------------------------------------------*/
case OP_COND:
case OP_SCOND:
{
int local_offsets[1000];
int local_workspace[1000];
int codelink = GET(code, 1);
int condcode;
/* Because of the way auto-callout works during compile, a callout item
is inserted between OP_COND and an assertion condition. This does not
happen for the other conditions. */
if (code[LINK_SIZE+1] == OP_CALLOUT)
{
rrc = 0;
if (PUBL(callout) != NULL)
{
PUBL(callout_block) cb;
cb.version = 1; /* Version 1 of the callout block */
cb.callout_number = code[LINK_SIZE+2];
cb.offset_vector = offsets;
#if defined COMPILE_PCRE8
cb.subject = (PCRE_SPTR)start_subject;
#elif defined COMPILE_PCRE16
cb.subject = (PCRE_SPTR16)start_subject;
#elif defined COMPILE_PCRE32
cb.subject = (PCRE_SPTR32)start_subject;
#endif
cb.subject_length = (int)(end_subject - start_subject);
cb.start_match = (int)(current_subject - start_subject);
cb.current_position = (int)(ptr - start_subject);
cb.pattern_position = GET(code, LINK_SIZE + 3);
cb.next_item_length = GET(code, 3 + 2*LINK_SIZE);
cb.capture_top = 1;
cb.capture_last = -1;
cb.callout_data = md->callout_data;
cb.mark = NULL; /* No (*MARK) support */
if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */
}
if (rrc > 0) break; /* Fail this thread */
code += PRIV(OP_lengths)[OP_CALLOUT]; /* Skip callout data */
}
condcode = code[LINK_SIZE+1];
/* Back reference conditions and duplicate named recursion conditions
are not supported */
if (condcode == OP_CREF || condcode == OP_DNCREF ||
condcode == OP_DNRREF)
return PCRE_ERROR_DFA_UCOND;
/* The DEFINE condition is always false, and the assertion (?!) is
converted to OP_FAIL. */
if (condcode == OP_DEF || condcode == OP_FAIL)
{ ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); }
/* The only supported version of OP_RREF is for the value RREF_ANY,
which means "test if in any recursion". We can't test for specifically
recursed groups. */
else if (condcode == OP_RREF)
{
int value = GET2(code, LINK_SIZE + 2);
if (value != RREF_ANY) return PCRE_ERROR_DFA_UCOND;
if (md->recursive != NULL)
{ ADD_ACTIVE(state_offset + LINK_SIZE + 2 + IMM2_SIZE, 0); }
else { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); }
}
/* Otherwise, the condition is an assertion */
else
{
int rc;
const pcre_uchar *asscode = code + LINK_SIZE + 1;
const pcre_uchar *endasscode = asscode + GET(asscode, 1);
while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1);
rc = internal_dfa_exec(
md, /* fixed match data */
asscode, /* this subexpression's code */
ptr, /* where we currently are */
(int)(ptr - start_subject), /* start offset */
local_offsets, /* offset vector */
sizeof(local_offsets)/sizeof(int), /* size of same */
local_workspace, /* workspace vector */
sizeof(local_workspace)/sizeof(int), /* size of same */
rlevel); /* function recursion level */
if (rc == PCRE_ERROR_DFA_UITEM) return rc;
if ((rc >= 0) ==
(condcode == OP_ASSERT || condcode == OP_ASSERTBACK))
{ ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); }
else
{ ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); }
}
}
break;
/*-----------------------------------------------------------------*/
case OP_RECURSE:
{
dfa_recursion_info *ri;
int local_offsets[1000];
int local_workspace[1000];
const pcre_uchar *callpat = start_code + GET(code, 1);
int recno = (callpat == md->start_code)? 0 :
GET2(callpat, 1 + LINK_SIZE);
int rc;
DPRINTF(("%.*sStarting regex recursion\n", rlevel*2-2, SP));
/* Check for repeating a recursion without advancing the subject
pointer. This should catch convoluted mutual recursions. (Some simple
cases are caught at compile time.) */
for (ri = md->recursive; ri != NULL; ri = ri->prevrec)
if (recno == ri->group_num && ptr == ri->subject_position)
return PCRE_ERROR_RECURSELOOP;
/* Remember this recursion and where we started it so as to
catch infinite loops. */
new_recursive.group_num = recno;
new_recursive.subject_position = ptr;
new_recursive.prevrec = md->recursive;
md->recursive = &new_recursive;
rc = internal_dfa_exec(
md, /* fixed match data */
callpat, /* this subexpression's code */
ptr, /* where we currently are */
(int)(ptr - start_subject), /* start offset */
local_offsets, /* offset vector */
sizeof(local_offsets)/sizeof(int), /* size of same */
local_workspace, /* workspace vector */
sizeof(local_workspace)/sizeof(int), /* size of same */
rlevel); /* function recursion level */
md->recursive = new_recursive.prevrec; /* Done this recursion */
DPRINTF(("%.*sReturn from regex recursion: rc=%d\n", rlevel*2-2, SP,
rc));
/* Ran out of internal offsets */
if (rc == 0) return PCRE_ERROR_DFA_RECURSE;
/* For each successful matched substring, set up the next state with a
count of characters to skip before trying it. Note that the count is in
characters, not bytes. */
if (rc > 0)
{
for (rc = rc*2 - 2; rc >= 0; rc -= 2)
{
int charcount = local_offsets[rc+1] - local_offsets[rc];
#if defined SUPPORT_UTF && !defined COMPILE_PCRE32
if (utf)
{
const pcre_uchar *p = start_subject + local_offsets[rc];
const pcre_uchar *pp = start_subject + local_offsets[rc+1];
while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--;
}
#endif
if (charcount > 0)
{
ADD_NEW_DATA(-(state_offset + LINK_SIZE + 1), 0, (charcount - 1));
}
else
{
ADD_ACTIVE(state_offset + LINK_SIZE + 1, 0);
}
}
}
else if (rc != PCRE_ERROR_NOMATCH) return rc;
}
break;
/*-----------------------------------------------------------------*/
case OP_BRAPOS:
case OP_SBRAPOS:
case OP_CBRAPOS:
case OP_SCBRAPOS:
case OP_BRAPOSZERO:
{
int charcount, matched_count;
const pcre_uchar *local_ptr = ptr;
BOOL allow_zero;
if (codevalue == OP_BRAPOSZERO)
{
allow_zero = TRUE;
codevalue = *(++code); /* Codevalue will be one of above BRAs */
}
else allow_zero = FALSE;
/* Loop to match the subpattern as many times as possible as if it were
a complete pattern. */
for (matched_count = 0;; matched_count++)
{
int local_offsets[2];
int local_workspace[1000];
int rc = internal_dfa_exec(
md, /* fixed match data */
code, /* this subexpression's code */
local_ptr, /* where we currently are */
(int)(ptr - start_subject), /* start offset */
local_offsets, /* offset vector */
sizeof(local_offsets)/sizeof(int), /* size of same */
local_workspace, /* workspace vector */
sizeof(local_workspace)/sizeof(int), /* size of same */
rlevel); /* function recursion level */
/* Failed to match */
if (rc < 0)
{
if (rc != PCRE_ERROR_NOMATCH) return rc;
break;
}
/* Matched: break the loop if zero characters matched. */
charcount = local_offsets[1] - local_offsets[0];
if (charcount == 0) break;
local_ptr += charcount; /* Advance temporary position ptr */
}
/* At this point we have matched the subpattern matched_count
times, and local_ptr is pointing to the character after the end of the
last match. */
if (matched_count > 0 || allow_zero)
{
const pcre_uchar *end_subpattern = code;
int next_state_offset;
do { end_subpattern += GET(end_subpattern, 1); }
while (*end_subpattern == OP_ALT);
next_state_offset =
(int)(end_subpattern - start_code + LINK_SIZE + 1);
/* Optimization: if there are no more active states, and there
are no new states yet set up, then skip over the subject string
right here, to save looping. Otherwise, set up the new state to swing
into action when the end of the matched substring is reached. */
if (i + 1 >= active_count && new_count == 0)
{
ptr = local_ptr;
clen = 0;
ADD_NEW(next_state_offset, 0);
}
else
{
const pcre_uchar *p = ptr;
const pcre_uchar *pp = local_ptr;
charcount = (int)(pp - p);
#if defined SUPPORT_UTF && !defined COMPILE_PCRE32
if (utf) while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--;
#endif
ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1));
}
}
}
break;
/*-----------------------------------------------------------------*/
case OP_ONCE:
case OP_ONCE_NC:
{
int local_offsets[2];
int local_workspace[1000];
int rc = internal_dfa_exec(
md, /* fixed match data */
code, /* this subexpression's code */
ptr, /* where we currently are */
(int)(ptr - start_subject), /* start offset */
local_offsets, /* offset vector */
sizeof(local_offsets)/sizeof(int), /* size of same */
local_workspace, /* workspace vector */
sizeof(local_workspace)/sizeof(int), /* size of same */
rlevel); /* function recursion level */
if (rc >= 0)
{
const pcre_uchar *end_subpattern = code;
int charcount = local_offsets[1] - local_offsets[0];
int next_state_offset, repeat_state_offset;
do { end_subpattern += GET(end_subpattern, 1); }
while (*end_subpattern == OP_ALT);
next_state_offset =
(int)(end_subpattern - start_code + LINK_SIZE + 1);
/* If the end of this subpattern is KETRMAX or KETRMIN, we must
arrange for the repeat state also to be added to the relevant list.
Calculate the offset, or set -1 for no repeat. */
repeat_state_offset = (*end_subpattern == OP_KETRMAX ||
*end_subpattern == OP_KETRMIN)?
(int)(end_subpattern - start_code - GET(end_subpattern, 1)) : -1;
/* If we have matched an empty string, add the next state at the
current character pointer. This is important so that the duplicate
checking kicks in, which is what breaks infinite loops that match an
empty string. */
if (charcount == 0)
{
ADD_ACTIVE(next_state_offset, 0);
}
/* Optimization: if there are no more active states, and there
are no new states yet set up, then skip over the subject string
right here, to save looping. Otherwise, set up the new state to swing
into action when the end of the matched substring is reached. */
else if (i + 1 >= active_count && new_count == 0)
{
ptr += charcount;
clen = 0;
ADD_NEW(next_state_offset, 0);
/* If we are adding a repeat state at the new character position,
we must fudge things so that it is the only current state.
Otherwise, it might be a duplicate of one we processed before, and
that would cause it to be skipped. */
if (repeat_state_offset >= 0)
{
next_active_state = active_states;
active_count = 0;
i = -1;
ADD_ACTIVE(repeat_state_offset, 0);
}
}
else
{
#if defined SUPPORT_UTF && !defined COMPILE_PCRE32
if (utf)
{
const pcre_uchar *p = start_subject + local_offsets[0];
const pcre_uchar *pp = start_subject + local_offsets[1];
while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--;
}
#endif
ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1));
if (repeat_state_offset >= 0)
{ ADD_NEW_DATA(-repeat_state_offset, 0, (charcount - 1)); }
}
}
else if (rc != PCRE_ERROR_NOMATCH) return rc;
}
break;
/* ========================================================================== */
/* Handle callouts */
case OP_CALLOUT:
rrc = 0;
if (PUBL(callout) != NULL)
{
PUBL(callout_block) cb;
cb.version = 1; /* Version 1 of the callout block */
cb.callout_number = code[1];
cb.offset_vector = offsets;
#if defined COMPILE_PCRE8
cb.subject = (PCRE_SPTR)start_subject;
#elif defined COMPILE_PCRE16
cb.subject = (PCRE_SPTR16)start_subject;
#elif defined COMPILE_PCRE32
cb.subject = (PCRE_SPTR32)start_subject;
#endif
cb.subject_length = (int)(end_subject - start_subject);
cb.start_match = (int)(current_subject - start_subject);
cb.current_position = (int)(ptr - start_subject);
cb.pattern_position = GET(code, 2);
cb.next_item_length = GET(code, 2 + LINK_SIZE);
cb.capture_top = 1;
cb.capture_last = -1;
cb.callout_data = md->callout_data;
cb.mark = NULL; /* No (*MARK) support */
if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */
}
if (rrc == 0)
{ ADD_ACTIVE(state_offset + PRIV(OP_lengths)[OP_CALLOUT], 0); }
break;
/* ========================================================================== */
default: /* Unsupported opcode */
return PCRE_ERROR_DFA_UITEM;
}
NEXT_ACTIVE_STATE: continue;
} /* End of loop scanning active states */
/* We have finished the processing at the current subject character. If no
new states have been set for the next character, we have found all the
matches that we are going to find. If we are at the top level and partial
matching has been requested, check for appropriate conditions.
The "forced_ fail" variable counts the number of (*F) encountered for the
character. If it is equal to the original active_count (saved in
workspace[1]) it means that (*F) was found on every active state. In this
case we don't want to give a partial match.
The "could_continue" variable is true if a state could have continued but
for the fact that the end of the subject was reached. */
if (new_count <= 0)
{
if (rlevel == 1 && /* Top level, and */
could_continue && /* Some could go on, and */
forced_fail != workspace[1] && /* Not all forced fail & */
( /* either... */
(md->moptions & PCRE_PARTIAL_HARD) != 0 /* Hard partial */
|| /* or... */
((md->moptions & PCRE_PARTIAL_SOFT) != 0 && /* Soft partial and */
match_count < 0) /* no matches */
) && /* And... */
(
partial_newline || /* Either partial NL */
( /* or ... */
ptr >= end_subject && /* End of subject and */
ptr > md->start_used_ptr) /* Inspected non-empty string */
)
)
match_count = PCRE_ERROR_PARTIAL;
DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n"
"%.*s---------------------\n\n", rlevel*2-2, SP, rlevel, match_count,
rlevel*2-2, SP));
break; /* In effect, "return", but see the comment below */
}
/* One or more states are active for the next character. */
ptr += clen; /* Advance to next subject character */
} /* Loop to move along the subject string */
/* Control gets here from "break" a few lines above. We do it this way because
if we use "return" above, we have compiler trouble. Some compilers warn if
there's nothing here because they think the function doesn't return a value. On
the other hand, if we put a dummy statement here, some more clever compilers
complain that it can't be reached. Sigh. */
return match_count;
}
/*************************************************
* Execute a Regular Expression - DFA engine *
*************************************************/
/* This external function applies a compiled re to a subject string using a DFA
engine. This function calls the internal function multiple times if the pattern
is not anchored.
Arguments:
argument_re points to the compiled expression
extra_data points to extra data or is NULL
subject points to the subject string
length length of subject string (may contain binary zeros)
start_offset where to start in the subject string
options option bits
offsets vector of match offsets
offsetcount size of same
workspace workspace vector
wscount size of same
Returns: > 0 => number of match offset pairs placed in offsets
= 0 => offsets overflowed; longest matches are present
-1 => failed to match
< -1 => some kind of unexpected problem
*/
#if defined COMPILE_PCRE8
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre_dfa_exec(const pcre *argument_re, const pcre_extra *extra_data,
const char *subject, int length, int start_offset, int options, int *offsets,
int offsetcount, int *workspace, int wscount)
#elif defined COMPILE_PCRE16
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre16_dfa_exec(const pcre16 *argument_re, const pcre16_extra *extra_data,
PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets,
int offsetcount, int *workspace, int wscount)
#elif defined COMPILE_PCRE32
PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
pcre32_dfa_exec(const pcre32 *argument_re, const pcre32_extra *extra_data,
PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets,
int offsetcount, int *workspace, int wscount)
#endif
{
REAL_PCRE *re = (REAL_PCRE *)argument_re;
dfa_match_data match_block;
dfa_match_data *md = &match_block;
BOOL utf, anchored, startline, firstline;
const pcre_uchar *current_subject, *end_subject;
const pcre_study_data *study = NULL;
const pcre_uchar *req_char_ptr;
const pcre_uint8 *start_bits = NULL;
BOOL has_first_char = FALSE;
BOOL has_req_char = FALSE;
pcre_uchar first_char = 0;
pcre_uchar first_char2 = 0;
pcre_uchar req_char = 0;
pcre_uchar req_char2 = 0;
int newline;
/* Plausibility checks */
if ((options & ~PUBLIC_DFA_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION;
if (re == NULL || subject == NULL || workspace == NULL ||
(offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL;
if (offsetcount < 0) return PCRE_ERROR_BADCOUNT;
if (wscount < 20) return PCRE_ERROR_DFA_WSSIZE;
if (length < 0) return PCRE_ERROR_BADLENGTH;
if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET;
/* Check that the first field in the block is the magic number. If it is not,
return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to
REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which
means that the pattern is likely compiled with different endianness. */
if (re->magic_number != MAGIC_NUMBER)
return re->magic_number == REVERSED_MAGIC_NUMBER?
PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC;
if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE;
/* If restarting after a partial match, do some sanity checks on the contents
of the workspace. */
if ((options & PCRE_DFA_RESTART) != 0)
{
if ((workspace[0] & (-2)) != 0 || workspace[1] < 1 ||
workspace[1] > (wscount - 2)/INTS_PER_STATEBLOCK)
return PCRE_ERROR_DFA_BADRESTART;
}
/* Set up study, callout, and table data */
md->tables = re->tables;
md->callout_data = NULL;
if (extra_data != NULL)
{
unsigned long int flags = extra_data->flags;
if ((flags & PCRE_EXTRA_STUDY_DATA) != 0)
study = (const pcre_study_data *)extra_data->study_data;
if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) return PCRE_ERROR_DFA_UMLIMIT;
if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0)
return PCRE_ERROR_DFA_UMLIMIT;
if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0)
md->callout_data = extra_data->callout_data;
if ((flags & PCRE_EXTRA_TABLES) != 0)
md->tables = extra_data->tables;
}
/* Set some local values */
current_subject = (const pcre_uchar *)subject + start_offset;
end_subject = (const pcre_uchar *)subject + length;
req_char_ptr = current_subject - 1;
#ifdef SUPPORT_UTF
/* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */
utf = (re->options & PCRE_UTF8) != 0;
#else
utf = FALSE;
#endif
anchored = (options & (PCRE_ANCHORED|PCRE_DFA_RESTART)) != 0 ||
(re->options & PCRE_ANCHORED) != 0;
/* The remaining fixed data for passing around. */
md->start_code = (const pcre_uchar *)argument_re +
re->name_table_offset + re->name_count * re->name_entry_size;
md->start_subject = (const pcre_uchar *)subject;
md->end_subject = end_subject;
md->start_offset = start_offset;
md->moptions = options;
md->poptions = re->options;
/* If the BSR option is not set at match time, copy what was set
at compile time. */
if ((md->moptions & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == 0)
{
if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0)
md->moptions |= re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE);
#ifdef BSR_ANYCRLF
else md->moptions |= PCRE_BSR_ANYCRLF;
#endif
}
/* Handle different types of newline. The three bits give eight cases. If
nothing is set at run time, whatever was used at compile time applies. */
switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options : (pcre_uint32)options) &
PCRE_NEWLINE_BITS)
{
case 0: newline = NEWLINE; break; /* Compile-time default */
case PCRE_NEWLINE_CR: newline = CHAR_CR; break;
case PCRE_NEWLINE_LF: newline = CHAR_NL; break;
case PCRE_NEWLINE_CR+
PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break;
case PCRE_NEWLINE_ANY: newline = -1; break;
case PCRE_NEWLINE_ANYCRLF: newline = -2; break;
default: return PCRE_ERROR_BADNEWLINE;
}
if (newline == -2)
{
md->nltype = NLTYPE_ANYCRLF;
}
else if (newline < 0)
{
md->nltype = NLTYPE_ANY;
}
else
{
md->nltype = NLTYPE_FIXED;
if (newline > 255)
{
md->nllen = 2;
md->nl[0] = (newline >> 8) & 255;
md->nl[1] = newline & 255;
}
else
{
md->nllen = 1;
md->nl[0] = newline;
}
}
/* Check a UTF-8 string if required. Unfortunately there's no way of passing
back the character offset. */
#ifdef SUPPORT_UTF
if (utf && (options & PCRE_NO_UTF8_CHECK) == 0)
{
int erroroffset;
int errorcode = PRIV(valid_utf)((pcre_uchar *)subject, length, &erroroffset);
if (errorcode != 0)
{
if (offsetcount >= 2)
{
offsets[0] = erroroffset;
offsets[1] = errorcode;
}
#if defined COMPILE_PCRE8
return (errorcode <= PCRE_UTF8_ERR5 && (options & PCRE_PARTIAL_HARD) != 0) ?
PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8;
#elif defined COMPILE_PCRE16
return (errorcode <= PCRE_UTF16_ERR1 && (options & PCRE_PARTIAL_HARD) != 0) ?
PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16;
#elif defined COMPILE_PCRE32
return PCRE_ERROR_BADUTF32;
#endif
}
#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16
if (start_offset > 0 && start_offset < length &&
NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset]))
return PCRE_ERROR_BADUTF8_OFFSET;
#endif
}
#endif
/* If the exec call supplied NULL for tables, use the inbuilt ones. This
is a feature that makes it possible to save compiled regex and re-use them
in other programs later. */
if (md->tables == NULL) md->tables = PRIV(default_tables);
/* The "must be at the start of a line" flags are used in a loop when finding
where to start. */
startline = (re->flags & PCRE_STARTLINE) != 0;
firstline = (re->options & PCRE_FIRSTLINE) != 0;
/* Set up the first character to match, if available. The first_byte value is
never set for an anchored regular expression, but the anchoring may be forced
at run time, so we have to test for anchoring. The first char may be unset for
an unanchored pattern, of course. If there's no first char and the pattern was
studied, there may be a bitmap of possible first characters. */
if (!anchored)
{
if ((re->flags & PCRE_FIRSTSET) != 0)
{
has_first_char = TRUE;
first_char = first_char2 = (pcre_uchar)(re->first_char);
if ((re->flags & PCRE_FCH_CASELESS) != 0)
{
first_char2 = TABLE_GET(first_char, md->tables + fcc_offset, first_char);
#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
if (utf && first_char > 127)
first_char2 = UCD_OTHERCASE(first_char);
#endif
}
}
else
{
if (!startline && study != NULL &&
(study->flags & PCRE_STUDY_MAPPED) != 0)
start_bits = study->start_bits;
}
}
/* For anchored or unanchored matches, there may be a "last known required
character" set. */
if ((re->flags & PCRE_REQCHSET) != 0)
{
has_req_char = TRUE;
req_char = req_char2 = (pcre_uchar)(re->req_char);
if ((re->flags & PCRE_RCH_CASELESS) != 0)
{
req_char2 = TABLE_GET(req_char, md->tables + fcc_offset, req_char);
#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8)
if (utf && req_char > 127)
req_char2 = UCD_OTHERCASE(req_char);
#endif
}
}
/* Call the main matching function, looping for a non-anchored regex after a
failed match. If not restarting, perform certain optimizations at the start of
a match. */
for (;;)
{
int rc;
if ((options & PCRE_DFA_RESTART) == 0)
{
const pcre_uchar *save_end_subject = end_subject;
/* If firstline is TRUE, the start of the match is constrained to the first
line of a multiline string. Implement this by temporarily adjusting
end_subject so that we stop scanning at a newline. If the match fails at
the newline, later code breaks this loop. */
if (firstline)
{
PCRE_PUCHAR t = current_subject;
#ifdef SUPPORT_UTF
if (utf)
{
while (t < md->end_subject && !IS_NEWLINE(t))
{
t++;
ACROSSCHAR(t < end_subject, *t, t++);
}
}
else
#endif
while (t < md->end_subject && !IS_NEWLINE(t)) t++;
end_subject = t;
}
/* There are some optimizations that avoid running the match if a known
starting point is not found. However, there is an option that disables
these, for testing and for ensuring that all callouts do actually occur.
The option can be set in the regex by (*NO_START_OPT) or passed in
match-time options. */
if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0)
{
/* Advance to a known first pcre_uchar (i.e. data item) */
if (has_first_char)
{
if (first_char != first_char2)
{
pcre_uchar csc;
while (current_subject < end_subject &&
(csc = UCHAR21TEST(current_subject)) != first_char && csc != first_char2)
current_subject++;
}
else
while (current_subject < end_subject &&
UCHAR21TEST(current_subject) != first_char)
current_subject++;
}
/* Or to just after a linebreak for a multiline match if possible */
else if (startline)
{
if (current_subject > md->start_subject + start_offset)
{
#ifdef SUPPORT_UTF
if (utf)
{
while (current_subject < end_subject &&
!WAS_NEWLINE(current_subject))
{
current_subject++;
ACROSSCHAR(current_subject < end_subject, *current_subject,
current_subject++);
}
}
else
#endif
while (current_subject < end_subject && !WAS_NEWLINE(current_subject))
current_subject++;
/* If we have just passed a CR and the newline option is ANY or
ANYCRLF, and we are now at a LF, advance the match position by one
more character. */
if (UCHAR21TEST(current_subject - 1) == CHAR_CR &&
(md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) &&
current_subject < end_subject &&
UCHAR21TEST(current_subject) == CHAR_NL)
current_subject++;
}
}
/* Advance to a non-unique first pcre_uchar after study */
else if (start_bits != NULL)
{
while (current_subject < end_subject)
{
register pcre_uint32 c = UCHAR21TEST(current_subject);
#ifndef COMPILE_PCRE8
if (c > 255) c = 255;
#endif
if ((start_bits[c/8] & (1 << (c&7))) != 0) break;
current_subject++;
}
}
}
/* Restore fudged end_subject */
end_subject = save_end_subject;
/* The following two optimizations are disabled for partial matching or if
disabling is explicitly requested (and of course, by the test above, this
code is not obeyed when restarting after a partial match). */
if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 &&
(options & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) == 0)
{
/* If the pattern was studied, a minimum subject length may be set. This
is a lower bound; no actual string of that length may actually match the
pattern. Although the value is, strictly, in characters, we treat it as
in pcre_uchar units to avoid spending too much time in this optimization.
*/
if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 &&
(pcre_uint32)(end_subject - current_subject) < study->minlength)
return PCRE_ERROR_NOMATCH;
/* If req_char is set, we know that that pcre_uchar must appear in the
subject for the match to succeed. If the first pcre_uchar is set,
req_char must be later in the subject; otherwise the test starts at the
match point. This optimization can save a huge amount of work in patterns
with nested unlimited repeats that aren't going to match. Writing
separate code for cased/caseless versions makes it go faster, as does
using an autoincrement and backing off on a match.
HOWEVER: when the subject string is very, very long, searching to its end
can take a long time, and give bad performance on quite ordinary
patterns. This showed up when somebody was matching /^C/ on a 32-megabyte
string... so we don't do this when the string is sufficiently long. */
if (has_req_char && end_subject - current_subject < REQ_BYTE_MAX)
{
register PCRE_PUCHAR p = current_subject + (has_first_char? 1:0);
/* We don't need to repeat the search if we haven't yet reached the
place we found it at last time. */
if (p > req_char_ptr)
{
if (req_char != req_char2)
{
while (p < end_subject)
{
register pcre_uint32 pp = UCHAR21INCTEST(p);
if (pp == req_char || pp == req_char2) { p--; break; }
}
}
else
{
while (p < end_subject)
{
if (UCHAR21INCTEST(p) == req_char) { p--; break; }
}
}
/* If we can't find the required pcre_uchar, break the matching loop,
which will cause a return or PCRE_ERROR_NOMATCH. */
if (p >= end_subject) break;
/* If we have found the required pcre_uchar, save the point where we
found it, so that we don't search again next time round the loop if
the start hasn't passed this point yet. */
req_char_ptr = p;
}
}
}
} /* End of optimizations that are done when not restarting */
/* OK, now we can do the business */
md->start_used_ptr = current_subject;
md->recursive = NULL;
rc = internal_dfa_exec(
md, /* fixed match data */
md->start_code, /* this subexpression's code */
current_subject, /* where we currently are */
start_offset, /* start offset in subject */
offsets, /* offset vector */
offsetcount, /* size of same */
workspace, /* workspace vector */
wscount, /* size of same */
0); /* function recurse level */
/* Anything other than "no match" means we are done, always; otherwise, carry
on only if not anchored. */
if (rc != PCRE_ERROR_NOMATCH || anchored)
{
if (rc == PCRE_ERROR_PARTIAL && offsetcount >= 2)
{
offsets[0] = (int)(md->start_used_ptr - (PCRE_PUCHAR)subject);
offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject);
if (offsetcount > 2)
offsets[2] = (int)(current_subject - (PCRE_PUCHAR)subject);
}
return rc;
}
/* Advance to the next subject character unless we are at the end of a line
and firstline is set. */
if (firstline && IS_NEWLINE(current_subject)) break;
current_subject++;
#ifdef SUPPORT_UTF
if (utf)
{
ACROSSCHAR(current_subject < end_subject, *current_subject,
current_subject++);
}
#endif
if (current_subject > end_subject) break;
/* If we have just passed a CR and we are now at a LF, and the pattern does
not contain any explicit matches for \r or \n, and the newline option is CRLF
or ANY or ANYCRLF, advance the match position by one more character. */
if (UCHAR21TEST(current_subject - 1) == CHAR_CR &&
current_subject < end_subject &&
UCHAR21TEST(current_subject) == CHAR_NL &&
(re->flags & PCRE_HASCRORLF) == 0 &&
(md->nltype == NLTYPE_ANY ||
md->nltype == NLTYPE_ANYCRLF ||
md->nllen == 2))
current_subject++;
} /* "Bumpalong" loop */
return PCRE_ERROR_NOMATCH;
}
/* End of pcre_dfa_exec.c */
| libgit2-main | deps/pcre/pcre_dfa_exec.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2014 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains global variables that are exported by the PCRE library.
PCRE is thread-clean and doesn't use any global variables in the normal sense.
However, it calls memory allocation and freeing functions via the four
indirections below, and it can optionally do callouts, using the fifth
indirection. These values can be changed by the caller, but are shared between
all threads.
For MS Visual Studio and Symbian OS, there are problems in initializing these
variables to non-local functions. In these cases, therefore, an indirection via
a local function is used.
Also, when compiling for Virtual Pascal, things are done differently, and
global variables are not used. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#if defined _MSC_VER || defined __SYMBIAN32__
static void* LocalPcreMalloc(size_t aSize)
{
return malloc(aSize);
}
static void LocalPcreFree(void* aPtr)
{
free(aPtr);
}
PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = LocalPcreMalloc;
PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = LocalPcreFree;
PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = LocalPcreMalloc;
PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = LocalPcreFree;
PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL;
PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL;
#elif !defined VPCOMPAT
PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = malloc;
PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = free;
PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = malloc;
PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = free;
PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL;
PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL;
#endif
/* End of pcre_globals.c */
| libgit2-main | deps/pcre/pcre_globals.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This file contains a private PCRE function that converts an ordinal
character value into a UTF8 string. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define COMPILE_PCRE8
#include "pcre_internal.h"
/*************************************************
* Convert character value to UTF-8 *
*************************************************/
/* This function takes an integer value in the range 0 - 0x10ffff
and encodes it as a UTF-8 character in 1 to 4 pcre_uchars.
Arguments:
cvalue the character value
buffer pointer to buffer for result - at least 6 pcre_uchars long
Returns: number of characters placed in the buffer
*/
unsigned
int
PRIV(ord2utf)(pcre_uint32 cvalue, pcre_uchar *buffer)
{
#ifdef SUPPORT_UTF
register int i, j;
for (i = 0; i < PRIV(utf8_table1_size); i++)
if ((int)cvalue <= PRIV(utf8_table1)[i]) break;
buffer += i;
for (j = i; j > 0; j--)
{
*buffer-- = 0x80 | (cvalue & 0x3f);
cvalue >>= 6;
}
*buffer = PRIV(utf8_table2)[i] | cvalue;
return i + 1;
#else
(void)(cvalue); /* Keep compiler happy; this function won't ever be */
(void)(buffer); /* called when SUPPORT_UTF is not defined. */
return 0;
#endif
}
/* End of pcre_ord2utf8.c */
| libgit2-main | deps/pcre/pcre_ord2utf8.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2013 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains an internal function for validating UTF-8 character
strings. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Validate a UTF-8 string *
*************************************************/
/* This function is called (optionally) at the start of compile or match, to
check that a supposed UTF-8 string is actually valid. The early check means
that subsequent code can assume it is dealing with a valid string. The check
can be turned off for maximum performance, but the consequences of supplying an
invalid string are then undefined.
Originally, this function checked according to RFC 2279, allowing for values in
the range 0 to 0x7fffffff, up to 6 bytes long, but ensuring that they were in
the canonical format. Once somebody had pointed out RFC 3629 to me (it
obsoletes 2279), additional restrictions were applied. The values are now
limited to be between 0 and 0x0010ffff, no more than 4 bytes long, and the
subrange 0xd000 to 0xdfff is excluded. However, the format of 5-byte and 6-byte
characters is still checked.
From release 8.13 more information about the details of the error are passed
back in the returned value:
PCRE_UTF8_ERR0 No error
PCRE_UTF8_ERR1 Missing 1 byte at the end of the string
PCRE_UTF8_ERR2 Missing 2 bytes at the end of the string
PCRE_UTF8_ERR3 Missing 3 bytes at the end of the string
PCRE_UTF8_ERR4 Missing 4 bytes at the end of the string
PCRE_UTF8_ERR5 Missing 5 bytes at the end of the string
PCRE_UTF8_ERR6 2nd-byte's two top bits are not 0x80
PCRE_UTF8_ERR7 3rd-byte's two top bits are not 0x80
PCRE_UTF8_ERR8 4th-byte's two top bits are not 0x80
PCRE_UTF8_ERR9 5th-byte's two top bits are not 0x80
PCRE_UTF8_ERR10 6th-byte's two top bits are not 0x80
PCRE_UTF8_ERR11 5-byte character is not permitted by RFC 3629
PCRE_UTF8_ERR12 6-byte character is not permitted by RFC 3629
PCRE_UTF8_ERR13 4-byte character with value > 0x10ffff is not permitted
PCRE_UTF8_ERR14 3-byte character with value 0xd000-0xdfff is not permitted
PCRE_UTF8_ERR15 Overlong 2-byte sequence
PCRE_UTF8_ERR16 Overlong 3-byte sequence
PCRE_UTF8_ERR17 Overlong 4-byte sequence
PCRE_UTF8_ERR18 Overlong 5-byte sequence (won't ever occur)
PCRE_UTF8_ERR19 Overlong 6-byte sequence (won't ever occur)
PCRE_UTF8_ERR20 Isolated 0x80 byte (not within UTF-8 character)
PCRE_UTF8_ERR21 Byte with the illegal value 0xfe or 0xff
PCRE_UTF8_ERR22 Unused (was non-character)
Arguments:
string points to the string
length length of string, or -1 if the string is zero-terminated
errp pointer to an error position offset variable
Returns: = 0 if the string is a valid UTF-8 string
> 0 otherwise, setting the offset of the bad character
*/
int
PRIV(valid_utf)(PCRE_PUCHAR string, int length, int *erroroffset)
{
#ifdef SUPPORT_UTF
register PCRE_PUCHAR p;
if (length < 0)
{
for (p = string; *p != 0; p++);
length = (int)(p - string);
}
for (p = string; length-- > 0; p++)
{
register pcre_uchar ab, c, d;
c = *p;
if (c < 128) continue; /* ASCII character */
if (c < 0xc0) /* Isolated 10xx xxxx byte */
{
*erroroffset = (int)(p - string);
return PCRE_UTF8_ERR20;
}
if (c >= 0xfe) /* Invalid 0xfe or 0xff bytes */
{
*erroroffset = (int)(p - string);
return PCRE_UTF8_ERR21;
}
ab = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes */
if (length < ab)
{
*erroroffset = (int)(p - string); /* Missing bytes */
return ab - length; /* Codes ERR1 to ERR5 */
}
length -= ab; /* Length remaining */
/* Check top bits in the second byte */
if (((d = *(++p)) & 0xc0) != 0x80)
{
*erroroffset = (int)(p - string) - 1;
return PCRE_UTF8_ERR6;
}
/* For each length, check that the remaining bytes start with the 0x80 bit
set and not the 0x40 bit. Then check for an overlong sequence, and for the
excluded range 0xd800 to 0xdfff. */
switch (ab)
{
/* 2-byte character. No further bytes to check for 0x80. Check first byte
for for xx00 000x (overlong sequence). */
case 1: if ((c & 0x3e) == 0)
{
*erroroffset = (int)(p - string) - 1;
return PCRE_UTF8_ERR15;
}
break;
/* 3-byte character. Check third byte for 0x80. Then check first 2 bytes
for 1110 0000, xx0x xxxx (overlong sequence) or
1110 1101, 1010 xxxx (0xd800 - 0xdfff) */
case 2:
if ((*(++p) & 0xc0) != 0x80) /* Third byte */
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR7;
}
if (c == 0xe0 && (d & 0x20) == 0)
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR16;
}
if (c == 0xed && d >= 0xa0)
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR14;
}
break;
/* 4-byte character. Check 3rd and 4th bytes for 0x80. Then check first 2
bytes for for 1111 0000, xx00 xxxx (overlong sequence), then check for a
character greater than 0x0010ffff (f4 8f bf bf) */
case 3:
if ((*(++p) & 0xc0) != 0x80) /* Third byte */
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR7;
}
if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */
{
*erroroffset = (int)(p - string) - 3;
return PCRE_UTF8_ERR8;
}
if (c == 0xf0 && (d & 0x30) == 0)
{
*erroroffset = (int)(p - string) - 3;
return PCRE_UTF8_ERR17;
}
if (c > 0xf4 || (c == 0xf4 && d > 0x8f))
{
*erroroffset = (int)(p - string) - 3;
return PCRE_UTF8_ERR13;
}
break;
/* 5-byte and 6-byte characters are not allowed by RFC 3629, and will be
rejected by the length test below. However, we do the appropriate tests
here so that overlong sequences get diagnosed, and also in case there is
ever an option for handling these larger code points. */
/* 5-byte character. Check 3rd, 4th, and 5th bytes for 0x80. Then check for
1111 1000, xx00 0xxx */
case 4:
if ((*(++p) & 0xc0) != 0x80) /* Third byte */
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR7;
}
if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */
{
*erroroffset = (int)(p - string) - 3;
return PCRE_UTF8_ERR8;
}
if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */
{
*erroroffset = (int)(p - string) - 4;
return PCRE_UTF8_ERR9;
}
if (c == 0xf8 && (d & 0x38) == 0)
{
*erroroffset = (int)(p - string) - 4;
return PCRE_UTF8_ERR18;
}
break;
/* 6-byte character. Check 3rd-6th bytes for 0x80. Then check for
1111 1100, xx00 00xx. */
case 5:
if ((*(++p) & 0xc0) != 0x80) /* Third byte */
{
*erroroffset = (int)(p - string) - 2;
return PCRE_UTF8_ERR7;
}
if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */
{
*erroroffset = (int)(p - string) - 3;
return PCRE_UTF8_ERR8;
}
if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */
{
*erroroffset = (int)(p - string) - 4;
return PCRE_UTF8_ERR9;
}
if ((*(++p) & 0xc0) != 0x80) /* Sixth byte */
{
*erroroffset = (int)(p - string) - 5;
return PCRE_UTF8_ERR10;
}
if (c == 0xfc && (d & 0x3c) == 0)
{
*erroroffset = (int)(p - string) - 5;
return PCRE_UTF8_ERR19;
}
break;
}
/* Character is valid under RFC 2279, but 4-byte and 5-byte characters are
excluded by RFC 3629. The pointer p is currently at the last byte of the
character. */
if (ab > 3)
{
*erroroffset = (int)(p - string) - ab;
return (ab == 4)? PCRE_UTF8_ERR11 : PCRE_UTF8_ERR12;
}
}
#else /* Not SUPPORT_UTF */
(void)(string); /* Keep picky compilers happy */
(void)(length);
(void)(erroroffset);
#endif
return PCRE_UTF8_ERR0; /* This indicates success */
}
/* End of pcre_valid_utf8.c */
| libgit2-main | deps/pcre/pcre_valid_utf8.c |
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* This file contains character tables that are used when no external tables
are passed to PCRE by the application that calls it. The tables are used only
for characters whose code values are less than 256.
This is a default version of the tables that assumes ASCII encoding. A program
called dftables (which is distributed with PCRE) can be used to build
alternative versions of this file. This is necessary if you are running in an
EBCDIC environment, or if you want to default to a different encoding, for
example ISO-8859-1. When dftables is run, it creates these tables in the
current locale. If PCRE is configured with --enable-rebuild-chartables, this
happens automatically.
The following #includes are present because without them gcc 4.x may remove the
array definition from the final binary if PCRE is built into a static library
and dead code stripping is activated. This leads to link errors. Pulling in the
header ensures that the array gets flagged as "someone outside this compilation
unit might reference this" and so it will always be supplied to the linker. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
const pcre_uint8 PRIV(default_tables)[] = {
/* This table is a lower casing table. */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table is a case flipping table. */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table contains bit maps for various character classes. Each map is 32
bytes long and the bits run from the least significant end of each byte. The
classes that have their own maps are: space, xdigit, digit, upper, lower, word,
graph, print, punct, and cntrl. Other classes are built from combinations. */
0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc,
0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
/* This table identifies various classes of character by individual bits:
0x01 white space character
0x02 letter
0x04 decimal digit
0x08 hexadecimal digit
0x10 alphanumeric or '_'
0x80 regular expression metacharacter or binary zero
*/
0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */
0x00,0x01,0x01,0x01,0x01,0x01,0x00,0x00, /* 8- 15 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */
0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */
0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */
0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */
0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */
0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */
0x12,0x12,0x12,0x80,0x80,0x00,0x80,0x10, /* X - _ */
0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */
0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
/* End of pcre_chartables.c */
| libgit2-main | deps/pcre/pcre_chartables.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include "git2.h"
#include "futils.h"
#include "path.h"
#include "standalone_driver.h"
static int run_one_file(const char *filename)
{
git_str buf = GIT_STR_INIT;
int error = 0;
if (git_futils_readbuffer(&buf, filename) < 0) {
fprintf(stderr, "Failed to read %s: %s\n", filename, git_error_last()->message);
error = -1;
goto exit;
}
LLVMFuzzerTestOneInput((const unsigned char *)buf.ptr, buf.size);
exit:
git_str_dispose(&buf);
return error;
}
int main(int argc, char **argv)
{
git_vector corpus_files = GIT_VECTOR_INIT;
char *filename = NULL;
unsigned i = 0;
int error = 0;
if (git_libgit2_init() < 0) {
fprintf(stderr, "Failed to initialize libgit2\n");
abort();
}
if (argc != 2) {
fprintf(stderr, "Usage: %s <corpus directory>\n", argv[0]);
error = -1;
goto exit;
}
fprintf(stderr, "Running %s against %s\n", argv[0], argv[1]);
LLVMFuzzerInitialize(&argc, &argv);
if (git_fs_path_dirload(&corpus_files, argv[1], 0, 0x0) < 0) {
fprintf(stderr, "Failed to scan corpus directory '%s': %s\n",
argv[1], git_error_last()->message);
error = -1;
goto exit;
}
git_vector_foreach(&corpus_files, i, filename) {
fprintf(stderr, "\tRunning %s...\n", filename);
if (run_one_file(filename) < 0) {
error = -1;
goto exit;
}
}
fprintf(stderr, "Done %d runs\n", i);
exit:
git_vector_free_deep(&corpus_files);
git_libgit2_shutdown();
return error;
}
| libgit2-main | fuzzers/standalone_driver.c |
/*
* libgit2 packfile fuzzer target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2.h"
#include "object.h"
#include "standalone_driver.h"
#define UNUSED(x) (void)(x)
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
UNUSED(argc);
UNUSED(argv);
if (git_libgit2_init() < 0)
abort();
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
const git_object_t types[] = {
GIT_OBJECT_BLOB, GIT_OBJECT_TREE, GIT_OBJECT_COMMIT, GIT_OBJECT_TAG
};
git_object *object = NULL;
size_t i;
/*
* Brute-force parse this as every object type. We want
* to stress the parsing logic anyway, so this is fine
* to do.
*/
for (i = 0; i < ARRAY_SIZE(types); i++) {
if (git_object__from_raw(&object, (const char *) data, size, types[i]) < 0)
continue;
git_object_free(object);
object = NULL;
}
return 0;
}
| libgit2-main | fuzzers/objects_fuzzer.c |
/*
* libgit2 raw packfile fuzz target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "git2.h"
#include "git2/sys/transport.h"
#include "futils.h"
#include "standalone_driver.h"
#define UNUSED(x) (void)(x)
struct fuzzer_buffer {
const unsigned char *data;
size_t size;
};
struct fuzzer_stream {
git_smart_subtransport_stream base;
const unsigned char *readp;
const unsigned char *endp;
};
struct fuzzer_subtransport {
git_smart_subtransport base;
git_transport *owner;
struct fuzzer_buffer data;
};
static git_repository *repo;
static int fuzzer_stream_read(git_smart_subtransport_stream *stream,
char *buffer,
size_t buf_size,
size_t *bytes_read)
{
struct fuzzer_stream *fs = (struct fuzzer_stream *) stream;
size_t avail = fs->endp - fs->readp;
*bytes_read = (buf_size > avail) ? avail : buf_size;
memcpy(buffer, fs->readp, *bytes_read);
fs->readp += *bytes_read;
return 0;
}
static int fuzzer_stream_write(git_smart_subtransport_stream *stream,
const char *buffer, size_t len)
{
UNUSED(stream);
UNUSED(buffer);
UNUSED(len);
return 0;
}
static void fuzzer_stream_free(git_smart_subtransport_stream *stream)
{
free(stream);
}
static int fuzzer_stream_new(
struct fuzzer_stream **out,
const struct fuzzer_buffer *data)
{
struct fuzzer_stream *stream = malloc(sizeof(*stream));
if (!stream)
return -1;
stream->readp = data->data;
stream->endp = data->data + data->size;
stream->base.read = fuzzer_stream_read;
stream->base.write = fuzzer_stream_write;
stream->base.free = fuzzer_stream_free;
*out = stream;
return 0;
}
static int fuzzer_subtransport_action(
git_smart_subtransport_stream **out,
git_smart_subtransport *transport,
const char *url,
git_smart_service_t action)
{
struct fuzzer_subtransport *ft = (struct fuzzer_subtransport *) transport;
UNUSED(url);
UNUSED(action);
return fuzzer_stream_new((struct fuzzer_stream **) out, &ft->data);
}
static int fuzzer_subtransport_close(git_smart_subtransport *transport)
{
UNUSED(transport);
return 0;
}
static void fuzzer_subtransport_free(git_smart_subtransport *transport)
{
free(transport);
}
static int fuzzer_subtransport_new(
struct fuzzer_subtransport **out,
git_transport *owner,
const struct fuzzer_buffer *data)
{
struct fuzzer_subtransport *sub = malloc(sizeof(*sub));
if (!sub)
return -1;
sub->owner = owner;
sub->data.data = data->data;
sub->data.size = data->size;
sub->base.action = fuzzer_subtransport_action;
sub->base.close = fuzzer_subtransport_close;
sub->base.free = fuzzer_subtransport_free;
*out = sub;
return 0;
}
static int fuzzer_subtransport_cb(
git_smart_subtransport **out,
git_transport *owner,
void *payload)
{
struct fuzzer_buffer *buf = (struct fuzzer_buffer *) payload;
struct fuzzer_subtransport *sub;
if (fuzzer_subtransport_new(&sub, owner, buf) < 0)
return -1;
*out = &sub->base;
return 0;
}
static int fuzzer_transport_cb(git_transport **out, git_remote *owner, void *param)
{
git_smart_subtransport_definition def = {
fuzzer_subtransport_cb,
1,
param
};
return git_transport_smart(out, owner, &def);
}
static void fuzzer_git_abort(const char *op)
{
const git_error *err = git_error_last();
fprintf(stderr, "unexpected libgit error: %s: %s\n",
op, err ? err->message : "<none>");
abort();
}
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
#if defined(_WIN32)
char tmpdir[MAX_PATH], path[MAX_PATH];
if (GetTempPath((DWORD)sizeof(tmpdir), tmpdir) == 0)
abort();
if (GetTempFileName(tmpdir, "lg2", 1, path) == 0)
abort();
if (git_futils_mkdir(path, 0700, 0) < 0)
abort();
#else
char path[] = "/tmp/git2.XXXXXX";
if (mkdtemp(path) != path)
abort();
#endif
if (git_libgit2_init() < 0)
abort();
if (git_libgit2_opts(GIT_OPT_SET_PACK_MAX_OBJECTS, 10000000) < 0)
abort();
UNUSED(argc);
UNUSED(argv);
if (git_repository_init(&repo, path, 1) < 0)
fuzzer_git_abort("git_repository_init");
return 0;
}
int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size)
{
struct fuzzer_buffer buffer = { data, size };
git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
git_remote *remote;
if (git_remote_create_anonymous(&remote, repo, "fuzzer://remote-url") < 0)
fuzzer_git_abort("git_remote_create");
callbacks.transport = fuzzer_transport_cb;
callbacks.payload = &buffer;
if (git_remote_connect(remote, GIT_DIRECTION_FETCH,
&callbacks, NULL, NULL) < 0)
goto out;
git_remote_download(remote, NULL, NULL);
out:
git_remote_free(remote);
return 0;
}
| libgit2-main | fuzzers/download_refs_fuzzer.c |
/*
* libgit2 patch parser fuzzer target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2.h"
#include "patch.h"
#include "patch_parse.h"
#include "standalone_driver.h"
#define UNUSED(x) (void)(x)
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
UNUSED(argc);
UNUSED(argv);
if (git_libgit2_init() < 0)
abort();
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
if (size) {
git_patch *patch = NULL;
git_patch_options opts = GIT_PATCH_OPTIONS_INIT;
opts.prefix_len = (uint32_t)data[0];
git_patch_from_buffer(&patch, (const char *)data + 1, size - 1,
&opts);
git_patch_free(patch);
}
return 0;
}
| libgit2-main | fuzzers/patch_parse_fuzzer.c |
/*
* libgit2 multi-pack-index fuzzer target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include "git2.h"
#include "common.h"
#include "futils.h"
#include "hash.h"
#include "midx.h"
#include "standalone_driver.h"
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
GIT_UNUSED(argc);
GIT_UNUSED(argv);
if (git_libgit2_init() < 0) {
fprintf(stderr, "Failed to initialize libgit2\n");
abort();
}
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
git_midx_file idx = {{0}};
git_midx_entry e;
git_str midx_buf = GIT_STR_INIT;
unsigned char hash[GIT_HASH_SHA1_SIZE];
git_oid oid = GIT_OID_NONE;
bool append_hash = false;
if (size < 4)
return 0;
/*
* If the first byte in the stream has the high bit set, append the
* SHA1 hash so that the packfile is somewhat valid.
*/
append_hash = *data & 0x80;
/* Keep a 4-byte alignment to avoid unaligned accesses. */
data += 4;
size -= 4;
if (append_hash) {
if (git_str_init(&midx_buf, size + GIT_HASH_SHA1_SIZE) < 0)
goto cleanup;
if (git_hash_buf(hash, data, size, GIT_HASH_ALGORITHM_SHA1) < 0) {
fprintf(stderr, "Failed to compute the SHA1 hash\n");
abort();
}
memcpy(midx_buf.ptr, data, size);
memcpy(midx_buf.ptr + size, hash, GIT_HASH_SHA1_SIZE);
memcpy(oid.id, hash, GIT_OID_SHA1_SIZE);
} else {
git_str_attach_notowned(&midx_buf, (char *)data, size);
}
if (git_midx_parse(&idx, (const unsigned char *)git_str_cstr(&midx_buf), git_str_len(&midx_buf)) < 0)
goto cleanup;
/* Search for any oid, just to exercise that codepath. */
if (git_midx_entry_find(&e, &idx, &oid, GIT_OID_SHA1_HEXSIZE) < 0)
goto cleanup;
cleanup:
git_midx_close(&idx);
git_str_dispose(&midx_buf);
return 0;
}
| libgit2-main | fuzzers/midx_fuzzer.c |
/*
* libgit2 commit-graph fuzzer target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include "git2.h"
#include "common.h"
#include "str.h"
#include "futils.h"
#include "hash.h"
#include "commit_graph.h"
#include "standalone_driver.h"
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
GIT_UNUSED(argc);
GIT_UNUSED(argv);
if (git_libgit2_init() < 0) {
fprintf(stderr, "Failed to initialize libgit2\n");
abort();
}
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
git_commit_graph_file file = {{0}};
git_commit_graph_entry e;
git_str commit_graph_buf = GIT_STR_INIT;
unsigned char hash[GIT_HASH_SHA1_SIZE];
git_oid oid = GIT_OID_NONE;
bool append_hash = false;
if (size < 4)
return 0;
/*
* If the first byte in the stream has the high bit set, append the
* SHA1 hash so that the file is somewhat valid.
*/
append_hash = *data & 0x80;
/* Keep a 4-byte alignment to avoid unaligned accesses. */
data += 4;
size -= 4;
if (append_hash) {
if (git_str_init(&commit_graph_buf, size + GIT_HASH_SHA1_SIZE) < 0)
goto cleanup;
if (git_hash_buf(hash, data, size, GIT_HASH_ALGORITHM_SHA1) < 0) {
fprintf(stderr, "Failed to compute the SHA1 hash\n");
abort();
}
memcpy(commit_graph_buf.ptr, data, size);
memcpy(commit_graph_buf.ptr + size, hash, GIT_HASH_SHA1_SIZE);
memcpy(oid.id, hash, GIT_OID_SHA1_SIZE);
} else {
git_str_attach_notowned(&commit_graph_buf, (char *)data, size);
}
if (git_commit_graph_file_parse(
&file,
(const unsigned char *)git_str_cstr(&commit_graph_buf),
git_str_len(&commit_graph_buf))
< 0)
goto cleanup;
/* Search for any oid, just to exercise that codepath. */
if (git_commit_graph_entry_find(&e, &file, &oid, GIT_OID_SHA1_HEXSIZE) < 0)
goto cleanup;
cleanup:
git_commit_graph_file_close(&file);
git_str_dispose(&commit_graph_buf);
return 0;
}
| libgit2-main | fuzzers/commit_graph_fuzzer.c |
/*
* libgit2 config file parser fuzz target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2.h"
#include "config_backend.h"
#include "standalone_driver.h"
#define UNUSED(x) (void)(x)
static int foreach_cb(const git_config_entry *entry, void *payload)
{
UNUSED(entry);
UNUSED(payload);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
UNUSED(argc);
UNUSED(argv);
if (git_libgit2_init() < 0)
abort();
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
git_config *cfg = NULL;
git_config_backend *backend = NULL;
int err = 0;
if ((err = git_config_new(&cfg)) != 0) {
goto out;
}
if ((err = git_config_backend_from_string(&backend, (const char*)data, size)) != 0) {
goto out;
}
if ((err = git_config_add_backend(cfg, backend, 0, NULL, 0)) != 0) {
goto out;
}
/* Now owned by the config */
backend = NULL;
git_config_foreach(cfg, foreach_cb, NULL);
out:
git_config_backend_free(backend);
git_config_free(cfg);
return 0;
}
| libgit2-main | fuzzers/config_file_fuzzer.c |
/*
* libgit2 packfile fuzzer target.
*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include "git2.h"
#include "git2/sys/mempack.h"
#include "common.h"
#include "str.h"
#include "standalone_driver.h"
static git_odb *odb = NULL;
static git_odb_backend *mempack = NULL;
/* Arbitrary object to seed the ODB. */
static const unsigned char base_obj[] = { 07, 076 };
static const unsigned int base_obj_len = 2;
int LLVMFuzzerInitialize(int *argc, char ***argv)
{
GIT_UNUSED(argc);
GIT_UNUSED(argv);
if (git_libgit2_init() < 0) {
fprintf(stderr, "Failed to initialize libgit2\n");
abort();
}
if (git_libgit2_opts(GIT_OPT_SET_PACK_MAX_OBJECTS, 10000000) < 0) {
fprintf(stderr, "Failed to limit maximum pack object count\n");
abort();
}
#ifdef GIT_EXPERIMENTAL_SHA256
if (git_odb_new(&odb, NULL) < 0) {
fprintf(stderr, "Failed to create the odb\n");
abort();
}
#else
if (git_odb_new(&odb) < 0) {
fprintf(stderr, "Failed to create the odb\n");
abort();
}
#endif
if (git_mempack_new(&mempack) < 0) {
fprintf(stderr, "Failed to create the mempack\n");
abort();
}
if (git_odb_add_backend(odb, mempack, 999) < 0) {
fprintf(stderr, "Failed to add the mempack\n");
abort();
}
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
git_indexer_progress stats = {0, 0};
git_indexer *indexer = NULL;
git_str path = GIT_STR_INIT;
git_oid oid;
bool append_hash = false;
if (size == 0)
return 0;
if (!odb || !mempack) {
fprintf(stderr, "Global state not initialized\n");
abort();
}
git_mempack_reset(mempack);
if (git_odb_write(&oid, odb, base_obj, base_obj_len, GIT_OBJECT_BLOB) < 0) {
fprintf(stderr, "Failed to add an object to the odb\n");
abort();
}
if (git_indexer_new(&indexer, ".", 0, odb, NULL) < 0) {
fprintf(stderr, "Failed to create the indexer: %s\n",
git_error_last()->message);
abort();
}
/*
* If the first byte in the stream has the high bit set, append the
* SHA1 hash so that the packfile is somewhat valid.
*/
append_hash = *data & 0x80;
++data;
--size;
if (git_indexer_append(indexer, data, size, &stats) < 0)
goto cleanup;
if (append_hash) {
#ifdef GIT_EXPERIMENTAL_SHA256
if (git_odb_hash(&oid, data, size, GIT_OBJECT_BLOB, GIT_OID_SHA1) < 0) {
fprintf(stderr, "Failed to compute the SHA1 hash\n");
abort();
}
#else
if (git_odb_hash(&oid, data, size, GIT_OBJECT_BLOB) < 0) {
fprintf(stderr, "Failed to compute the SHA1 hash\n");
abort();
}
#endif
if (git_indexer_append(indexer, &oid.id, GIT_OID_SHA1_SIZE, &stats) < 0) {
goto cleanup;
}
}
if (git_indexer_commit(indexer, &stats) < 0)
goto cleanup;
if (git_str_printf(&path, "pack-%s.idx", git_indexer_name(indexer)) < 0)
goto cleanup;
p_unlink(git_str_cstr(&path));
git_str_clear(&path);
if (git_str_printf(&path, "pack-%s.pack", git_indexer_name(indexer)) < 0)
goto cleanup;
p_unlink(git_str_cstr(&path));
cleanup:
git_mempack_reset(mempack);
git_indexer_free(indexer);
git_str_dispose(&path);
return 0;
}
| libgit2-main | fuzzers/packfile_fuzzer.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#if !defined(GIT_THREADS)
#define TLSDATA_MAX 16
typedef struct {
void *value;
void (GIT_SYSTEM_CALL *destroy_fn)(void *);
} tlsdata_value;
static tlsdata_value tlsdata_values[TLSDATA_MAX];
static int tlsdata_cnt = 0;
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
if (tlsdata_cnt >= TLSDATA_MAX)
return -1;
tlsdata_values[tlsdata_cnt].value = NULL;
tlsdata_values[tlsdata_cnt].destroy_fn = destroy_fn;
*key = tlsdata_cnt;
tlsdata_cnt++;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (key < 0 || key > tlsdata_cnt)
return -1;
tlsdata_values[key].value = value;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
if (key < 0 || key > tlsdata_cnt)
return NULL;
return tlsdata_values[key].value;
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
void *value;
void (*destroy_fn)(void *) = NULL;
if (key < 0 || key > tlsdata_cnt)
return -1;
value = tlsdata_values[key].value;
destroy_fn = tlsdata_values[key].destroy_fn;
tlsdata_values[key].value = NULL;
tlsdata_values[key].destroy_fn = NULL;
if (value && destroy_fn)
destroy_fn(value);
return 0;
}
#elif defined(GIT_WIN32)
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
DWORD fls_index = FlsAlloc(destroy_fn);
if (fls_index == FLS_OUT_OF_INDEXES)
return -1;
*key = fls_index;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (!FlsSetValue(key, value))
return -1;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
return FlsGetValue(key);
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
if (!FlsFree(key))
return -1;
return 0;
}
#elif defined(_POSIX_THREADS)
int git_tlsdata_init(git_tlsdata_key *key, void (GIT_SYSTEM_CALL *destroy_fn)(void *))
{
if (pthread_key_create(key, destroy_fn) != 0)
return -1;
return 0;
}
int git_tlsdata_set(git_tlsdata_key key, void *value)
{
if (pthread_setspecific(key, value) != 0)
return -1;
return 0;
}
void *git_tlsdata_get(git_tlsdata_key key)
{
return pthread_getspecific(key);
}
int git_tlsdata_dispose(git_tlsdata_key key)
{
if (pthread_key_delete(key) != 0)
return -1;
return 0;
}
#else
# error unknown threading model
#endif
| libgit2-main | src/util/thread.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*
* Do shell-style pattern matching for ?, \, [], and * characters.
* It is 8bit clean.
*
* Written by Rich $alz, mirror!rs, Wed Nov 26 19:03:17 EST 1986.
* Rich $alz is now <rsalz@bbn.com>.
*
* Modified by Wayne Davison to special-case '/' matching, to make '**'
* work differently than '*', and to fix the character-class code.
*
* Imported from git.git.
*/
#include "wildmatch.h"
#define GIT_SPACE 0x01
#define GIT_DIGIT 0x02
#define GIT_ALPHA 0x04
#define GIT_GLOB_SPECIAL 0x08
#define GIT_REGEX_SPECIAL 0x10
#define GIT_PATHSPEC_MAGIC 0x20
#define GIT_CNTRL 0x40
#define GIT_PUNCT 0x80
enum {
S = GIT_SPACE,
A = GIT_ALPHA,
D = GIT_DIGIT,
G = GIT_GLOB_SPECIAL, /* *, ?, [, \\ */
R = GIT_REGEX_SPECIAL, /* $, (, ), +, ., ^, {, | */
P = GIT_PATHSPEC_MAGIC, /* other non-alnum, except for ] and } */
X = GIT_CNTRL,
U = GIT_PUNCT,
Z = GIT_CNTRL | GIT_SPACE
};
static const unsigned char sane_ctype[256] = {
X, X, X, X, X, X, X, X, X, Z, Z, X, X, Z, X, X, /* 0.. 15 */
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 16.. 31 */
S, P, P, P, R, P, P, P, R, R, G, R, P, P, R, P, /* 32.. 47 */
D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, G, /* 48.. 63 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 64.. 79 */
A, A, A, A, A, A, A, A, A, A, A, G, G, U, R, P, /* 80.. 95 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 96..111 */
A, A, A, A, A, A, A, A, A, A, A, R, R, U, P, X, /* 112..127 */
/* Nothing in the 128.. range */
};
#define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
#define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
typedef unsigned char uchar;
/* What character marks an inverted character class? */
#define NEGATE_CLASS '!'
#define NEGATE_CLASS2 '^'
#define CC_EQ(class, len, litmatch) ((len) == sizeof (litmatch)-1 \
&& *(class) == *(litmatch) \
&& strncmp((char*)class, litmatch, len) == 0)
#if defined STDC_HEADERS || !defined isascii
# define ISASCII(c) 1
#else
# define ISASCII(c) isascii(c)
#endif
#ifdef isblank
# define ISBLANK(c) (ISASCII(c) && isblank(c))
#else
# define ISBLANK(c) ((c) == ' ' || (c) == '\t')
#endif
#ifdef isgraph
# define ISGRAPH(c) (ISASCII(c) && isgraph(c))
#else
# define ISGRAPH(c) (ISASCII(c) && isprint(c) && !isspace(c))
#endif
#define ISPRINT(c) (ISASCII(c) && isprint(c))
#define ISDIGIT(c) (ISASCII(c) && isdigit(c))
#define ISALNUM(c) (ISASCII(c) && isalnum(c))
#define ISALPHA(c) (ISASCII(c) && isalpha(c))
#define ISCNTRL(c) (ISASCII(c) && iscntrl(c))
#define ISLOWER(c) (ISASCII(c) && islower(c))
#define ISPUNCT(c) (ISASCII(c) && ispunct(c))
#define ISSPACE(c) (ISASCII(c) && isspace(c))
#define ISUPPER(c) (ISASCII(c) && isupper(c))
#define ISXDIGIT(c) (ISASCII(c) && isxdigit(c))
/* Match pattern "p" against "text" */
static int dowild(const uchar *p, const uchar *text, unsigned int flags)
{
uchar p_ch;
const uchar *pattern = p;
for ( ; (p_ch = *p) != '\0'; text++, p++) {
int matched, match_slash, negated;
uchar t_ch, prev_ch;
if ((t_ch = *text) == '\0' && p_ch != '*')
return WM_ABORT_ALL;
if ((flags & WM_CASEFOLD) && ISUPPER(t_ch))
t_ch = tolower(t_ch);
if ((flags & WM_CASEFOLD) && ISUPPER(p_ch))
p_ch = tolower(p_ch);
switch (p_ch) {
case '\\':
/* Literal match with following character. Note that the test
* in "default" handles the p[1] == '\0' failure case. */
p_ch = *++p;
/* FALLTHROUGH */
default:
if (t_ch != p_ch)
return WM_NOMATCH;
continue;
case '?':
/* Match anything but '/'. */
if ((flags & WM_PATHNAME) && t_ch == '/')
return WM_NOMATCH;
continue;
case '*':
if (*++p == '*') {
const uchar *prev_p = p - 2;
while (*++p == '*') {}
if (!(flags & WM_PATHNAME))
/* without WM_PATHNAME, '*' == '**' */
match_slash = 1;
else if ((prev_p < pattern || *prev_p == '/') &&
(*p == '\0' || *p == '/' ||
(p[0] == '\\' && p[1] == '/'))) {
/*
* Assuming we already match 'foo/' and are at
* <star star slash>, just assume it matches
* nothing and go ahead match the rest of the
* pattern with the remaining string. This
* helps make foo/<*><*>/bar (<> because
* otherwise it breaks C comment syntax) match
* both foo/bar and foo/a/bar.
*/
if (p[0] == '/' &&
dowild(p + 1, text, flags) == WM_MATCH)
return WM_MATCH;
match_slash = 1;
} else /* WM_PATHNAME is set */
match_slash = 0;
} else
/* without WM_PATHNAME, '*' == '**' */
match_slash = flags & WM_PATHNAME ? 0 : 1;
if (*p == '\0') {
/* Trailing "**" matches everything. Trailing "*" matches
* only if there are no more slash characters. */
if (!match_slash) {
if (strchr((char*)text, '/') != NULL)
return WM_NOMATCH;
}
return WM_MATCH;
} else if (!match_slash && *p == '/') {
/*
* _one_ asterisk followed by a slash
* with WM_PATHNAME matches the next
* directory
*/
const char *slash = strchr((char*)text, '/');
if (!slash)
return WM_NOMATCH;
text = (const uchar*)slash;
/* the slash is consumed by the top-level for loop */
break;
}
while (1) {
if (t_ch == '\0')
break;
/*
* Try to advance faster when an asterisk is
* followed by a literal. We know in this case
* that the string before the literal
* must belong to "*".
* If match_slash is false, do not look past
* the first slash as it cannot belong to '*'.
*/
if (!is_glob_special(*p)) {
p_ch = *p;
if ((flags & WM_CASEFOLD) && ISUPPER(p_ch))
p_ch = tolower(p_ch);
while ((t_ch = *text) != '\0' &&
(match_slash || t_ch != '/')) {
if ((flags & WM_CASEFOLD) && ISUPPER(t_ch))
t_ch = tolower(t_ch);
if (t_ch == p_ch)
break;
text++;
}
if (t_ch != p_ch)
return WM_NOMATCH;
}
if ((matched = dowild(p, text, flags)) != WM_NOMATCH) {
if (!match_slash || matched != WM_ABORT_TO_STARSTAR)
return matched;
} else if (!match_slash && t_ch == '/')
return WM_ABORT_TO_STARSTAR;
t_ch = *++text;
}
return WM_ABORT_ALL;
case '[':
p_ch = *++p;
#ifdef NEGATE_CLASS2
if (p_ch == NEGATE_CLASS2)
p_ch = NEGATE_CLASS;
#endif
/* Assign literal 1/0 because of "matched" comparison. */
negated = p_ch == NEGATE_CLASS ? 1 : 0;
if (negated) {
/* Inverted character class. */
p_ch = *++p;
}
prev_ch = 0;
matched = 0;
do {
if (!p_ch)
return WM_ABORT_ALL;
if (p_ch == '\\') {
p_ch = *++p;
if (!p_ch)
return WM_ABORT_ALL;
if (t_ch == p_ch)
matched = 1;
} else if (p_ch == '-' && prev_ch && p[1] && p[1] != ']') {
p_ch = *++p;
if (p_ch == '\\') {
p_ch = *++p;
if (!p_ch)
return WM_ABORT_ALL;
}
if (t_ch <= p_ch && t_ch >= prev_ch)
matched = 1;
else if ((flags & WM_CASEFOLD) && ISLOWER(t_ch)) {
uchar t_ch_upper = toupper(t_ch);
if (t_ch_upper <= p_ch && t_ch_upper >= prev_ch)
matched = 1;
}
p_ch = 0; /* This makes "prev_ch" get set to 0. */
} else if (p_ch == '[' && p[1] == ':') {
const uchar *s;
int i;
for (s = p += 2; (p_ch = *p) && p_ch != ']'; p++) {} /*SHARED ITERATOR*/
if (!p_ch)
return WM_ABORT_ALL;
i = (int)(p - s - 1);
if (i < 0 || p[-1] != ':') {
/* Didn't find ":]", so treat like a normal set. */
p = s - 2;
p_ch = '[';
if (t_ch == p_ch)
matched = 1;
continue;
}
if (CC_EQ(s,i, "alnum")) {
if (ISALNUM(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "alpha")) {
if (ISALPHA(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "blank")) {
if (ISBLANK(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "cntrl")) {
if (ISCNTRL(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "digit")) {
if (ISDIGIT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "graph")) {
if (ISGRAPH(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "lower")) {
if (ISLOWER(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "print")) {
if (ISPRINT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "punct")) {
if (ISPUNCT(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "space")) {
if (ISSPACE(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "upper")) {
if (ISUPPER(t_ch))
matched = 1;
else if ((flags & WM_CASEFOLD) && ISLOWER(t_ch))
matched = 1;
} else if (CC_EQ(s,i, "xdigit")) {
if (ISXDIGIT(t_ch))
matched = 1;
} else /* malformed [:class:] string */
return WM_ABORT_ALL;
p_ch = 0; /* This makes "prev_ch" get set to 0. */
} else if (t_ch == p_ch)
matched = 1;
} while (prev_ch = p_ch, (p_ch = *++p) != ']');
if (matched == negated ||
((flags & WM_PATHNAME) && t_ch == '/'))
return WM_NOMATCH;
continue;
}
}
return *text ? WM_NOMATCH : WM_MATCH;
}
/* Match the "pattern" against the "text" string. */
int wildmatch(const char *pattern, const char *text, unsigned int flags)
{
return dowild((const uchar*)pattern, (const uchar*)text, flags);
}
| libgit2-main | src/util/wildmatch.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
/**
* An array-of-pointers implementation of Python's Timsort
* Based on code by Christopher Swenson under the MIT license
*
* Copyright (c) 2010 Christopher Swenson
* Copyright (c) 2011 Vicent Marti
*/
#ifndef MAX
# define MAX(x,y) (((x) > (y) ? (x) : (y)))
#endif
#ifndef MIN
# define MIN(x,y) (((x) < (y) ? (x) : (y)))
#endif
static int binsearch(
void **dst, const void *x, size_t size, git__sort_r_cmp cmp, void *payload)
{
int l, c, r;
void *lx, *cx;
l = 0;
r = (int)size - 1;
c = r >> 1;
lx = dst[l];
/* check for beginning conditions */
if (cmp(x, lx, payload) < 0)
return 0;
else if (cmp(x, lx, payload) == 0) {
int i = 1;
while (cmp(x, dst[i], payload) == 0)
i++;
return i;
}
/* guaranteed not to be >= rx */
cx = dst[c];
while (1) {
const int val = cmp(x, cx, payload);
if (val < 0) {
if (c - l <= 1) return c;
r = c;
} else if (val > 0) {
if (r - c <= 1) return c + 1;
l = c;
lx = cx;
} else {
do {
cx = dst[++c];
} while (cmp(x, cx, payload) == 0);
return c;
}
c = l + ((r - l) >> 1);
cx = dst[c];
}
}
/* Binary insertion sort, but knowing that the first "start" entries are sorted. Used in timsort. */
static void bisort(
void **dst, size_t start, size_t size, git__sort_r_cmp cmp, void *payload)
{
size_t i;
void *x;
int location;
for (i = start; i < size; i++) {
int j;
/* If this entry is already correct, just move along */
if (cmp(dst[i - 1], dst[i], payload) <= 0)
continue;
/* Else we need to find the right place, shift everything over, and squeeze in */
x = dst[i];
location = binsearch(dst, x, i, cmp, payload);
for (j = (int)i - 1; j >= location; j--) {
dst[j + 1] = dst[j];
}
dst[location] = x;
}
}
/* timsort implementation, based on timsort.txt */
struct tsort_run {
ssize_t start;
ssize_t length;
};
struct tsort_store {
size_t alloc;
git__sort_r_cmp cmp;
void *payload;
void **storage;
};
static void reverse_elements(void **dst, ssize_t start, ssize_t end)
{
while (start < end) {
void *tmp = dst[start];
dst[start] = dst[end];
dst[end] = tmp;
start++;
end--;
}
}
static ssize_t count_run(
void **dst, ssize_t start, ssize_t size, struct tsort_store *store)
{
ssize_t curr = start + 2;
if (size - start == 1)
return 1;
if (start >= size - 2) {
if (store->cmp(dst[size - 2], dst[size - 1], store->payload) > 0) {
void *tmp = dst[size - 1];
dst[size - 1] = dst[size - 2];
dst[size - 2] = tmp;
}
return 2;
}
if (store->cmp(dst[start], dst[start + 1], store->payload) <= 0) {
while (curr < size - 1 &&
store->cmp(dst[curr - 1], dst[curr], store->payload) <= 0)
curr++;
return curr - start;
} else {
while (curr < size - 1 &&
store->cmp(dst[curr - 1], dst[curr], store->payload) > 0)
curr++;
/* reverse in-place */
reverse_elements(dst, start, curr - 1);
return curr - start;
}
}
static size_t compute_minrun(size_t n)
{
int r = 0;
while (n >= 64) {
r |= n & 1;
n >>= 1;
}
return n + r;
}
static int check_invariant(struct tsort_run *stack, ssize_t stack_curr)
{
if (stack_curr < 2)
return 1;
else if (stack_curr == 2) {
const ssize_t A = stack[stack_curr - 2].length;
const ssize_t B = stack[stack_curr - 1].length;
return (A > B);
} else {
const ssize_t A = stack[stack_curr - 3].length;
const ssize_t B = stack[stack_curr - 2].length;
const ssize_t C = stack[stack_curr - 1].length;
return !((A <= B + C) || (B <= C));
}
}
static int resize(struct tsort_store *store, size_t new_size)
{
if (store->alloc < new_size) {
void **tempstore;
tempstore = git__reallocarray(store->storage, new_size, sizeof(void *));
/**
* Do not propagate on OOM; this will abort the sort and
* leave the array unsorted, but no error code will be
* raised
*/
if (tempstore == NULL)
return -1;
store->storage = tempstore;
store->alloc = new_size;
}
return 0;
}
static void merge(void **dst, const struct tsort_run *stack, ssize_t stack_curr, struct tsort_store *store)
{
const ssize_t A = stack[stack_curr - 2].length;
const ssize_t B = stack[stack_curr - 1].length;
const ssize_t curr = stack[stack_curr - 2].start;
void **storage;
ssize_t i, j, k;
if (resize(store, MIN(A, B)) < 0)
return;
storage = store->storage;
/* left merge */
if (A < B) {
memcpy(storage, &dst[curr], A * sizeof(void *));
i = 0;
j = curr + A;
for (k = curr; k < curr + A + B; k++) {
if ((i < A) && (j < curr + A + B)) {
if (store->cmp(storage[i], dst[j], store->payload) <= 0)
dst[k] = storage[i++];
else
dst[k] = dst[j++];
} else if (i < A) {
dst[k] = storage[i++];
} else
dst[k] = dst[j++];
}
} else {
memcpy(storage, &dst[curr + A], B * sizeof(void *));
i = B - 1;
j = curr + A - 1;
for (k = curr + A + B - 1; k >= curr; k--) {
if ((i >= 0) && (j >= curr)) {
if (store->cmp(dst[j], storage[i], store->payload) > 0)
dst[k] = dst[j--];
else
dst[k] = storage[i--];
} else if (i >= 0)
dst[k] = storage[i--];
else
dst[k] = dst[j--];
}
}
}
static ssize_t collapse(void **dst, struct tsort_run *stack, ssize_t stack_curr, struct tsort_store *store, ssize_t size)
{
ssize_t A, B, C;
while (1) {
/* if the stack only has one thing on it, we are done with the collapse */
if (stack_curr <= 1)
break;
/* if this is the last merge, just do it */
if ((stack_curr == 2) && (stack[0].length + stack[1].length == size)) {
merge(dst, stack, stack_curr, store);
stack[0].length += stack[1].length;
stack_curr--;
break;
}
/* check if the invariant is off for a stack of 2 elements */
else if ((stack_curr == 2) && (stack[0].length <= stack[1].length)) {
merge(dst, stack, stack_curr, store);
stack[0].length += stack[1].length;
stack_curr--;
break;
}
else if (stack_curr == 2)
break;
A = stack[stack_curr - 3].length;
B = stack[stack_curr - 2].length;
C = stack[stack_curr - 1].length;
/* check first invariant */
if (A <= B + C) {
if (A < C) {
merge(dst, stack, stack_curr - 1, store);
stack[stack_curr - 3].length += stack[stack_curr - 2].length;
stack[stack_curr - 2] = stack[stack_curr - 1];
stack_curr--;
} else {
merge(dst, stack, stack_curr, store);
stack[stack_curr - 2].length += stack[stack_curr - 1].length;
stack_curr--;
}
} else if (B <= C) {
merge(dst, stack, stack_curr, store);
stack[stack_curr - 2].length += stack[stack_curr - 1].length;
stack_curr--;
} else
break;
}
return stack_curr;
}
#define PUSH_NEXT() do {\
len = count_run(dst, curr, size, store);\
run = minrun;\
if (run > (ssize_t)size - curr) run = size - curr;\
if (run > len) {\
bisort(&dst[curr], len, run, cmp, payload);\
len = run;\
}\
run_stack[stack_curr].start = curr;\
run_stack[stack_curr++].length = len;\
curr += len;\
if (curr == (ssize_t)size) {\
/* finish up */ \
while (stack_curr > 1) { \
merge(dst, run_stack, stack_curr, store); \
run_stack[stack_curr - 2].length += run_stack[stack_curr - 1].length; \
stack_curr--; \
} \
if (store->storage != NULL) {\
git__free(store->storage);\
store->storage = NULL;\
}\
return;\
}\
}\
while (0)
void git__tsort_r(
void **dst, size_t size, git__sort_r_cmp cmp, void *payload)
{
struct tsort_store _store, *store = &_store;
struct tsort_run run_stack[128];
ssize_t stack_curr = 0;
ssize_t len, run;
ssize_t curr = 0;
ssize_t minrun;
if (size < 64) {
bisort(dst, 1, size, cmp, payload);
return;
}
/* compute the minimum run length */
minrun = (ssize_t)compute_minrun(size);
/* temporary storage for merges */
store->alloc = 0;
store->storage = NULL;
store->cmp = cmp;
store->payload = payload;
PUSH_NEXT();
PUSH_NEXT();
PUSH_NEXT();
while (1) {
if (!check_invariant(run_stack, stack_curr)) {
stack_curr = collapse(dst, run_stack, stack_curr, store, size);
continue;
}
PUSH_NEXT();
}
}
static int tsort_r_cmp(const void *a, const void *b, void *payload)
{
return ((git__tsort_cmp)payload)(a, b);
}
void git__tsort(void **dst, size_t size, git__tsort_cmp cmp)
{
git__tsort_r(dst, size, tsort_r_cmp, cmp);
}
| libgit2-main | src/util/tsort.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#include "runtime.h"
static git_runtime_shutdown_fn shutdown_callback[32];
static git_atomic32 shutdown_callback_count;
static git_atomic32 init_count;
static int init_common(git_runtime_init_fn init_fns[], size_t cnt)
{
size_t i;
int ret;
/* Initialize subsystems that have global state */
for (i = 0; i < cnt; i++) {
if ((ret = init_fns[i]()) != 0)
break;
}
GIT_MEMORY_BARRIER;
return ret;
}
static void shutdown_common(void)
{
git_runtime_shutdown_fn cb;
int pos;
for (pos = git_atomic32_get(&shutdown_callback_count);
pos > 0;
pos = git_atomic32_dec(&shutdown_callback_count)) {
cb = git_atomic_swap(shutdown_callback[pos - 1], NULL);
if (cb != NULL)
cb();
}
}
int git_runtime_shutdown_register(git_runtime_shutdown_fn callback)
{
int count = git_atomic32_inc(&shutdown_callback_count);
if (count > (int)ARRAY_SIZE(shutdown_callback) || count == 0) {
git_error_set(GIT_ERROR_INVALID,
"too many shutdown callbacks registered");
git_atomic32_dec(&shutdown_callback_count);
return -1;
}
shutdown_callback[count - 1] = callback;
return 0;
}
#if defined(GIT_THREADS) && defined(GIT_WIN32)
/*
* On Win32, we use a spinlock to provide locking semantics. This is
* lighter-weight than a proper critical section.
*/
static volatile LONG init_spinlock = 0;
GIT_INLINE(int) init_lock(void)
{
while (InterlockedCompareExchange(&init_spinlock, 1, 0)) { Sleep(0); }
return 0;
}
GIT_INLINE(int) init_unlock(void)
{
InterlockedExchange(&init_spinlock, 0);
return 0;
}
#elif defined(GIT_THREADS) && defined(_POSIX_THREADS)
/*
* On POSIX, we need to use a proper mutex for locking. We might prefer
* a spinlock here, too, but there's no static initializer for a
* pthread_spinlock_t.
*/
static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
GIT_INLINE(int) init_lock(void)
{
return pthread_mutex_lock(&init_mutex) == 0 ? 0 : -1;
}
GIT_INLINE(int) init_unlock(void)
{
return pthread_mutex_unlock(&init_mutex) == 0 ? 0 : -1;
}
#elif defined(GIT_THREADS)
# error unknown threading model
#else
# define init_lock() git__noop()
# define init_unlock() git__noop()
#endif
int git_runtime_init(git_runtime_init_fn init_fns[], size_t cnt)
{
int ret;
if (init_lock() < 0)
return -1;
/* Only do work on a 0 -> 1 transition of the refcount */
if ((ret = git_atomic32_inc(&init_count)) == 1) {
if (init_common(init_fns, cnt) < 0)
ret = -1;
}
if (init_unlock() < 0)
return -1;
return ret;
}
int git_runtime_init_count(void)
{
int ret;
if (init_lock() < 0)
return -1;
ret = git_atomic32_get(&init_count);
if (init_unlock() < 0)
return -1;
return ret;
}
int git_runtime_shutdown(void)
{
int ret;
/* Enter the lock */
if (init_lock() < 0)
return -1;
/* Only do work on a 1 -> 0 transition of the refcount */
if ((ret = git_atomic32_dec(&init_count)) == 0)
shutdown_common();
/* Exit the lock */
if (init_unlock() < 0)
return -1;
return ret;
}
| libgit2-main | src/util/runtime.c |
/* Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
#include "git2_util.h"
#include "rand.h"
#include "runtime.h"
#if defined(GIT_RAND_GETENTROPY)
# include <sys/random.h>
#endif
static uint64_t state[4];
static git_mutex state_lock;
typedef union {
double f;
uint64_t d;
} bits;
#if defined(GIT_WIN32)
GIT_INLINE(int) getseed(uint64_t *seed)
{
HCRYPTPROV provider;
SYSTEMTIME systemtime;
FILETIME filetime, idletime, kerneltime, usertime;
bits convert;
if (CryptAcquireContext(&provider, 0, 0, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
BOOL success = CryptGenRandom(provider, sizeof(uint64_t), (void *)seed);
CryptReleaseContext(provider, 0);
if (success)
return 0;
}
GetSystemTime(&systemtime);
if (!SystemTimeToFileTime(&systemtime, &filetime)) {
git_error_set(GIT_ERROR_OS, "could not get time for random seed");
return -1;
}
/* Fall-through: generate a seed from the time and system state */
*seed = 0;
*seed |= ((uint64_t)filetime.dwLowDateTime << 32);
*seed |= ((uint64_t)filetime.dwHighDateTime);
GetSystemTimes(&idletime, &kerneltime, &usertime);
*seed ^= ((uint64_t)idletime.dwLowDateTime << 32);
*seed ^= ((uint64_t)kerneltime.dwLowDateTime);
*seed ^= ((uint64_t)usertime.dwLowDateTime << 32);
*seed ^= ((uint64_t)idletime.dwHighDateTime);
*seed ^= ((uint64_t)kerneltime.dwHighDateTime << 12);
*seed ^= ((uint64_t)usertime.dwHighDateTime << 24);
*seed ^= ((uint64_t)GetCurrentProcessId() << 32);
*seed ^= ((uint64_t)GetCurrentThreadId() << 48);
convert.f = git__timer(); *seed ^= (convert.d);
/* Mix in the addresses of some functions and variables */
*seed ^= (((uint64_t)((uintptr_t)seed) << 32));
*seed ^= (((uint64_t)((uintptr_t)&errno)));
return 0;
}
#else
GIT_INLINE(int) getseed(uint64_t *seed)
{
struct timeval tv;
double loadavg[3];
bits convert;
int fd;
# if defined(GIT_RAND_GETENTROPY)
GIT_UNUSED((fd = 0));
if (getentropy(seed, sizeof(uint64_t)) == 0)
return 0;
# else
/*
* Try to read from /dev/urandom; most modern systems will have
* this, but we may be chrooted, etc, so it's not a fatal error
*/
if ((fd = open("/dev/urandom", O_RDONLY)) >= 0) {
ssize_t ret = read(fd, seed, sizeof(uint64_t));
close(fd);
if (ret == (ssize_t)sizeof(uint64_t))
return 0;
}
# endif
/* Fall-through: generate a seed from the time and system state */
if (gettimeofday(&tv, NULL) < 0) {
git_error_set(GIT_ERROR_OS, "could get time for random seed");
return -1;
}
*seed = 0;
*seed |= ((uint64_t)tv.tv_usec << 40);
*seed |= ((uint64_t)tv.tv_sec);
*seed ^= ((uint64_t)getpid() << 48);
*seed ^= ((uint64_t)getppid() << 32);
*seed ^= ((uint64_t)getpgid(0) << 28);
*seed ^= ((uint64_t)getsid(0) << 16);
*seed ^= ((uint64_t)getuid() << 8);
*seed ^= ((uint64_t)getgid());
# if defined(GIT_RAND_GETLOADAVG)
getloadavg(loadavg, 3);
convert.f = loadavg[0]; *seed ^= (convert.d >> 36);
convert.f = loadavg[1]; *seed ^= (convert.d);
convert.f = loadavg[2]; *seed ^= (convert.d >> 16);
# else
GIT_UNUSED(loadavg[0]);
# endif
convert.f = git__timer(); *seed ^= (convert.d);
/* Mix in the addresses of some variables */
*seed ^= ((uint64_t)((size_t)((void *)seed)) << 32);
*seed ^= ((uint64_t)((size_t)((void *)&errno)));
return 0;
}
#endif
static void git_rand_global_shutdown(void)
{
git_mutex_free(&state_lock);
}
int git_rand_global_init(void)
{
uint64_t seed = 0;
if (git_mutex_init(&state_lock) < 0 || getseed(&seed) < 0)
return -1;
if (!seed) {
git_error_set(GIT_ERROR_INTERNAL, "failed to generate random seed");
return -1;
}
git_rand_seed(seed);
git_runtime_shutdown_register(git_rand_global_shutdown);
return 0;
}
/*
* This is splitmix64. xoroshiro256** uses 256 bit seed; this is used
* to generate 256 bits of seed from the given 64, per the author's
* recommendation.
*/
GIT_INLINE(uint64_t) splitmix64(uint64_t *in)
{
uint64_t z;
*in += 0x9e3779b97f4a7c15;
z = *in;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
return z ^ (z >> 31);
}
void git_rand_seed(uint64_t seed)
{
uint64_t mixer;
mixer = seed;
git_mutex_lock(&state_lock);
state[0] = splitmix64(&mixer);
state[1] = splitmix64(&mixer);
state[2] = splitmix64(&mixer);
state[3] = splitmix64(&mixer);
git_mutex_unlock(&state_lock);
}
/* This is xoshiro256** 1.0, one of our all-purpose, rock-solid
generators. It has excellent (sub-ns) speed, a state (256 bits) that is
large enough for any parallel application, and it passes all tests we
are aware of.
For generating just floating-point numbers, xoshiro256+ is even faster.
The state must be seeded so that it is not everywhere zero. If you have
a 64-bit seed, we suggest to seed a splitmix64 generator and use its
output to fill s. */
GIT_INLINE(uint64_t) rotl(const uint64_t x, int k) {
return (x << k) | (x >> (64 - k));
}
uint64_t git_rand_next(void) {
uint64_t t, result;
git_mutex_lock(&state_lock);
result = rotl(state[1] * 5, 7) * 9;
t = state[1] << 17;
state[2] ^= state[0];
state[3] ^= state[1];
state[1] ^= state[2];
state[0] ^= state[3];
state[2] ^= t;
state[3] = rotl(state[3], 45);
git_mutex_unlock(&state_lock);
return result;
}
| libgit2-main | src/util/rand.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "util.h"
#include "git2_util.h"
#ifdef GIT_WIN32
# include "win32/utf-conv.h"
# include "win32/w32_buffer.h"
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef GIT_QSORT_S
# include <search.h>
# endif
#endif
#ifdef _MSC_VER
# include <Shlwapi.h>
#endif
#if defined(hpux) || defined(__hpux) || defined(_hpux)
# include <sys/pstat.h>
#endif
int git__strntol64(int64_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
const char *p;
int64_t n, nn, v;
int c, ovfl, neg, ndig;
p = nptr;
neg = 0;
n = 0;
ndig = 0;
ovfl = 0;
/*
* White space
*/
while (nptr_len && git__isspace(*p))
p++, nptr_len--;
if (!nptr_len)
goto Return;
/*
* Sign
*/
if (*p == '-' || *p == '+') {
if (*p == '-')
neg = 1;
p++;
nptr_len--;
}
if (!nptr_len)
goto Return;
/*
* Automatically detect the base if none was given to us.
* Right now, we assume that a number starting with '0x'
* is hexadecimal and a number starting with '0' is
* octal.
*/
if (base == 0) {
if (*p != '0')
base = 10;
else if (nptr_len > 2 && (p[1] == 'x' || p[1] == 'X'))
base = 16;
else
base = 8;
}
if (base < 0 || 36 < base)
goto Return;
/*
* Skip prefix of '0x'-prefixed hexadecimal numbers. There is no
* need to do the same for '0'-prefixed octal numbers as a
* leading '0' does not have any impact. Also, if we skip a
* leading '0' in such a string, then we may end up with no
* digits left and produce an error later on which isn't one.
*/
if (base == 16 && nptr_len > 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
p += 2;
nptr_len -= 2;
}
/*
* Non-empty sequence of digits
*/
for (; nptr_len > 0; p++,ndig++,nptr_len--) {
c = *p;
v = base;
if ('0'<=c && c<='9')
v = c - '0';
else if ('a'<=c && c<='z')
v = c - 'a' + 10;
else if ('A'<=c && c<='Z')
v = c - 'A' + 10;
if (v >= base)
break;
v = neg ? -v : v;
if (git__multiply_int64_overflow(&nn, n, base) || git__add_int64_overflow(&n, nn, v)) {
ovfl = 1;
/* Keep on iterating until the end of this number */
continue;
}
}
Return:
if (ndig == 0) {
git_error_set(GIT_ERROR_INVALID, "failed to convert string to long: not a number");
return -1;
}
if (endptr)
*endptr = p;
if (ovfl) {
git_error_set(GIT_ERROR_INVALID, "failed to convert string to long: overflow error");
return -1;
}
*result = n;
return 0;
}
int git__strntol32(int32_t *result, const char *nptr, size_t nptr_len, const char **endptr, int base)
{
const char *tmp_endptr;
int32_t tmp_int;
int64_t tmp_long;
int error;
if ((error = git__strntol64(&tmp_long, nptr, nptr_len, &tmp_endptr, base)) < 0)
return error;
tmp_int = tmp_long & 0xFFFFFFFF;
if (tmp_int != tmp_long) {
int len = (int)(tmp_endptr - nptr);
git_error_set(GIT_ERROR_INVALID, "failed to convert: '%.*s' is too large", len, nptr);
return -1;
}
*result = tmp_int;
if (endptr)
*endptr = tmp_endptr;
return error;
}
int git__strcasecmp(const char *a, const char *b)
{
while (*a && *b && git__tolower(*a) == git__tolower(*b))
++a, ++b;
return ((unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b));
}
int git__strcasesort_cmp(const char *a, const char *b)
{
int cmp = 0;
while (*a && *b) {
if (*a != *b) {
if (git__tolower(*a) != git__tolower(*b))
break;
/* use case in sort order even if not in equivalence */
if (!cmp)
cmp = (int)(*(const uint8_t *)a) - (int)(*(const uint8_t *)b);
}
++a, ++b;
}
if (*a || *b)
return (unsigned char)git__tolower(*a) - (unsigned char)git__tolower(*b);
return cmp;
}
int git__strncasecmp(const char *a, const char *b, size_t sz)
{
int al, bl;
do {
al = (unsigned char)git__tolower(*a);
bl = (unsigned char)git__tolower(*b);
++a, ++b;
} while (--sz && al && al == bl);
return al - bl;
}
void git__strntolower(char *str, size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
str[i] = (char)git__tolower(str[i]);
}
}
void git__strtolower(char *str)
{
git__strntolower(str, strlen(str));
}
GIT_INLINE(int) prefixcmp(const char *str, size_t str_n, const char *prefix, bool icase)
{
int s, p;
while (str_n--) {
s = (unsigned char)*str++;
p = (unsigned char)*prefix++;
if (icase) {
s = git__tolower(s);
p = git__tolower(p);
}
if (!p)
return 0;
if (s != p)
return s - p;
}
return (0 - *prefix);
}
int git__prefixcmp(const char *str, const char *prefix)
{
unsigned char s, p;
while (1) {
p = *prefix++;
s = *str++;
if (!p)
return 0;
if (s != p)
return s - p;
}
}
int git__prefixncmp(const char *str, size_t str_n, const char *prefix)
{
return prefixcmp(str, str_n, prefix, false);
}
int git__prefixcmp_icase(const char *str, const char *prefix)
{
return prefixcmp(str, SIZE_MAX, prefix, true);
}
int git__prefixncmp_icase(const char *str, size_t str_n, const char *prefix)
{
return prefixcmp(str, str_n, prefix, true);
}
int git__suffixcmp(const char *str, const char *suffix)
{
size_t a = strlen(str);
size_t b = strlen(suffix);
if (a < b)
return -1;
return strcmp(str + (a - b), suffix);
}
char *git__strtok(char **end, const char *sep)
{
char *ptr = *end;
while (*ptr && strchr(sep, *ptr))
++ptr;
if (*ptr) {
char *start = ptr;
*end = start + 1;
while (**end && !strchr(sep, **end))
++*end;
if (**end) {
**end = '\0';
++*end;
}
return start;
}
return NULL;
}
/* Similar to strtok, but does not collapse repeated tokens. */
char *git__strsep(char **end, const char *sep)
{
char *start = *end, *ptr = *end;
while (*ptr && !strchr(sep, *ptr))
++ptr;
if (*ptr) {
*end = ptr + 1;
*ptr = '\0';
return start;
}
return NULL;
}
size_t git__linenlen(const char *buffer, size_t buffer_len)
{
char *nl = memchr(buffer, '\n', buffer_len);
return nl ? (size_t)(nl - buffer) + 1 : buffer_len;
}
/*
* Adapted Not So Naive algorithm from http://www-igm.univ-mlv.fr/~lecroq/string/
*/
const void * git__memmem(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen)
{
const char *h, *n;
size_t j, k, l;
if (needlelen > haystacklen || !haystacklen || !needlelen)
return NULL;
h = (const char *) haystack,
n = (const char *) needle;
if (needlelen == 1)
return memchr(haystack, *n, haystacklen);
if (n[0] == n[1]) {
k = 2;
l = 1;
} else {
k = 1;
l = 2;
}
j = 0;
while (j <= haystacklen - needlelen) {
if (n[1] != h[j + 1]) {
j += k;
} else {
if (memcmp(n + 2, h + j + 2, needlelen - 2) == 0 &&
n[0] == h[j])
return h + j;
j += l;
}
}
return NULL;
}
void git__hexdump(const char *buffer, size_t len)
{
static const size_t LINE_WIDTH = 16;
size_t line_count, last_line, i, j;
const char *line;
line_count = (len / LINE_WIDTH);
last_line = (len % LINE_WIDTH);
for (i = 0; i < line_count; ++i) {
printf("%08" PRIxZ " ", (i * LINE_WIDTH));
line = buffer + (i * LINE_WIDTH);
for (j = 0; j < LINE_WIDTH; ++j, ++line) {
printf("%02x ", (unsigned char)*line & 0xFF);
if (j == (LINE_WIDTH / 2))
printf(" ");
}
printf(" |");
line = buffer + (i * LINE_WIDTH);
for (j = 0; j < LINE_WIDTH; ++j, ++line)
printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');
printf("|\n");
}
if (last_line > 0) {
printf("%08" PRIxZ " ", (line_count * LINE_WIDTH));
line = buffer + (line_count * LINE_WIDTH);
for (j = 0; j < last_line; ++j, ++line) {
printf("%02x ", (unsigned char)*line & 0xFF);
if (j == (LINE_WIDTH / 2))
printf(" ");
}
if (j < (LINE_WIDTH / 2))
printf(" ");
for (j = 0; j < (LINE_WIDTH - last_line); ++j)
printf(" ");
printf(" |");
line = buffer + (line_count * LINE_WIDTH);
for (j = 0; j < last_line; ++j, ++line)
printf("%c", (*line >= 32 && *line <= 126) ? *line : '.');
printf("|\n");
}
printf("\n");
}
#ifdef GIT_LEGACY_HASH
uint32_t git__hash(const void *key, int len, unsigned int seed)
{
const uint32_t m = 0x5bd1e995;
const int r = 24;
uint32_t h = seed ^ len;
const unsigned char *data = (const unsigned char *)key;
while(len >= 4) {
uint32_t k = *(uint32_t *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch(len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
#else
/*
Cross-platform version of Murmurhash3
http://code.google.com/p/smhasher/wiki/MurmurHash3
by Austin Appleby (aappleby@gmail.com)
This code is on the public domain.
*/
uint32_t git__hash(const void *key, int len, uint32_t seed)
{
#define MURMUR_BLOCK() {\
k1 *= c1; \
k1 = git__rotl(k1,11);\
k1 *= c2;\
h1 ^= k1;\
h1 = h1*3 + 0x52dce729;\
c1 = c1*5 + 0x7b7d159c;\
c2 = c2*5 + 0x6bce6396;\
}
const uint8_t *data = (const uint8_t*)key;
const int nblocks = len / 4;
const uint32_t *blocks = (const uint32_t *)(data + nblocks * 4);
const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);
uint32_t h1 = 0x971e137b ^ seed;
uint32_t k1;
uint32_t c1 = 0x95543787;
uint32_t c2 = 0x2ad7eb25;
int i;
for (i = -nblocks; i; i++) {
k1 = blocks[i];
MURMUR_BLOCK();
}
k1 = 0;
switch(len & 3) {
case 3: k1 ^= tail[2] << 16;
/* fall through */
case 2: k1 ^= tail[1] << 8;
/* fall through */
case 1: k1 ^= tail[0];
MURMUR_BLOCK();
}
h1 ^= len;
h1 ^= h1 >> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
#endif
/**
* A modified `bsearch` from the BSD glibc.
*
* Copyright (c) 1990 Regents of the University of California.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. [rescinded 22 July 1999]
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git__bsearch(
void **array,
size_t array_len,
const void *key,
int (*compare)(const void *, const void *),
size_t *position)
{
size_t lim;
int cmp = -1;
void **part, **base = array;
for (lim = array_len; lim != 0; lim >>= 1) {
part = base + (lim >> 1);
cmp = (*compare)(key, *part);
if (cmp == 0) {
base = part;
break;
}
if (cmp > 0) { /* key > p; take right partition */
base = part + 1;
lim--;
} /* else take left partition */
}
if (position)
*position = (base - array);
return (cmp == 0) ? 0 : GIT_ENOTFOUND;
}
int git__bsearch_r(
void **array,
size_t array_len,
const void *key,
int (*compare_r)(const void *, const void *, void *),
void *payload,
size_t *position)
{
size_t lim;
int cmp = -1;
void **part, **base = array;
for (lim = array_len; lim != 0; lim >>= 1) {
part = base + (lim >> 1);
cmp = (*compare_r)(key, *part, payload);
if (cmp == 0) {
base = part;
break;
}
if (cmp > 0) { /* key > p; take right partition */
base = part + 1;
lim--;
} /* else take left partition */
}
if (position)
*position = (base - array);
return (cmp == 0) ? 0 : GIT_ENOTFOUND;
}
/**
* A strcmp wrapper
*
* We don't want direct pointers to the CRT on Windows, we may
* get stdcall conflicts.
*/
int git__strcmp_cb(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
int git__strcasecmp_cb(const void *a, const void *b)
{
return strcasecmp((const char *)a, (const char *)b);
}
int git__parse_bool(int *out, const char *value)
{
/* A missing value means true */
if (value == NULL ||
!strcasecmp(value, "true") ||
!strcasecmp(value, "yes") ||
!strcasecmp(value, "on")) {
*out = 1;
return 0;
}
if (!strcasecmp(value, "false") ||
!strcasecmp(value, "no") ||
!strcasecmp(value, "off") ||
value[0] == '\0') {
*out = 0;
return 0;
}
return -1;
}
size_t git__unescape(char *str)
{
char *scan, *pos = str;
if (!str)
return 0;
for (scan = str; *scan; pos++, scan++) {
if (*scan == '\\' && *(scan + 1) != '\0')
scan++; /* skip '\' but include next char */
if (pos != scan)
*pos = *scan;
}
if (pos != scan) {
*pos = '\0';
}
return (pos - str);
}
#if defined(GIT_QSORT_S) || defined(GIT_QSORT_R_BSD)
typedef struct {
git__sort_r_cmp cmp;
void *payload;
} git__qsort_r_glue;
static int GIT_LIBGIT2_CALL git__qsort_r_glue_cmp(
void *payload, const void *a, const void *b)
{
git__qsort_r_glue *glue = payload;
return glue->cmp(a, b, glue->payload);
}
#endif
#if !defined(GIT_QSORT_R_BSD) && \
!defined(GIT_QSORT_R_GNU) && \
!defined(GIT_QSORT_S)
static void swap(uint8_t *a, uint8_t *b, size_t elsize)
{
char tmp[256];
while (elsize) {
size_t n = elsize < sizeof(tmp) ? elsize : sizeof(tmp);
memcpy(tmp, a + elsize - n, n);
memcpy(a + elsize - n, b + elsize - n, n);
memcpy(b + elsize - n, tmp, n);
elsize -= n;
}
}
static void insertsort(
void *els, size_t nel, size_t elsize,
git__sort_r_cmp cmp, void *payload)
{
uint8_t *base = els;
uint8_t *end = base + nel * elsize;
uint8_t *i, *j;
for (i = base + elsize; i < end; i += elsize)
for (j = i; j > base && cmp(j, j - elsize, payload) < 0; j -= elsize)
swap(j, j - elsize, elsize);
}
#endif
void git__qsort_r(
void *els, size_t nel, size_t elsize, git__sort_r_cmp cmp, void *payload)
{
#if defined(GIT_QSORT_R_BSD)
git__qsort_r_glue glue = { cmp, payload };
qsort_r(els, nel, elsize, &glue, git__qsort_r_glue_cmp);
#elif defined(GIT_QSORT_R_GNU)
qsort_r(els, nel, elsize, cmp, payload);
#elif defined(GIT_QSORT_S)
git__qsort_r_glue glue = { cmp, payload };
qsort_s(els, nel, elsize, git__qsort_r_glue_cmp, &glue);
#else
insertsort(els, nel, elsize, cmp, payload);
#endif
}
#ifdef GIT_WIN32
int git__getenv(git_str *out, const char *name)
{
wchar_t *wide_name = NULL, *wide_value = NULL;
DWORD value_len;
int error = -1;
git_str_clear(out);
if (git__utf8_to_16_alloc(&wide_name, name) < 0)
return -1;
if ((value_len = GetEnvironmentVariableW(wide_name, NULL, 0)) > 0) {
wide_value = git__malloc(value_len * sizeof(wchar_t));
GIT_ERROR_CHECK_ALLOC(wide_value);
value_len = GetEnvironmentVariableW(wide_name, wide_value, value_len);
}
if (value_len)
error = git_str_put_w(out, wide_value, value_len);
else if (GetLastError() == ERROR_SUCCESS || GetLastError() == ERROR_ENVVAR_NOT_FOUND)
error = GIT_ENOTFOUND;
else
git_error_set(GIT_ERROR_OS, "could not read environment variable '%s'", name);
git__free(wide_name);
git__free(wide_value);
return error;
}
#else
int git__getenv(git_str *out, const char *name)
{
const char *val = getenv(name);
git_str_clear(out);
if (!val)
return GIT_ENOTFOUND;
return git_str_puts(out, val);
}
#endif
/*
* By doing this in two steps we can at least get
* the function to be somewhat coherent, even
* with this disgusting nest of #ifdefs.
*/
#ifndef _SC_NPROCESSORS_ONLN
# ifdef _SC_NPROC_ONLN
# define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
# elif defined _SC_CRAY_NCPU
# define _SC_NPROCESSORS_ONLN _SC_CRAY_NCPU
# endif
#endif
int git__online_cpus(void)
{
#ifdef _SC_NPROCESSORS_ONLN
long ncpus;
#endif
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
if ((int)info.dwNumberOfProcessors > 0)
return (int)info.dwNumberOfProcessors;
#elif defined(hpux) || defined(__hpux) || defined(_hpux)
struct pst_dynamic psd;
if (!pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0))
return (int)psd.psd_proc_cnt;
#endif
#ifdef _SC_NPROCESSORS_ONLN
if ((ncpus = (long)sysconf(_SC_NPROCESSORS_ONLN)) > 0)
return (int)ncpus;
#endif
return 1;
}
| libgit2-main | src/util/util.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "posix.h"
#include "fs_path.h"
#include <stdio.h>
#include <ctype.h>
size_t p_fsync__cnt = 0;
#ifndef GIT_WIN32
#ifdef NO_ADDRINFO
int p_getaddrinfo(
const char *host,
const char *port,
struct addrinfo *hints,
struct addrinfo **info)
{
struct addrinfo *ainfo, *ai;
int p = 0;
GIT_UNUSED(hints);
if ((ainfo = git__malloc(sizeof(struct addrinfo))) == NULL)
return -1;
if ((ainfo->ai_hostent = gethostbyname(host)) == NULL) {
git__free(ainfo);
return -2;
}
ainfo->ai_servent = getservbyname(port, 0);
if (ainfo->ai_servent)
ainfo->ai_port = ainfo->ai_servent->s_port;
else
ainfo->ai_port = htons(atol(port));
memcpy(&ainfo->ai_addr_in.sin_addr,
ainfo->ai_hostent->h_addr_list[0],
ainfo->ai_hostent->h_length);
ainfo->ai_protocol = 0;
ainfo->ai_socktype = hints->ai_socktype;
ainfo->ai_family = ainfo->ai_hostent->h_addrtype;
ainfo->ai_addr_in.sin_family = ainfo->ai_family;
ainfo->ai_addr_in.sin_port = ainfo->ai_port;
ainfo->ai_addr = (struct addrinfo *)&ainfo->ai_addr_in;
ainfo->ai_addrlen = sizeof(struct sockaddr_in);
*info = ainfo;
if (ainfo->ai_hostent->h_addr_list[1] == NULL) {
ainfo->ai_next = NULL;
return 0;
}
ai = ainfo;
for (p = 1; ainfo->ai_hostent->h_addr_list[p] != NULL; p++) {
if (!(ai->ai_next = git__malloc(sizeof(struct addrinfo)))) {
p_freeaddrinfo(ainfo);
return -1;
}
memcpy(ai->ai_next, ainfo, sizeof(struct addrinfo));
memcpy(&ai->ai_next->ai_addr_in.sin_addr,
ainfo->ai_hostent->h_addr_list[p],
ainfo->ai_hostent->h_length);
ai->ai_next->ai_addr = (struct addrinfo *)&ai->ai_next->ai_addr_in;
ai = ai->ai_next;
}
ai->ai_next = NULL;
return 0;
}
void p_freeaddrinfo(struct addrinfo *info)
{
struct addrinfo *p, *next;
p = info;
while(p != NULL) {
next = p->ai_next;
git__free(p);
p = next;
}
}
const char *p_gai_strerror(int ret)
{
switch(ret) {
case -1: return "Out of memory"; break;
case -2: return "Address lookup failed"; break;
default: return "Unknown error"; break;
}
}
#endif /* NO_ADDRINFO */
int p_open(const char *path, volatile int flags, ...)
{
mode_t mode = 0;
#ifdef GIT_DEBUG_STRICT_OPEN
if (strstr(path, "//") != NULL) {
errno = EACCES;
return -1;
}
#endif
if (flags & O_CREAT) {
va_list arg_list;
va_start(arg_list, flags);
mode = (mode_t)va_arg(arg_list, int);
va_end(arg_list);
}
return open(path, flags | O_BINARY | O_CLOEXEC, mode);
}
int p_creat(const char *path, mode_t mode)
{
return open(path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_CLOEXEC, mode);
}
int p_getcwd(char *buffer_out, size_t size)
{
char *cwd_buffer;
GIT_ASSERT_ARG(buffer_out);
GIT_ASSERT_ARG(size > 0);
cwd_buffer = getcwd(buffer_out, size);
if (cwd_buffer == NULL)
return -1;
git_fs_path_mkposix(buffer_out);
git_fs_path_string_to_dir(buffer_out, size); /* append trailing slash */
return 0;
}
int p_rename(const char *from, const char *to)
{
if (!link(from, to)) {
p_unlink(from);
return 0;
}
if (!rename(from, to))
return 0;
return -1;
}
#endif /* GIT_WIN32 */
ssize_t p_read(git_file fd, void *buf, size_t cnt)
{
char *b = buf;
if (!git__is_ssizet(cnt)) {
#ifdef GIT_WIN32
SetLastError(ERROR_INVALID_PARAMETER);
#endif
errno = EINVAL;
return -1;
}
while (cnt) {
ssize_t r;
#ifdef GIT_WIN32
r = read(fd, b, cnt > INT_MAX ? INT_MAX : (unsigned int)cnt);
#else
r = read(fd, b, cnt);
#endif
if (r < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
return -1;
}
if (!r)
break;
cnt -= r;
b += r;
}
return (b - (char *)buf);
}
int p_write(git_file fd, const void *buf, size_t cnt)
{
const char *b = buf;
while (cnt) {
ssize_t r;
#ifdef GIT_WIN32
GIT_ASSERT((size_t)((unsigned int)cnt) == cnt);
r = write(fd, b, (unsigned int)cnt);
#else
r = write(fd, b, cnt);
#endif
if (r < 0) {
if (errno == EINTR || GIT_ISBLOCKED(errno))
continue;
return -1;
}
if (!r) {
errno = EPIPE;
return -1;
}
cnt -= r;
b += r;
}
return 0;
}
#ifdef NO_MMAP
#include "map.h"
int git__page_size(size_t *page_size)
{
/* dummy; here we don't need any alignment anyway */
*page_size = 4096;
return 0;
}
int git__mmap_alignment(size_t *alignment)
{
/* dummy; here we don't need any alignment anyway */
*alignment = 4096;
return 0;
}
int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset)
{
const char *ptr;
size_t remaining_len;
GIT_MMAP_VALIDATE(out, len, prot, flags);
/* writes cannot be emulated without handling pagefaults since write happens by
* writing to mapped memory */
if (prot & GIT_PROT_WRITE) {
git_error_set(GIT_ERROR_OS, "trying to map %s-writeable",
((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED) ? "shared": "private");
return -1;
}
if (!git__is_ssizet(len)) {
errno = EINVAL;
return -1;
}
out->len = 0;
out->data = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(out->data);
remaining_len = len;
ptr = (const char *)out->data;
while (remaining_len > 0) {
ssize_t nb;
HANDLE_EINTR(nb, p_pread(fd, (void *)ptr, remaining_len, offset));
if (nb <= 0) {
git_error_set(GIT_ERROR_OS, "mmap emulation failed");
git__free(out->data);
out->data = NULL;
return -1;
}
ptr += nb;
offset += nb;
remaining_len -= nb;
}
out->len = len;
return 0;
}
int p_munmap(git_map *map)
{
GIT_ASSERT_ARG(map);
git__free(map->data);
/* Initializing will help debug use-after-free */
map->len = 0;
map->data = NULL;
return 0;
}
#endif
| libgit2-main | src/util/posix.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "vector.h"
#include "integer.h"
/* In elements, not bytes */
#define MIN_ALLOCSIZE 8
GIT_INLINE(size_t) compute_new_size(git_vector *v)
{
size_t new_size = v->_alloc_size;
/* Use a resize factor of 1.5, which is quick to compute using integer
* instructions and less than the golden ratio (1.618...) */
if (new_size < MIN_ALLOCSIZE)
new_size = MIN_ALLOCSIZE;
else if (new_size <= (SIZE_MAX / 3) * 2)
new_size += new_size / 2;
else
new_size = SIZE_MAX;
return new_size;
}
GIT_INLINE(int) resize_vector(git_vector *v, size_t new_size)
{
void *new_contents;
if (new_size == 0)
return 0;
new_contents = git__reallocarray(v->contents, new_size, sizeof(void *));
GIT_ERROR_CHECK_ALLOC(new_contents);
v->_alloc_size = new_size;
v->contents = new_contents;
return 0;
}
int git_vector_size_hint(git_vector *v, size_t size_hint)
{
if (v->_alloc_size >= size_hint)
return 0;
return resize_vector(v, size_hint);
}
int git_vector_dup(git_vector *v, const git_vector *src, git_vector_cmp cmp)
{
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(src);
v->_alloc_size = 0;
v->contents = NULL;
v->_cmp = cmp ? cmp : src->_cmp;
v->length = src->length;
v->flags = src->flags;
if (cmp != src->_cmp)
git_vector_set_sorted(v, 0);
if (src->length) {
size_t bytes;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&bytes, src->length, sizeof(void *));
v->contents = git__malloc(bytes);
GIT_ERROR_CHECK_ALLOC(v->contents);
v->_alloc_size = src->length;
memcpy(v->contents, src->contents, bytes);
}
return 0;
}
void git_vector_free(git_vector *v)
{
if (!v)
return;
git__free(v->contents);
v->contents = NULL;
v->length = 0;
v->_alloc_size = 0;
}
void git_vector_free_deep(git_vector *v)
{
size_t i;
if (!v)
return;
for (i = 0; i < v->length; ++i) {
git__free(v->contents[i]);
v->contents[i] = NULL;
}
git_vector_free(v);
}
int git_vector_init(git_vector *v, size_t initial_size, git_vector_cmp cmp)
{
GIT_ASSERT_ARG(v);
v->_alloc_size = 0;
v->_cmp = cmp;
v->length = 0;
v->flags = GIT_VECTOR_SORTED;
v->contents = NULL;
return resize_vector(v, max(initial_size, MIN_ALLOCSIZE));
}
void **git_vector_detach(size_t *size, size_t *asize, git_vector *v)
{
void **data = v->contents;
if (size)
*size = v->length;
if (asize)
*asize = v->_alloc_size;
v->_alloc_size = 0;
v->length = 0;
v->contents = NULL;
return data;
}
int git_vector_insert(git_vector *v, void *element)
{
GIT_ASSERT_ARG(v);
if (v->length >= v->_alloc_size &&
resize_vector(v, compute_new_size(v)) < 0)
return -1;
v->contents[v->length++] = element;
git_vector_set_sorted(v, v->length <= 1);
return 0;
}
int git_vector_insert_sorted(
git_vector *v, void *element, int (*on_dup)(void **old, void *new))
{
int result;
size_t pos;
GIT_ASSERT_ARG(v);
GIT_ASSERT(v->_cmp);
if (!git_vector_is_sorted(v))
git_vector_sort(v);
if (v->length >= v->_alloc_size &&
resize_vector(v, compute_new_size(v)) < 0)
return -1;
/* If we find the element and have a duplicate handler callback,
* invoke it. If it returns non-zero, then cancel insert, otherwise
* proceed with normal insert.
*/
if (!git__bsearch(v->contents, v->length, element, v->_cmp, &pos) &&
on_dup && (result = on_dup(&v->contents[pos], element)) < 0)
return result;
/* shift elements to the right */
if (pos < v->length)
memmove(v->contents + pos + 1, v->contents + pos,
(v->length - pos) * sizeof(void *));
v->contents[pos] = element;
v->length++;
return 0;
}
void git_vector_sort(git_vector *v)
{
if (git_vector_is_sorted(v) || !v->_cmp)
return;
if (v->length > 1)
git__tsort(v->contents, v->length, v->_cmp);
git_vector_set_sorted(v, 1);
}
int git_vector_bsearch2(
size_t *at_pos,
git_vector *v,
git_vector_cmp key_lookup,
const void *key)
{
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(key);
GIT_ASSERT(key_lookup);
/* need comparison function to sort the vector */
if (!v->_cmp)
return -1;
git_vector_sort(v);
return git__bsearch(v->contents, v->length, key, key_lookup, at_pos);
}
int git_vector_search2(
size_t *at_pos, const git_vector *v, git_vector_cmp key_lookup, const void *key)
{
size_t i;
GIT_ASSERT_ARG(v);
GIT_ASSERT_ARG(key);
GIT_ASSERT(key_lookup);
for (i = 0; i < v->length; ++i) {
if (key_lookup(key, v->contents[i]) == 0) {
if (at_pos)
*at_pos = i;
return 0;
}
}
return GIT_ENOTFOUND;
}
static int strict_comparison(const void *a, const void *b)
{
return (a == b) ? 0 : -1;
}
int git_vector_search(size_t *at_pos, const git_vector *v, const void *entry)
{
return git_vector_search2(at_pos, v, v->_cmp ? v->_cmp : strict_comparison, entry);
}
int git_vector_remove(git_vector *v, size_t idx)
{
size_t shift_count;
GIT_ASSERT_ARG(v);
if (idx >= v->length)
return GIT_ENOTFOUND;
shift_count = v->length - idx - 1;
if (shift_count)
memmove(&v->contents[idx], &v->contents[idx + 1],
shift_count * sizeof(void *));
v->length--;
return 0;
}
void git_vector_pop(git_vector *v)
{
if (v->length > 0)
v->length--;
}
void git_vector_uniq(git_vector *v, void (*git_free_cb)(void *))
{
git_vector_cmp cmp;
size_t i, j;
if (v->length <= 1)
return;
git_vector_sort(v);
cmp = v->_cmp ? v->_cmp : strict_comparison;
for (i = 0, j = 1 ; j < v->length; ++j)
if (!cmp(v->contents[i], v->contents[j])) {
if (git_free_cb)
git_free_cb(v->contents[i]);
v->contents[i] = v->contents[j];
} else
v->contents[++i] = v->contents[j];
v->length -= j - i - 1;
}
void git_vector_remove_matching(
git_vector *v,
int (*match)(const git_vector *v, size_t idx, void *payload),
void *payload)
{
size_t i, j;
for (i = 0, j = 0; j < v->length; ++j) {
v->contents[i] = v->contents[j];
if (!match(v, i, payload))
i++;
}
v->length = i;
}
void git_vector_clear(git_vector *v)
{
v->length = 0;
git_vector_set_sorted(v, 1);
}
void git_vector_swap(git_vector *a, git_vector *b)
{
git_vector t;
if (a != b) {
memcpy(&t, a, sizeof(t));
memcpy(a, b, sizeof(t));
memcpy(b, &t, sizeof(t));
}
}
int git_vector_resize_to(git_vector *v, size_t new_length)
{
if (new_length > v->_alloc_size &&
resize_vector(v, new_length) < 0)
return -1;
if (new_length > v->length)
memset(&v->contents[v->length], 0,
sizeof(void *) * (new_length - v->length));
v->length = new_length;
return 0;
}
int git_vector_insert_null(git_vector *v, size_t idx, size_t insert_len)
{
size_t new_length;
GIT_ASSERT_ARG(insert_len > 0);
GIT_ASSERT_ARG(idx <= v->length);
GIT_ERROR_CHECK_ALLOC_ADD(&new_length, v->length, insert_len);
if (new_length > v->_alloc_size && resize_vector(v, new_length) < 0)
return -1;
memmove(&v->contents[idx + insert_len], &v->contents[idx],
sizeof(void *) * (v->length - idx));
memset(&v->contents[idx], 0, sizeof(void *) * insert_len);
v->length = new_length;
return 0;
}
int git_vector_remove_range(git_vector *v, size_t idx, size_t remove_len)
{
size_t new_length = v->length - remove_len;
size_t end_idx = 0;
GIT_ASSERT_ARG(remove_len > 0);
if (git__add_sizet_overflow(&end_idx, idx, remove_len))
GIT_ASSERT(0);
GIT_ASSERT(end_idx <= v->length);
if (end_idx < v->length)
memmove(&v->contents[idx], &v->contents[end_idx],
sizeof(void *) * (v->length - end_idx));
memset(&v->contents[new_length], 0, sizeof(void *) * remove_len);
v->length = new_length;
return 0;
}
int git_vector_set(void **old, git_vector *v, size_t position, void *value)
{
if (position + 1 > v->length) {
if (git_vector_resize_to(v, position + 1) < 0)
return -1;
}
if (old != NULL)
*old = v->contents[position];
v->contents[position] = value;
return 0;
}
int git_vector_verify_sorted(const git_vector *v)
{
size_t i;
if (!git_vector_is_sorted(v))
return -1;
for (i = 1; i < v->length; ++i) {
if (v->_cmp(v->contents[i - 1], v->contents[i]) > 0)
return -1;
}
return 0;
}
void git_vector_reverse(git_vector *v)
{
size_t a, b;
if (v->length == 0)
return;
a = 0;
b = v->length - 1;
while (a < b) {
void *tmp = v->contents[a];
v->contents[a] = v->contents[b];
v->contents[b] = tmp;
a++;
b--;
}
}
| libgit2-main | src/util/vector.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "str.h"
#include "posix.h"
#include <ctype.h>
/* Used as default value for git_str->ptr so that people can always
* assume ptr is non-NULL and zero terminated even for new git_strs.
*/
char git_str__initstr[1];
char git_str__oom[1];
#define ENSURE_SIZE(b, d) \
if ((b)->ptr == git_str__oom || \
((d) > (b)->asize && git_str_grow((b), (d)) < 0))\
return -1;
int git_str_init(git_str *buf, size_t initial_size)
{
buf->asize = 0;
buf->size = 0;
buf->ptr = git_str__initstr;
ENSURE_SIZE(buf, initial_size);
return 0;
}
int git_str_try_grow(
git_str *buf, size_t target_size, bool mark_oom)
{
char *new_ptr;
size_t new_size;
if (buf->ptr == git_str__oom)
return -1;
if (buf->asize == 0 && buf->size != 0) {
git_error_set(GIT_ERROR_INVALID, "cannot grow a borrowed buffer");
return GIT_EINVALID;
}
if (!target_size)
target_size = buf->size;
if (target_size <= buf->asize)
return 0;
if (buf->asize == 0) {
new_size = target_size;
new_ptr = NULL;
} else {
new_size = buf->asize;
/*
* Grow the allocated buffer by 1.5 to allow
* re-use of memory holes resulting from the
* realloc. If this is still too small, then just
* use the target size.
*/
if ((new_size = (new_size << 1) - (new_size >> 1)) < target_size)
new_size = target_size;
new_ptr = buf->ptr;
}
/* round allocation up to multiple of 8 */
new_size = (new_size + 7) & ~7;
if (new_size < buf->size) {
if (mark_oom) {
if (buf->ptr && buf->ptr != git_str__initstr)
git__free(buf->ptr);
buf->ptr = git_str__oom;
}
git_error_set_oom();
return -1;
}
new_ptr = git__realloc(new_ptr, new_size);
if (!new_ptr) {
if (mark_oom) {
if (buf->ptr && (buf->ptr != git_str__initstr))
git__free(buf->ptr);
buf->ptr = git_str__oom;
}
return -1;
}
buf->asize = new_size;
buf->ptr = new_ptr;
/* truncate the existing buffer size if necessary */
if (buf->size >= buf->asize)
buf->size = buf->asize - 1;
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_grow(git_str *buffer, size_t target_size)
{
return git_str_try_grow(buffer, target_size, true);
}
int git_str_grow_by(git_str *buffer, size_t additional_size)
{
size_t newsize;
if (GIT_ADD_SIZET_OVERFLOW(&newsize, buffer->size, additional_size)) {
buffer->ptr = git_str__oom;
return -1;
}
return git_str_try_grow(buffer, newsize, true);
}
void git_str_dispose(git_str *buf)
{
if (!buf) return;
if (buf->asize > 0 && buf->ptr != NULL && buf->ptr != git_str__oom)
git__free(buf->ptr);
git_str_init(buf, 0);
}
void git_str_clear(git_str *buf)
{
buf->size = 0;
if (!buf->ptr) {
buf->ptr = git_str__initstr;
buf->asize = 0;
}
if (buf->asize > 0)
buf->ptr[0] = '\0';
}
int git_str_set(git_str *buf, const void *data, size_t len)
{
size_t alloclen;
if (len == 0 || data == NULL) {
git_str_clear(buf);
} else {
if (data != buf->ptr) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, len, 1);
ENSURE_SIZE(buf, alloclen);
memmove(buf->ptr, data, len);
}
buf->size = len;
if (buf->asize > buf->size)
buf->ptr[buf->size] = '\0';
}
return 0;
}
int git_str_sets(git_str *buf, const char *string)
{
return git_str_set(buf, string, string ? strlen(string) : 0);
}
int git_str_putc(git_str *buf, char c)
{
size_t new_size;
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, 2);
ENSURE_SIZE(buf, new_size);
buf->ptr[buf->size++] = c;
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_putcn(git_str *buf, char c, size_t len)
{
size_t new_size;
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, len);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
memset(buf->ptr + buf->size, c, len);
buf->size += len;
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_put(git_str *buf, const char *data, size_t len)
{
if (len) {
size_t new_size;
GIT_ASSERT_ARG(data);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, len);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
memmove(buf->ptr + buf->size, data, len);
buf->size += len;
buf->ptr[buf->size] = '\0';
}
return 0;
}
int git_str_puts(git_str *buf, const char *string)
{
GIT_ASSERT_ARG(string);
return git_str_put(buf, string, strlen(string));
}
static char hex_encode[] = "0123456789abcdef";
int git_str_encode_hexstr(git_str *str, const char *data, size_t len)
{
size_t new_size, i;
char *s;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&new_size, len, 2);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
if (git_str_grow_by(str, new_size) < 0)
return -1;
s = str->ptr + str->size;
for (i = 0; i < len; i++) {
*s++ = hex_encode[(data[i] & 0xf0) >> 4];
*s++ = hex_encode[(data[i] & 0x0f)];
}
str->size += (len * 2);
str->ptr[str->size] = '\0';
return 0;
}
static const char base64_encode[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int git_str_encode_base64(git_str *buf, const char *data, size_t len)
{
size_t extra = len % 3;
uint8_t *write, a, b, c;
const uint8_t *read = (const uint8_t *)data;
size_t blocks = (len / 3) + !!extra, alloclen;
GIT_ERROR_CHECK_ALLOC_ADD(&blocks, blocks, 1);
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&alloclen, blocks, 4);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, buf->size);
ENSURE_SIZE(buf, alloclen);
write = (uint8_t *)&buf->ptr[buf->size];
/* convert each run of 3 bytes into 4 output bytes */
for (len -= extra; len > 0; len -= 3) {
a = *read++;
b = *read++;
c = *read++;
*write++ = base64_encode[a >> 2];
*write++ = base64_encode[(a & 0x03) << 4 | b >> 4];
*write++ = base64_encode[(b & 0x0f) << 2 | c >> 6];
*write++ = base64_encode[c & 0x3f];
}
if (extra > 0) {
a = *read++;
b = (extra > 1) ? *read++ : 0;
*write++ = base64_encode[a >> 2];
*write++ = base64_encode[(a & 0x03) << 4 | b >> 4];
*write++ = (extra > 1) ? base64_encode[(b & 0x0f) << 2] : '=';
*write++ = '=';
}
buf->size = ((char *)write) - buf->ptr;
buf->ptr[buf->size] = '\0';
return 0;
}
/* The inverse of base64_encode */
static const int8_t base64_decode[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
int git_str_decode_base64(git_str *buf, const char *base64, size_t len)
{
size_t i;
int8_t a, b, c, d;
size_t orig_size = buf->size, new_size;
if (len % 4) {
git_error_set(GIT_ERROR_INVALID, "invalid base64 input");
return -1;
}
GIT_ASSERT_ARG(len % 4 == 0);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, (len / 4 * 3), buf->size);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
for (i = 0; i < len; i += 4) {
if ((a = base64_decode[(unsigned char)base64[i]]) < 0 ||
(b = base64_decode[(unsigned char)base64[i+1]]) < 0 ||
(c = base64_decode[(unsigned char)base64[i+2]]) < 0 ||
(d = base64_decode[(unsigned char)base64[i+3]]) < 0) {
buf->size = orig_size;
buf->ptr[buf->size] = '\0';
git_error_set(GIT_ERROR_INVALID, "invalid base64 input");
return -1;
}
buf->ptr[buf->size++] = ((a << 2) | (b & 0x30) >> 4);
buf->ptr[buf->size++] = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
buf->ptr[buf->size++] = (c & 0x03) << 6 | (d & 0x3f);
}
buf->ptr[buf->size] = '\0';
return 0;
}
static const char base85_encode[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
int git_str_encode_base85(git_str *buf, const char *data, size_t len)
{
size_t blocks = (len / 4) + !!(len % 4), alloclen;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&alloclen, blocks, 5);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, buf->size);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
ENSURE_SIZE(buf, alloclen);
while (len) {
uint32_t acc = 0;
char b85[5];
int i;
for (i = 24; i >= 0; i -= 8) {
uint8_t ch = *data++;
acc |= (uint32_t)ch << i;
if (--len == 0)
break;
}
for (i = 4; i >= 0; i--) {
int val = acc % 85;
acc /= 85;
b85[i] = base85_encode[val];
}
for (i = 0; i < 5; i++)
buf->ptr[buf->size++] = b85[i];
}
buf->ptr[buf->size] = '\0';
return 0;
}
/* The inverse of base85_encode */
static const int8_t base85_decode[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 63, -1, 64, 65, 66, 67, -1, 68, 69, 70, 71, -1, 72, -1, -1,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, 73, 74, 75, 76, 77,
78, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, -1, -1, -1, 79, 80,
81, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 82, 83, 84, 85, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
int git_str_decode_base85(
git_str *buf,
const char *base85,
size_t base85_len,
size_t output_len)
{
size_t orig_size = buf->size, new_size;
if (base85_len % 5 ||
output_len > base85_len * 4 / 5) {
git_error_set(GIT_ERROR_INVALID, "invalid base85 input");
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, output_len, buf->size);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
while (output_len) {
unsigned acc = 0;
int de, cnt = 4;
unsigned char ch;
do {
ch = *base85++;
de = base85_decode[ch];
if (--de < 0)
goto on_error;
acc = acc * 85 + de;
} while (--cnt);
ch = *base85++;
de = base85_decode[ch];
if (--de < 0)
goto on_error;
/* Detect overflow. */
if (0xffffffff / 85 < acc ||
0xffffffff - de < (acc *= 85))
goto on_error;
acc += de;
cnt = (output_len < 4) ? (int)output_len : 4;
output_len -= cnt;
do {
acc = (acc << 8) | (acc >> 24);
buf->ptr[buf->size++] = acc;
} while (--cnt);
}
buf->ptr[buf->size] = 0;
return 0;
on_error:
buf->size = orig_size;
buf->ptr[buf->size] = '\0';
git_error_set(GIT_ERROR_INVALID, "invalid base85 input");
return -1;
}
#define HEX_DECODE(c) ((c | 32) % 39 - 9)
int git_str_decode_percent(
git_str *buf,
const char *str,
size_t str_len)
{
size_t str_pos, new_size;
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, str_len);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
for (str_pos = 0; str_pos < str_len; buf->size++, str_pos++) {
if (str[str_pos] == '%' &&
str_len > str_pos + 2 &&
isxdigit(str[str_pos + 1]) &&
isxdigit(str[str_pos + 2])) {
buf->ptr[buf->size] = (HEX_DECODE(str[str_pos + 1]) << 4) +
HEX_DECODE(str[str_pos + 2]);
str_pos += 2;
} else {
buf->ptr[buf->size] = str[str_pos];
}
}
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_vprintf(git_str *buf, const char *format, va_list ap)
{
size_t expected_size, new_size;
int len;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&expected_size, strlen(format), 2);
GIT_ERROR_CHECK_ALLOC_ADD(&expected_size, expected_size, buf->size);
ENSURE_SIZE(buf, expected_size);
while (1) {
va_list args;
va_copy(args, ap);
len = p_vsnprintf(
buf->ptr + buf->size,
buf->asize - buf->size,
format, args
);
va_end(args);
if (len < 0) {
git__free(buf->ptr);
buf->ptr = git_str__oom;
return -1;
}
if ((size_t)len + 1 <= buf->asize - buf->size) {
buf->size += len;
break;
}
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, len);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
ENSURE_SIZE(buf, new_size);
}
return 0;
}
int git_str_printf(git_str *buf, const char *format, ...)
{
int r;
va_list ap;
va_start(ap, format);
r = git_str_vprintf(buf, format, ap);
va_end(ap);
return r;
}
int git_str_copy_cstr(char *data, size_t datasize, const git_str *buf)
{
size_t copylen;
GIT_ASSERT_ARG(data);
GIT_ASSERT_ARG(datasize);
GIT_ASSERT_ARG(buf);
data[0] = '\0';
if (buf->size == 0 || buf->asize <= 0)
return 0;
copylen = buf->size;
if (copylen > datasize - 1)
copylen = datasize - 1;
memmove(data, buf->ptr, copylen);
data[copylen] = '\0';
return 0;
}
void git_str_consume_bytes(git_str *buf, size_t len)
{
git_str_consume(buf, buf->ptr + len);
}
void git_str_consume(git_str *buf, const char *end)
{
if (end > buf->ptr && end <= buf->ptr + buf->size) {
size_t consumed = end - buf->ptr;
memmove(buf->ptr, end, buf->size - consumed);
buf->size -= consumed;
buf->ptr[buf->size] = '\0';
}
}
void git_str_truncate(git_str *buf, size_t len)
{
if (len >= buf->size)
return;
buf->size = len;
if (buf->size < buf->asize)
buf->ptr[buf->size] = '\0';
}
void git_str_shorten(git_str *buf, size_t amount)
{
if (buf->size > amount)
git_str_truncate(buf, buf->size - amount);
else
git_str_clear(buf);
}
void git_str_truncate_at_char(git_str *buf, char separator)
{
ssize_t idx = git_str_find(buf, separator);
if (idx >= 0)
git_str_truncate(buf, (size_t)idx);
}
void git_str_rtruncate_at_char(git_str *buf, char separator)
{
ssize_t idx = git_str_rfind_next(buf, separator);
git_str_truncate(buf, idx < 0 ? 0 : (size_t)idx);
}
void git_str_swap(git_str *str_a, git_str *str_b)
{
git_str t = *str_a;
*str_a = *str_b;
*str_b = t;
}
char *git_str_detach(git_str *buf)
{
char *data = buf->ptr;
if (buf->asize == 0 || buf->ptr == git_str__oom)
return NULL;
git_str_init(buf, 0);
return data;
}
int git_str_attach(git_str *buf, char *ptr, size_t asize)
{
git_str_dispose(buf);
if (ptr) {
buf->ptr = ptr;
buf->size = strlen(ptr);
if (asize)
buf->asize = (asize < buf->size) ? buf->size + 1 : asize;
else /* pass 0 to fall back on strlen + 1 */
buf->asize = buf->size + 1;
}
ENSURE_SIZE(buf, asize);
return 0;
}
void git_str_attach_notowned(git_str *buf, const char *ptr, size_t size)
{
if (git_str_is_allocated(buf))
git_str_dispose(buf);
if (!size) {
git_str_init(buf, 0);
} else {
buf->ptr = (char *)ptr;
buf->asize = 0;
buf->size = size;
}
}
int git_str_join_n(git_str *buf, char separator, int nbuf, ...)
{
va_list ap;
int i;
size_t total_size = 0, original_size = buf->size;
char *out, *original = buf->ptr;
if (buf->size > 0 && buf->ptr[buf->size - 1] != separator)
++total_size; /* space for initial separator */
/* Make two passes to avoid multiple reallocation */
va_start(ap, nbuf);
for (i = 0; i < nbuf; ++i) {
const char *segment;
size_t segment_len;
segment = va_arg(ap, const char *);
if (!segment)
continue;
segment_len = strlen(segment);
GIT_ERROR_CHECK_ALLOC_ADD(&total_size, total_size, segment_len);
if (segment_len == 0 || segment[segment_len - 1] != separator)
GIT_ERROR_CHECK_ALLOC_ADD(&total_size, total_size, 1);
}
va_end(ap);
/* expand buffer if needed */
if (total_size == 0)
return 0;
GIT_ERROR_CHECK_ALLOC_ADD(&total_size, total_size, 1);
if (git_str_grow_by(buf, total_size) < 0)
return -1;
out = buf->ptr + buf->size;
/* append separator to existing buf if needed */
if (buf->size > 0 && out[-1] != separator)
*out++ = separator;
va_start(ap, nbuf);
for (i = 0; i < nbuf; ++i) {
const char *segment;
size_t segment_len;
segment = va_arg(ap, const char *);
if (!segment)
continue;
/* deal with join that references buffer's original content */
if (segment >= original && segment < original + original_size) {
size_t offset = (segment - original);
segment = buf->ptr + offset;
segment_len = original_size - offset;
} else {
segment_len = strlen(segment);
}
/* skip leading separators */
if (out > buf->ptr && out[-1] == separator)
while (segment_len > 0 && *segment == separator) {
segment++;
segment_len--;
}
/* copy over next buffer */
if (segment_len > 0) {
memmove(out, segment, segment_len);
out += segment_len;
}
/* append trailing separator (except for last item) */
if (i < nbuf - 1 && out > buf->ptr && out[-1] != separator)
*out++ = separator;
}
va_end(ap);
/* set size based on num characters actually written */
buf->size = out - buf->ptr;
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_join(
git_str *buf,
char separator,
const char *str_a,
const char *str_b)
{
size_t strlen_a = str_a ? strlen(str_a) : 0;
size_t strlen_b = strlen(str_b);
size_t alloc_len;
int need_sep = 0;
ssize_t offset_a = -1;
/* not safe to have str_b point internally to the buffer */
if (buf->size)
GIT_ASSERT_ARG(str_b < buf->ptr || str_b >= buf->ptr + buf->size);
/* figure out if we need to insert a separator */
if (separator && strlen_a) {
while (*str_b == separator) { str_b++; strlen_b--; }
if (str_a[strlen_a - 1] != separator)
need_sep = 1;
}
/* str_a could be part of the buffer */
if (buf->size && str_a >= buf->ptr && str_a < buf->ptr + buf->size)
offset_a = str_a - buf->ptr;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, strlen_a, strlen_b);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, need_sep);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
ENSURE_SIZE(buf, alloc_len);
/* fix up internal pointers */
if (offset_a >= 0)
str_a = buf->ptr + offset_a;
/* do the actual copying */
if (offset_a != 0 && str_a)
memmove(buf->ptr, str_a, strlen_a);
if (need_sep)
buf->ptr[strlen_a] = separator;
memcpy(buf->ptr + strlen_a + need_sep, str_b, strlen_b);
buf->size = strlen_a + strlen_b + need_sep;
buf->ptr[buf->size] = '\0';
return 0;
}
int git_str_join3(
git_str *buf,
char separator,
const char *str_a,
const char *str_b,
const char *str_c)
{
size_t len_a = strlen(str_a),
len_b = strlen(str_b),
len_c = strlen(str_c),
len_total;
int sep_a = 0, sep_b = 0;
char *tgt;
/* for this function, disallow pointers into the existing buffer */
GIT_ASSERT(str_a < buf->ptr || str_a >= buf->ptr + buf->size);
GIT_ASSERT(str_b < buf->ptr || str_b >= buf->ptr + buf->size);
GIT_ASSERT(str_c < buf->ptr || str_c >= buf->ptr + buf->size);
if (separator) {
if (len_a > 0) {
while (*str_b == separator) { str_b++; len_b--; }
sep_a = (str_a[len_a - 1] != separator);
}
if (len_a > 0 || len_b > 0)
while (*str_c == separator) { str_c++; len_c--; }
if (len_b > 0)
sep_b = (str_b[len_b - 1] != separator);
}
GIT_ERROR_CHECK_ALLOC_ADD(&len_total, len_a, sep_a);
GIT_ERROR_CHECK_ALLOC_ADD(&len_total, len_total, len_b);
GIT_ERROR_CHECK_ALLOC_ADD(&len_total, len_total, sep_b);
GIT_ERROR_CHECK_ALLOC_ADD(&len_total, len_total, len_c);
GIT_ERROR_CHECK_ALLOC_ADD(&len_total, len_total, 1);
ENSURE_SIZE(buf, len_total);
tgt = buf->ptr;
if (len_a) {
memcpy(tgt, str_a, len_a);
tgt += len_a;
}
if (sep_a)
*tgt++ = separator;
if (len_b) {
memcpy(tgt, str_b, len_b);
tgt += len_b;
}
if (sep_b)
*tgt++ = separator;
if (len_c)
memcpy(tgt, str_c, len_c);
buf->size = len_a + sep_a + len_b + sep_b + len_c;
buf->ptr[buf->size] = '\0';
return 0;
}
void git_str_rtrim(git_str *buf)
{
while (buf->size > 0) {
if (!git__isspace(buf->ptr[buf->size - 1]))
break;
buf->size--;
}
if (buf->asize > buf->size)
buf->ptr[buf->size] = '\0';
}
int git_str_cmp(const git_str *a, const git_str *b)
{
int result = memcmp(a->ptr, b->ptr, min(a->size, b->size));
return (result != 0) ? result :
(a->size < b->size) ? -1 : (a->size > b->size) ? 1 : 0;
}
int git_str_splice(
git_str *buf,
size_t where,
size_t nb_to_remove,
const char *data,
size_t nb_to_insert)
{
char *splice_loc;
size_t new_size, alloc_size;
GIT_ASSERT(buf);
GIT_ASSERT(where <= buf->size);
GIT_ASSERT(nb_to_remove <= buf->size - where);
splice_loc = buf->ptr + where;
/* Ported from git.git
* https://github.com/git/git/blob/16eed7c/strbuf.c#L159-176
*/
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, (buf->size - nb_to_remove), nb_to_insert);
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, new_size, 1);
ENSURE_SIZE(buf, alloc_size);
memmove(splice_loc + nb_to_insert,
splice_loc + nb_to_remove,
buf->size - where - nb_to_remove);
memcpy(splice_loc, data, nb_to_insert);
buf->size = new_size;
buf->ptr[buf->size] = '\0';
return 0;
}
/* Quote per http://marc.info/?l=git&m=112927316408690&w=2 */
int git_str_quote(git_str *buf)
{
const char whitespace[] = { 'a', 'b', 't', 'n', 'v', 'f', 'r' };
git_str quoted = GIT_STR_INIT;
size_t i = 0;
bool quote = false;
int error = 0;
/* walk to the first char that needs quoting */
if (buf->size && buf->ptr[0] == '!')
quote = true;
for (i = 0; !quote && i < buf->size; i++) {
if (buf->ptr[i] == '"' || buf->ptr[i] == '\\' ||
buf->ptr[i] < ' ' || buf->ptr[i] > '~') {
quote = true;
break;
}
}
if (!quote)
goto done;
git_str_putc("ed, '"');
git_str_put("ed, buf->ptr, i);
for (; i < buf->size; i++) {
/* whitespace - use the map above, which is ordered by ascii value */
if (buf->ptr[i] >= '\a' && buf->ptr[i] <= '\r') {
git_str_putc("ed, '\\');
git_str_putc("ed, whitespace[buf->ptr[i] - '\a']);
}
/* double quote and backslash must be escaped */
else if (buf->ptr[i] == '"' || buf->ptr[i] == '\\') {
git_str_putc("ed, '\\');
git_str_putc("ed, buf->ptr[i]);
}
/* escape anything unprintable as octal */
else if (buf->ptr[i] != ' ' &&
(buf->ptr[i] < '!' || buf->ptr[i] > '~')) {
git_str_printf("ed, "\\%03o", (unsigned char)buf->ptr[i]);
}
/* yay, printable! */
else {
git_str_putc("ed, buf->ptr[i]);
}
}
git_str_putc("ed, '"');
if (git_str_oom("ed)) {
error = -1;
goto done;
}
git_str_swap("ed, buf);
done:
git_str_dispose("ed);
return error;
}
/* Unquote per http://marc.info/?l=git&m=112927316408690&w=2 */
int git_str_unquote(git_str *buf)
{
size_t i, j;
char ch;
git_str_rtrim(buf);
if (buf->size < 2 || buf->ptr[0] != '"' || buf->ptr[buf->size-1] != '"')
goto invalid;
for (i = 0, j = 1; j < buf->size-1; i++, j++) {
ch = buf->ptr[j];
if (ch == '\\') {
if (j == buf->size-2)
goto invalid;
ch = buf->ptr[++j];
switch (ch) {
/* \" or \\ simply copy the char in */
case '"': case '\\':
break;
/* add the appropriate escaped char */
case 'a': ch = '\a'; break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'n': ch = '\n'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case 'v': ch = '\v'; break;
/* \xyz digits convert to the char*/
case '0': case '1': case '2': case '3':
if (j == buf->size-3) {
git_error_set(GIT_ERROR_INVALID,
"truncated quoted character \\%c", ch);
return -1;
}
if (buf->ptr[j+1] < '0' || buf->ptr[j+1] > '7' ||
buf->ptr[j+2] < '0' || buf->ptr[j+2] > '7') {
git_error_set(GIT_ERROR_INVALID,
"truncated quoted character \\%c%c%c",
buf->ptr[j], buf->ptr[j+1], buf->ptr[j+2]);
return -1;
}
ch = ((buf->ptr[j] - '0') << 6) |
((buf->ptr[j+1] - '0') << 3) |
(buf->ptr[j+2] - '0');
j += 2;
break;
default:
git_error_set(GIT_ERROR_INVALID, "invalid quoted character \\%c", ch);
return -1;
}
}
buf->ptr[i] = ch;
}
buf->ptr[i] = '\0';
buf->size = i;
return 0;
invalid:
git_error_set(GIT_ERROR_INVALID, "invalid quoted line");
return -1;
}
int git_str_puts_escaped(
git_str *buf,
const char *string,
const char *esc_chars,
const char *esc_with)
{
const char *scan;
size_t total = 0, esc_len = strlen(esc_with), count, alloclen;
if (!string)
return 0;
for (scan = string; *scan; ) {
/* count run of non-escaped characters */
count = strcspn(scan, esc_chars);
total += count;
scan += count;
/* count run of escaped characters */
count = strspn(scan, esc_chars);
total += count * (esc_len + 1);
scan += count;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, total, 1);
if (git_str_grow_by(buf, alloclen) < 0)
return -1;
for (scan = string; *scan; ) {
count = strcspn(scan, esc_chars);
memmove(buf->ptr + buf->size, scan, count);
scan += count;
buf->size += count;
for (count = strspn(scan, esc_chars); count > 0; --count) {
/* copy escape sequence */
memmove(buf->ptr + buf->size, esc_with, esc_len);
buf->size += esc_len;
/* copy character to be escaped */
buf->ptr[buf->size] = *scan;
buf->size++;
scan++;
}
}
buf->ptr[buf->size] = '\0';
return 0;
}
void git_str_unescape(git_str *buf)
{
buf->size = git__unescape(buf->ptr);
}
int git_str_crlf_to_lf(git_str *tgt, const git_str *src)
{
const char *scan = src->ptr;
const char *scan_end = src->ptr + src->size;
const char *next = memchr(scan, '\r', src->size);
size_t new_size;
char *out;
GIT_ASSERT(tgt != src);
if (!next)
return git_str_set(tgt, src->ptr, src->size);
/* reduce reallocs while in the loop */
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, src->size, 1);
if (git_str_grow(tgt, new_size) < 0)
return -1;
out = tgt->ptr;
tgt->size = 0;
/* Find the next \r and copy whole chunk up to there to tgt */
for (; next; scan = next + 1, next = memchr(scan, '\r', scan_end - scan)) {
if (next > scan) {
size_t copylen = (size_t)(next - scan);
memcpy(out, scan, copylen);
out += copylen;
}
/* Do not drop \r unless it is followed by \n */
if (next + 1 == scan_end || next[1] != '\n')
*out++ = '\r';
}
/* Copy remaining input into dest */
if (scan < scan_end) {
size_t remaining = (size_t)(scan_end - scan);
memcpy(out, scan, remaining);
out += remaining;
}
tgt->size = (size_t)(out - tgt->ptr);
tgt->ptr[tgt->size] = '\0';
return 0;
}
int git_str_lf_to_crlf(git_str *tgt, const git_str *src)
{
const char *start = src->ptr;
const char *end = start + src->size;
const char *scan = start;
const char *next = memchr(scan, '\n', src->size);
size_t alloclen;
GIT_ASSERT(tgt != src);
if (!next)
return git_str_set(tgt, src->ptr, src->size);
/* attempt to reduce reallocs while in the loop */
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, src->size, src->size >> 4);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
if (git_str_grow(tgt, alloclen) < 0)
return -1;
tgt->size = 0;
for (; next; scan = next + 1, next = memchr(scan, '\n', end - scan)) {
size_t copylen = next - scan;
/* if we find mixed line endings, carry on */
if (copylen && next[-1] == '\r')
copylen--;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, copylen, 3);
if (git_str_grow_by(tgt, alloclen) < 0)
return -1;
if (copylen) {
memcpy(tgt->ptr + tgt->size, scan, copylen);
tgt->size += copylen;
}
tgt->ptr[tgt->size++] = '\r';
tgt->ptr[tgt->size++] = '\n';
}
tgt->ptr[tgt->size] = '\0';
return git_str_put(tgt, scan, end - scan);
}
int git_str_common_prefix(git_str *buf, char *const *const strings, size_t count)
{
size_t i;
const char *str, *pfx;
git_str_clear(buf);
if (!strings || !count)
return 0;
/* initialize common prefix to first string */
if (git_str_sets(buf, strings[0]) < 0)
return -1;
/* go through the rest of the strings, truncating to shared prefix */
for (i = 1; i < count; ++i) {
for (str = strings[i], pfx = buf->ptr;
*str && *str == *pfx;
str++, pfx++)
/* scanning */;
git_str_truncate(buf, pfx - buf->ptr);
if (!buf->size)
break;
}
return 0;
}
int git_str_is_binary(const git_str *buf)
{
const char *scan = buf->ptr, *end = buf->ptr + buf->size;
git_str_bom_t bom;
int printable = 0, nonprintable = 0;
scan += git_str_detect_bom(&bom, buf);
if (bom > GIT_STR_BOM_UTF8)
return 1;
while (scan < end) {
unsigned char c = *scan++;
/* Printable characters are those above SPACE (0x1F) excluding DEL,
* and including BS, ESC and FF.
*/
if ((c > 0x1F && c != 127) || c == '\b' || c == '\033' || c == '\014')
printable++;
else if (c == '\0')
return true;
else if (!git__isspace(c))
nonprintable++;
}
return ((printable >> 7) < nonprintable);
}
int git_str_contains_nul(const git_str *buf)
{
return (memchr(buf->ptr, '\0', buf->size) != NULL);
}
int git_str_detect_bom(git_str_bom_t *bom, const git_str *buf)
{
const char *ptr;
size_t len;
*bom = GIT_STR_BOM_NONE;
/* need at least 2 bytes to look for any BOM */
if (buf->size < 2)
return 0;
ptr = buf->ptr;
len = buf->size;
switch (*ptr++) {
case 0:
if (len >= 4 && ptr[0] == 0 && ptr[1] == '\xFE' && ptr[2] == '\xFF') {
*bom = GIT_STR_BOM_UTF32_BE;
return 4;
}
break;
case '\xEF':
if (len >= 3 && ptr[0] == '\xBB' && ptr[1] == '\xBF') {
*bom = GIT_STR_BOM_UTF8;
return 3;
}
break;
case '\xFE':
if (*ptr == '\xFF') {
*bom = GIT_STR_BOM_UTF16_BE;
return 2;
}
break;
case '\xFF':
if (*ptr != '\xFE')
break;
if (len >= 4 && ptr[1] == 0 && ptr[2] == 0) {
*bom = GIT_STR_BOM_UTF32_LE;
return 4;
} else {
*bom = GIT_STR_BOM_UTF16_LE;
return 2;
}
break;
default:
break;
}
return 0;
}
bool git_str_gather_text_stats(
git_str_text_stats *stats, const git_str *buf, bool skip_bom)
{
const char *scan = buf->ptr, *end = buf->ptr + buf->size;
int skip;
memset(stats, 0, sizeof(*stats));
/* BOM detection */
skip = git_str_detect_bom(&stats->bom, buf);
if (skip_bom)
scan += skip;
/* Ignore EOF character */
if (buf->size > 0 && end[-1] == '\032')
end--;
/* Counting loop */
while (scan < end) {
unsigned char c = *scan++;
if (c > 0x1F && c != 0x7F)
stats->printable++;
else switch (c) {
case '\0':
stats->nul++;
stats->nonprintable++;
break;
case '\n':
stats->lf++;
break;
case '\r':
stats->cr++;
if (scan < end && *scan == '\n')
stats->crlf++;
break;
case '\t': case '\f': case '\v': case '\b': case 0x1b: /*ESC*/
stats->printable++;
break;
default:
stats->nonprintable++;
break;
}
}
/* Treat files with a bare CR as binary */
return (stats->cr != stats->crlf || stats->nul > 0 ||
((stats->printable >> 7) < stats->nonprintable));
}
| libgit2-main | src/util/str.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "filebuf.h"
#include "futils.h"
static const size_t WRITE_BUFFER_SIZE = (4096 * 2);
enum buferr_t {
BUFERR_OK = 0,
BUFERR_WRITE,
BUFERR_ZLIB,
BUFERR_MEM
};
#define ENSURE_BUF_OK(buf) if ((buf)->last_error != BUFERR_OK) { return -1; }
static int verify_last_error(git_filebuf *file)
{
switch (file->last_error) {
case BUFERR_WRITE:
git_error_set(GIT_ERROR_OS, "failed to write out file");
return -1;
case BUFERR_MEM:
git_error_set_oom();
return -1;
case BUFERR_ZLIB:
git_error_set(GIT_ERROR_ZLIB,
"Buffer error when writing out ZLib data");
return -1;
default:
return 0;
}
}
static int lock_file(git_filebuf *file, int flags, mode_t mode)
{
if (git_fs_path_exists(file->path_lock) == true) {
git_error_clear(); /* actual OS error code just confuses */
git_error_set(GIT_ERROR_OS,
"failed to lock file '%s' for writing", file->path_lock);
return GIT_ELOCKED;
}
/* create path to the file buffer is required */
if (flags & GIT_FILEBUF_CREATE_LEADING_DIRS) {
/* XXX: Should dirmode here be configurable? Or is 0777 always fine? */
file->fd = git_futils_creat_locked_withpath(file->path_lock, 0777, mode);
} else {
file->fd = git_futils_creat_locked(file->path_lock, mode);
}
if (file->fd < 0)
return file->fd;
file->fd_is_open = true;
if ((flags & GIT_FILEBUF_APPEND) && git_fs_path_exists(file->path_original) == true) {
git_file source;
char buffer[GIT_BUFSIZE_FILEIO];
ssize_t read_bytes;
int error = 0;
source = p_open(file->path_original, O_RDONLY);
if (source < 0) {
git_error_set(GIT_ERROR_OS,
"failed to open file '%s' for reading",
file->path_original);
return -1;
}
while ((read_bytes = p_read(source, buffer, sizeof(buffer))) > 0) {
if ((error = p_write(file->fd, buffer, read_bytes)) < 0)
break;
if (file->compute_digest)
git_hash_update(&file->digest, buffer, read_bytes);
}
p_close(source);
if (read_bytes < 0) {
git_error_set(GIT_ERROR_OS, "failed to read file '%s'", file->path_original);
return -1;
} else if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to write file '%s'", file->path_lock);
return -1;
}
}
return 0;
}
void git_filebuf_cleanup(git_filebuf *file)
{
if (file->fd_is_open && file->fd >= 0)
p_close(file->fd);
if (file->created_lock && !file->did_rename && file->path_lock && git_fs_path_exists(file->path_lock))
p_unlink(file->path_lock);
if (file->compute_digest) {
git_hash_ctx_cleanup(&file->digest);
file->compute_digest = 0;
}
if (file->buffer)
git__free(file->buffer);
/* use the presence of z_buf to decide if we need to deflateEnd */
if (file->z_buf) {
git__free(file->z_buf);
deflateEnd(&file->zs);
}
if (file->path_original)
git__free(file->path_original);
if (file->path_lock)
git__free(file->path_lock);
memset(file, 0x0, sizeof(git_filebuf));
file->fd = -1;
}
GIT_INLINE(int) flush_buffer(git_filebuf *file)
{
int result = file->write(file, file->buffer, file->buf_pos);
file->buf_pos = 0;
return result;
}
int git_filebuf_flush(git_filebuf *file)
{
return flush_buffer(file);
}
static int write_normal(git_filebuf *file, void *source, size_t len)
{
if (len > 0) {
if (p_write(file->fd, (void *)source, len) < 0) {
file->last_error = BUFERR_WRITE;
return -1;
}
if (file->compute_digest)
git_hash_update(&file->digest, source, len);
}
return 0;
}
static int write_deflate(git_filebuf *file, void *source, size_t len)
{
z_stream *zs = &file->zs;
if (len > 0 || file->flush_mode == Z_FINISH) {
zs->next_in = source;
zs->avail_in = (uInt)len;
do {
size_t have;
zs->next_out = file->z_buf;
zs->avail_out = (uInt)file->buf_size;
if (deflate(zs, file->flush_mode) == Z_STREAM_ERROR) {
file->last_error = BUFERR_ZLIB;
return -1;
}
have = file->buf_size - (size_t)zs->avail_out;
if (p_write(file->fd, file->z_buf, have) < 0) {
file->last_error = BUFERR_WRITE;
return -1;
}
} while (zs->avail_out == 0);
GIT_ASSERT(zs->avail_in == 0);
if (file->compute_digest)
git_hash_update(&file->digest, source, len);
}
return 0;
}
#define MAX_SYMLINK_DEPTH 5
static int resolve_symlink(git_str *out, const char *path)
{
int i, error, root;
ssize_t ret;
struct stat st;
git_str curpath = GIT_STR_INIT, target = GIT_STR_INIT;
if ((error = git_str_grow(&target, GIT_PATH_MAX + 1)) < 0 ||
(error = git_str_puts(&curpath, path)) < 0)
return error;
for (i = 0; i < MAX_SYMLINK_DEPTH; i++) {
error = p_lstat(curpath.ptr, &st);
if (error < 0 && errno == ENOENT) {
error = git_str_puts(out, curpath.ptr);
goto cleanup;
}
if (error < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", curpath.ptr);
error = -1;
goto cleanup;
}
if (!S_ISLNK(st.st_mode)) {
error = git_str_puts(out, curpath.ptr);
goto cleanup;
}
ret = p_readlink(curpath.ptr, target.ptr, GIT_PATH_MAX);
if (ret < 0) {
git_error_set(GIT_ERROR_OS, "failed to read symlink '%s'", curpath.ptr);
error = -1;
goto cleanup;
}
if (ret == GIT_PATH_MAX) {
git_error_set(GIT_ERROR_INVALID, "symlink target too long");
error = -1;
goto cleanup;
}
/* readlink(2) won't NUL-terminate for us */
target.ptr[ret] = '\0';
target.size = ret;
root = git_fs_path_root(target.ptr);
if (root >= 0) {
if ((error = git_str_sets(&curpath, target.ptr)) < 0)
goto cleanup;
} else {
git_str dir = GIT_STR_INIT;
if ((error = git_fs_path_dirname_r(&dir, curpath.ptr)) < 0)
goto cleanup;
git_str_swap(&curpath, &dir);
git_str_dispose(&dir);
if ((error = git_fs_path_apply_relative(&curpath, target.ptr)) < 0)
goto cleanup;
}
}
git_error_set(GIT_ERROR_INVALID, "maximum symlink depth reached");
error = -1;
cleanup:
git_str_dispose(&curpath);
git_str_dispose(&target);
return error;
}
int git_filebuf_open(git_filebuf *file, const char *path, int flags, mode_t mode)
{
return git_filebuf_open_withsize(file, path, flags, mode, WRITE_BUFFER_SIZE);
}
int git_filebuf_open_withsize(git_filebuf *file, const char *path, int flags, mode_t mode, size_t size)
{
int compression, error = -1;
size_t path_len, alloc_len;
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(path);
GIT_ASSERT(file->buffer == NULL);
memset(file, 0x0, sizeof(git_filebuf));
if (flags & GIT_FILEBUF_DO_NOT_BUFFER)
file->do_not_buffer = true;
if (flags & GIT_FILEBUF_FSYNC)
file->do_fsync = true;
file->buf_size = size;
file->buf_pos = 0;
file->fd = -1;
file->last_error = BUFERR_OK;
/* Allocate the main cache buffer */
if (!file->do_not_buffer) {
file->buffer = git__malloc(file->buf_size);
GIT_ERROR_CHECK_ALLOC(file->buffer);
}
/* If we are hashing on-write, allocate a new hash context */
if (flags & GIT_FILEBUF_HASH_CONTENTS) {
file->compute_digest = 1;
if (git_hash_ctx_init(&file->digest, GIT_HASH_ALGORITHM_SHA1) < 0)
goto cleanup;
}
compression = flags >> GIT_FILEBUF_DEFLATE_SHIFT;
/* If we are deflating on-write, */
if (compression != 0) {
/* Initialize the ZLib stream */
if (deflateInit(&file->zs, compression) != Z_OK) {
git_error_set(GIT_ERROR_ZLIB, "failed to initialize zlib");
goto cleanup;
}
/* Allocate the Zlib cache buffer */
file->z_buf = git__malloc(file->buf_size);
GIT_ERROR_CHECK_ALLOC(file->z_buf);
/* Never flush */
file->flush_mode = Z_NO_FLUSH;
file->write = &write_deflate;
} else {
file->write = &write_normal;
}
/* If we are writing to a temp file */
if (flags & GIT_FILEBUF_TEMPORARY) {
git_str tmp_path = GIT_STR_INIT;
/* Open the file as temporary for locking */
file->fd = git_futils_mktmp(&tmp_path, path, mode);
if (file->fd < 0) {
git_str_dispose(&tmp_path);
goto cleanup;
}
file->fd_is_open = true;
file->created_lock = true;
/* No original path */
file->path_original = NULL;
file->path_lock = git_str_detach(&tmp_path);
GIT_ERROR_CHECK_ALLOC(file->path_lock);
} else {
git_str resolved_path = GIT_STR_INIT;
if ((error = resolve_symlink(&resolved_path, path)) < 0)
goto cleanup;
/* Save the original path of the file */
path_len = resolved_path.size;
file->path_original = git_str_detach(&resolved_path);
/* create the locking path by appending ".lock" to the original */
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, path_len, GIT_FILELOCK_EXTLENGTH);
file->path_lock = git__malloc(alloc_len);
GIT_ERROR_CHECK_ALLOC(file->path_lock);
memcpy(file->path_lock, file->path_original, path_len);
memcpy(file->path_lock + path_len, GIT_FILELOCK_EXTENSION, GIT_FILELOCK_EXTLENGTH);
if (git_fs_path_isdir(file->path_original)) {
git_error_set(GIT_ERROR_FILESYSTEM, "path '%s' is a directory", file->path_original);
error = GIT_EDIRECTORY;
goto cleanup;
}
/* open the file for locking */
if ((error = lock_file(file, flags, mode)) < 0)
goto cleanup;
file->created_lock = true;
}
return 0;
cleanup:
git_filebuf_cleanup(file);
return error;
}
int git_filebuf_hash(unsigned char *out, git_filebuf *file)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(file->compute_digest);
flush_buffer(file);
if (verify_last_error(file) < 0)
return -1;
git_hash_final(out, &file->digest);
git_hash_ctx_cleanup(&file->digest);
file->compute_digest = 0;
return 0;
}
int git_filebuf_commit_at(git_filebuf *file, const char *path)
{
git__free(file->path_original);
file->path_original = git__strdup(path);
GIT_ERROR_CHECK_ALLOC(file->path_original);
return git_filebuf_commit(file);
}
int git_filebuf_commit(git_filebuf *file)
{
/* temporary files cannot be committed */
GIT_ASSERT_ARG(file);
GIT_ASSERT(file->path_original);
file->flush_mode = Z_FINISH;
flush_buffer(file);
if (verify_last_error(file) < 0)
goto on_error;
file->fd_is_open = false;
if (file->do_fsync && p_fsync(file->fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to fsync '%s'", file->path_lock);
goto on_error;
}
if (p_close(file->fd) < 0) {
git_error_set(GIT_ERROR_OS, "failed to close file at '%s'", file->path_lock);
goto on_error;
}
file->fd = -1;
if (p_rename(file->path_lock, file->path_original) < 0) {
git_error_set(GIT_ERROR_OS, "failed to rename lockfile to '%s'", file->path_original);
goto on_error;
}
if (file->do_fsync && git_futils_fsync_parent(file->path_original) < 0)
goto on_error;
file->did_rename = true;
git_filebuf_cleanup(file);
return 0;
on_error:
git_filebuf_cleanup(file);
return -1;
}
GIT_INLINE(void) add_to_cache(git_filebuf *file, const void *buf, size_t len)
{
memcpy(file->buffer + file->buf_pos, buf, len);
file->buf_pos += len;
}
int git_filebuf_write(git_filebuf *file, const void *buff, size_t len)
{
const unsigned char *buf = buff;
ENSURE_BUF_OK(file);
if (file->do_not_buffer)
return file->write(file, (void *)buff, len);
for (;;) {
size_t space_left = file->buf_size - file->buf_pos;
/* cache if it's small */
if (space_left > len) {
add_to_cache(file, buf, len);
return 0;
}
add_to_cache(file, buf, space_left);
if (flush_buffer(file) < 0)
return -1;
len -= space_left;
buf += space_left;
}
}
int git_filebuf_reserve(git_filebuf *file, void **buffer, size_t len)
{
size_t space_left = file->buf_size - file->buf_pos;
*buffer = NULL;
ENSURE_BUF_OK(file);
if (len > file->buf_size) {
file->last_error = BUFERR_MEM;
return -1;
}
if (space_left <= len) {
if (flush_buffer(file) < 0)
return -1;
}
*buffer = (file->buffer + file->buf_pos);
file->buf_pos += len;
return 0;
}
int git_filebuf_printf(git_filebuf *file, const char *format, ...)
{
va_list arglist;
size_t space_left, len, alloclen;
int written, res;
char *tmp_buffer;
ENSURE_BUF_OK(file);
space_left = file->buf_size - file->buf_pos;
do {
va_start(arglist, format);
written = p_vsnprintf((char *)file->buffer + file->buf_pos, space_left, format, arglist);
va_end(arglist);
if (written < 0) {
file->last_error = BUFERR_MEM;
return -1;
}
len = written;
if (len + 1 <= space_left) {
file->buf_pos += len;
return 0;
}
if (flush_buffer(file) < 0)
return -1;
space_left = file->buf_size - file->buf_pos;
} while (len + 1 <= space_left);
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, len, 1) ||
!(tmp_buffer = git__malloc(alloclen))) {
file->last_error = BUFERR_MEM;
return -1;
}
va_start(arglist, format);
written = p_vsnprintf(tmp_buffer, len + 1, format, arglist);
va_end(arglist);
if (written < 0) {
git__free(tmp_buffer);
file->last_error = BUFERR_MEM;
return -1;
}
res = git_filebuf_write(file, tmp_buffer, len);
git__free(tmp_buffer);
return res;
}
int git_filebuf_stats(time_t *mtime, size_t *size, git_filebuf *file)
{
int res;
struct stat st;
if (file->fd_is_open)
res = p_fstat(file->fd, &st);
else
res = p_stat(file->path_original, &st);
if (res < 0) {
git_error_set(GIT_ERROR_OS, "could not get stat info for '%s'",
file->path_original);
return res;
}
if (mtime)
*mtime = st.st_mtime;
if (size)
*size = (size_t)st.st_size;
return 0;
}
| libgit2-main | src/util/filebuf.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "pqueue.h"
#include "util.h"
#define PQUEUE_LCHILD_OF(I) (((I)<<1)+1)
#define PQUEUE_RCHILD_OF(I) (((I)<<1)+2)
#define PQUEUE_PARENT_OF(I) (((I)-1)>>1)
int git_pqueue_init(
git_pqueue *pq,
uint32_t flags,
size_t init_size,
git_vector_cmp cmp)
{
int error = git_vector_init(pq, init_size, cmp);
if (!error) {
/* mix in our flags */
pq->flags |= flags;
/* if fixed size heap, pretend vector is exactly init_size elements */
if ((flags & GIT_PQUEUE_FIXED_SIZE) && init_size > 0)
pq->_alloc_size = init_size;
}
return error;
}
static void pqueue_up(git_pqueue *pq, size_t el)
{
size_t parent_el = PQUEUE_PARENT_OF(el);
void *kid = git_vector_get(pq, el);
while (el > 0) {
void *parent = pq->contents[parent_el];
if (pq->_cmp(parent, kid) <= 0)
break;
pq->contents[el] = parent;
el = parent_el;
parent_el = PQUEUE_PARENT_OF(el);
}
pq->contents[el] = kid;
}
static void pqueue_down(git_pqueue *pq, size_t el)
{
void *parent = git_vector_get(pq, el), *kid, *rkid;
while (1) {
size_t kid_el = PQUEUE_LCHILD_OF(el);
if ((kid = git_vector_get(pq, kid_el)) == NULL)
break;
if ((rkid = git_vector_get(pq, kid_el + 1)) != NULL &&
pq->_cmp(kid, rkid) > 0) {
kid = rkid;
kid_el += 1;
}
if (pq->_cmp(parent, kid) <= 0)
break;
pq->contents[el] = kid;
el = kid_el;
}
pq->contents[el] = parent;
}
int git_pqueue_insert(git_pqueue *pq, void *item)
{
int error = 0;
/* if heap is full, pop the top element if new one should replace it */
if ((pq->flags & GIT_PQUEUE_FIXED_SIZE) != 0 &&
pq->length >= pq->_alloc_size)
{
/* skip this item if below min item in heap or if
* we do not have a comparison function */
if (!pq->_cmp || pq->_cmp(item, git_vector_get(pq, 0)) <= 0)
return 0;
/* otherwise remove the min item before inserting new */
(void)git_pqueue_pop(pq);
}
if (!(error = git_vector_insert(pq, item)) && pq->_cmp)
pqueue_up(pq, pq->length - 1);
return error;
}
void *git_pqueue_pop(git_pqueue *pq)
{
void *rval;
if (!pq->_cmp) {
rval = git_vector_last(pq);
} else {
rval = git_pqueue_get(pq, 0);
}
if (git_pqueue_size(pq) > 1 && pq->_cmp) {
/* move last item to top of heap, shrink, and push item down */
pq->contents[0] = git_vector_last(pq);
git_vector_pop(pq);
pqueue_down(pq, 0);
} else {
/* all we need to do is shrink the heap in this case */
git_vector_pop(pq);
}
return rval;
}
| libgit2-main | src/util/pqueue.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "utf8.h"
#include "git2_util.h"
/*
* git_utf8_iterate is taken from the utf8proc project,
* http://www.public-software-group.org/utf8proc
*
* Copyright (c) 2009 Public Software Group e. V., Berlin, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the ""Software""),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
static const uint8_t utf8proc_utf8class[256] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0
};
static int utf8_charlen(const uint8_t *str, size_t str_len)
{
uint8_t length;
size_t i;
length = utf8proc_utf8class[str[0]];
if (!length)
return -1;
if (str_len > 0 && length > str_len)
return -1;
for (i = 1; i < length; i++) {
if ((str[i] & 0xC0) != 0x80)
return -1;
}
return (int)length;
}
int git_utf8_iterate(uint32_t *out, const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
uint32_t uc = 0;
int length;
*out = 0;
if ((length = utf8_charlen(str, str_len)) < 0)
return -1;
switch (length) {
case 1:
uc = str[0];
break;
case 2:
uc = ((str[0] & 0x1F) << 6) + (str[1] & 0x3F);
if (uc < 0x80) uc = -1;
break;
case 3:
uc = ((str[0] & 0x0F) << 12) + ((str[1] & 0x3F) << 6)
+ (str[2] & 0x3F);
if (uc < 0x800 || (uc >= 0xD800 && uc < 0xE000) ||
(uc >= 0xFDD0 && uc < 0xFDF0)) uc = -1;
break;
case 4:
uc = ((str[0] & 0x07) << 18) + ((str[1] & 0x3F) << 12)
+ ((str[2] & 0x3F) << 6) + (str[3] & 0x3F);
if (uc < 0x10000 || uc >= 0x110000) uc = -1;
break;
default:
return -1;
}
if ((uc & 0xFFFF) >= 0xFFFE)
return -1;
*out = uc;
return length;
}
size_t git_utf8_char_length(const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
size_t offset = 0, count = 0;
while (offset < str_len) {
int length = utf8_charlen(str + offset, str_len - offset);
if (length < 0)
length = 1;
offset += length;
count++;
}
return count;
}
size_t git_utf8_valid_buf_length(const char *_str, size_t str_len)
{
const uint8_t *str = (const uint8_t *)_str;
size_t offset = 0;
while (offset < str_len) {
int length = utf8_charlen(str + offset, str_len - offset);
if (length < 0)
break;
offset += length;
}
return offset;
}
| libgit2-main | src/util/utf8.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "regexp.h"
#if defined(GIT_REGEX_BUILTIN) || defined(GIT_REGEX_PCRE)
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
int erroffset, cflags = 0;
const char *error = NULL;
if (flags & GIT_REGEXP_ICASE)
cflags |= PCRE_CASELESS;
if ((*r = pcre_compile(pattern, cflags, &error, &erroffset, NULL)) == NULL) {
git_error_set_str(GIT_ERROR_REGEX, error);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
pcre_free(*r);
*r = NULL;
}
int git_regexp_match(const git_regexp *r, const char *string)
{
int error;
if ((error = pcre_exec(*r, NULL, string, (int) strlen(string), 0, 0, NULL, 0)) < 0)
return (error == PCRE_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
int static_ovec[9] = {0}, *ovec;
int error;
size_t i;
/* The ovec array always needs to be a multiple of three */
if (nmatches <= ARRAY_SIZE(static_ovec) / 3)
ovec = static_ovec;
else
ovec = git__calloc(nmatches * 3, sizeof(*ovec));
GIT_ERROR_CHECK_ALLOC(ovec);
if ((error = pcre_exec(*r, NULL, string, (int) strlen(string), 0, 0, ovec, (int) nmatches * 3)) < 0)
goto out;
if (error == 0)
error = (int) nmatches;
for (i = 0; i < (unsigned int) error; i++) {
matches[i].start = (ovec[i * 2] < 0) ? -1 : ovec[i * 2];
matches[i].end = (ovec[i * 2 + 1] < 0) ? -1 : ovec[i * 2 + 1];
}
for (i = (unsigned int) error; i < nmatches; i++)
matches[i].start = matches[i].end = -1;
out:
if (nmatches > ARRAY_SIZE(static_ovec) / 3)
git__free(ovec);
if (error < 0)
return (error == PCRE_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#elif defined(GIT_REGEX_PCRE2)
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
unsigned char errmsg[1024];
PCRE2_SIZE erroff;
int error, cflags = 0;
if (flags & GIT_REGEXP_ICASE)
cflags |= PCRE2_CASELESS;
if ((*r = pcre2_compile((const unsigned char *) pattern, PCRE2_ZERO_TERMINATED,
cflags, &error, &erroff, NULL)) == NULL) {
pcre2_get_error_message(error, errmsg, sizeof(errmsg));
git_error_set_str(GIT_ERROR_REGEX, (char *) errmsg);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
pcre2_code_free(*r);
*r = NULL;
}
int git_regexp_match(const git_regexp *r, const char *string)
{
pcre2_match_data *data;
int error;
data = pcre2_match_data_create(1, NULL);
GIT_ERROR_CHECK_ALLOC(data);
if ((error = pcre2_match(*r, (const unsigned char *) string, strlen(string),
0, 0, data, NULL)) < 0)
return (error == PCRE2_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
pcre2_match_data_free(data);
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
pcre2_match_data *data = NULL;
PCRE2_SIZE *ovec;
int error;
size_t i;
if ((data = pcre2_match_data_create(nmatches, NULL)) == NULL) {
git_error_set_oom();
goto out;
}
if ((error = pcre2_match(*r, (const unsigned char *) string, strlen(string),
0, 0, data, NULL)) < 0)
goto out;
if (error == 0 || (unsigned int) error > nmatches)
error = nmatches;
ovec = pcre2_get_ovector_pointer(data);
for (i = 0; i < (unsigned int) error; i++) {
matches[i].start = (ovec[i * 2] == PCRE2_UNSET) ? -1 : (ssize_t) ovec[i * 2];
matches[i].end = (ovec[i * 2 + 1] == PCRE2_UNSET) ? -1 : (ssize_t) ovec[i * 2 + 1];
}
for (i = (unsigned int) error; i < nmatches; i++)
matches[i].start = matches[i].end = -1;
out:
pcre2_match_data_free(data);
if (error < 0)
return (error == PCRE2_ERROR_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#elif defined(GIT_REGEX_REGCOMP) || defined(GIT_REGEX_REGCOMP_L)
#if defined(GIT_REGEX_REGCOMP_L)
# include <xlocale.h>
#endif
int git_regexp_compile(git_regexp *r, const char *pattern, int flags)
{
int cflags = REG_EXTENDED, error;
char errmsg[1024];
if (flags & GIT_REGEXP_ICASE)
cflags |= REG_ICASE;
# if defined(GIT_REGEX_REGCOMP)
if ((error = regcomp(r, pattern, cflags)) != 0)
# else
if ((error = regcomp_l(r, pattern, cflags, (locale_t) 0)) != 0)
# endif
{
regerror(error, r, errmsg, sizeof(errmsg));
git_error_set_str(GIT_ERROR_REGEX, errmsg);
return GIT_EINVALIDSPEC;
}
return 0;
}
void git_regexp_dispose(git_regexp *r)
{
regfree(r);
}
int git_regexp_match(const git_regexp *r, const char *string)
{
int error;
if ((error = regexec(r, string, 0, NULL, 0)) != 0)
return (error == REG_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
int git_regexp_search(const git_regexp *r, const char *string, size_t nmatches, git_regmatch *matches)
{
regmatch_t static_m[3], *m;
int error;
size_t i;
if (nmatches <= ARRAY_SIZE(static_m))
m = static_m;
else
m = git__calloc(nmatches, sizeof(*m));
if ((error = regexec(r, string, nmatches, m, 0)) != 0)
goto out;
for (i = 0; i < nmatches; i++) {
matches[i].start = (m[i].rm_so < 0) ? -1 : m[i].rm_so;
matches[i].end = (m[i].rm_eo < 0) ? -1 : m[i].rm_eo;
}
out:
if (nmatches > ARRAY_SIZE(static_m))
git__free(m);
if (error)
return (error == REG_NOMATCH) ? GIT_ENOTFOUND : GIT_EINVALIDSPEC;
return 0;
}
#endif
| libgit2-main | src/util/regexp.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "alloc.h"
#include "runtime.h"
#include "allocators/failalloc.h"
#include "allocators/stdalloc.h"
#include "allocators/win32_leakcheck.h"
/* Fail any allocation until git_libgit2_init is called. */
git_allocator git__allocator = {
git_failalloc_malloc,
git_failalloc_calloc,
git_failalloc_strdup,
git_failalloc_strndup,
git_failalloc_substrdup,
git_failalloc_realloc,
git_failalloc_reallocarray,
git_failalloc_mallocarray,
git_failalloc_free
};
static int setup_default_allocator(void)
{
#if defined(GIT_WIN32_LEAKCHECK)
return git_win32_leakcheck_init_allocator(&git__allocator);
#else
return git_stdalloc_init_allocator(&git__allocator);
#endif
}
int git_allocator_global_init(void)
{
/*
* We don't want to overwrite any allocator which has been set
* before the init function is called.
*/
if (git__allocator.gmalloc != git_failalloc_malloc)
return 0;
return setup_default_allocator();
}
int git_allocator_setup(git_allocator *allocator)
{
if (!allocator)
return setup_default_allocator();
memcpy(&git__allocator, allocator, sizeof(*allocator));
return 0;
}
| libgit2-main | src/util/alloc.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "hash.h"
int git_hash_global_init(void)
{
if (git_hash_sha1_global_init() < 0 ||
git_hash_sha256_global_init() < 0)
return -1;
return 0;
}
int git_hash_ctx_init(git_hash_ctx *ctx, git_hash_algorithm_t algorithm)
{
int error;
switch (algorithm) {
case GIT_HASH_ALGORITHM_SHA1:
error = git_hash_sha1_ctx_init(&ctx->ctx.sha1);
break;
case GIT_HASH_ALGORITHM_SHA256:
error = git_hash_sha256_ctx_init(&ctx->ctx.sha256);
break;
default:
git_error_set(GIT_ERROR_INTERNAL, "unknown hash algorithm");
error = -1;
}
ctx->algorithm = algorithm;
return error;
}
void git_hash_ctx_cleanup(git_hash_ctx *ctx)
{
switch (ctx->algorithm) {
case GIT_HASH_ALGORITHM_SHA1:
git_hash_sha1_ctx_cleanup(&ctx->ctx.sha1);
return;
case GIT_HASH_ALGORITHM_SHA256:
git_hash_sha256_ctx_cleanup(&ctx->ctx.sha256);
return;
default:
/* unreachable */ ;
}
}
int git_hash_init(git_hash_ctx *ctx)
{
switch (ctx->algorithm) {
case GIT_HASH_ALGORITHM_SHA1:
return git_hash_sha1_init(&ctx->ctx.sha1);
case GIT_HASH_ALGORITHM_SHA256:
return git_hash_sha256_init(&ctx->ctx.sha256);
default:
/* unreachable */ ;
}
git_error_set(GIT_ERROR_INTERNAL, "unknown hash algorithm");
return -1;
}
int git_hash_update(git_hash_ctx *ctx, const void *data, size_t len)
{
switch (ctx->algorithm) {
case GIT_HASH_ALGORITHM_SHA1:
return git_hash_sha1_update(&ctx->ctx.sha1, data, len);
case GIT_HASH_ALGORITHM_SHA256:
return git_hash_sha256_update(&ctx->ctx.sha256, data, len);
default:
/* unreachable */ ;
}
git_error_set(GIT_ERROR_INTERNAL, "unknown hash algorithm");
return -1;
}
int git_hash_final(unsigned char *out, git_hash_ctx *ctx)
{
switch (ctx->algorithm) {
case GIT_HASH_ALGORITHM_SHA1:
return git_hash_sha1_final(out, &ctx->ctx.sha1);
case GIT_HASH_ALGORITHM_SHA256:
return git_hash_sha256_final(out, &ctx->ctx.sha256);
default:
/* unreachable */ ;
}
git_error_set(GIT_ERROR_INTERNAL, "unknown hash algorithm");
return -1;
}
int git_hash_buf(
unsigned char *out,
const void *data,
size_t len,
git_hash_algorithm_t algorithm)
{
git_hash_ctx ctx;
int error = 0;
if (git_hash_ctx_init(&ctx, algorithm) < 0)
return -1;
if ((error = git_hash_update(&ctx, data, len)) >= 0)
error = git_hash_final(out, &ctx);
git_hash_ctx_cleanup(&ctx);
return error;
}
int git_hash_vec(
unsigned char *out,
git_str_vec *vec,
size_t n,
git_hash_algorithm_t algorithm)
{
git_hash_ctx ctx;
size_t i;
int error = 0;
if (git_hash_ctx_init(&ctx, algorithm) < 0)
return -1;
for (i = 0; i < n; i++) {
if ((error = git_hash_update(&ctx, vec[i].data, vec[i].len)) < 0)
goto done;
}
error = git_hash_final(out, &ctx);
done:
git_hash_ctx_cleanup(&ctx);
return error;
}
int git_hash_fmt(char *out, unsigned char *hash, size_t hash_len)
{
static char hex[] = "0123456789abcdef";
char *str = out;
size_t i;
for (i = 0; i < hash_len; i++) {
*str++ = hex[hash[i] >> 4];
*str++ = hex[hash[i] & 0x0f];
}
*str++ = '\0';
return 0;
}
| libgit2-main | src/util/hash.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "fs_path.h"
#include "git2_util.h"
#include "futils.h"
#include "posix.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
#define ensure_error_set(code) do { \
const git_error *e = git_error_last(); \
if (!e || !e->message) \
git_error_set(e ? e->klass : GIT_ERROR_CALLBACK, \
"filesystem callback returned %d", code); \
} while(0)
static int dos_drive_prefix_length(const char *path)
{
int i;
/*
* Does it start with an ASCII letter (i.e. highest bit not set),
* followed by a colon?
*/
if (!(0x80 & (unsigned char)*path))
return *path && path[1] == ':' ? 2 : 0;
/*
* While drive letters must be letters of the English alphabet, it is
* possible to assign virtually _any_ Unicode character via `subst` as
* a drive letter to "virtual drives". Even `1`, or `ä`. Or fun stuff
* like this:
*
* subst ֍: %USERPROFILE%\Desktop
*/
for (i = 1; i < 4 && (0x80 & (unsigned char)path[i]); i++)
; /* skip first UTF-8 character */
return path[i] == ':' ? i + 1 : 0;
}
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_fs_path_basename_r(git_str *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_str_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual length. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git'
* will return 'C:/' here
*/
if (dos_drive_prefix_length(path) == len)
return len;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_fs_path_dirname_r(git_str *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
return -1;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
return -1;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_str_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_str_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_fs_path_dirname(const char *path)
{
git_str buf = GIT_STR_INIT;
char *dirname;
git_fs_path_dirname_r(&buf, path);
dirname = git_str_detach(&buf);
git_str_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_fs_path_basename(const char *path)
{
git_str buf = GIT_STR_INIT;
char *basename;
git_fs_path_basename_r(&buf, path);
basename = git_str_detach(&buf);
git_str_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_fs_path_basename_offset(git_str *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_str_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
int git_fs_path_root(const char *path)
{
int offset = 0, prefix_len;
/* Does the root of the path look like a windows drive ? */
if ((prefix_len = dos_drive_prefix_length(path)))
offset += prefix_len;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
static void path_trim_slashes(git_str *path)
{
int ceiling = git_fs_path_root(path->ptr) + 1;
if (ceiling < 0)
return;
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_fs_path_join_unrooted(
git_str *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
GIT_ASSERT_ARG(path_out);
GIT_ASSERT_ARG(path);
root = (ssize_t)git_fs_path_root(path);
if (base != NULL && root < 0) {
if (git_str_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_str_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_fs_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_fs_path_squash_slashes(git_str *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_fs_path_prettify(git_str *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
GIT_ASSERT_ARG(path_out);
GIT_ASSERT_ARG(path);
/* construct path if needed */
if (base != NULL && git_fs_path_root(path) < 0) {
if (git_str_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_str_clear(path_out);
return error;
}
return git_str_sets(path_out, buf);
}
int git_fs_path_prettify_dir(git_str *path_out, const char *path, const char *base)
{
int error = git_fs_path_prettify(path_out, path, base);
return (error < 0) ? error : git_fs_path_to_dir(path_out);
}
int git_fs_path_to_dir(git_str *path)
{
if (path->asize > 0 &&
git_str_len(path) > 0 &&
path->ptr[git_str_len(path) - 1] != '/')
git_str_putc(path, '/');
return git_str_oom(path) ? -1 : 0;
}
void git_fs_path_string_to_dir(char *path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_str *decoded_out, const char *input)
{
int len, hi, lo, i;
GIT_ASSERT_ARG(decoded_out);
GIT_ASSERT_ARG(input);
len = (int)strlen(input);
git_str_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_str_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_fs_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_fs_path_fromurl(git_str *local_path_out, const char *file_url)
{
int offset;
GIT_ASSERT_ARG(local_path_out);
GIT_ASSERT_ARG(file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_str_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_fs_path_walk_up(
git_str *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_str iter;
ssize_t stop = 0, scan;
char oldc = '\0';
GIT_ASSERT_ARG(path);
GIT_ASSERT_ARG(cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_str_len(path);
}
scan = git_str_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
ensure_error_set(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_str_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
ensure_error_set(error);
break;
}
scan = git_str_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
ensure_error_set(error);
}
return error;
}
bool git_fs_path_exists(const char *path)
{
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
return p_access(path, F_OK) == 0;
}
bool git_fs_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_fs_path_isfile(const char *path)
{
struct stat st;
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_fs_path_islink(const char *path)
{
struct stat st;
GIT_ASSERT_ARG_WITH_RETVAL(path, false);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_fs_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_fs_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_fs_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_str *path)
{
GIT_UNUSED(payload);
return !git_fs_path_is_dot_or_dotdot(path->ptr);
}
bool git_fs_path_is_empty_dir(const char *path)
{
int error;
git_str dir = GIT_STR_INIT;
if (!git_fs_path_isdir(path))
return false;
if ((error = git_str_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_fs_path_direach(&dir, 0, path_found_entry, NULL);
git_str_dispose(&dir);
return !error;
}
#endif
int git_fs_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_fs_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_fs_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_str *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_str_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_str_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_str_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_str_truncate(dir, dir_size);
return result;
}
bool git_fs_path_contains(git_str *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_fs_path_exists);
}
bool git_fs_path_contains_dir(git_str *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_fs_path_isdir);
}
bool git_fs_path_contains_file(git_str *base, const char *file)
{
return _check_dir_contents(base, file, &git_fs_path_isfile);
}
int git_fs_path_find_dir(git_str *dir)
{
int error = 0;
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_str_sets(dir, buf);
/* call dirname if this is not a directory */
if (!error) /* && git_fs_path_isdir(dir->ptr) == false) */
error = (git_fs_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_fs_path_to_dir(dir);
return error;
}
int git_fs_path_resolve_relative(git_str *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_STR(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_fs_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_fs_path_apply_relative(git_str *target, const char *relpath)
{
return git_str_joinpath(target, git_str_cstr(target), relpath) ||
git_fs_path_resolve_relative(target, 0);
}
int git_fs_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_fs_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_fs_path_make_relative(git_str *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_str_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_str_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_str_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_fs_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_fs_path_iconv_init_precompose(git_fs_path_iconv_t *ic)
{
git_str_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_fs_path_iconv_clear(git_fs_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_str_dispose(&ic->buf);
}
}
int git_fs_path_iconv(git_fs_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_fs_path_has_non_ascii(*in, *inlen))
return 0;
git_str_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_str_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_fs_path_does_decompose_unicode(const char *root)
{
git_str nfc_path = GIT_STR_INIT;
git_str nfd_path = GIT_STR_INIT;
int fd;
bool found_decomposed = false;
size_t orig_len;
const char *trailer;
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_str_joinpath(&nfc_path, root, nfc_file) < 0)
goto done;
/* record original path length before trailer */
orig_len = nfc_path.size;
if ((fd = git_futils_mktmp(&nfc_path, nfc_path.ptr, 0666)) < 0)
goto done;
p_close(fd);
trailer = nfc_path.ptr + orig_len;
/* try to look up as NFD path */
if (git_str_joinpath(&nfd_path, root, nfd_file) < 0 ||
git_str_puts(&nfd_path, trailer) < 0)
goto done;
found_decomposed = git_fs_path_exists(nfd_path.ptr);
/* remove temporary file (using original precomposed path) */
(void)p_unlink(nfc_path.ptr);
done:
git_str_dispose(&nfc_path);
git_str_dispose(&nfd_path);
return found_decomposed;
}
#else
bool git_fs_path_does_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_fs_path_direach(
git_str *path,
uint32_t flags,
int (*fn)(void *, git_str *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_fs_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_fs_path_to_dir(path) < 0)
return -1;
wd_len = git_str_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_fs_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_fs_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_fs_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_str_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_str_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
ensure_error_set(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_fs_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_fs_path_diriter_init(
git_fs_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT_ARG(path);
memset(diriter, 0, sizeof(git_fs_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_str_puts(&diriter->path_utf8, path) < 0)
return -1;
path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_fs_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_str_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_str_putc(&diriter->path_utf8, '/');
git_str_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_str_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_fs_path_diriter_next(git_fs_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_FS_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_fs_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_fs_path_diriter_filename(
const char **out,
size_t *out_len,
git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_fs_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_fs_path_diriter_stat(struct stat *out, git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_fs_path_diriter_free(git_fs_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_str_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_fs_path_diriter_init(
git_fs_path_diriter *diriter,
const char *path,
unsigned int flags)
{
GIT_ASSERT_ARG(diriter);
GIT_ASSERT_ARG(path);
memset(diriter, 0, sizeof(git_fs_path_diriter));
if (git_str_puts(&diriter->path, path) < 0)
return -1;
path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_str_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_fs_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_fs_path_diriter_next(git_fs_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_FS_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
GIT_ASSERT_ARG(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_fs_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_FS_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_fs_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_str_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_str_putc(&diriter->path, '/');
git_str_put(&diriter->path, filename, filename_len);
if (git_str_oom(&diriter->path))
return -1;
return error;
}
int git_fs_path_diriter_filename(
const char **out,
size_t *out_len,
git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
GIT_ASSERT(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_fs_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(out_len);
GIT_ASSERT_ARG(diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_fs_path_diriter_stat(struct stat *out, git_fs_path_diriter *diriter)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diriter);
return git_fs_path_lstat(diriter->path.ptr, out);
}
void git_fs_path_diriter_free(git_fs_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_fs_path_iconv_clear(&diriter->ic);
#endif
git_str_dispose(&diriter->path);
}
#endif
int git_fs_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_fs_path_diriter iter = GIT_FS_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
GIT_ASSERT_ARG(contents);
GIT_ASSERT_ARG(path);
if ((error = git_fs_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_fs_path_diriter_next(&iter)) == 0) {
if ((error = git_fs_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
GIT_ASSERT(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_fs_path_diriter_free(&iter);
return error;
}
int git_fs_path_from_url_or_path(git_str *local_path_out, const char *url_or_path)
{
if (git_fs_path_is_local_file_url(url_or_path))
return git_fs_path_fromurl(local_path_out, url_or_path);
else
return git_str_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) validate_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
GIT_INLINE(bool) validate_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_FS_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_FS_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_FS_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (to avoid escaping a sandbox): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool validate_component(
const char *component,
size_t len,
unsigned int flags)
{
if (len == 0)
return !(flags & GIT_FS_PATH_REJECT_EMPTY_COMPONENT);
if ((flags & GIT_FS_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_FS_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_FS_PATH_REJECT_TRAILING_DOT) &&
component[len - 1] == '.')
return false;
if ((flags & GIT_FS_PATH_REJECT_TRAILING_SPACE) &&
component[len - 1] == ' ')
return false;
if ((flags & GIT_FS_PATH_REJECT_TRAILING_COLON) &&
component[len - 1] == ':')
return false;
if (flags & GIT_FS_PATH_REJECT_DOS_PATHS) {
if (!validate_dospath(component, len, "CON", false) ||
!validate_dospath(component, len, "PRN", false) ||
!validate_dospath(component, len, "AUX", false) ||
!validate_dospath(component, len, "NUL", false) ||
!validate_dospath(component, len, "COM", true) ||
!validate_dospath(component, len, "LPT", true))
return false;
}
return true;
}
#ifdef GIT_WIN32
GIT_INLINE(bool) validate_length(
const char *path,
size_t len,
size_t utf8_char_len)
{
GIT_UNUSED(path);
GIT_UNUSED(len);
return (utf8_char_len <= MAX_PATH);
}
#endif
bool git_fs_path_str_is_valid_ext(
const git_str *path,
unsigned int flags,
bool (*validate_char_cb)(char ch, void *payload),
bool (*validate_component_cb)(const char *component, size_t len, void *payload),
bool (*validate_length_cb)(const char *path, size_t len, size_t utf8_char_len),
void *payload)
{
const char *start, *c;
size_t len = 0;
if (!flags)
return true;
for (start = c = path->ptr; *c && len < path->size; c++, len++) {
if (!validate_char(*c, flags))
return false;
if (validate_char_cb && !validate_char_cb(*c, payload))
return false;
if (*c != '/')
continue;
if (!validate_component(start, (c - start), flags))
return false;
if (validate_component_cb &&
!validate_component_cb(start, (c - start), payload))
return false;
start = c + 1;
}
/*
* We want to support paths specified as either `const char *`
* or `git_str *`; we pass size as `SIZE_MAX` when we use a
* `const char *` to avoid a `strlen`. Ensure that we didn't
* have a NUL in the buffer if there was a non-SIZE_MAX length.
*/
if (path->size != SIZE_MAX && len != path->size)
return false;
if (!validate_component(start, (c - start), flags))
return false;
if (validate_component_cb &&
!validate_component_cb(start, (c - start), payload))
return false;
#ifdef GIT_WIN32
if ((flags & GIT_FS_PATH_REJECT_LONG_PATHS) != 0) {
size_t utf8_len = git_utf8_char_length(path->ptr, len);
if (!validate_length(path->ptr, len, utf8_len))
return false;
if (validate_length_cb &&
!validate_length_cb(path->ptr, len, utf8_len))
return false;
}
#else
GIT_UNUSED(validate_length_cb);
#endif
return true;
}
int git_fs_path_validate_str_length_with_suffix(
git_str *path,
size_t suffix_len)
{
#ifdef GIT_WIN32
size_t utf8_len = git_utf8_char_length(path->ptr, path->size);
size_t total_len;
if (GIT_ADD_SIZET_OVERFLOW(&total_len, utf8_len, suffix_len) ||
total_len > MAX_PATH) {
git_error_set(GIT_ERROR_FILESYSTEM, "path too long: '%.*s'",
(int)path->size, path->ptr);
return -1;
}
#else
GIT_UNUSED(path);
GIT_UNUSED(suffix_len);
#endif
return 0;
}
int git_fs_path_normalize_slashes(git_str *out, const char *path)
{
int error;
char *p;
if ((error = git_str_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
bool git_fs_path_supports_symlinks(const char *dir)
{
git_str path = GIT_STR_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_str_dispose(&path);
return supported;
}
static git_fs_path_owner_t mock_owner = GIT_FS_PATH_OWNER_NONE;
void git_fs_path__set_owner(git_fs_path_owner_t owner)
{
mock_owner = owner;
}
#ifdef GIT_WIN32
static PSID *sid_dup(PSID sid)
{
DWORD len;
PSID dup;
len = GetLengthSid(sid);
if ((dup = git__malloc(len)) == NULL)
return NULL;
if (!CopySid(len, dup, sid)) {
git_error_set(GIT_ERROR_OS, "could not duplicate sid");
git__free(dup);
return NULL;
}
return dup;
}
static int current_user_sid(PSID *out)
{
TOKEN_USER *info = NULL;
HANDLE token = NULL;
DWORD len = 0;
int error = -1;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
git_error_set(GIT_ERROR_OS, "could not lookup process information");
goto done;
}
if (GetTokenInformation(token, TokenUser, NULL, 0, &len) ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
git_error_set(GIT_ERROR_OS, "could not lookup token metadata");
goto done;
}
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git_error_set(GIT_ERROR_OS, "could not lookup current user");
goto done;
}
if ((*out = sid_dup(info->User.Sid)))
error = 0;
done:
if (token)
CloseHandle(token);
git__free(info);
return error;
}
static int file_owner_sid(PSID *out, const char *path)
{
git_win32_path path_w32;
PSECURITY_DESCRIPTOR descriptor = NULL;
PSID owner_sid;
DWORD ret;
int error = -1;
if (git_win32_path_from_utf8(path_w32, path) < 0)
return -1;
ret = GetNamedSecurityInfoW(path_w32, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (ret == ERROR_FILE_NOT_FOUND || ret == ERROR_PATH_NOT_FOUND)
error = GIT_ENOTFOUND;
else if (ret != ERROR_SUCCESS)
git_error_set(GIT_ERROR_OS, "failed to get security information");
else if (!IsValidSid(owner_sid))
git_error_set(GIT_ERROR_OS, "file owner is not valid");
else if ((*out = sid_dup(owner_sid)))
error = 0;
if (descriptor)
LocalFree(descriptor);
return error;
}
int git_fs_path_owner_is(
bool *out,
const char *path,
git_fs_path_owner_t owner_type)
{
PSID owner_sid = NULL, user_sid = NULL;
BOOL is_admin, admin_owned;
int error;
if (mock_owner) {
*out = ((mock_owner & owner_type) != 0);
return 0;
}
if ((error = file_owner_sid(&owner_sid, path)) < 0)
goto done;
if ((owner_type & GIT_FS_PATH_OWNER_CURRENT_USER) != 0) {
if ((error = current_user_sid(&user_sid)) < 0)
goto done;
if (EqualSid(owner_sid, user_sid)) {
*out = true;
goto done;
}
}
admin_owned =
IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid);
if (admin_owned &&
(owner_type & GIT_FS_PATH_OWNER_ADMINISTRATOR) != 0) {
*out = true;
goto done;
}
if (admin_owned &&
(owner_type & GIT_FS_PATH_USER_IS_ADMINISTRATOR) != 0 &&
CheckTokenMembership(NULL, owner_sid, &is_admin) &&
is_admin) {
*out = true;
goto done;
}
*out = false;
done:
git__free(owner_sid);
git__free(user_sid);
return error;
}
#else
static int sudo_uid_lookup(uid_t *out)
{
git_str uid_str = GIT_STR_INIT;
int64_t uid;
int error;
if ((error = git__getenv(&uid_str, "SUDO_UID")) == 0 &&
(error = git__strntol64(&uid, uid_str.ptr, uid_str.size, NULL, 10)) == 0 &&
uid == (int64_t)((uid_t)uid)) {
*out = (uid_t)uid;
}
git_str_dispose(&uid_str);
return error;
}
int git_fs_path_owner_is(
bool *out,
const char *path,
git_fs_path_owner_t owner_type)
{
struct stat st;
uid_t euid, sudo_uid;
if (mock_owner) {
*out = ((mock_owner & owner_type) != 0);
return 0;
}
euid = geteuid();
if (p_lstat(path, &st) != 0) {
if (errno == ENOENT)
return GIT_ENOTFOUND;
git_error_set(GIT_ERROR_OS, "could not stat '%s'", path);
return -1;
}
if ((owner_type & GIT_FS_PATH_OWNER_CURRENT_USER) != 0 &&
st.st_uid == euid) {
*out = true;
return 0;
}
if ((owner_type & GIT_FS_PATH_OWNER_ADMINISTRATOR) != 0 &&
st.st_uid == 0) {
*out = true;
return 0;
}
if ((owner_type & GIT_FS_PATH_OWNER_RUNNING_SUDO) != 0 &&
euid == 0 &&
sudo_uid_lookup(&sudo_uid) == 0 &&
st.st_uid == sudo_uid) {
*out = true;
return 0;
}
*out = false;
return 0;
}
#endif
int git_fs_path_owner_is_current_user(bool *out, const char *path)
{
return git_fs_path_owner_is(out, path, GIT_FS_PATH_OWNER_CURRENT_USER);
}
int git_fs_path_owner_is_system(bool *out, const char *path)
{
return git_fs_path_owner_is(out, path, GIT_FS_PATH_OWNER_ADMINISTRATOR);
}
int git_fs_path_find_executable(git_str *fullpath, const char *executable)
{
#ifdef GIT_WIN32
git_win32_path fullpath_w, executable_w;
int error;
if (git__utf8_to_16(executable_w, GIT_WIN_PATH_MAX, executable) < 0)
return -1;
error = git_win32_path_find_executable(fullpath_w, executable_w);
if (error == 0)
error = git_str_put_w(fullpath, fullpath_w, wcslen(fullpath_w));
return error;
#else
git_str path = GIT_STR_INIT;
const char *current_dir, *term;
bool found = false;
if (git__getenv(&path, "PATH") < 0)
return -1;
current_dir = path.ptr;
while (*current_dir) {
if (! (term = strchr(current_dir, GIT_PATH_LIST_SEPARATOR)))
term = strchr(current_dir, '\0');
git_str_clear(fullpath);
if (git_str_put(fullpath, current_dir, (term - current_dir)) < 0 ||
git_str_putc(fullpath, '/') < 0 ||
git_str_puts(fullpath, executable) < 0)
return -1;
if (git_fs_path_isfile(fullpath->ptr)) {
found = true;
break;
}
current_dir = term;
while (*current_dir == GIT_PATH_LIST_SEPARATOR)
current_dir++;
}
git_str_dispose(&path);
if (found)
return 0;
git_str_clear(fullpath);
return GIT_ENOTFOUND;
#endif
}
| libgit2-main | src/util/fs_path.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "futils.h"
#include "runtime.h"
#include "strmap.h"
#include "hash.h"
#include "rand.h"
#include <ctype.h>
#if GIT_WIN32
#include "win32/findfile.h"
#endif
#define GIT_FILEMODE_DEFAULT 0100666
int git_futils_mkpath2file(const char *file_path, const mode_t mode)
{
return git_futils_mkdir(
file_path, mode,
GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST | GIT_MKDIR_VERIFY_DIR);
}
int git_futils_mktmp(git_str *path_out, const char *filename, mode_t mode)
{
const int open_flags = O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC;
unsigned int tries = 32;
int fd;
while (tries--) {
uint64_t rand = git_rand_next();
git_str_sets(path_out, filename);
git_str_puts(path_out, "_git2_");
git_str_encode_hexstr(path_out, (void *)&rand, sizeof(uint64_t));
if (git_str_oom(path_out))
return -1;
/* Note that we open with O_CREAT | O_EXCL */
if ((fd = p_open(path_out->ptr, open_flags, mode)) >= 0)
return fd;
}
git_error_set(GIT_ERROR_OS,
"failed to create temporary file '%s'", path_out->ptr);
git_str_dispose(path_out);
return -1;
}
int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode)
{
int fd;
if (git_futils_mkpath2file(path, dirmode) < 0)
return -1;
fd = p_creat(path, mode);
if (fd < 0) {
git_error_set(GIT_ERROR_OS, "failed to create file '%s'", path);
return -1;
}
return fd;
}
int git_futils_creat_locked(const char *path, const mode_t mode)
{
int fd = p_open(path, O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC,
mode);
if (fd < 0) {
int error = errno;
git_error_set(GIT_ERROR_OS, "failed to create locked file '%s'", path);
switch (error) {
case EEXIST:
return GIT_ELOCKED;
case ENOENT:
return GIT_ENOTFOUND;
default:
return -1;
}
}
return fd;
}
int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode)
{
if (git_futils_mkpath2file(path, dirmode) < 0)
return -1;
return git_futils_creat_locked(path, mode);
}
int git_futils_open_ro(const char *path)
{
int fd = p_open(path, O_RDONLY);
if (fd < 0)
return git_fs_path_set_error(errno, path, "open");
return fd;
}
int git_futils_truncate(const char *path, int mode)
{
int fd = p_open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
if (fd < 0)
return git_fs_path_set_error(errno, path, "open");
close(fd);
return 0;
}
int git_futils_filesize(uint64_t *out, git_file fd)
{
struct stat sb;
if (p_fstat(fd, &sb)) {
git_error_set(GIT_ERROR_OS, "failed to stat file descriptor");
return -1;
}
if (sb.st_size < 0) {
git_error_set(GIT_ERROR_INVALID, "invalid file size");
return -1;
}
*out = sb.st_size;
return 0;
}
mode_t git_futils_canonical_mode(mode_t raw_mode)
{
if (S_ISREG(raw_mode))
return S_IFREG | GIT_PERMS_CANONICAL(raw_mode);
else if (S_ISLNK(raw_mode))
return S_IFLNK;
else if (S_ISGITLINK(raw_mode))
return S_IFGITLINK;
else if (S_ISDIR(raw_mode))
return S_IFDIR;
else
return 0;
}
int git_futils_readbuffer_fd(git_str *buf, git_file fd, size_t len)
{
ssize_t read_size = 0;
size_t alloc_len;
git_str_clear(buf);
if (!git__is_ssizet(len)) {
git_error_set(GIT_ERROR_INVALID, "read too large");
return -1;
}
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
if (git_str_grow(buf, alloc_len) < 0)
return -1;
/* p_read loops internally to read len bytes */
read_size = p_read(fd, buf->ptr, len);
if (read_size < 0) {
git_error_set(GIT_ERROR_OS, "failed to read descriptor");
git_str_dispose(buf);
return -1;
}
if ((size_t)read_size != len) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not read (expected %" PRIuZ " bytes, read %" PRIuZ ")", len, (size_t)read_size);
git_str_dispose(buf);
return -1;
}
buf->ptr[read_size] = '\0';
buf->size = read_size;
return 0;
}
int git_futils_readbuffer_fd_full(git_str *buf, git_file fd)
{
static size_t blocksize = 10240;
size_t alloc_len = 0, total_size = 0;
ssize_t read_size = 0;
git_str_clear(buf);
while (true) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, blocksize);
if (git_str_grow(buf, alloc_len) < 0)
return -1;
/* p_read loops internally to read blocksize bytes */
read_size = p_read(fd, buf->ptr, blocksize);
if (read_size < 0) {
git_error_set(GIT_ERROR_OS, "failed to read descriptor");
git_str_dispose(buf);
return -1;
}
total_size += read_size;
if ((size_t)read_size < blocksize) {
break;
}
}
buf->ptr[total_size] = '\0';
buf->size = total_size;
return 0;
}
int git_futils_readbuffer_updated(
git_str *out,
const char *path,
unsigned char checksum[GIT_HASH_SHA1_SIZE],
int *updated)
{
int error;
git_file fd;
struct stat st;
git_str buf = GIT_STR_INIT;
unsigned char checksum_new[GIT_HASH_SHA1_SIZE];
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(path && *path);
if (updated != NULL)
*updated = 0;
if (p_stat(path, &st) < 0)
return git_fs_path_set_error(errno, path, "stat");
if (S_ISDIR(st.st_mode)) {
git_error_set(GIT_ERROR_INVALID, "requested file is a directory");
return GIT_ENOTFOUND;
}
if (!git__is_sizet(st.st_size+1)) {
git_error_set(GIT_ERROR_OS, "invalid regular file stat for '%s'", path);
return -1;
}
if ((fd = git_futils_open_ro(path)) < 0)
return fd;
if (git_futils_readbuffer_fd(&buf, fd, (size_t)st.st_size) < 0) {
p_close(fd);
return -1;
}
p_close(fd);
if (checksum) {
if ((error = git_hash_buf(checksum_new, buf.ptr, buf.size, GIT_HASH_ALGORITHM_SHA1)) < 0) {
git_str_dispose(&buf);
return error;
}
/*
* If we were given a checksum, we only want to use it if it's different
*/
if (!memcmp(checksum, checksum_new, GIT_HASH_SHA1_SIZE)) {
git_str_dispose(&buf);
if (updated)
*updated = 0;
return 0;
}
memcpy(checksum, checksum_new, GIT_HASH_SHA1_SIZE);
}
/*
* If we're here, the file did change, or the user didn't have an old version
*/
if (updated != NULL)
*updated = 1;
git_str_swap(out, &buf);
git_str_dispose(&buf);
return 0;
}
int git_futils_readbuffer(git_str *buf, const char *path)
{
return git_futils_readbuffer_updated(buf, path, NULL, NULL);
}
int git_futils_writebuffer(
const git_str *buf, const char *path, int flags, mode_t mode)
{
int fd, do_fsync = 0, error = 0;
if (!flags)
flags = O_CREAT | O_TRUNC | O_WRONLY;
if ((flags & O_FSYNC) != 0)
do_fsync = 1;
flags &= ~O_FSYNC;
if (!mode)
mode = GIT_FILEMODE_DEFAULT;
if ((fd = p_open(path, flags, mode)) < 0) {
git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
return fd;
}
if ((error = p_write(fd, git_str_cstr(buf), git_str_len(buf))) < 0) {
git_error_set(GIT_ERROR_OS, "could not write to '%s'", path);
(void)p_close(fd);
return error;
}
if (do_fsync && (error = p_fsync(fd)) < 0) {
git_error_set(GIT_ERROR_OS, "could not fsync '%s'", path);
p_close(fd);
return error;
}
if ((error = p_close(fd)) < 0) {
git_error_set(GIT_ERROR_OS, "error while closing '%s'", path);
return error;
}
if (do_fsync && (flags & O_CREAT))
error = git_futils_fsync_parent(path);
return error;
}
int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode)
{
if (git_futils_mkpath2file(to, dirmode) < 0)
return -1;
if (p_rename(from, to) < 0) {
git_error_set(GIT_ERROR_OS, "failed to rename '%s' to '%s'", from, to);
return -1;
}
return 0;
}
int git_futils_mmap_ro(git_map *out, git_file fd, off64_t begin, size_t len)
{
return p_mmap(out, len, GIT_PROT_READ, GIT_MAP_SHARED, fd, begin);
}
int git_futils_mmap_ro_file(git_map *out, const char *path)
{
git_file fd = git_futils_open_ro(path);
uint64_t len;
int result;
if (fd < 0)
return fd;
if ((result = git_futils_filesize(&len, fd)) < 0)
goto out;
if (!git__is_sizet(len)) {
git_error_set(GIT_ERROR_OS, "file `%s` too large to mmap", path);
result = -1;
goto out;
}
result = git_futils_mmap_ro(out, fd, 0, (size_t)len);
out:
p_close(fd);
return result;
}
void git_futils_mmap_free(git_map *out)
{
p_munmap(out);
}
GIT_INLINE(int) mkdir_validate_dir(
const char *path,
struct stat *st,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
/* with exclusive create, existing dir is an error */
if ((flags & GIT_MKDIR_EXCL) != 0) {
git_error_set(GIT_ERROR_FILESYSTEM,
"failed to make directory '%s': directory exists", path);
return GIT_EEXISTS;
}
if ((S_ISREG(st->st_mode) && (flags & GIT_MKDIR_REMOVE_FILES)) ||
(S_ISLNK(st->st_mode) && (flags & GIT_MKDIR_REMOVE_SYMLINKS))) {
if (p_unlink(path) < 0) {
git_error_set(GIT_ERROR_OS, "failed to remove %s '%s'",
S_ISLNK(st->st_mode) ? "symlink" : "file", path);
return GIT_EEXISTS;
}
opts->perfdata.mkdir_calls++;
if (p_mkdir(path, mode) < 0) {
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
return GIT_EEXISTS;
}
}
else if (S_ISLNK(st->st_mode)) {
/* Re-stat the target, make sure it's a directory */
opts->perfdata.stat_calls++;
if (p_stat(path, st) < 0) {
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
return GIT_EEXISTS;
}
}
else if (!S_ISDIR(st->st_mode)) {
git_error_set(GIT_ERROR_FILESYSTEM,
"failed to make directory '%s': directory exists", path);
return GIT_EEXISTS;
}
return 0;
}
GIT_INLINE(int) mkdir_validate_mode(
const char *path,
struct stat *st,
bool terminal_path,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
if (((terminal_path && (flags & GIT_MKDIR_CHMOD) != 0) ||
(flags & GIT_MKDIR_CHMOD_PATH) != 0) && st->st_mode != mode) {
opts->perfdata.chmod_calls++;
if (p_chmod(path, mode) < 0) {
git_error_set(GIT_ERROR_OS, "failed to set permissions on '%s'", path);
return -1;
}
}
return 0;
}
GIT_INLINE(int) mkdir_canonicalize(
git_str *path,
uint32_t flags)
{
ssize_t root_len;
if (path->size == 0) {
git_error_set(GIT_ERROR_OS, "attempt to create empty path");
return -1;
}
/* Trim trailing slashes (except the root) */
if ((root_len = git_fs_path_root(path->ptr)) < 0)
root_len = 0;
else
root_len++;
while (path->size > (size_t)root_len && path->ptr[path->size - 1] == '/')
path->ptr[--path->size] = '\0';
/* if we are not supposed to made the last element, truncate it */
if ((flags & GIT_MKDIR_SKIP_LAST2) != 0) {
git_fs_path_dirname_r(path, path->ptr);
flags |= GIT_MKDIR_SKIP_LAST;
}
if ((flags & GIT_MKDIR_SKIP_LAST) != 0) {
git_fs_path_dirname_r(path, path->ptr);
}
/* We were either given the root path (or trimmed it to
* the root), we don't have anything to do.
*/
if (path->size <= (size_t)root_len)
git_str_clear(path);
return 0;
}
int git_futils_mkdir(
const char *path,
mode_t mode,
uint32_t flags)
{
git_str make_path = GIT_STR_INIT, parent_path = GIT_STR_INIT;
const char *relative;
struct git_futils_mkdir_options opts = { 0 };
struct stat st;
size_t depth = 0;
int len = 0, root_len, error;
if ((error = git_str_puts(&make_path, path)) < 0 ||
(error = mkdir_canonicalize(&make_path, flags)) < 0 ||
(error = git_str_puts(&parent_path, make_path.ptr)) < 0 ||
make_path.size == 0)
goto done;
root_len = git_fs_path_root(make_path.ptr);
/* find the first parent directory that exists. this will be used
* as the base to dirname_relative.
*/
for (relative = make_path.ptr; parent_path.size; ) {
error = p_lstat(parent_path.ptr, &st);
if (error == 0) {
break;
} else if (errno != ENOENT) {
git_error_set(GIT_ERROR_OS, "failed to stat '%s'", parent_path.ptr);
error = -1;
goto done;
}
depth++;
/* examine the parent of the current path */
if ((len = git_fs_path_dirname_r(&parent_path, parent_path.ptr)) < 0) {
error = len;
goto done;
}
GIT_ASSERT(len);
/*
* We've walked all the given path's parents and it's either relative
* (the parent is simply '.') or rooted (the length is less than or
* equal to length of the root path). The path may be less than the
* root path length on Windows, where `C:` == `C:/`.
*/
if ((len == 1 && parent_path.ptr[0] == '.') ||
(len == 1 && parent_path.ptr[0] == '/') ||
len <= root_len) {
relative = make_path.ptr;
break;
}
relative = make_path.ptr + len + 1;
/* not recursive? just make this directory relative to its parent. */
if ((flags & GIT_MKDIR_PATH) == 0)
break;
}
/* we found an item at the location we're trying to create,
* validate it.
*/
if (depth == 0) {
error = mkdir_validate_dir(make_path.ptr, &st, mode, flags, &opts);
if (!error)
error = mkdir_validate_mode(
make_path.ptr, &st, true, mode, flags, &opts);
goto done;
}
/* we already took `SKIP_LAST` and `SKIP_LAST2` into account when
* canonicalizing `make_path`.
*/
flags &= ~(GIT_MKDIR_SKIP_LAST2 | GIT_MKDIR_SKIP_LAST);
error = git_futils_mkdir_relative(relative,
parent_path.size ? parent_path.ptr : NULL, mode, flags, &opts);
done:
git_str_dispose(&make_path);
git_str_dispose(&parent_path);
return error;
}
int git_futils_mkdir_r(const char *path, const mode_t mode)
{
return git_futils_mkdir(path, mode, GIT_MKDIR_PATH);
}
int git_futils_mkdir_relative(
const char *relative_path,
const char *base,
mode_t mode,
uint32_t flags,
struct git_futils_mkdir_options *opts)
{
git_str make_path = GIT_STR_INIT;
ssize_t root = 0, min_root_len;
char lastch = '/', *tail;
struct stat st;
struct git_futils_mkdir_options empty_opts = {0};
int error;
if (!opts)
opts = &empty_opts;
/* build path and find "root" where we should start calling mkdir */
if (git_fs_path_join_unrooted(&make_path, relative_path, base, &root) < 0)
return -1;
if ((error = mkdir_canonicalize(&make_path, flags)) < 0 ||
make_path.size == 0)
goto done;
/* if we are not supposed to make the whole path, reset root */
if ((flags & GIT_MKDIR_PATH) == 0)
root = git_str_rfind(&make_path, '/');
/* advance root past drive name or network mount prefix */
min_root_len = git_fs_path_root(make_path.ptr);
if (root < min_root_len)
root = min_root_len;
while (root >= 0 && make_path.ptr[root] == '/')
++root;
/* clip root to make_path length */
if (root > (ssize_t)make_path.size)
root = (ssize_t)make_path.size; /* i.e. NUL byte of string */
if (root < 0)
root = 0;
/* walk down tail of path making each directory */
for (tail = &make_path.ptr[root]; *tail; *tail = lastch) {
bool mkdir_attempted = false;
/* advance tail to include next path component */
while (*tail == '/')
tail++;
while (*tail && *tail != '/')
tail++;
/* truncate path at next component */
lastch = *tail;
*tail = '\0';
st.st_mode = 0;
if (opts->dir_map && git_strmap_exists(opts->dir_map, make_path.ptr))
continue;
/* See what's going on with this path component */
opts->perfdata.stat_calls++;
retry_lstat:
if (p_lstat(make_path.ptr, &st) < 0) {
if (mkdir_attempted || errno != ENOENT) {
git_error_set(GIT_ERROR_OS, "cannot access component in path '%s'", make_path.ptr);
error = -1;
goto done;
}
git_error_clear();
opts->perfdata.mkdir_calls++;
mkdir_attempted = true;
if (p_mkdir(make_path.ptr, mode) < 0) {
if (errno == EEXIST)
goto retry_lstat;
git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", make_path.ptr);
error = -1;
goto done;
}
} else {
if ((error = mkdir_validate_dir(
make_path.ptr, &st, mode, flags, opts)) < 0)
goto done;
}
/* chmod if requested and necessary */
if ((error = mkdir_validate_mode(
make_path.ptr, &st, (lastch == '\0'), mode, flags, opts)) < 0)
goto done;
if (opts->dir_map && opts->pool) {
char *cache_path;
size_t alloc_size;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, make_path.size, 1);
cache_path = git_pool_malloc(opts->pool, alloc_size);
GIT_ERROR_CHECK_ALLOC(cache_path);
memcpy(cache_path, make_path.ptr, make_path.size + 1);
if ((error = git_strmap_set(opts->dir_map, cache_path, cache_path)) < 0)
goto done;
}
}
error = 0;
/* check that full path really is a directory if requested & needed */
if ((flags & GIT_MKDIR_VERIFY_DIR) != 0 &&
lastch != '\0') {
opts->perfdata.stat_calls++;
if (p_stat(make_path.ptr, &st) < 0 || !S_ISDIR(st.st_mode)) {
git_error_set(GIT_ERROR_OS, "path is not a directory '%s'",
make_path.ptr);
error = GIT_ENOTFOUND;
}
}
done:
git_str_dispose(&make_path);
return error;
}
typedef struct {
const char *base;
size_t baselen;
uint32_t flags;
int depth;
} futils__rmdir_data;
#define FUTILS_MAX_DEPTH 100
static int futils__error_cannot_rmdir(const char *path, const char *filemsg)
{
if (filemsg)
git_error_set(GIT_ERROR_OS, "could not remove directory '%s': %s",
path, filemsg);
else
git_error_set(GIT_ERROR_OS, "could not remove directory '%s'", path);
return -1;
}
static int futils__rm_first_parent(git_str *path, const char *ceiling)
{
int error = GIT_ENOTFOUND;
struct stat st;
while (error == GIT_ENOTFOUND) {
git_str_rtruncate_at_char(path, '/');
if (!path->size || git__prefixcmp(path->ptr, ceiling) != 0)
error = 0;
else if (p_lstat_posixly(path->ptr, &st) == 0) {
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
error = p_unlink(path->ptr);
else if (!S_ISDIR(st.st_mode))
error = -1; /* fail to remove non-regular file */
} else if (errno != ENOTDIR)
error = -1;
}
if (error)
futils__error_cannot_rmdir(path->ptr, "cannot remove parent");
return error;
}
static int futils__rmdir_recurs_foreach(void *opaque, git_str *path)
{
int error = 0;
futils__rmdir_data *data = opaque;
struct stat st;
if (data->depth > FUTILS_MAX_DEPTH)
error = futils__error_cannot_rmdir(
path->ptr, "directory nesting too deep");
else if ((error = p_lstat_posixly(path->ptr, &st)) < 0) {
if (errno == ENOENT)
error = 0;
else if (errno == ENOTDIR) {
/* asked to remove a/b/c/d/e and a/b is a normal file */
if ((data->flags & GIT_RMDIR_REMOVE_BLOCKERS) != 0)
error = futils__rm_first_parent(path, data->base);
else
futils__error_cannot_rmdir(
path->ptr, "parent is not directory");
}
else
error = git_fs_path_set_error(errno, path->ptr, "rmdir");
}
else if (S_ISDIR(st.st_mode)) {
data->depth++;
error = git_fs_path_direach(path, 0, futils__rmdir_recurs_foreach, data);
data->depth--;
if (error < 0)
return error;
if (data->depth == 0 && (data->flags & GIT_RMDIR_SKIP_ROOT) != 0)
return error;
if ((error = p_rmdir(path->ptr)) < 0) {
if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) != 0 &&
(errno == ENOTEMPTY || errno == EEXIST || errno == EBUSY))
error = 0;
else
error = git_fs_path_set_error(errno, path->ptr, "rmdir");
}
}
else if ((data->flags & GIT_RMDIR_REMOVE_FILES) != 0) {
if (p_unlink(path->ptr) < 0)
error = git_fs_path_set_error(errno, path->ptr, "remove");
}
else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0)
error = futils__error_cannot_rmdir(path->ptr, "still present");
return error;
}
static int futils__rmdir_empty_parent(void *opaque, const char *path)
{
futils__rmdir_data *data = opaque;
int error = 0;
if (strlen(path) <= data->baselen)
error = GIT_ITEROVER;
else if (p_rmdir(path) < 0) {
int en = errno;
if (en == ENOENT || en == ENOTDIR) {
/* do nothing */
} else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0 &&
en == EBUSY) {
error = git_fs_path_set_error(errno, path, "rmdir");
} else if (en == ENOTEMPTY || en == EEXIST || en == EBUSY) {
error = GIT_ITEROVER;
} else {
error = git_fs_path_set_error(errno, path, "rmdir");
}
}
return error;
}
int git_futils_rmdir_r(
const char *path, const char *base, uint32_t flags)
{
int error;
git_str fullpath = GIT_STR_INIT;
futils__rmdir_data data;
/* build path and find "root" where we should start calling mkdir */
if (git_fs_path_join_unrooted(&fullpath, path, base, NULL) < 0)
return -1;
memset(&data, 0, sizeof(data));
data.base = base ? base : "";
data.baselen = base ? strlen(base) : 0;
data.flags = flags;
error = futils__rmdir_recurs_foreach(&data, &fullpath);
/* remove now-empty parents if requested */
if (!error && (flags & GIT_RMDIR_EMPTY_PARENTS) != 0)
error = git_fs_path_walk_up(
&fullpath, base, futils__rmdir_empty_parent, &data);
if (error == GIT_ITEROVER) {
git_error_clear();
error = 0;
}
git_str_dispose(&fullpath);
return error;
}
int git_futils_fake_symlink(const char *target, const char *path)
{
int retcode = GIT_ERROR;
int fd = git_futils_creat_withpath(path, 0755, 0644);
if (fd >= 0) {
retcode = p_write(fd, target, strlen(target));
p_close(fd);
}
return retcode;
}
static int cp_by_fd(int ifd, int ofd, bool close_fd_when_done)
{
int error = 0;
char buffer[GIT_BUFSIZE_FILEIO];
ssize_t len = 0;
while (!error && (len = p_read(ifd, buffer, sizeof(buffer))) > 0)
/* p_write() does not have the same semantics as write(). It loops
* internally and will return 0 when it has completed writing.
*/
error = p_write(ofd, buffer, len);
if (len < 0) {
git_error_set(GIT_ERROR_OS, "read error while copying file");
error = (int)len;
}
if (error < 0)
git_error_set(GIT_ERROR_OS, "write error while copying file");
if (close_fd_when_done) {
p_close(ifd);
p_close(ofd);
}
return error;
}
int git_futils_cp(const char *from, const char *to, mode_t filemode)
{
int ifd, ofd;
if ((ifd = git_futils_open_ro(from)) < 0)
return ifd;
if ((ofd = p_open(to, O_WRONLY | O_CREAT | O_EXCL, filemode)) < 0) {
p_close(ifd);
return git_fs_path_set_error(errno, to, "open for writing");
}
return cp_by_fd(ifd, ofd, true);
}
int git_futils_touch(const char *path, time_t *when)
{
struct p_timeval times[2];
int ret;
times[0].tv_sec = times[1].tv_sec = when ? *when : time(NULL);
times[0].tv_usec = times[1].tv_usec = 0;
ret = p_utimes(path, times);
return (ret < 0) ? git_fs_path_set_error(errno, path, "touch") : 0;
}
static int cp_link(const char *from, const char *to, size_t link_size)
{
int error = 0;
ssize_t read_len;
char *link_data;
size_t alloc_size;
GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, link_size, 1);
link_data = git__malloc(alloc_size);
GIT_ERROR_CHECK_ALLOC(link_data);
read_len = p_readlink(from, link_data, link_size);
if (read_len != (ssize_t)link_size) {
git_error_set(GIT_ERROR_OS, "failed to read symlink data for '%s'", from);
error = -1;
}
else {
link_data[read_len] = '\0';
if (p_symlink(link_data, to) < 0) {
git_error_set(GIT_ERROR_OS, "could not symlink '%s' as '%s'",
link_data, to);
error = -1;
}
}
git__free(link_data);
return error;
}
typedef struct {
const char *to_root;
git_str to;
ssize_t from_prefix;
uint32_t flags;
uint32_t mkdir_flags;
mode_t dirmode;
} cp_r_info;
#define GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT (1u << 10)
static int _cp_r_mkdir(cp_r_info *info, git_str *from)
{
int error = 0;
/* create root directory the first time we need to create a directory */
if ((info->flags & GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT) == 0) {
error = git_futils_mkdir(
info->to_root, info->dirmode,
(info->flags & GIT_CPDIR_CHMOD_DIRS) ? GIT_MKDIR_CHMOD : 0);
info->flags |= GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT;
}
/* create directory with root as base to prevent excess chmods */
if (!error)
error = git_futils_mkdir_relative(
from->ptr + info->from_prefix, info->to_root,
info->dirmode, info->mkdir_flags, NULL);
return error;
}
static int _cp_r_callback(void *ref, git_str *from)
{
int error = 0;
cp_r_info *info = ref;
struct stat from_st, to_st;
bool exists = false;
if ((info->flags & GIT_CPDIR_COPY_DOTFILES) == 0 &&
from->ptr[git_fs_path_basename_offset(from)] == '.')
return 0;
if ((error = git_str_joinpath(
&info->to, info->to_root, from->ptr + info->from_prefix)) < 0)
return error;
if (!(error = git_fs_path_lstat(info->to.ptr, &to_st)))
exists = true;
else if (error != GIT_ENOTFOUND)
return error;
else {
git_error_clear();
error = 0;
}
if ((error = git_fs_path_lstat(from->ptr, &from_st)) < 0)
return error;
if (S_ISDIR(from_st.st_mode)) {
mode_t oldmode = info->dirmode;
/* if we are not chmod'ing, then overwrite dirmode */
if ((info->flags & GIT_CPDIR_CHMOD_DIRS) == 0)
info->dirmode = from_st.st_mode;
/* make directory now if CREATE_EMPTY_DIRS is requested and needed */
if (!exists && (info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) != 0)
error = _cp_r_mkdir(info, from);
/* recurse onto target directory */
if (!error && (!exists || S_ISDIR(to_st.st_mode)))
error = git_fs_path_direach(from, 0, _cp_r_callback, info);
if (oldmode != 0)
info->dirmode = oldmode;
return error;
}
if (exists) {
if ((info->flags & GIT_CPDIR_OVERWRITE) == 0)
return 0;
if (p_unlink(info->to.ptr) < 0) {
git_error_set(GIT_ERROR_OS, "cannot overwrite existing file '%s'",
info->to.ptr);
return GIT_EEXISTS;
}
}
/* Done if this isn't a regular file or a symlink */
if (!S_ISREG(from_st.st_mode) &&
(!S_ISLNK(from_st.st_mode) ||
(info->flags & GIT_CPDIR_COPY_SYMLINKS) == 0))
return 0;
/* Make container directory on demand if needed */
if ((info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0 &&
(error = _cp_r_mkdir(info, from)) < 0)
return error;
/* make symlink or regular file */
if (info->flags & GIT_CPDIR_LINK_FILES) {
if ((error = p_link(from->ptr, info->to.ptr)) < 0)
git_error_set(GIT_ERROR_OS, "failed to link '%s'", from->ptr);
} else if (S_ISLNK(from_st.st_mode)) {
error = cp_link(from->ptr, info->to.ptr, (size_t)from_st.st_size);
} else {
mode_t usemode = from_st.st_mode;
if ((info->flags & GIT_CPDIR_SIMPLE_TO_MODE) != 0)
usemode = GIT_PERMS_FOR_WRITE(usemode);
error = git_futils_cp(from->ptr, info->to.ptr, usemode);
}
return error;
}
int git_futils_cp_r(
const char *from,
const char *to,
uint32_t flags,
mode_t dirmode)
{
int error;
git_str path = GIT_STR_INIT;
cp_r_info info;
if (git_str_joinpath(&path, from, "") < 0) /* ensure trailing slash */
return -1;
memset(&info, 0, sizeof(info));
info.to_root = to;
info.flags = flags;
info.dirmode = dirmode;
info.from_prefix = path.size;
git_str_init(&info.to, 0);
/* precalculate mkdir flags */
if ((flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0) {
/* if not creating empty dirs, then use mkdir to create the path on
* demand right before files are copied.
*/
info.mkdir_flags = GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST;
if ((flags & GIT_CPDIR_CHMOD_DIRS) != 0)
info.mkdir_flags |= GIT_MKDIR_CHMOD_PATH;
} else {
/* otherwise, we will do simple mkdir as directories are encountered */
info.mkdir_flags =
((flags & GIT_CPDIR_CHMOD_DIRS) != 0) ? GIT_MKDIR_CHMOD : 0;
}
error = _cp_r_callback(&info, &path);
git_str_dispose(&path);
git_str_dispose(&info.to);
return error;
}
int git_futils_filestamp_check(
git_futils_filestamp *stamp, const char *path)
{
struct stat st;
/* if the stamp is NULL, then always reload */
if (stamp == NULL)
return 1;
if (p_stat(path, &st) < 0)
return GIT_ENOTFOUND;
if (stamp->mtime.tv_sec == st.st_mtime &&
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec == st.st_mtime_nsec &&
#endif
stamp->size == (uint64_t)st.st_size &&
stamp->ino == (unsigned int)st.st_ino)
return 0;
stamp->mtime.tv_sec = st.st_mtime;
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec = st.st_mtime_nsec;
#endif
stamp->size = (uint64_t)st.st_size;
stamp->ino = (unsigned int)st.st_ino;
return 1;
}
void git_futils_filestamp_set(
git_futils_filestamp *target, const git_futils_filestamp *source)
{
if (source)
memcpy(target, source, sizeof(*target));
else
memset(target, 0, sizeof(*target));
}
void git_futils_filestamp_set_from_stat(
git_futils_filestamp *stamp, struct stat *st)
{
if (st) {
stamp->mtime.tv_sec = st->st_mtime;
#if defined(GIT_USE_NSEC)
stamp->mtime.tv_nsec = st->st_mtime_nsec;
#else
stamp->mtime.tv_nsec = 0;
#endif
stamp->size = (uint64_t)st->st_size;
stamp->ino = (unsigned int)st->st_ino;
} else {
memset(stamp, 0, sizeof(*stamp));
}
}
int git_futils_fsync_dir(const char *path)
{
#ifdef GIT_WIN32
GIT_UNUSED(path);
return 0;
#else
int fd, error = -1;
if ((fd = p_open(path, O_RDONLY)) < 0) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s' for fsync", path);
return -1;
}
if ((error = p_fsync(fd)) < 0)
git_error_set(GIT_ERROR_OS, "failed to fsync directory '%s'", path);
p_close(fd);
return error;
#endif
}
int git_futils_fsync_parent(const char *path)
{
char *parent;
int error;
if ((parent = git_fs_path_dirname(path)) == NULL)
return -1;
error = git_futils_fsync_dir(parent);
git__free(parent);
return error;
}
| libgit2-main | src/util/futils.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "zstream.h"
#include <zlib.h>
#include "str.h"
#define ZSTREAM_BUFFER_SIZE (1024 * 1024)
#define ZSTREAM_BUFFER_MIN_EXTRA 8
GIT_INLINE(int) zstream_seterr(git_zstream *zs)
{
switch (zs->zerr) {
case Z_OK:
case Z_STREAM_END:
case Z_BUF_ERROR: /* not fatal; we retry with a larger buffer */
return 0;
case Z_MEM_ERROR:
git_error_set_oom();
break;
default:
if (zs->z.msg)
git_error_set_str(GIT_ERROR_ZLIB, zs->z.msg);
else
git_error_set(GIT_ERROR_ZLIB, "unknown compression error");
}
return -1;
}
int git_zstream_init(git_zstream *zstream, git_zstream_t type)
{
zstream->type = type;
if (zstream->type == GIT_ZSTREAM_INFLATE)
zstream->zerr = inflateInit(&zstream->z);
else
zstream->zerr = deflateInit(&zstream->z, Z_DEFAULT_COMPRESSION);
return zstream_seterr(zstream);
}
void git_zstream_free(git_zstream *zstream)
{
if (zstream->type == GIT_ZSTREAM_INFLATE)
inflateEnd(&zstream->z);
else
deflateEnd(&zstream->z);
}
void git_zstream_reset(git_zstream *zstream)
{
if (zstream->type == GIT_ZSTREAM_INFLATE)
inflateReset(&zstream->z);
else
deflateReset(&zstream->z);
zstream->in = NULL;
zstream->in_len = 0;
zstream->zerr = Z_STREAM_END;
}
int git_zstream_set_input(git_zstream *zstream, const void *in, size_t in_len)
{
zstream->in = in;
zstream->in_len = in_len;
zstream->zerr = Z_OK;
return 0;
}
bool git_zstream_done(git_zstream *zstream)
{
return (!zstream->in_len && zstream->zerr == Z_STREAM_END);
}
bool git_zstream_eos(git_zstream *zstream)
{
return zstream->zerr == Z_STREAM_END;
}
size_t git_zstream_suggest_output_len(git_zstream *zstream)
{
if (zstream->in_len > ZSTREAM_BUFFER_SIZE)
return ZSTREAM_BUFFER_SIZE;
else if (zstream->in_len > ZSTREAM_BUFFER_MIN_EXTRA)
return zstream->in_len;
else
return ZSTREAM_BUFFER_MIN_EXTRA;
}
int git_zstream_get_output_chunk(
void *out, size_t *out_len, git_zstream *zstream)
{
size_t in_queued, in_used, out_queued;
/* set up input data */
zstream->z.next_in = (Bytef *)zstream->in;
/* feed as much data to zlib as it can consume, at most UINT_MAX */
if (zstream->in_len > UINT_MAX) {
zstream->z.avail_in = UINT_MAX;
zstream->flush = Z_NO_FLUSH;
} else {
zstream->z.avail_in = (uInt)zstream->in_len;
zstream->flush = Z_FINISH;
}
in_queued = (size_t)zstream->z.avail_in;
/* set up output data */
zstream->z.next_out = out;
zstream->z.avail_out = (uInt)*out_len;
if ((size_t)zstream->z.avail_out != *out_len)
zstream->z.avail_out = UINT_MAX;
out_queued = (size_t)zstream->z.avail_out;
/* compress next chunk */
if (zstream->type == GIT_ZSTREAM_INFLATE)
zstream->zerr = inflate(&zstream->z, zstream->flush);
else
zstream->zerr = deflate(&zstream->z, zstream->flush);
if (zstream_seterr(zstream))
return -1;
in_used = (in_queued - zstream->z.avail_in);
zstream->in_len -= in_used;
zstream->in += in_used;
*out_len = (out_queued - zstream->z.avail_out);
return 0;
}
int git_zstream_get_output(void *out, size_t *out_len, git_zstream *zstream)
{
size_t out_remain = *out_len;
if (zstream->in_len && zstream->zerr == Z_STREAM_END) {
git_error_set(GIT_ERROR_ZLIB, "zlib input had trailing garbage");
return -1;
}
while (out_remain > 0 && zstream->zerr != Z_STREAM_END) {
size_t out_written = out_remain;
if (git_zstream_get_output_chunk(out, &out_written, zstream) < 0)
return -1;
out_remain -= out_written;
out = ((char *)out) + out_written;
}
/* either we finished the input or we did not flush the data */
GIT_ASSERT(zstream->in_len > 0 || zstream->flush == Z_FINISH);
/* set out_size to number of bytes actually written to output */
*out_len = *out_len - out_remain;
return 0;
}
static int zstream_buf(git_str *out, const void *in, size_t in_len, git_zstream_t type)
{
git_zstream zs = GIT_ZSTREAM_INIT;
int error = 0;
if ((error = git_zstream_init(&zs, type)) < 0)
return error;
if ((error = git_zstream_set_input(&zs, in, in_len)) < 0)
goto done;
while (!git_zstream_done(&zs)) {
size_t step = git_zstream_suggest_output_len(&zs), written;
if ((error = git_str_grow_by(out, step)) < 0)
goto done;
written = out->asize - out->size;
if ((error = git_zstream_get_output(
out->ptr + out->size, &written, &zs)) < 0)
goto done;
out->size += written;
}
/* NULL terminate for consistency if possible */
if (out->size < out->asize)
out->ptr[out->size] = '\0';
done:
git_zstream_free(&zs);
return error;
}
int git_zstream_deflatebuf(git_str *out, const void *in, size_t in_len)
{
return zstream_buf(out, in, in_len, GIT_ZSTREAM_DEFLATE);
}
int git_zstream_inflatebuf(git_str *out, const void *in, size_t in_len)
{
return zstream_buf(out, in, in_len, GIT_ZSTREAM_INFLATE);
}
| libgit2-main | src/util/zstream.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "varint.h"
uintmax_t git_decode_varint(const unsigned char *bufp, size_t *varint_len)
{
const unsigned char *buf = bufp;
unsigned char c = *buf++;
uintmax_t val = c & 127;
while (c & 128) {
val += 1;
if (!val || MSB(val, 7)) {
/* This is not a valid varint_len, so it signals
the error */
*varint_len = 0;
return 0; /* overflow */
}
c = *buf++;
val = (val << 7) + (c & 127);
}
*varint_len = buf - bufp;
return val;
}
int git_encode_varint(unsigned char *buf, size_t bufsize, uintmax_t value)
{
unsigned char varint[16];
unsigned pos = sizeof(varint) - 1;
varint[pos] = value & 127;
while (value >>= 7)
varint[--pos] = 128 | (--value & 127);
if (buf) {
if (bufsize < (sizeof(varint) - pos))
return -1;
memcpy(buf, varint + pos, sizeof(varint) - pos);
}
return sizeof(varint) - pos;
}
| libgit2-main | src/util/varint.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "net.h"
#include <ctype.h>
#include "posix.h"
#include "str.h"
#include "http_parser.h"
#include "runtime.h"
#define DEFAULT_PORT_HTTP "80"
#define DEFAULT_PORT_HTTPS "443"
#define DEFAULT_PORT_GIT "9418"
#define DEFAULT_PORT_SSH "22"
bool git_net_str_is_url(const char *str)
{
const char *c;
for (c = str; *c; c++) {
if (*c == ':' && *(c+1) == '/' && *(c+2) == '/')
return true;
if ((*c < 'a' || *c > 'z') &&
(*c < 'A' || *c > 'Z') &&
(*c < '0' || *c > '9') &&
(*c != '+' && *c != '-' && *c != '.'))
break;
}
return false;
}
static const char *default_port_for_scheme(const char *scheme)
{
if (strcmp(scheme, "http") == 0)
return DEFAULT_PORT_HTTP;
else if (strcmp(scheme, "https") == 0)
return DEFAULT_PORT_HTTPS;
else if (strcmp(scheme, "git") == 0)
return DEFAULT_PORT_GIT;
else if (strcmp(scheme, "ssh") == 0 ||
strcmp(scheme, "ssh+git") == 0 ||
strcmp(scheme, "git+ssh") == 0)
return DEFAULT_PORT_SSH;
return NULL;
}
int git_net_url_dup(git_net_url *out, git_net_url *in)
{
if (in->scheme) {
out->scheme = git__strdup(in->scheme);
GIT_ERROR_CHECK_ALLOC(out->scheme);
}
if (in->host) {
out->host = git__strdup(in->host);
GIT_ERROR_CHECK_ALLOC(out->host);
}
if (in->port) {
out->port = git__strdup(in->port);
GIT_ERROR_CHECK_ALLOC(out->port);
}
if (in->path) {
out->path = git__strdup(in->path);
GIT_ERROR_CHECK_ALLOC(out->path);
}
if (in->query) {
out->query = git__strdup(in->query);
GIT_ERROR_CHECK_ALLOC(out->query);
}
if (in->username) {
out->username = git__strdup(in->username);
GIT_ERROR_CHECK_ALLOC(out->username);
}
if (in->password) {
out->password = git__strdup(in->password);
GIT_ERROR_CHECK_ALLOC(out->password);
}
return 0;
}
int git_net_url_parse(git_net_url *url, const char *given)
{
struct http_parser_url u = {0};
bool has_scheme, has_host, has_port, has_path, has_query, has_userinfo;
git_str scheme = GIT_STR_INIT,
host = GIT_STR_INIT,
port = GIT_STR_INIT,
path = GIT_STR_INIT,
username = GIT_STR_INIT,
password = GIT_STR_INIT,
query = GIT_STR_INIT;
int error = GIT_EINVALIDSPEC;
if (http_parser_parse_url(given, strlen(given), false, &u)) {
git_error_set(GIT_ERROR_NET, "malformed URL '%s'", given);
goto done;
}
has_scheme = !!(u.field_set & (1 << UF_SCHEMA));
has_host = !!(u.field_set & (1 << UF_HOST));
has_port = !!(u.field_set & (1 << UF_PORT));
has_path = !!(u.field_set & (1 << UF_PATH));
has_query = !!(u.field_set & (1 << UF_QUERY));
has_userinfo = !!(u.field_set & (1 << UF_USERINFO));
if (has_scheme) {
const char *url_scheme = given + u.field_data[UF_SCHEMA].off;
size_t url_scheme_len = u.field_data[UF_SCHEMA].len;
git_str_put(&scheme, url_scheme, url_scheme_len);
git__strntolower(scheme.ptr, scheme.size);
} else {
git_error_set(GIT_ERROR_NET, "malformed URL '%s'", given);
goto done;
}
if (has_host) {
const char *url_host = given + u.field_data[UF_HOST].off;
size_t url_host_len = u.field_data[UF_HOST].len;
git_str_decode_percent(&host, url_host, url_host_len);
}
if (has_port) {
const char *url_port = given + u.field_data[UF_PORT].off;
size_t url_port_len = u.field_data[UF_PORT].len;
git_str_put(&port, url_port, url_port_len);
} else {
const char *default_port = default_port_for_scheme(scheme.ptr);
if (default_port == NULL) {
git_error_set(GIT_ERROR_NET, "unknown scheme for URL '%s'", given);
goto done;
}
git_str_puts(&port, default_port);
}
if (has_path) {
const char *url_path = given + u.field_data[UF_PATH].off;
size_t url_path_len = u.field_data[UF_PATH].len;
git_str_put(&path, url_path, url_path_len);
} else {
git_str_puts(&path, "/");
}
if (has_query) {
const char *url_query = given + u.field_data[UF_QUERY].off;
size_t url_query_len = u.field_data[UF_QUERY].len;
git_str_decode_percent(&query, url_query, url_query_len);
}
if (has_userinfo) {
const char *url_userinfo = given + u.field_data[UF_USERINFO].off;
size_t url_userinfo_len = u.field_data[UF_USERINFO].len;
const char *colon = memchr(url_userinfo, ':', url_userinfo_len);
if (colon) {
const char *url_username = url_userinfo;
size_t url_username_len = colon - url_userinfo;
const char *url_password = colon + 1;
size_t url_password_len = url_userinfo_len - (url_username_len + 1);
git_str_decode_percent(&username, url_username, url_username_len);
git_str_decode_percent(&password, url_password, url_password_len);
} else {
git_str_decode_percent(&username, url_userinfo, url_userinfo_len);
}
}
if (git_str_oom(&scheme) ||
git_str_oom(&host) ||
git_str_oom(&port) ||
git_str_oom(&path) ||
git_str_oom(&query) ||
git_str_oom(&username) ||
git_str_oom(&password))
return -1;
url->scheme = git_str_detach(&scheme);
url->host = git_str_detach(&host);
url->port = git_str_detach(&port);
url->path = git_str_detach(&path);
url->query = git_str_detach(&query);
url->username = git_str_detach(&username);
url->password = git_str_detach(&password);
error = 0;
done:
git_str_dispose(&scheme);
git_str_dispose(&host);
git_str_dispose(&port);
git_str_dispose(&path);
git_str_dispose(&query);
git_str_dispose(&username);
git_str_dispose(&password);
return error;
}
static int scp_invalid(const char *message)
{
git_error_set(GIT_ERROR_NET, "invalid scp-style path: %s", message);
return GIT_EINVALIDSPEC;
}
static bool is_ipv6(const char *str)
{
const char *c;
size_t colons = 0;
if (*str++ != '[')
return false;
for (c = str; *c; c++) {
if (*c == ':')
colons++;
if (*c == ']')
return (colons > 1);
if (*c != ':' &&
(*c < '0' || *c > '9') &&
(*c < 'a' || *c > 'f') &&
(*c < 'A' || *c > 'F'))
return false;
}
return false;
}
static bool has_at(const char *str)
{
const char *c;
for (c = str; *c; c++) {
if (*c == '@')
return true;
if (*c == ':')
break;
}
return false;
}
int git_net_url_parse_scp(git_net_url *url, const char *given)
{
const char *default_port = default_port_for_scheme("ssh");
const char *c, *user, *host, *port, *path = NULL;
size_t user_len = 0, host_len = 0, port_len = 0;
unsigned short bracket = 0;
enum {
NONE,
USER,
HOST_START, HOST, HOST_END,
IPV6, IPV6_END,
PORT_START, PORT, PORT_END,
PATH_START
} state = NONE;
memset(url, 0, sizeof(git_net_url));
for (c = given; *c && !path; c++) {
switch (state) {
case NONE:
switch (*c) {
case '@':
return scp_invalid("unexpected '@'");
case ':':
return scp_invalid("unexpected ':'");
case '[':
if (is_ipv6(c)) {
state = IPV6;
host = c;
} else if (bracket++ > 1) {
return scp_invalid("unexpected '['");
}
break;
default:
if (has_at(c)) {
state = USER;
user = c;
} else {
state = HOST;
host = c;
}
break;
}
break;
case USER:
if (*c == '@') {
user_len = (c - user);
state = HOST_START;
}
break;
case HOST_START:
state = (*c == '[') ? IPV6 : HOST;
host = c;
break;
case HOST:
if (*c == ':') {
host_len = (c - host);
state = bracket ? PORT_START : PATH_START;
} else if (*c == ']') {
if (bracket-- == 0)
return scp_invalid("unexpected ']'");
host_len = (c - host);
state = HOST_END;
}
break;
case HOST_END:
if (*c != ':')
return scp_invalid("unexpected character after hostname");
state = PATH_START;
break;
case IPV6:
if (*c == ']')
state = IPV6_END;
break;
case IPV6_END:
if (*c != ':')
return scp_invalid("unexpected character after ipv6 address");
host_len = (c - host);
state = bracket ? PORT_START : PATH_START;
break;
case PORT_START:
port = c;
state = PORT;
break;
case PORT:
if (*c == ']') {
if (bracket-- == 0)
return scp_invalid("unexpected ']'");
port_len = c - port;
state = PORT_END;
}
break;
case PORT_END:
if (*c != ':')
return scp_invalid("unexpected character after ipv6 address");
state = PATH_START;
break;
case PATH_START:
path = c;
break;
default:
GIT_ASSERT("unhandled state");
}
}
if (!path)
return scp_invalid("path is required");
GIT_ERROR_CHECK_ALLOC(url->scheme = git__strdup("ssh"));
if (user_len)
GIT_ERROR_CHECK_ALLOC(url->username = git__strndup(user, user_len));
GIT_ASSERT(host_len);
GIT_ERROR_CHECK_ALLOC(url->host = git__strndup(host, host_len));
if (port_len)
GIT_ERROR_CHECK_ALLOC(url->port = git__strndup(port, port_len));
else
GIT_ERROR_CHECK_ALLOC(url->port = git__strdup(default_port));
GIT_ASSERT(path);
GIT_ERROR_CHECK_ALLOC(url->path = git__strdup(path));
return 0;
}
int git_net_url_joinpath(
git_net_url *out,
git_net_url *one,
const char *two)
{
git_str path = GIT_STR_INIT;
const char *query;
size_t one_len, two_len;
git_net_url_dispose(out);
if ((query = strchr(two, '?')) != NULL) {
two_len = query - two;
if (*(++query) != '\0') {
out->query = git__strdup(query);
GIT_ERROR_CHECK_ALLOC(out->query);
}
} else {
two_len = strlen(two);
}
/* Strip all trailing `/`s from the first path */
one_len = one->path ? strlen(one->path) : 0;
while (one_len && one->path[one_len - 1] == '/')
one_len--;
/* Strip all leading `/`s from the second path */
while (*two == '/') {
two++;
two_len--;
}
git_str_put(&path, one->path, one_len);
git_str_putc(&path, '/');
git_str_put(&path, two, two_len);
if (git_str_oom(&path))
return -1;
out->path = git_str_detach(&path);
if (one->scheme) {
out->scheme = git__strdup(one->scheme);
GIT_ERROR_CHECK_ALLOC(out->scheme);
}
if (one->host) {
out->host = git__strdup(one->host);
GIT_ERROR_CHECK_ALLOC(out->host);
}
if (one->port) {
out->port = git__strdup(one->port);
GIT_ERROR_CHECK_ALLOC(out->port);
}
if (one->username) {
out->username = git__strdup(one->username);
GIT_ERROR_CHECK_ALLOC(out->username);
}
if (one->password) {
out->password = git__strdup(one->password);
GIT_ERROR_CHECK_ALLOC(out->password);
}
return 0;
}
/*
* Some servers strip the query parameters from the Location header
* when sending a redirect. Others leave it in place.
* Check for both, starting with the stripped case first,
* since it appears to be more common.
*/
static void remove_service_suffix(
git_net_url *url,
const char *service_suffix)
{
const char *service_query = strchr(service_suffix, '?');
size_t full_suffix_len = strlen(service_suffix);
size_t suffix_len = service_query ?
(size_t)(service_query - service_suffix) : full_suffix_len;
size_t path_len = strlen(url->path);
ssize_t truncate = -1;
/*
* Check for a redirect without query parameters,
* like "/newloc/info/refs"'
*/
if (suffix_len && path_len >= suffix_len) {
size_t suffix_offset = path_len - suffix_len;
if (git__strncmp(url->path + suffix_offset, service_suffix, suffix_len) == 0 &&
(!service_query || git__strcmp(url->query, service_query + 1) == 0)) {
truncate = suffix_offset;
}
}
/*
* If we haven't already found where to truncate to remove the
* suffix, check for a redirect with query parameters, like
* "/newloc/info/refs?service=git-upload-pack"
*/
if (truncate < 0 && git__suffixcmp(url->path, service_suffix) == 0)
truncate = path_len - full_suffix_len;
/* Ensure we leave a minimum of '/' as the path */
if (truncate == 0)
truncate++;
if (truncate > 0) {
url->path[truncate] = '\0';
git__free(url->query);
url->query = NULL;
}
}
int git_net_url_apply_redirect(
git_net_url *url,
const char *redirect_location,
bool allow_offsite,
const char *service_suffix)
{
git_net_url tmp = GIT_NET_URL_INIT;
int error = 0;
GIT_ASSERT(url);
GIT_ASSERT(redirect_location);
if (redirect_location[0] == '/') {
git__free(url->path);
if ((url->path = git__strdup(redirect_location)) == NULL) {
error = -1;
goto done;
}
} else {
git_net_url *original = url;
if ((error = git_net_url_parse(&tmp, redirect_location)) < 0)
goto done;
/* Validate that this is a legal redirection */
if (original->scheme &&
strcmp(original->scheme, tmp.scheme) != 0 &&
strcmp(tmp.scheme, "https") != 0) {
git_error_set(GIT_ERROR_NET, "cannot redirect from '%s' to '%s'",
original->scheme, tmp.scheme);
error = -1;
goto done;
}
if (original->host &&
!allow_offsite &&
git__strcasecmp(original->host, tmp.host) != 0) {
git_error_set(GIT_ERROR_NET, "cannot redirect from '%s' to '%s'",
original->host, tmp.host);
error = -1;
goto done;
}
git_net_url_swap(url, &tmp);
}
/* Remove the service suffix if it was given to us */
if (service_suffix)
remove_service_suffix(url, service_suffix);
done:
git_net_url_dispose(&tmp);
return error;
}
bool git_net_url_valid(git_net_url *url)
{
return (url->host && url->port && url->path);
}
bool git_net_url_is_default_port(git_net_url *url)
{
const char *default_port;
if ((default_port = default_port_for_scheme(url->scheme)) != NULL)
return (strcmp(url->port, default_port) == 0);
else
return false;
}
bool git_net_url_is_ipv6(git_net_url *url)
{
return (strchr(url->host, ':') != NULL);
}
void git_net_url_swap(git_net_url *a, git_net_url *b)
{
git_net_url tmp = GIT_NET_URL_INIT;
memcpy(&tmp, a, sizeof(git_net_url));
memcpy(a, b, sizeof(git_net_url));
memcpy(b, &tmp, sizeof(git_net_url));
}
int git_net_url_fmt(git_str *buf, git_net_url *url)
{
GIT_ASSERT_ARG(url);
GIT_ASSERT_ARG(url->scheme);
GIT_ASSERT_ARG(url->host);
git_str_puts(buf, url->scheme);
git_str_puts(buf, "://");
if (url->username) {
git_str_puts(buf, url->username);
if (url->password) {
git_str_puts(buf, ":");
git_str_puts(buf, url->password);
}
git_str_putc(buf, '@');
}
git_str_puts(buf, url->host);
if (url->port && !git_net_url_is_default_port(url)) {
git_str_putc(buf, ':');
git_str_puts(buf, url->port);
}
git_str_puts(buf, url->path ? url->path : "/");
if (url->query) {
git_str_putc(buf, '?');
git_str_puts(buf, url->query);
}
return git_str_oom(buf) ? -1 : 0;
}
int git_net_url_fmt_path(git_str *buf, git_net_url *url)
{
git_str_puts(buf, url->path ? url->path : "/");
if (url->query) {
git_str_putc(buf, '?');
git_str_puts(buf, url->query);
}
return git_str_oom(buf) ? -1 : 0;
}
static bool matches_pattern(
git_net_url *url,
const char *pattern,
size_t pattern_len)
{
const char *domain, *port = NULL, *colon;
size_t host_len, domain_len, port_len = 0, wildcard = 0;
GIT_UNUSED(url);
GIT_UNUSED(pattern);
if (!pattern_len)
return false;
else if (pattern_len == 1 && pattern[0] == '*')
return true;
else if (pattern_len > 1 && pattern[0] == '*' && pattern[1] == '.')
wildcard = 2;
else if (pattern[0] == '.')
wildcard = 1;
domain = pattern + wildcard;
domain_len = pattern_len - wildcard;
if ((colon = memchr(domain, ':', domain_len)) != NULL) {
domain_len = colon - domain;
port = colon + 1;
port_len = pattern_len - wildcard - domain_len - 1;
}
/* A pattern's port *must* match if it's specified */
if (port_len && git__strlcmp(url->port, port, port_len) != 0)
return false;
/* No wildcard? Host must match exactly. */
if (!wildcard)
return !git__strlcmp(url->host, domain, domain_len);
/* Wildcard: ensure there's (at least) a suffix match */
if ((host_len = strlen(url->host)) < domain_len ||
memcmp(url->host + (host_len - domain_len), domain, domain_len))
return false;
/* The pattern is *.domain and the host is simply domain */
if (host_len == domain_len)
return true;
/* The pattern is *.domain and the host is foo.domain */
return (url->host[host_len - domain_len - 1] == '.');
}
bool git_net_url_matches_pattern(git_net_url *url, const char *pattern)
{
return matches_pattern(url, pattern, strlen(pattern));
}
bool git_net_url_matches_pattern_list(
git_net_url *url,
const char *pattern_list)
{
const char *pattern, *pattern_end, *sep;
for (pattern = pattern_list;
pattern && *pattern;
pattern = sep ? sep + 1 : NULL) {
sep = strchr(pattern, ',');
pattern_end = sep ? sep : strchr(pattern, '\0');
if (matches_pattern(url, pattern, (pattern_end - pattern)))
return true;
}
return false;
}
void git_net_url_dispose(git_net_url *url)
{
if (url->username)
git__memzero(url->username, strlen(url->username));
if (url->password)
git__memzero(url->password, strlen(url->password));
git__free(url->scheme); url->scheme = NULL;
git__free(url->host); url->host = NULL;
git__free(url->port); url->port = NULL;
git__free(url->path); url->path = NULL;
git__free(url->query); url->query = NULL;
git__free(url->username); url->username = NULL;
git__free(url->password); url->password = NULL;
}
| libgit2-main | src/util/net.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "pool.h"
#include "posix.h"
#ifndef GIT_WIN32
#include <unistd.h>
#endif
struct git_pool_page {
git_pool_page *next;
size_t size;
size_t avail;
GIT_ALIGN(char data[GIT_FLEX_ARRAY], 8);
};
static void *pool_alloc_page(git_pool *pool, size_t size);
#ifndef GIT_DEBUG_POOL
static size_t system_page_size = 0;
int git_pool_global_init(void)
{
if (git__page_size(&system_page_size) < 0)
system_page_size = 4096;
/* allow space for malloc overhead */
system_page_size -= (2 * sizeof(void *)) + sizeof(git_pool_page);
return 0;
}
int git_pool_init(git_pool *pool, size_t item_size)
{
GIT_ASSERT_ARG(pool);
GIT_ASSERT_ARG(item_size >= 1);
memset(pool, 0, sizeof(git_pool));
pool->item_size = item_size;
pool->page_size = system_page_size;
return 0;
}
void git_pool_clear(git_pool *pool)
{
git_pool_page *scan, *next;
for (scan = pool->pages; scan != NULL; scan = next) {
next = scan->next;
git__free(scan);
}
pool->pages = NULL;
}
static void *pool_alloc_page(git_pool *pool, size_t size)
{
git_pool_page *page;
const size_t new_page_size = (size <= pool->page_size) ? pool->page_size : size;
size_t alloc_size;
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, new_page_size, sizeof(git_pool_page)) ||
!(page = git__malloc(alloc_size)))
return NULL;
page->size = new_page_size;
page->avail = new_page_size - size;
page->next = pool->pages;
pool->pages = page;
return page->data;
}
static void *pool_alloc(git_pool *pool, size_t size)
{
git_pool_page *page = pool->pages;
void *ptr = NULL;
if (!page || page->avail < size)
return pool_alloc_page(pool, size);
ptr = &page->data[page->size - page->avail];
page->avail -= size;
return ptr;
}
uint32_t git_pool__open_pages(git_pool *pool)
{
uint32_t ct = 0;
git_pool_page *scan;
for (scan = pool->pages; scan != NULL; scan = scan->next) ct++;
return ct;
}
bool git_pool__ptr_in_pool(git_pool *pool, void *ptr)
{
git_pool_page *scan;
for (scan = pool->pages; scan != NULL; scan = scan->next)
if ((void *)scan->data <= ptr &&
(void *)(((char *)scan->data) + scan->size) > ptr)
return true;
return false;
}
#else
int git_pool_global_init(void)
{
return 0;
}
static int git_pool__ptr_cmp(const void * a, const void * b)
{
if(a > b) {
return 1;
}
if(a < b) {
return -1;
}
else {
return 0;
}
}
int git_pool_init(git_pool *pool, size_t item_size)
{
GIT_ASSERT_ARG(pool);
GIT_ASSERT_ARG(item_size >= 1);
memset(pool, 0, sizeof(git_pool));
pool->item_size = item_size;
pool->page_size = git_pool__system_page_size();
git_vector_init(&pool->allocations, 100, git_pool__ptr_cmp);
return 0;
}
void git_pool_clear(git_pool *pool)
{
git_vector_free_deep(&pool->allocations);
}
static void *pool_alloc(git_pool *pool, size_t size) {
void *ptr = NULL;
if((ptr = git__malloc(size)) == NULL) {
return NULL;
}
git_vector_insert_sorted(&pool->allocations, ptr, NULL);
return ptr;
}
bool git_pool__ptr_in_pool(git_pool *pool, void *ptr)
{
size_t pos;
return git_vector_bsearch(&pos, &pool->allocations, ptr) != GIT_ENOTFOUND;
}
#endif
void git_pool_swap(git_pool *a, git_pool *b)
{
git_pool temp;
if (a == b)
return;
memcpy(&temp, a, sizeof(temp));
memcpy(a, b, sizeof(temp));
memcpy(b, &temp, sizeof(temp));
}
static size_t alloc_size(git_pool *pool, size_t count)
{
const size_t align = sizeof(void *) - 1;
if (pool->item_size > 1) {
const size_t item_size = (pool->item_size + align) & ~align;
return item_size * count;
}
return (count + align) & ~align;
}
void *git_pool_malloc(git_pool *pool, size_t items)
{
return pool_alloc(pool, alloc_size(pool, items));
}
void *git_pool_mallocz(git_pool *pool, size_t items)
{
const size_t size = alloc_size(pool, items);
void *ptr = pool_alloc(pool, size);
if (ptr)
memset(ptr, 0x0, size);
return ptr;
}
char *git_pool_strndup(git_pool *pool, const char *str, size_t n)
{
char *ptr = NULL;
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(str, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
if (n == SIZE_MAX)
return NULL;
if ((ptr = git_pool_malloc(pool, (n + 1))) != NULL) {
memcpy(ptr, str, n);
ptr[n] = '\0';
}
return ptr;
}
char *git_pool_strdup(git_pool *pool, const char *str)
{
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(str, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
return git_pool_strndup(pool, str, strlen(str));
}
char *git_pool_strdup_safe(git_pool *pool, const char *str)
{
return str ? git_pool_strdup(pool, str) : NULL;
}
char *git_pool_strcat(git_pool *pool, const char *a, const char *b)
{
void *ptr;
size_t len_a, len_b, total;
GIT_ASSERT_ARG_WITH_RETVAL(pool, NULL);
GIT_ASSERT_ARG_WITH_RETVAL(pool->item_size == sizeof(char), NULL);
len_a = a ? strlen(a) : 0;
len_b = b ? strlen(b) : 0;
if (GIT_ADD_SIZET_OVERFLOW(&total, len_a, len_b) ||
GIT_ADD_SIZET_OVERFLOW(&total, total, 1))
return NULL;
if ((ptr = git_pool_malloc(pool, total)) != NULL) {
if (len_a)
memcpy(ptr, a, len_a);
if (len_b)
memcpy(((char *)ptr) + len_a, b, len_b);
*(((char *)ptr) + len_a + len_b) = '\0';
}
return ptr;
}
| libgit2-main | src/util/pool.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#ifndef GIT_WIN32
#include <sys/time.h>
#endif
#include "util.h"
#include "posix.h"
#include "date.h"
#include <ctype.h>
#include <time.h>
typedef enum {
DATE_NORMAL = 0,
DATE_RELATIVE,
DATE_SHORT,
DATE_LOCAL,
DATE_ISO8601,
DATE_RFC2822,
DATE_RAW
} date_mode;
/*
* This is like mktime, but without normalization of tm_wday and tm_yday.
*/
static git_time_t tm_to_time_t(const struct tm *tm)
{
static const int mdays[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int year = tm->tm_year - 70;
int month = tm->tm_mon;
int day = tm->tm_mday;
if (year < 0 || year > 129) /* algo only works for 1970-2099 */
return -1;
if (month < 0 || month > 11) /* array bounds */
return -1;
if (month < 2 || (year + 2) % 4)
day--;
if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
return -1;
return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
}
static const char *month_names[] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
static const char *weekday_names[] = {
"Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
};
/*
* Check these. And note how it doesn't do the summer-time conversion.
*
* In my world, it's always summer, and things are probably a bit off
* in other ways too.
*/
static const struct {
const char *name;
int offset;
int dst;
} timezone_names[] = {
{ "IDLW", -12, 0, }, /* International Date Line West */
{ "NT", -11, 0, }, /* Nome */
{ "CAT", -10, 0, }, /* Central Alaska */
{ "HST", -10, 0, }, /* Hawaii Standard */
{ "HDT", -10, 1, }, /* Hawaii Daylight */
{ "YST", -9, 0, }, /* Yukon Standard */
{ "YDT", -9, 1, }, /* Yukon Daylight */
{ "PST", -8, 0, }, /* Pacific Standard */
{ "PDT", -8, 1, }, /* Pacific Daylight */
{ "MST", -7, 0, }, /* Mountain Standard */
{ "MDT", -7, 1, }, /* Mountain Daylight */
{ "CST", -6, 0, }, /* Central Standard */
{ "CDT", -6, 1, }, /* Central Daylight */
{ "EST", -5, 0, }, /* Eastern Standard */
{ "EDT", -5, 1, }, /* Eastern Daylight */
{ "AST", -3, 0, }, /* Atlantic Standard */
{ "ADT", -3, 1, }, /* Atlantic Daylight */
{ "WAT", -1, 0, }, /* West Africa */
{ "GMT", 0, 0, }, /* Greenwich Mean */
{ "UTC", 0, 0, }, /* Universal (Coordinated) */
{ "Z", 0, 0, }, /* Zulu, alias for UTC */
{ "WET", 0, 0, }, /* Western European */
{ "BST", 0, 1, }, /* British Summer */
{ "CET", +1, 0, }, /* Central European */
{ "MET", +1, 0, }, /* Middle European */
{ "MEWT", +1, 0, }, /* Middle European Winter */
{ "MEST", +1, 1, }, /* Middle European Summer */
{ "CEST", +1, 1, }, /* Central European Summer */
{ "MESZ", +1, 1, }, /* Middle European Summer */
{ "FWT", +1, 0, }, /* French Winter */
{ "FST", +1, 1, }, /* French Summer */
{ "EET", +2, 0, }, /* Eastern Europe */
{ "EEST", +2, 1, }, /* Eastern European Daylight */
{ "WAST", +7, 0, }, /* West Australian Standard */
{ "WADT", +7, 1, }, /* West Australian Daylight */
{ "CCT", +8, 0, }, /* China Coast */
{ "JST", +9, 0, }, /* Japan Standard */
{ "EAST", +10, 0, }, /* Eastern Australian Standard */
{ "EADT", +10, 1, }, /* Eastern Australian Daylight */
{ "GST", +10, 0, }, /* Guam Standard */
{ "NZT", +12, 0, }, /* New Zealand */
{ "NZST", +12, 0, }, /* New Zealand Standard */
{ "NZDT", +12, 1, }, /* New Zealand Daylight */
{ "IDLE", +12, 0, }, /* International Date Line East */
};
static size_t match_string(const char *date, const char *str)
{
size_t i = 0;
for (i = 0; *date; date++, str++, i++) {
if (*date == *str)
continue;
if (toupper(*date) == toupper(*str))
continue;
if (!isalnum(*date))
break;
return 0;
}
return i;
}
static int skip_alpha(const char *date)
{
int i = 0;
do {
i++;
} while (isalpha(date[i]));
return i;
}
/*
* Parse month, weekday, or timezone name
*/
static size_t match_alpha(const char *date, struct tm *tm, int *offset)
{
unsigned int i;
for (i = 0; i < 12; i++) {
size_t match = match_string(date, month_names[i]);
if (match >= 3) {
tm->tm_mon = i;
return match;
}
}
for (i = 0; i < 7; i++) {
size_t match = match_string(date, weekday_names[i]);
if (match >= 3) {
tm->tm_wday = i;
return match;
}
}
for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
size_t match = match_string(date, timezone_names[i].name);
if (match >= 3 || match == strlen(timezone_names[i].name)) {
int off = timezone_names[i].offset;
/* This is bogus, but we like summer */
off += timezone_names[i].dst;
/* Only use the tz name offset if we don't have anything better */
if (*offset == -1)
*offset = 60*off;
return match;
}
}
if (match_string(date, "PM") == 2) {
tm->tm_hour = (tm->tm_hour % 12) + 12;
return 2;
}
if (match_string(date, "AM") == 2) {
tm->tm_hour = (tm->tm_hour % 12) + 0;
return 2;
}
/* BAD */
return skip_alpha(date);
}
static int is_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
{
if (month > 0 && month < 13 && day > 0 && day < 32) {
struct tm check = *tm;
struct tm *r = (now_tm ? &check : tm);
git_time_t specified;
r->tm_mon = month - 1;
r->tm_mday = day;
if (year == -1) {
if (!now_tm)
return 1;
r->tm_year = now_tm->tm_year;
}
else if (year >= 1970 && year < 2100)
r->tm_year = year - 1900;
else if (year > 70 && year < 100)
r->tm_year = year;
else if (year < 38)
r->tm_year = year + 100;
else
return 0;
if (!now_tm)
return 1;
specified = tm_to_time_t(r);
/* Be it commit time or author time, it does not make
* sense to specify timestamp way into the future. Make
* sure it is not later than ten days from now...
*/
if (now + 10*24*3600 < specified)
return 0;
tm->tm_mon = r->tm_mon;
tm->tm_mday = r->tm_mday;
if (year != -1)
tm->tm_year = r->tm_year;
return 1;
}
return 0;
}
static size_t match_multi_number(unsigned long num, char c, const char *date, char *end, struct tm *tm)
{
time_t now;
struct tm now_tm;
struct tm *refuse_future;
long num2, num3;
num2 = strtol(end+1, &end, 10);
num3 = -1;
if (*end == c && isdigit(end[1]))
num3 = strtol(end+1, &end, 10);
/* Time? Date? */
switch (c) {
case ':':
if (num3 < 0)
num3 = 0;
if (num < 25 && num2 >= 0 && num2 < 60 && num3 >= 0 && num3 <= 60) {
tm->tm_hour = num;
tm->tm_min = num2;
tm->tm_sec = num3;
break;
}
return 0;
case '-':
case '/':
case '.':
now = time(NULL);
refuse_future = NULL;
if (p_gmtime_r(&now, &now_tm))
refuse_future = &now_tm;
if (num > 70) {
/* yyyy-mm-dd? */
if (is_date(num, num2, num3, refuse_future, now, tm))
break;
/* yyyy-dd-mm? */
if (is_date(num, num3, num2, refuse_future, now, tm))
break;
}
/* Our eastern European friends say dd.mm.yy[yy]
* is the norm there, so giving precedence to
* mm/dd/yy[yy] form only when separator is not '.'
*/
if (c != '.' &&
is_date(num3, num, num2, refuse_future, now, tm))
break;
/* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
if (is_date(num3, num2, num, refuse_future, now, tm))
break;
/* Funny European mm.dd.yy */
if (c == '.' &&
is_date(num3, num, num2, refuse_future, now, tm))
break;
return 0;
}
return end - date;
}
/*
* Have we filled in any part of the time/date yet?
* We just do a binary 'and' to see if the sign bit
* is set in all the values.
*/
static int nodate(struct tm *tm)
{
return (tm->tm_year &
tm->tm_mon &
tm->tm_mday &
tm->tm_hour &
tm->tm_min &
tm->tm_sec) < 0;
}
/*
* We've seen a digit. Time? Year? Date?
*/
static size_t match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
{
size_t n;
char *end;
unsigned long num;
num = strtoul(date, &end, 10);
/*
* Seconds since 1970? We trigger on that for any numbers with
* more than 8 digits. This is because we don't want to rule out
* numbers like 20070606 as a YYYYMMDD date.
*/
if (num >= 100000000 && nodate(tm)) {
time_t time = num;
if (p_gmtime_r(&time, tm)) {
*tm_gmt = 1;
return end - date;
}
}
/*
* Check for special formats: num[-.:/]num[same]num
*/
switch (*end) {
case ':':
case '.':
case '/':
case '-':
if (isdigit(end[1])) {
size_t match = match_multi_number(num, *end, date, end, tm);
if (match)
return match;
}
}
/*
* None of the special formats? Try to guess what
* the number meant. We use the number of digits
* to make a more educated guess..
*/
n = 0;
do {
n++;
} while (isdigit(date[n]));
/* Four-digit year or a timezone? */
if (n == 4) {
if (num <= 1400 && *offset == -1) {
unsigned int minutes = num % 100;
unsigned int hours = num / 100;
*offset = hours*60 + minutes;
} else if (num > 1900 && num < 2100)
tm->tm_year = num - 1900;
return n;
}
/*
* Ignore lots of numerals. We took care of 4-digit years above.
* Days or months must be one or two digits.
*/
if (n > 2)
return n;
/*
* NOTE! We will give precedence to day-of-month over month or
* year numbers in the 1-12 range. So 05 is always "mday 5",
* unless we already have a mday..
*
* IOW, 01 Apr 05 parses as "April 1st, 2005".
*/
if (num > 0 && num < 32 && tm->tm_mday < 0) {
tm->tm_mday = num;
return n;
}
/* Two-digit year? */
if (n == 2 && tm->tm_year < 0) {
if (num < 10 && tm->tm_mday >= 0) {
tm->tm_year = num + 100;
return n;
}
if (num >= 70) {
tm->tm_year = num;
return n;
}
}
if (num > 0 && num < 13 && tm->tm_mon < 0)
tm->tm_mon = num-1;
return n;
}
static size_t match_tz(const char *date, int *offp)
{
char *end;
int hour = strtoul(date + 1, &end, 10);
size_t n = end - (date + 1);
int min = 0;
if (n == 4) {
/* hhmm */
min = hour % 100;
hour = hour / 100;
} else if (n != 2) {
min = 99; /* random stuff */
} else if (*end == ':') {
/* hh:mm? */
min = strtoul(end + 1, &end, 10);
if (end - (date + 1) != 5)
min = 99; /* random stuff */
} /* otherwise we parsed "hh" */
/*
* Don't accept any random stuff. Even though some places have
* offset larger than 12 hours (e.g. Pacific/Kiritimati is at
* UTC+14), there is something wrong if hour part is much
* larger than that. We might also want to check that the
* minutes are divisible by 15 or something too. (Offset of
* Kathmandu, Nepal is UTC+5:45)
*/
if (min < 60 && hour < 24) {
int offset = hour * 60 + min;
if (*date == '-')
offset = -offset;
*offp = offset;
}
return end - date;
}
/*
* Parse a string like "0 +0000" as ancient timestamp near epoch, but
* only when it appears not as part of any other string.
*/
static int match_object_header_date(const char *date, git_time_t *timestamp, int *offset)
{
char *end;
unsigned long stamp;
int ofs;
if (*date < '0' || '9' <= *date)
return -1;
stamp = strtoul(date, &end, 10);
if (*end != ' ' || stamp == ULONG_MAX || (end[1] != '+' && end[1] != '-'))
return -1;
date = end + 2;
ofs = strtol(date, &end, 10);
if ((*end != '\0' && (*end != '\n')) || end != date + 4)
return -1;
ofs = (ofs / 100) * 60 + (ofs % 100);
if (date[-1] == '-')
ofs = -ofs;
*timestamp = stamp;
*offset = ofs;
return 0;
}
/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
(i.e. English) day/month names, and it doesn't work correctly with %z. */
static int parse_date_basic(const char *date, git_time_t *timestamp, int *offset)
{
struct tm tm;
int tm_gmt;
git_time_t dummy_timestamp;
int dummy_offset;
if (!timestamp)
timestamp = &dummy_timestamp;
if (!offset)
offset = &dummy_offset;
memset(&tm, 0, sizeof(tm));
tm.tm_year = -1;
tm.tm_mon = -1;
tm.tm_mday = -1;
tm.tm_isdst = -1;
tm.tm_hour = -1;
tm.tm_min = -1;
tm.tm_sec = -1;
*offset = -1;
tm_gmt = 0;
if (*date == '@' &&
!match_object_header_date(date + 1, timestamp, offset))
return 0; /* success */
for (;;) {
size_t match = 0;
unsigned char c = *date;
/* Stop at end of string or newline */
if (!c || c == '\n')
break;
if (isalpha(c))
match = match_alpha(date, &tm, offset);
else if (isdigit(c))
match = match_digit(date, &tm, offset, &tm_gmt);
else if ((c == '-' || c == '+') && isdigit(date[1]))
match = match_tz(date, offset);
if (!match) {
/* BAD */
match = 1;
}
date += match;
}
/* mktime uses local timezone */
*timestamp = tm_to_time_t(&tm);
if (*offset == -1)
*offset = (int)((time_t)*timestamp - mktime(&tm)) / 60;
if (*timestamp == (git_time_t)-1)
return -1;
if (!tm_gmt)
*timestamp -= *offset * 60;
return 0; /* success */
}
/*
* Relative time update (eg "2 days ago"). If we haven't set the time
* yet, we need to set it from current time.
*/
static git_time_t update_tm(struct tm *tm, struct tm *now, unsigned long sec)
{
time_t n;
if (tm->tm_mday < 0)
tm->tm_mday = now->tm_mday;
if (tm->tm_mon < 0)
tm->tm_mon = now->tm_mon;
if (tm->tm_year < 0) {
tm->tm_year = now->tm_year;
if (tm->tm_mon > now->tm_mon)
tm->tm_year--;
}
n = mktime(tm) - sec;
p_localtime_r(&n, tm);
return n;
}
static void date_now(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
update_tm(tm, now, 0);
}
static void date_yesterday(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
update_tm(tm, now, 24*60*60);
}
static void date_time(struct tm *tm, struct tm *now, int hour)
{
if (tm->tm_hour < hour)
date_yesterday(tm, now, NULL);
tm->tm_hour = hour;
tm->tm_min = 0;
tm->tm_sec = 0;
}
static void date_midnight(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 0);
}
static void date_noon(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 12);
}
static void date_tea(struct tm *tm, struct tm *now, int *num)
{
GIT_UNUSED(num);
date_time(tm, now, 17);
}
static void date_pm(struct tm *tm, struct tm *now, int *num)
{
int hour, n = *num;
*num = 0;
GIT_UNUSED(now);
hour = tm->tm_hour;
if (n) {
hour = n;
tm->tm_min = 0;
tm->tm_sec = 0;
}
tm->tm_hour = (hour % 12) + 12;
}
static void date_am(struct tm *tm, struct tm *now, int *num)
{
int hour, n = *num;
*num = 0;
GIT_UNUSED(now);
hour = tm->tm_hour;
if (n) {
hour = n;
tm->tm_min = 0;
tm->tm_sec = 0;
}
tm->tm_hour = (hour % 12);
}
static void date_never(struct tm *tm, struct tm *now, int *num)
{
time_t n = 0;
GIT_UNUSED(now);
GIT_UNUSED(num);
p_localtime_r(&n, tm);
}
static const struct special {
const char *name;
void (*fn)(struct tm *, struct tm *, int *);
} special[] = {
{ "yesterday", date_yesterday },
{ "noon", date_noon },
{ "midnight", date_midnight },
{ "tea", date_tea },
{ "PM", date_pm },
{ "AM", date_am },
{ "never", date_never },
{ "now", date_now },
{ NULL }
};
static const char *number_name[] = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
};
static const struct typelen {
const char *type;
int length;
} typelen[] = {
{ "seconds", 1 },
{ "minutes", 60 },
{ "hours", 60*60 },
{ "days", 24*60*60 },
{ "weeks", 7*24*60*60 },
{ NULL }
};
static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
{
const struct typelen *tl;
const struct special *s;
const char *end = date;
int i;
while (isalpha(*++end))
/* scan to non-alpha */;
for (i = 0; i < 12; i++) {
size_t match = match_string(date, month_names[i]);
if (match >= 3) {
tm->tm_mon = i;
*touched = 1;
return end;
}
}
for (s = special; s->name; s++) {
size_t len = strlen(s->name);
if (match_string(date, s->name) == len) {
s->fn(tm, now, num);
*touched = 1;
return end;
}
}
if (!*num) {
for (i = 1; i < 11; i++) {
size_t len = strlen(number_name[i]);
if (match_string(date, number_name[i]) == len) {
*num = i;
*touched = 1;
return end;
}
}
if (match_string(date, "last") == 4) {
*num = 1;
*touched = 1;
}
return end;
}
tl = typelen;
while (tl->type) {
size_t len = strlen(tl->type);
if (match_string(date, tl->type) >= len-1) {
update_tm(tm, now, tl->length * (unsigned long)*num);
*num = 0;
*touched = 1;
return end;
}
tl++;
}
for (i = 0; i < 7; i++) {
size_t match = match_string(date, weekday_names[i]);
if (match >= 3) {
int diff, n = *num -1;
*num = 0;
diff = tm->tm_wday - i;
if (diff <= 0)
n++;
diff += 7*n;
update_tm(tm, now, diff * 24 * 60 * 60);
*touched = 1;
return end;
}
}
if (match_string(date, "months") >= 5) {
int n;
update_tm(tm, now, 0); /* fill in date fields if needed */
n = tm->tm_mon - *num;
*num = 0;
while (n < 0) {
n += 12;
tm->tm_year--;
}
tm->tm_mon = n;
*touched = 1;
return end;
}
if (match_string(date, "years") >= 4) {
update_tm(tm, now, 0); /* fill in date fields if needed */
tm->tm_year -= *num;
*num = 0;
*touched = 1;
return end;
}
return end;
}
static const char *approxidate_digit(const char *date, struct tm *tm, int *num)
{
char *end;
unsigned long number = strtoul(date, &end, 10);
switch (*end) {
case ':':
case '.':
case '/':
case '-':
if (isdigit(end[1])) {
size_t match = match_multi_number(number, *end, date, end, tm);
if (match)
return date + match;
}
}
/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
if (date[0] != '0' || end - date <= 2)
*num = number;
return end;
}
/*
* Do we have a pending number at the end, or when
* we see a new one? Let's assume it's a month day,
* as in "Dec 6, 1992"
*/
static void pending_number(struct tm *tm, int *num)
{
int number = *num;
if (number) {
*num = 0;
if (tm->tm_mday < 0 && number < 32)
tm->tm_mday = number;
else if (tm->tm_mon < 0 && number < 13)
tm->tm_mon = number-1;
else if (tm->tm_year < 0) {
if (number > 1969 && number < 2100)
tm->tm_year = number - 1900;
else if (number > 69 && number < 100)
tm->tm_year = number;
else if (number < 38)
tm->tm_year = 100 + number;
/* We mess up for number = 00 ? */
}
}
}
static git_time_t approxidate_str(const char *date,
time_t time_sec,
int *error_ret)
{
int number = 0;
int touched = 0;
struct tm tm = {0}, now;
p_localtime_r(&time_sec, &tm);
now = tm;
tm.tm_year = -1;
tm.tm_mon = -1;
tm.tm_mday = -1;
for (;;) {
unsigned char c = *date;
if (!c)
break;
date++;
if (isdigit(c)) {
pending_number(&tm, &number);
date = approxidate_digit(date-1, &tm, &number);
touched = 1;
continue;
}
if (isalpha(c))
date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
}
pending_number(&tm, &number);
if (!touched)
*error_ret = -1;
return update_tm(&tm, &now, 0);
}
int git_date_parse(git_time_t *out, const char *date)
{
time_t time_sec;
git_time_t timestamp;
int offset, error_ret=0;
if (!parse_date_basic(date, ×tamp, &offset)) {
*out = timestamp;
return 0;
}
if (time(&time_sec) == -1)
return -1;
*out = approxidate_str(date, time_sec, &error_ret);
return error_ret;
}
int git_date_rfc2822_fmt(git_str *out, git_time_t time, int offset)
{
time_t t;
struct tm gmt;
GIT_ASSERT_ARG(out);
t = (time_t) (time + offset * 60);
if (p_gmtime_r(&t, &gmt) == NULL)
return -1;
return git_str_printf(out, "%.3s, %u %.3s %.4u %02u:%02u:%02u %+03d%02d",
weekday_names[gmt.tm_wday],
gmt.tm_mday,
month_names[gmt.tm_mon],
gmt.tm_year + 1900,
gmt.tm_hour, gmt.tm_min, gmt.tm_sec,
offset / 60, offset % 60);
}
| libgit2-main | src/util/date.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "strmap.h"
#define kmalloc git__malloc
#define kcalloc git__calloc
#define krealloc git__realloc
#define kreallocarray git__reallocarray
#define kfree git__free
#include "khash.h"
__KHASH_TYPE(str, const char *, void *)
__KHASH_IMPL(str, static kh_inline, const char *, void *, 1, kh_str_hash_func, kh_str_hash_equal)
int git_strmap_new(git_strmap **out)
{
*out = kh_init(str);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
void git_strmap_free(git_strmap *map)
{
kh_destroy(str, map);
}
void git_strmap_clear(git_strmap *map)
{
kh_clear(str, map);
}
size_t git_strmap_size(git_strmap *map)
{
return kh_size(map);
}
void *git_strmap_get(git_strmap *map, const char *key)
{
size_t idx = kh_get(str, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_strmap_set(git_strmap *map, const char *key, void *value)
{
size_t idx;
int rval;
idx = kh_put(str, map, key, &rval);
if (rval < 0)
return -1;
if (rval == 0)
kh_key(map, idx) = key;
kh_val(map, idx) = value;
return 0;
}
int git_strmap_delete(git_strmap *map, const char *key)
{
khiter_t idx = kh_get(str, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(str, map, idx);
return 0;
}
int git_strmap_exists(git_strmap *map, const char *key)
{
return kh_get(str, map, key) != kh_end(map);
}
int git_strmap_iterate(void **value, git_strmap *map, size_t *iter, const char **key)
{
size_t i = *iter;
while (i < map->n_buckets && !kh_exist(map, i))
i++;
if (i >= map->n_buckets)
return GIT_ITEROVER;
if (key)
*key = kh_key(map, i);
if (value)
*value = kh_val(map, i);
*iter = ++i;
return 0;
}
| libgit2-main | src/util/strmap.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "sortedcache.h"
int git_sortedcache_new(
git_sortedcache **out,
size_t item_path_offset,
git_sortedcache_free_item_fn free_item,
void *free_item_payload,
git_vector_cmp item_cmp,
const char *path)
{
git_sortedcache *sc;
size_t pathlen, alloclen;
pathlen = path ? strlen(path) : 0;
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_sortedcache), pathlen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
sc = git__calloc(1, alloclen);
GIT_ERROR_CHECK_ALLOC(sc);
if (git_pool_init(&sc->pool, 1) < 0 ||
git_vector_init(&sc->items, 4, item_cmp) < 0 ||
git_strmap_new(&sc->map) < 0)
goto fail;
if (git_rwlock_init(&sc->lock)) {
git_error_set(GIT_ERROR_OS, "failed to initialize lock");
goto fail;
}
sc->item_path_offset = item_path_offset;
sc->free_item = free_item;
sc->free_item_payload = free_item_payload;
GIT_REFCOUNT_INC(sc);
if (pathlen)
memcpy(sc->path, path, pathlen);
*out = sc;
return 0;
fail:
git_strmap_free(sc->map);
git_vector_free(&sc->items);
git_pool_clear(&sc->pool);
git__free(sc);
return -1;
}
void git_sortedcache_incref(git_sortedcache *sc)
{
GIT_REFCOUNT_INC(sc);
}
const char *git_sortedcache_path(git_sortedcache *sc)
{
return sc->path;
}
static void sortedcache_clear(git_sortedcache *sc)
{
git_strmap_clear(sc->map);
if (sc->free_item) {
size_t i;
void *item;
git_vector_foreach(&sc->items, i, item) {
sc->free_item(sc->free_item_payload, item);
}
}
git_vector_clear(&sc->items);
git_pool_clear(&sc->pool);
}
static void sortedcache_free(git_sortedcache *sc)
{
/* acquire write lock to make sure everyone else is done */
if (git_sortedcache_wlock(sc) < 0)
return;
sortedcache_clear(sc);
git_vector_free(&sc->items);
git_strmap_free(sc->map);
git_sortedcache_wunlock(sc);
git_rwlock_free(&sc->lock);
git__free(sc);
}
void git_sortedcache_free(git_sortedcache *sc)
{
if (!sc)
return;
GIT_REFCOUNT_DEC(sc, sortedcache_free);
}
static int sortedcache_copy_item(void *payload, void *tgt_item, void *src_item)
{
git_sortedcache *sc = payload;
/* path will already have been copied by upsert */
memcpy(tgt_item, src_item, sc->item_path_offset);
return 0;
}
/* copy a sorted cache */
int git_sortedcache_copy(
git_sortedcache **out,
git_sortedcache *src,
bool lock,
int (*copy_item)(void *payload, void *tgt_item, void *src_item),
void *payload)
{
int error = 0;
git_sortedcache *tgt;
size_t i;
void *src_item, *tgt_item;
/* just use memcpy if no special copy fn is passed in */
if (!copy_item) {
copy_item = sortedcache_copy_item;
payload = src;
}
if ((error = git_sortedcache_new(
&tgt, src->item_path_offset,
src->free_item, src->free_item_payload,
src->items._cmp, src->path)) < 0)
return error;
if (lock && git_sortedcache_rlock(src) < 0) {
git_sortedcache_free(tgt);
return -1;
}
git_vector_foreach(&src->items, i, src_item) {
char *path = ((char *)src_item) + src->item_path_offset;
if ((error = git_sortedcache_upsert(&tgt_item, tgt, path)) < 0 ||
(error = copy_item(payload, tgt_item, src_item)) < 0)
break;
}
if (lock)
git_sortedcache_runlock(src);
if (error)
git_sortedcache_free(tgt);
*out = !error ? tgt : NULL;
return error;
}
/* lock sortedcache while making modifications */
int git_sortedcache_wlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
if (git_rwlock_wrlock(&sc->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to acquire write lock on cache");
return -1;
}
return 0;
}
/* unlock sorted cache when done with modifications */
void git_sortedcache_wunlock(git_sortedcache *sc)
{
git_vector_sort(&sc->items);
git_rwlock_wrunlock(&sc->lock);
}
/* lock sortedcache for read */
int git_sortedcache_rlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
if (git_rwlock_rdlock(&sc->lock) < 0) {
git_error_set(GIT_ERROR_OS, "unable to acquire read lock on cache");
return -1;
}
return 0;
}
/* unlock sorted cache when done reading */
void git_sortedcache_runlock(git_sortedcache *sc)
{
GIT_UNUSED(sc); /* prevent warning when compiled w/o threads */
git_rwlock_rdunlock(&sc->lock);
}
/* if the file has changed, lock cache and load file contents into buf;
* returns <0 on error, >0 if file has not changed
*/
int git_sortedcache_lockandload(git_sortedcache *sc, git_str *buf)
{
int error, fd;
struct stat st;
if ((error = git_sortedcache_wlock(sc)) < 0)
return error;
if ((error = git_futils_filestamp_check(&sc->stamp, sc->path)) <= 0)
goto unlock;
if ((fd = git_futils_open_ro(sc->path)) < 0) {
error = fd;
goto unlock;
}
if (p_fstat(fd, &st) < 0) {
git_error_set(GIT_ERROR_OS, "failed to stat file");
error = -1;
(void)p_close(fd);
goto unlock;
}
if (!git__is_sizet(st.st_size)) {
git_error_set(GIT_ERROR_INVALID, "unable to load file larger than size_t");
error = -1;
(void)p_close(fd);
goto unlock;
}
if (buf)
error = git_futils_readbuffer_fd(buf, fd, (size_t)st.st_size);
(void)p_close(fd);
if (error < 0)
goto unlock;
return 1; /* return 1 -> file needs reload and was successfully loaded */
unlock:
git_sortedcache_wunlock(sc);
return error;
}
void git_sortedcache_updated(git_sortedcache *sc)
{
/* update filestamp to latest value */
git_futils_filestamp_check(&sc->stamp, sc->path);
}
/* release all items in sorted cache */
int git_sortedcache_clear(git_sortedcache *sc, bool wlock)
{
if (wlock && git_sortedcache_wlock(sc) < 0)
return -1;
sortedcache_clear(sc);
if (wlock)
git_sortedcache_wunlock(sc);
return 0;
}
/* find and/or insert item, returning pointer to item data */
int git_sortedcache_upsert(void **out, git_sortedcache *sc, const char *key)
{
size_t keylen, itemlen;
int error = 0;
char *item_key;
void *item;
if ((item = git_strmap_get(sc->map, key)) != NULL)
goto done;
keylen = strlen(key);
itemlen = sc->item_path_offset + keylen + 1;
itemlen = (itemlen + 7) & ~7;
if ((item = git_pool_mallocz(&sc->pool, itemlen)) == NULL) {
/* don't use GIT_ERROR_CHECK_ALLOC b/c of lock */
error = -1;
goto done;
}
/* one strange thing is that even if the vector or hash table insert
* fail, there is no way to free the pool item so we just abandon it
*/
item_key = ((char *)item) + sc->item_path_offset;
memcpy(item_key, key, keylen);
if ((error = git_strmap_set(sc->map, item_key, item)) < 0)
goto done;
if ((error = git_vector_insert(&sc->items, item)) < 0)
git_strmap_delete(sc->map, item_key);
done:
if (out)
*out = !error ? item : NULL;
return error;
}
/* lookup item by key */
void *git_sortedcache_lookup(const git_sortedcache *sc, const char *key)
{
return git_strmap_get(sc->map, key);
}
/* find out how many items are in the cache */
size_t git_sortedcache_entrycount(const git_sortedcache *sc)
{
return git_vector_length(&sc->items);
}
/* lookup item by index */
void *git_sortedcache_entry(git_sortedcache *sc, size_t pos)
{
/* make sure the items are sorted so this gets the correct item */
if (!git_vector_is_sorted(&sc->items))
git_vector_sort(&sc->items);
return git_vector_get(&sc->items, pos);
}
/* helper struct so bsearch callback can know offset + key value for cmp */
struct sortedcache_magic_key {
size_t offset;
const char *key;
};
static int sortedcache_magic_cmp(const void *key, const void *value)
{
const struct sortedcache_magic_key *magic = key;
const char *value_key = ((const char *)value) + magic->offset;
return strcmp(magic->key, value_key);
}
/* lookup index of item by key */
int git_sortedcache_lookup_index(
size_t *out, git_sortedcache *sc, const char *key)
{
struct sortedcache_magic_key magic;
magic.offset = sc->item_path_offset;
magic.key = key;
return git_vector_bsearch2(out, &sc->items, sortedcache_magic_cmp, &magic);
}
/* remove entry from cache */
int git_sortedcache_remove(git_sortedcache *sc, size_t pos)
{
char *item;
/*
* Because of pool allocation, this can't actually remove the item,
* but we can remove it from the items vector and the hash table.
*/
if ((item = git_vector_get(&sc->items, pos)) == NULL) {
git_error_set(GIT_ERROR_INVALID, "removing item out of range");
return GIT_ENOTFOUND;
}
(void)git_vector_remove(&sc->items, pos);
git_strmap_delete(sc->map, item + sc->item_path_offset);
if (sc->free_item)
sc->free_item(sc->free_item_payload, item);
return 0;
}
| libgit2-main | src/util/sortedcache.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "mbedtls.h"
#ifdef GIT_SHA1_MBEDTLS
int git_hash_sha1_global_init(void)
{
return 0;
}
int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx)
{
return git_hash_sha1_init(ctx);
}
void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx)
{
if (ctx)
mbedtls_sha1_free(&ctx->c);
}
int git_hash_sha1_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha1_init(&ctx->c);
mbedtls_sha1_starts(&ctx->c);
return 0;
}
int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha1_update(&ctx->c, data, len);
return 0;
}
int git_hash_sha1_final(unsigned char *out, git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha1_finish(&ctx->c, out);
return 0;
}
#endif
#ifdef GIT_SHA256_MBEDTLS
int git_hash_sha256_global_init(void)
{
return 0;
}
int git_hash_sha256_ctx_init(git_hash_sha256_ctx *ctx)
{
return git_hash_sha256_init(ctx);
}
void git_hash_sha256_ctx_cleanup(git_hash_sha256_ctx *ctx)
{
if (ctx)
mbedtls_sha256_free(&ctx->c);
}
int git_hash_sha256_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha256_init(&ctx->c);
mbedtls_sha256_starts(&ctx->c, 0);
return 0;
}
int git_hash_sha256_update(git_hash_sha256_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha256_update(&ctx->c, data, len);
return 0;
}
int git_hash_sha256_final(unsigned char *out, git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
mbedtls_sha256_finish(&ctx->c, out);
return 0;
}
#endif
| libgit2-main | src/util/hash/mbedtls.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common_crypto.h"
#define CC_LONG_MAX ((CC_LONG)-1)
#ifdef GIT_SHA1_COMMON_CRYPTO
int git_hash_sha1_global_init(void)
{
return 0;
}
int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx)
{
return git_hash_sha1_init(ctx);
}
void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha1_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
CC_SHA1_Init(&ctx->c);
return 0;
}
int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *_data, size_t len)
{
const unsigned char *data = _data;
GIT_ASSERT_ARG(ctx);
while (len > 0) {
CC_LONG chunk = (len > CC_LONG_MAX) ? CC_LONG_MAX : (CC_LONG)len;
CC_SHA1_Update(&ctx->c, data, chunk);
data += chunk;
len -= chunk;
}
return 0;
}
int git_hash_sha1_final(unsigned char *out, git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
CC_SHA1_Final(out, &ctx->c);
return 0;
}
#endif
#ifdef GIT_SHA256_COMMON_CRYPTO
int git_hash_sha256_global_init(void)
{
return 0;
}
int git_hash_sha256_ctx_init(git_hash_sha256_ctx *ctx)
{
return git_hash_sha256_init(ctx);
}
void git_hash_sha256_ctx_cleanup(git_hash_sha256_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha256_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
CC_SHA256_Init(&ctx->c);
return 0;
}
int git_hash_sha256_update(git_hash_sha256_ctx *ctx, const void *_data, size_t len)
{
const unsigned char *data = _data;
GIT_ASSERT_ARG(ctx);
while (len > 0) {
CC_LONG chunk = (len > CC_LONG_MAX) ? CC_LONG_MAX : (CC_LONG)len;
CC_SHA256_Update(&ctx->c, data, chunk);
data += chunk;
len -= chunk;
}
return 0;
}
int git_hash_sha256_final(unsigned char *out, git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
CC_SHA256_Final(out, &ctx->c);
return 0;
}
#endif
| libgit2-main | src/util/hash/common_crypto.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "builtin.h"
int git_hash_sha256_global_init(void)
{
return 0;
}
int git_hash_sha256_ctx_init(git_hash_sha256_ctx *ctx)
{
return git_hash_sha256_init(ctx);
}
void git_hash_sha256_ctx_cleanup(git_hash_sha256_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha256_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA256Reset(&ctx->c)) {
git_error_set(GIT_ERROR_SHA, "SHA256 error");
return -1;
}
return 0;
}
int git_hash_sha256_update(git_hash_sha256_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
if (SHA256Input(&ctx->c, data, len)) {
git_error_set(GIT_ERROR_SHA, "SHA256 error");
return -1;
}
return 0;
}
int git_hash_sha256_final(unsigned char *out, git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA256Result(&ctx->c, out)) {
git_error_set(GIT_ERROR_SHA, "SHA256 error");
return -1;
}
return 0;
}
| libgit2-main | src/util/hash/builtin.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "openssl.h"
#ifdef GIT_OPENSSL_DYNAMIC
# include <dlfcn.h>
int handle_count;
void *openssl_handle;
static int git_hash_openssl_global_shutdown(void)
{
if (--handle_count == 0) {
dlclose(openssl_handle);
openssl_handle = NULL;
}
return 0;
}
static int git_hash_openssl_global_init(void)
{
if (!handle_count) {
if ((openssl_handle = dlopen("libssl.so.1.1", RTLD_NOW)) == NULL &&
(openssl_handle = dlopen("libssl.1.1.dylib", RTLD_NOW)) == NULL &&
(openssl_handle = dlopen("libssl.so.1.0.0", RTLD_NOW)) == NULL &&
(openssl_handle = dlopen("libssl.1.0.0.dylib", RTLD_NOW)) == NULL &&
(openssl_handle = dlopen("libssl.so.10", RTLD_NOW)) == NULL) {
git_error_set(GIT_ERROR_SSL, "could not load ssl libraries");
return -1;
}
}
if (git_hash_openssl_global_shutdown() < 0)
return -1;
handle_count++;
return 0;
}
#endif
#ifdef GIT_SHA1_OPENSSL
# ifdef GIT_OPENSSL_DYNAMIC
static int (*SHA1_Init)(SHA_CTX *c);
static int (*SHA1_Update)(SHA_CTX *c, const void *data, size_t len);
static int (*SHA1_Final)(unsigned char *md, SHA_CTX *c);
# endif
int git_hash_sha1_global_init(void)
{
#ifdef GIT_OPENSSL_DYNAMIC
if (git_hash_openssl_global_init() < 0)
return -1;
if ((SHA1_Init = dlsym(openssl_handle, "SHA1_Init")) == NULL ||
(SHA1_Update = dlsym(openssl_handle, "SHA1_Update")) == NULL ||
(SHA1_Final = dlsym(openssl_handle, "SHA1_Final")) == NULL) {
const char *msg = dlerror();
git_error_set(GIT_ERROR_SSL, "could not load hash function: %s", msg ? msg : "unknown error");
return -1;
}
#endif
return 0;
}
int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx)
{
return git_hash_sha1_init(ctx);
}
void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha1_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA1_Init(&ctx->c) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to initialize sha1 context");
return -1;
}
return 0;
}
int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
if (SHA1_Update(&ctx->c, data, len) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to update sha1");
return -1;
}
return 0;
}
int git_hash_sha1_final(unsigned char *out, git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA1_Final(out, &ctx->c) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to finalize sha1");
return -1;
}
return 0;
}
#endif
#ifdef GIT_SHA256_OPENSSL
# ifdef GIT_OPENSSL_DYNAMIC
static int (*SHA256_Init)(SHA256_CTX *c);
static int (*SHA256_Update)(SHA256_CTX *c, const void *data, size_t len);
static int (*SHA256_Final)(unsigned char *md, SHA256_CTX *c);
#endif
int git_hash_sha256_global_init(void)
{
#ifdef GIT_OPENSSL_DYNAMIC
if (git_hash_openssl_global_init() < 0)
return -1;
if ((SHA256_Init = dlsym(openssl_handle, "SHA256_Init")) == NULL ||
(SHA256_Update = dlsym(openssl_handle, "SHA256_Update")) == NULL ||
(SHA256_Final = dlsym(openssl_handle, "SHA256_Final")) == NULL) {
const char *msg = dlerror();
git_error_set(GIT_ERROR_SSL, "could not load hash function: %s", msg ? msg : "unknown error");
return -1;
}
#endif
return 0;
}
int git_hash_sha256_ctx_init(git_hash_sha256_ctx *ctx)
{
return git_hash_sha256_init(ctx);
}
void git_hash_sha256_ctx_cleanup(git_hash_sha256_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha256_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA256_Init(&ctx->c) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to initialize sha256 context");
return -1;
}
return 0;
}
int git_hash_sha256_update(git_hash_sha256_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
if (SHA256_Update(&ctx->c, data, len) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to update sha256");
return -1;
}
return 0;
}
int git_hash_sha256_final(unsigned char *out, git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA256_Final(out, &ctx->c) != 1) {
git_error_set(GIT_ERROR_SHA, "failed to finalize sha256");
return -1;
}
return 0;
}
#endif
| libgit2-main | src/util/hash/openssl.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "win32.h"
#include "runtime.h"
#include <wincrypt.h>
#include <strsafe.h>
#define GIT_HASH_CNG_DLL_NAME "bcrypt.dll"
/* BCRYPT_SHA1_ALGORITHM */
#define GIT_HASH_CNG_SHA1_TYPE L"SHA1"
#define GIT_HASH_CNG_SHA256_TYPE L"SHA256"
/* BCRYPT_OBJECT_LENGTH */
#define GIT_HASH_CNG_HASH_OBJECT_LEN L"ObjectLength"
/* BCRYPT_HASH_REUSEABLE_FLAGS */
#define GIT_HASH_CNG_HASH_REUSABLE 0x00000020
/* Definitions */
/* CryptoAPI is available for hashing on Windows XP and newer. */
struct cryptoapi_provider {
HCRYPTPROV handle;
};
/*
* CNG (bcrypt.dll) is significantly more performant than CryptoAPI and is
* preferred, however it is only available on Windows 2008 and newer and
* must therefore be dynamically loaded, and we must inline constants that
* would not exist when building in pre-Windows 2008 environments.
*/
/* Function declarations for CNG */
typedef NTSTATUS (WINAPI *cng_open_algorithm_provider_fn)(
HANDLE /* BCRYPT_ALG_HANDLE */ *phAlgorithm,
LPCWSTR pszAlgId,
LPCWSTR pszImplementation,
DWORD dwFlags);
typedef NTSTATUS (WINAPI *cng_get_property_fn)(
HANDLE /* BCRYPT_HANDLE */ hObject,
LPCWSTR pszProperty,
PUCHAR pbOutput,
ULONG cbOutput,
ULONG *pcbResult,
ULONG dwFlags);
typedef NTSTATUS (WINAPI *cng_create_hash_fn)(
HANDLE /* BCRYPT_ALG_HANDLE */ hAlgorithm,
HANDLE /* BCRYPT_HASH_HANDLE */ *phHash,
PUCHAR pbHashObject, ULONG cbHashObject,
PUCHAR pbSecret,
ULONG cbSecret,
ULONG dwFlags);
typedef NTSTATUS (WINAPI *cng_finish_hash_fn)(
HANDLE /* BCRYPT_HASH_HANDLE */ hHash,
PUCHAR pbOutput,
ULONG cbOutput,
ULONG dwFlags);
typedef NTSTATUS (WINAPI *cng_hash_data_fn)(
HANDLE /* BCRYPT_HASH_HANDLE */ hHash,
PUCHAR pbInput,
ULONG cbInput,
ULONG dwFlags);
typedef NTSTATUS (WINAPI *cng_destroy_hash_fn)(
HANDLE /* BCRYPT_HASH_HANDLE */ hHash);
typedef NTSTATUS (WINAPI *cng_close_algorithm_provider_fn)(
HANDLE /* BCRYPT_ALG_HANDLE */ hAlgorithm,
ULONG dwFlags);
struct cng_provider {
/* DLL for CNG */
HINSTANCE dll;
/* Function pointers for CNG */
cng_open_algorithm_provider_fn open_algorithm_provider;
cng_get_property_fn get_property;
cng_create_hash_fn create_hash;
cng_finish_hash_fn finish_hash;
cng_hash_data_fn hash_data;
cng_destroy_hash_fn destroy_hash;
cng_close_algorithm_provider_fn close_algorithm_provider;
HANDLE /* BCRYPT_ALG_HANDLE */ sha1_handle;
DWORD sha1_object_size;
HANDLE /* BCRYPT_ALG_HANDLE */ sha256_handle;
DWORD sha256_object_size;
};
typedef struct {
git_hash_win32_provider_t type;
union {
struct cryptoapi_provider cryptoapi;
struct cng_provider cng;
} provider;
} hash_win32_provider;
/* Hash provider definition */
static hash_win32_provider hash_provider = {0};
/* Hash initialization */
/* Initialize CNG, if available */
GIT_INLINE(int) cng_provider_init(void)
{
char dll_path[MAX_PATH];
DWORD dll_path_len, size_len;
/* Only use CNG on Windows 2008 / Vista SP1 or better (Windows 6.0 SP1) */
if (!git_has_win32_version(6, 0, 1)) {
git_error_set(GIT_ERROR_SHA, "CryptoNG is not supported on this platform");
return -1;
}
/* Load bcrypt.dll explicitly from the system directory */
if ((dll_path_len = GetSystemDirectory(dll_path, MAX_PATH)) == 0 ||
dll_path_len > MAX_PATH ||
StringCchCat(dll_path, MAX_PATH, "\\") < 0 ||
StringCchCat(dll_path, MAX_PATH, GIT_HASH_CNG_DLL_NAME) < 0 ||
(hash_provider.provider.cng.dll = LoadLibrary(dll_path)) == NULL) {
git_error_set(GIT_ERROR_SHA, "CryptoNG library could not be loaded");
return -1;
}
/* Load the function addresses */
if ((hash_provider.provider.cng.open_algorithm_provider = (cng_open_algorithm_provider_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptOpenAlgorithmProvider"))) == NULL ||
(hash_provider.provider.cng.get_property = (cng_get_property_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptGetProperty"))) == NULL ||
(hash_provider.provider.cng.create_hash = (cng_create_hash_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptCreateHash"))) == NULL ||
(hash_provider.provider.cng.finish_hash = (cng_finish_hash_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptFinishHash"))) == NULL ||
(hash_provider.provider.cng.hash_data = (cng_hash_data_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptHashData"))) == NULL ||
(hash_provider.provider.cng.destroy_hash = (cng_destroy_hash_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptDestroyHash"))) == NULL ||
(hash_provider.provider.cng.close_algorithm_provider = (cng_close_algorithm_provider_fn)((void *)GetProcAddress(hash_provider.provider.cng.dll, "BCryptCloseAlgorithmProvider"))) == NULL) {
FreeLibrary(hash_provider.provider.cng.dll);
git_error_set(GIT_ERROR_OS, "CryptoNG functions could not be loaded");
return -1;
}
/* Load the SHA1 algorithm */
if (hash_provider.provider.cng.open_algorithm_provider(&hash_provider.provider.cng.sha1_handle, GIT_HASH_CNG_SHA1_TYPE, NULL, GIT_HASH_CNG_HASH_REUSABLE) < 0 ||
hash_provider.provider.cng.get_property(hash_provider.provider.cng.sha1_handle, GIT_HASH_CNG_HASH_OBJECT_LEN, (PBYTE)&hash_provider.provider.cng.sha1_object_size, sizeof(DWORD), &size_len, 0) < 0) {
git_error_set(GIT_ERROR_OS, "algorithm provider could not be initialized");
goto on_error;
}
/* Load the SHA256 algorithm */
if (hash_provider.provider.cng.open_algorithm_provider(&hash_provider.provider.cng.sha256_handle, GIT_HASH_CNG_SHA256_TYPE, NULL, GIT_HASH_CNG_HASH_REUSABLE) < 0 ||
hash_provider.provider.cng.get_property(hash_provider.provider.cng.sha256_handle, GIT_HASH_CNG_HASH_OBJECT_LEN, (PBYTE)&hash_provider.provider.cng.sha256_object_size, sizeof(DWORD), &size_len, 0) < 0) {
git_error_set(GIT_ERROR_OS, "algorithm provider could not be initialized");
goto on_error;
}
hash_provider.type = GIT_HASH_WIN32_CNG;
return 0;
on_error:
if (hash_provider.provider.cng.sha1_handle)
hash_provider.provider.cng.close_algorithm_provider(hash_provider.provider.cng.sha1_handle, 0);
if (hash_provider.provider.cng.sha256_handle)
hash_provider.provider.cng.close_algorithm_provider(hash_provider.provider.cng.sha256_handle, 0);
if (hash_provider.provider.cng.dll)
FreeLibrary(hash_provider.provider.cng.dll);
return -1;
}
GIT_INLINE(void) cng_provider_shutdown(void)
{
if (hash_provider.type == GIT_HASH_WIN32_INVALID)
return;
hash_provider.provider.cng.close_algorithm_provider(hash_provider.provider.cng.sha1_handle, 0);
hash_provider.provider.cng.close_algorithm_provider(hash_provider.provider.cng.sha256_handle, 0);
FreeLibrary(hash_provider.provider.cng.dll);
hash_provider.type = GIT_HASH_WIN32_INVALID;
}
/* Initialize CryptoAPI */
GIT_INLINE(int) cryptoapi_provider_init(void)
{
if (!CryptAcquireContext(&hash_provider.provider.cryptoapi.handle, NULL, 0, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
git_error_set(GIT_ERROR_OS, "legacy hash context could not be started");
return -1;
}
hash_provider.type = GIT_HASH_WIN32_CRYPTOAPI;
return 0;
}
GIT_INLINE(void) cryptoapi_provider_shutdown(void)
{
if (hash_provider.type == GIT_HASH_WIN32_INVALID)
return;
CryptReleaseContext(hash_provider.provider.cryptoapi.handle, 0);
hash_provider.type = GIT_HASH_WIN32_INVALID;
}
static void hash_provider_shutdown(void)
{
if (hash_provider.type == GIT_HASH_WIN32_CNG)
cng_provider_shutdown();
else if (hash_provider.type == GIT_HASH_WIN32_CRYPTOAPI)
cryptoapi_provider_shutdown();
}
static int hash_provider_init(void)
{
int error = 0;
if (hash_provider.type != GIT_HASH_WIN32_INVALID)
return 0;
if ((error = cng_provider_init()) < 0)
error = cryptoapi_provider_init();
if (!error)
error = git_runtime_shutdown_register(hash_provider_shutdown);
return error;
}
git_hash_win32_provider_t git_hash_win32_provider(void)
{
return hash_provider.type;
}
int git_hash_win32_set_provider(git_hash_win32_provider_t provider)
{
if (provider == hash_provider.type)
return 0;
hash_provider_shutdown();
if (provider == GIT_HASH_WIN32_CNG)
return cng_provider_init();
else if (provider == GIT_HASH_WIN32_CRYPTOAPI)
return cryptoapi_provider_init();
git_error_set(GIT_ERROR_SHA, "unsupported win32 provider");
return -1;
}
/* CryptoAPI: available in Windows XP and newer */
GIT_INLINE(int) hash_cryptoapi_init(git_hash_win32_ctx *ctx)
{
if (ctx->ctx.cryptoapi.valid)
CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle);
if (!CryptCreateHash(hash_provider.provider.cryptoapi.handle, ctx->algorithm, 0, 0, &ctx->ctx.cryptoapi.hash_handle)) {
ctx->ctx.cryptoapi.valid = 0;
git_error_set(GIT_ERROR_OS, "legacy hash implementation could not be created");
return -1;
}
ctx->ctx.cryptoapi.valid = 1;
return 0;
}
GIT_INLINE(int) hash_cryptoapi_update(git_hash_win32_ctx *ctx, const void *_data, size_t len)
{
const BYTE *data = (BYTE *)_data;
GIT_ASSERT(ctx->ctx.cryptoapi.valid);
while (len > 0) {
DWORD chunk = (len > MAXDWORD) ? MAXDWORD : (DWORD)len;
if (!CryptHashData(ctx->ctx.cryptoapi.hash_handle, data, chunk, 0)) {
git_error_set(GIT_ERROR_OS, "legacy hash data could not be updated");
return -1;
}
data += chunk;
len -= chunk;
}
return 0;
}
GIT_INLINE(int) hash_cryptoapi_final(unsigned char *out, git_hash_win32_ctx *ctx)
{
DWORD len = ctx->algorithm == CALG_SHA_256 ? GIT_HASH_SHA256_SIZE : GIT_HASH_SHA1_SIZE;
int error = 0;
GIT_ASSERT(ctx->ctx.cryptoapi.valid);
if (!CryptGetHashParam(ctx->ctx.cryptoapi.hash_handle, HP_HASHVAL, out, &len, 0)) {
git_error_set(GIT_ERROR_OS, "legacy hash data could not be finished");
error = -1;
}
CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle);
ctx->ctx.cryptoapi.valid = 0;
return error;
}
GIT_INLINE(void) hash_ctx_cryptoapi_cleanup(git_hash_win32_ctx *ctx)
{
if (ctx->ctx.cryptoapi.valid)
CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle);
}
GIT_INLINE(int) hash_sha1_cryptoapi_ctx_init_init(git_hash_win32_ctx *ctx)
{
ctx->algorithm = CALG_SHA1;
return hash_cryptoapi_init(ctx);
}
GIT_INLINE(int) hash_sha256_cryptoapi_ctx_init(git_hash_win32_ctx *ctx)
{
ctx->algorithm = CALG_SHA_256;
return hash_cryptoapi_init(ctx);
}
/* CNG: Available in Windows Server 2008 and newer */
GIT_INLINE(int) hash_sha1_cng_ctx_init(git_hash_win32_ctx *ctx)
{
if ((ctx->ctx.cng.hash_object = git__malloc(hash_provider.provider.cng.sha1_object_size)) == NULL)
return -1;
if (hash_provider.provider.cng.create_hash(hash_provider.provider.cng.sha1_handle, &ctx->ctx.cng.hash_handle, ctx->ctx.cng.hash_object, hash_provider.provider.cng.sha1_object_size, NULL, 0, 0) < 0) {
git__free(ctx->ctx.cng.hash_object);
git_error_set(GIT_ERROR_OS, "sha1 implementation could not be created");
return -1;
}
ctx->algorithm = CALG_SHA1;
return 0;
}
GIT_INLINE(int) hash_sha256_cng_ctx_init(git_hash_win32_ctx *ctx)
{
if ((ctx->ctx.cng.hash_object = git__malloc(hash_provider.provider.cng.sha256_object_size)) == NULL)
return -1;
if (hash_provider.provider.cng.create_hash(hash_provider.provider.cng.sha256_handle, &ctx->ctx.cng.hash_handle, ctx->ctx.cng.hash_object, hash_provider.provider.cng.sha256_object_size, NULL, 0, 0) < 0) {
git__free(ctx->ctx.cng.hash_object);
git_error_set(GIT_ERROR_OS, "sha256 implementation could not be created");
return -1;
}
ctx->algorithm = CALG_SHA_256;
return 0;
}
GIT_INLINE(int) hash_cng_init(git_hash_win32_ctx *ctx)
{
BYTE hash[GIT_HASH_SHA256_SIZE];
ULONG size = ctx->algorithm == CALG_SHA_256 ? GIT_HASH_SHA256_SIZE : GIT_HASH_SHA1_SIZE;
if (!ctx->ctx.cng.updated)
return 0;
/* CNG needs to be finished to restart */
if (hash_provider.provider.cng.finish_hash(ctx->ctx.cng.hash_handle, hash, size, 0) < 0) {
git_error_set(GIT_ERROR_OS, "hash implementation could not be finished");
return -1;
}
ctx->ctx.cng.updated = 0;
return 0;
}
GIT_INLINE(int) hash_cng_update(git_hash_win32_ctx *ctx, const void *_data, size_t len)
{
PBYTE data = (PBYTE)_data;
while (len > 0) {
ULONG chunk = (len > ULONG_MAX) ? ULONG_MAX : (ULONG)len;
if (hash_provider.provider.cng.hash_data(ctx->ctx.cng.hash_handle, data, chunk, 0) < 0) {
git_error_set(GIT_ERROR_OS, "hash could not be updated");
return -1;
}
data += chunk;
len -= chunk;
}
return 0;
}
GIT_INLINE(int) hash_cng_final(unsigned char *out, git_hash_win32_ctx *ctx)
{
ULONG size = ctx->algorithm == CALG_SHA_256 ? GIT_HASH_SHA256_SIZE : GIT_HASH_SHA1_SIZE;
if (hash_provider.provider.cng.finish_hash(ctx->ctx.cng.hash_handle, out, size, 0) < 0) {
git_error_set(GIT_ERROR_OS, "hash could not be finished");
return -1;
}
ctx->ctx.cng.updated = 0;
return 0;
}
GIT_INLINE(void) hash_ctx_cng_cleanup(git_hash_win32_ctx *ctx)
{
hash_provider.provider.cng.destroy_hash(ctx->ctx.cng.hash_handle);
git__free(ctx->ctx.cng.hash_object);
}
/* Indirection between CryptoAPI and CNG */
GIT_INLINE(int) hash_sha1_win32_ctx_init(git_hash_win32_ctx *ctx)
{
GIT_ASSERT_ARG(hash_provider.type);
memset(ctx, 0x0, sizeof(git_hash_win32_ctx));
return (hash_provider.type == GIT_HASH_WIN32_CNG) ? hash_sha1_cng_ctx_init(ctx) : hash_sha1_cryptoapi_ctx_init_init(ctx);
}
GIT_INLINE(int) hash_sha256_win32_ctx_init(git_hash_win32_ctx *ctx)
{
GIT_ASSERT_ARG(hash_provider.type);
memset(ctx, 0x0, sizeof(git_hash_win32_ctx));
return (hash_provider.type == GIT_HASH_WIN32_CNG) ? hash_sha256_cng_ctx_init(ctx) : hash_sha256_cryptoapi_ctx_init(ctx);
}
GIT_INLINE(int) hash_win32_init(git_hash_win32_ctx *ctx)
{
return (hash_provider.type == GIT_HASH_WIN32_CNG) ? hash_cng_init(ctx) : hash_cryptoapi_init(ctx);
}
GIT_INLINE(int) hash_win32_update(git_hash_win32_ctx *ctx, const void *data, size_t len)
{
return (hash_provider.type == GIT_HASH_WIN32_CNG) ? hash_cng_update(ctx, data, len) : hash_cryptoapi_update(ctx, data, len);
}
GIT_INLINE(int) hash_win32_final(unsigned char *out, git_hash_win32_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return (hash_provider.type == GIT_HASH_WIN32_CNG) ? hash_cng_final(out, ctx) : hash_cryptoapi_final(out, ctx);
}
GIT_INLINE(void) hash_win32_cleanup(git_hash_win32_ctx *ctx)
{
if (hash_provider.type == GIT_HASH_WIN32_CNG)
hash_ctx_cng_cleanup(ctx);
else if(hash_provider.type == GIT_HASH_WIN32_CRYPTOAPI)
hash_ctx_cryptoapi_cleanup(ctx);
}
#ifdef GIT_SHA1_WIN32
int git_hash_sha1_global_init(void)
{
return hash_provider_init();
}
int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_sha1_win32_ctx_init(&ctx->win32);
}
int git_hash_sha1_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_init(&ctx->win32);
}
int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_update(&ctx->win32, data, len);
}
int git_hash_sha1_final(unsigned char *out, git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_final(out, &ctx->win32);
}
void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx)
{
if (!ctx)
return;
hash_win32_cleanup(&ctx->win32);
}
#endif
#ifdef GIT_SHA256_WIN32
int git_hash_sha256_global_init(void)
{
return hash_provider_init();
}
int git_hash_sha256_ctx_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_sha256_win32_ctx_init(&ctx->win32);
}
int git_hash_sha256_init(git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_init(&ctx->win32);
}
int git_hash_sha256_update(git_hash_sha256_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_update(&ctx->win32, data, len);
}
int git_hash_sha256_final(unsigned char *out, git_hash_sha256_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
return hash_win32_final(out, &ctx->win32);
}
void git_hash_sha256_ctx_cleanup(git_hash_sha256_ctx *ctx)
{
if (!ctx)
return;
hash_win32_cleanup(&ctx->win32);
}
#endif
| libgit2-main | src/util/hash/win32.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "collisiondetect.h"
int git_hash_sha1_global_init(void)
{
return 0;
}
int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx)
{
return git_hash_sha1_init(ctx);
}
void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx)
{
GIT_UNUSED(ctx);
}
int git_hash_sha1_init(git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
SHA1DCInit(&ctx->c);
return 0;
}
int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len)
{
GIT_ASSERT_ARG(ctx);
SHA1DCUpdate(&ctx->c, data, len);
return 0;
}
int git_hash_sha1_final(unsigned char *out, git_hash_sha1_ctx *ctx)
{
GIT_ASSERT_ARG(ctx);
if (SHA1DCFinal(out, &ctx->c)) {
git_error_set(GIT_ERROR_SHA, "SHA1 collision attack detected");
return -1;
}
return 0;
}
| libgit2-main | src/util/hash/collisiondetect.c |
/************************* sha224-256.c ************************/
/***************** See RFC 6234 for details. *******************/
/* Copyright (c) 2011 IETF Trust and the persons identified as */
/* authors of the code. All rights reserved. */
/* See sha.h for terms of use and redistribution. */
/*
* Description:
* This file implements the Secure Hash Algorithms SHA-224 and
* SHA-256 as defined in the U.S. National Institute of Standards
* and Technology Federal Information Processing Standards
* Publication (FIPS PUB) 180-3 published in October 2008
* and formerly defined in its predecessors, FIPS PUB 180-1
* and FIP PUB 180-2.
*
* A combined document showing all algorithms is available at
* http://csrc.nist.gov/publications/fips/
* fips180-3/fips180-3_final.pdf
*
* The SHA-224 and SHA-256 algorithms produce 224-bit and 256-bit
* message digests for a given data stream. It should take about
* 2**n steps to find a message with the same digest as a given
* message and 2**(n/2) to find any two messages with the same
* digest, when n is the digest size in bits. Therefore, this
* algorithm can serve as a means of providing a
* "fingerprint" for a message.
*
* Portability Issues:
* SHA-224 and SHA-256 are defined in terms of 32-bit "words".
* This code uses <stdint.h> (included via "sha.h") to define 32-
* and 8-bit unsigned integer types. If your C compiler does not
* support 32-bit unsigned integers, this code is not
* appropriate.
*
* Caveats:
* SHA-224 and SHA-256 are designed to work with messages less
* than 2^64 bits long. This implementation uses SHA224/256Input()
* to hash the bits that are a multiple of the size of an 8-bit
* octet, and then optionally uses SHA224/256FinalBits()
* to hash the final few bits of the input.
*/
#include "sha.h"
/*
* These definitions are defined in FIPS 180-3, section 4.1.
* Ch() and Maj() are defined identically in sections 4.1.1,
* 4.1.2, and 4.1.3.
*
* The definitions used in FIPS 180-3 are as follows:
*/
#ifndef USE_MODIFIED_MACROS
#define SHA_Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
#define SHA_Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#else /* USE_MODIFIED_MACROS */
/*
* The following definitions are equivalent and potentially faster.
*/
#define SHA_Ch(x, y, z) (((x) & ((y) ^ (z))) ^ (z))
#define SHA_Maj(x, y, z) (((x) & ((y) | (z))) | ((y) & (z)))
#endif /* USE_MODIFIED_MACROS */
#define SHA_Parity(x, y, z) ((x) ^ (y) ^ (z))
/* Define the SHA shift, rotate left, and rotate right macros */
#define SHA256_SHR(bits,word) ((word) >> (bits))
#define SHA256_ROTL(bits,word) \
(((word) << (bits)) | ((word) >> (32-(bits))))
#define SHA256_ROTR(bits,word) \
(((word) >> (bits)) | ((word) << (32-(bits))))
/* Define the SHA SIGMA and sigma macros */
#define SHA256_SIGMA0(word) \
(SHA256_ROTR( 2,word) ^ SHA256_ROTR(13,word) ^ SHA256_ROTR(22,word))
#define SHA256_SIGMA1(word) \
(SHA256_ROTR( 6,word) ^ SHA256_ROTR(11,word) ^ SHA256_ROTR(25,word))
#define SHA256_sigma0(word) \
(SHA256_ROTR( 7,word) ^ SHA256_ROTR(18,word) ^ SHA256_SHR( 3,word))
#define SHA256_sigma1(word) \
(SHA256_ROTR(17,word) ^ SHA256_ROTR(19,word) ^ SHA256_SHR(10,word))
/*
* Add "length" to the length.
* Set Corrupted when overflow has occurred.
*/
static uint32_t addTemp;
#define SHA224_256AddLength(context, length) \
(addTemp = (context)->Length_Low, (context)->Corrupted = \
(((context)->Length_Low += (length)) < addTemp) && \
(++(context)->Length_High == 0) ? shaInputTooLong : \
(context)->Corrupted )
/* Local Function Prototypes */
static int SHA224_256Reset(SHA256Context *context, uint32_t *H0);
static void SHA224_256ProcessMessageBlock(SHA256Context *context);
static void SHA224_256Finalize(SHA256Context *context,
uint8_t Pad_Byte);
static void SHA224_256PadMessage(SHA256Context *context,
uint8_t Pad_Byte);
static int SHA224_256ResultN(SHA256Context *context,
uint8_t Message_Digest[ ], int HashSize);
/* Initial Hash Values: FIPS 180-3 section 5.3.2 */
static uint32_t SHA224_H0[SHA256HashSize/4] = {
0xC1059ED8, 0x367CD507, 0x3070DD17, 0xF70E5939,
0xFFC00B31, 0x68581511, 0x64F98FA7, 0xBEFA4FA4
};
/* Initial Hash Values: FIPS 180-3 section 5.3.3 */
static uint32_t SHA256_H0[SHA256HashSize/4] = {
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
};
/*
* SHA224Reset
*
* Description:
* This function will initialize the SHA224Context in preparation
* for computing a new SHA224 message digest.
*
* Parameters:
* context: [in/out]
* The context to reset.
*
* Returns:
* sha Error Code.
*/
int SHA224Reset(SHA224Context *context)
{
return SHA224_256Reset(context, SHA224_H0);
}
/*
* SHA224Input
*
* Description:
* This function accepts an array of octets as the next portion
* of the message.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
* message_array[ ]: [in]
* An array of octets representing the next portion of
* the message.
* length: [in]
* The length of the message in message_array.
*
* Returns:
* sha Error Code.
*
*/
int SHA224Input(SHA224Context *context, const uint8_t *message_array,
unsigned int length)
{
return SHA256Input(context, message_array, length);
}
/*
* SHA224FinalBits
*
* Description:
* This function will add in any final bits of the message.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
* message_bits: [in]
* The final bits of the message, in the upper portion of the
* byte. (Use 0b###00000 instead of 0b00000### to input the
* three bits ###.)
* length: [in]
* The number of bits in message_bits, between 1 and 7.
*
* Returns:
* sha Error Code.
*/
int SHA224FinalBits(SHA224Context *context,
uint8_t message_bits, unsigned int length)
{
return SHA256FinalBits(context, message_bits, length);
}
/*
* SHA224Result
*
* Description:
* This function will return the 224-bit message digest
* into the Message_Digest array provided by the caller.
* NOTE:
* The first octet of hash is stored in the element with index 0,
* the last octet of hash in the element with index 27.
*
* Parameters:
* context: [in/out]
* The context to use to calculate the SHA hash.
* Message_Digest[ ]: [out]
* Where the digest is returned.
*
* Returns:
* sha Error Code.
*/
int SHA224Result(SHA224Context *context,
uint8_t Message_Digest[SHA224HashSize])
{
return SHA224_256ResultN(context, Message_Digest, SHA224HashSize);
}
/*
* SHA256Reset
*
* Description:
* This function will initialize the SHA256Context in preparation
* for computing a new SHA256 message digest.
*
* Parameters:
* context: [in/out]
* The context to reset.
*
* Returns:
* sha Error Code.
*/
int SHA256Reset(SHA256Context *context)
{
return SHA224_256Reset(context, SHA256_H0);
}
/*
* SHA256Input
*
* Description:
* This function accepts an array of octets as the next portion
* of the message.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
* message_array[ ]: [in]
* An array of octets representing the next portion of
* the message.
* length: [in]
* The length of the message in message_array.
*
* Returns:
* sha Error Code.
*/
int SHA256Input(SHA256Context *context, const uint8_t *message_array,
unsigned int length)
{
if (!context) return shaNull;
if (!length) return shaSuccess;
if (!message_array) return shaNull;
if (context->Computed) return context->Corrupted = shaStateError;
if (context->Corrupted) return context->Corrupted;
while (length--) {
context->Message_Block[context->Message_Block_Index++] =
*message_array;
if ((SHA224_256AddLength(context, 8) == shaSuccess) &&
(context->Message_Block_Index == SHA256_Message_Block_Size))
SHA224_256ProcessMessageBlock(context);
message_array++;
}
return context->Corrupted;
}
/*
* SHA256FinalBits
*
* Description:
* This function will add in any final bits of the message.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
* message_bits: [in]
* The final bits of the message, in the upper portion of the
* byte. (Use 0b###00000 instead of 0b00000### to input the
* three bits ###.)
* length: [in]
* The number of bits in message_bits, between 1 and 7.
*
* Returns:
* sha Error Code.
*/
int SHA256FinalBits(SHA256Context *context,
uint8_t message_bits, unsigned int length)
{
static uint8_t masks[8] = {
/* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80,
/* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0,
/* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8,
/* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE
};
static uint8_t markbit[8] = {
/* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40,
/* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10,
/* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04,
/* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01
};
if (!context) return shaNull;
if (!length) return shaSuccess;
if (context->Corrupted) return context->Corrupted;
if (context->Computed) return context->Corrupted = shaStateError;
if (length >= 8) return context->Corrupted = shaBadParam;
SHA224_256AddLength(context, length);
SHA224_256Finalize(context, (uint8_t)
((message_bits & masks[length]) | markbit[length]));
return context->Corrupted;
}
/*
* SHA256Result
*
* Description:
* This function will return the 256-bit message digest
* into the Message_Digest array provided by the caller.
* NOTE:
* The first octet of hash is stored in the element with index 0,
* the last octet of hash in the element with index 31.
*
* Parameters:
* context: [in/out]
* The context to use to calculate the SHA hash.
* Message_Digest[ ]: [out]
* Where the digest is returned.
*
* Returns:
* sha Error Code.
*/
int SHA256Result(SHA256Context *context,
uint8_t Message_Digest[SHA256HashSize])
{
return SHA224_256ResultN(context, Message_Digest, SHA256HashSize);
}
/*
* SHA224_256Reset
*
* Description:
* This helper function will initialize the SHA256Context in
* preparation for computing a new SHA-224 or SHA-256 message digest.
*
* Parameters:
* context: [in/out]
* The context to reset.
* H0[ ]: [in]
* The initial hash value array to use.
*
* Returns:
* sha Error Code.
*/
static int SHA224_256Reset(SHA256Context *context, uint32_t *H0)
{
if (!context) return shaNull;
context->Length_High = context->Length_Low = 0;
context->Message_Block_Index = 0;
context->Intermediate_Hash[0] = H0[0];
context->Intermediate_Hash[1] = H0[1];
context->Intermediate_Hash[2] = H0[2];
context->Intermediate_Hash[3] = H0[3];
context->Intermediate_Hash[4] = H0[4];
context->Intermediate_Hash[5] = H0[5];
context->Intermediate_Hash[6] = H0[6];
context->Intermediate_Hash[7] = H0[7];
context->Computed = 0;
context->Corrupted = shaSuccess;
return shaSuccess;
}
/*
* SHA224_256ProcessMessageBlock
*
* Description:
* This helper function will process the next 512 bits of the
* message stored in the Message_Block array.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
*
* Returns:
* Nothing.
*
* Comments:
* Many of the variable names in this code, especially the
* single character names, were used because those were the
* names used in the Secure Hash Standard.
*/
static void SHA224_256ProcessMessageBlock(SHA256Context *context)
{
/* Constants defined in FIPS 180-3, section 4.2.2 */
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
int t, t4; /* Loop counter */
uint32_t temp1, temp2; /* Temporary word value */
uint32_t W[64]; /* Word sequence */
uint32_t A, B, C, D, E, F, G, H; /* Word buffers */
/*
* Initialize the first 16 words in the array W
*/
for (t = t4 = 0; t < 16; t++, t4 += 4)
W[t] = (((uint32_t)context->Message_Block[t4]) << 24) |
(((uint32_t)context->Message_Block[t4 + 1]) << 16) |
(((uint32_t)context->Message_Block[t4 + 2]) << 8) |
(((uint32_t)context->Message_Block[t4 + 3]));
for (t = 16; t < 64; t++)
W[t] = SHA256_sigma1(W[t-2]) + W[t-7] +
SHA256_sigma0(W[t-15]) + W[t-16];
A = context->Intermediate_Hash[0];
B = context->Intermediate_Hash[1];
C = context->Intermediate_Hash[2];
D = context->Intermediate_Hash[3];
E = context->Intermediate_Hash[4];
F = context->Intermediate_Hash[5];
G = context->Intermediate_Hash[6];
H = context->Intermediate_Hash[7];
for (t = 0; t < 64; t++) {
temp1 = H + SHA256_SIGMA1(E) + SHA_Ch(E,F,G) + K[t] + W[t];
temp2 = SHA256_SIGMA0(A) + SHA_Maj(A,B,C);
H = G;
G = F;
F = E;
E = D + temp1;
D = C;
C = B;
B = A;
A = temp1 + temp2;
}
context->Intermediate_Hash[0] += A;
context->Intermediate_Hash[1] += B;
context->Intermediate_Hash[2] += C;
context->Intermediate_Hash[3] += D;
context->Intermediate_Hash[4] += E;
context->Intermediate_Hash[5] += F;
context->Intermediate_Hash[6] += G;
context->Intermediate_Hash[7] += H;
context->Message_Block_Index = 0;
}
/*
* SHA224_256Finalize
*
* Description:
* This helper function finishes off the digest calculations.
*
* Parameters:
* context: [in/out]
* The SHA context to update.
* Pad_Byte: [in]
* The last byte to add to the message block before the 0-padding
* and length. This will contain the last bits of the message
* followed by another single bit. If the message was an
* exact multiple of 8-bits long, Pad_Byte will be 0x80.
*
* Returns:
* sha Error Code.
*/
static void SHA224_256Finalize(SHA256Context *context,
uint8_t Pad_Byte)
{
int i;
SHA224_256PadMessage(context, Pad_Byte);
/* message may be sensitive, so clear it out */
for (i = 0; i < SHA256_Message_Block_Size; ++i)
context->Message_Block[i] = 0;
context->Length_High = 0; /* and clear length */
context->Length_Low = 0;
context->Computed = 1;
}
/*
* SHA224_256PadMessage
*
* Description:
* According to the standard, the message must be padded to the next
* even multiple of 512 bits. The first padding bit must be a '1'.
* The last 64 bits represent the length of the original message.
* All bits in between should be 0. This helper function will pad
* the message according to those rules by filling the
* Message_Block array accordingly. When it returns, it can be
* assumed that the message digest has been computed.
*
* Parameters:
* context: [in/out]
* The context to pad.
* Pad_Byte: [in]
* The last byte to add to the message block before the 0-padding
* and length. This will contain the last bits of the message
* followed by another single bit. If the message was an
* exact multiple of 8-bits long, Pad_Byte will be 0x80.
*
* Returns:
* Nothing.
*/
static void SHA224_256PadMessage(SHA256Context *context,
uint8_t Pad_Byte)
{
/*
* Check to see if the current message block is too small to hold
* the initial padding bits and length. If so, we will pad the
* block, process it, and then continue padding into a second
* block.
*/
if (context->Message_Block_Index >= (SHA256_Message_Block_Size-8)) {
context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
while (context->Message_Block_Index < SHA256_Message_Block_Size)
context->Message_Block[context->Message_Block_Index++] = 0;
SHA224_256ProcessMessageBlock(context);
} else
context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
while (context->Message_Block_Index < (SHA256_Message_Block_Size-8))
context->Message_Block[context->Message_Block_Index++] = 0;
/*
* Store the message length as the last 8 octets
*/
context->Message_Block[56] = (uint8_t)(context->Length_High >> 24);
context->Message_Block[57] = (uint8_t)(context->Length_High >> 16);
context->Message_Block[58] = (uint8_t)(context->Length_High >> 8);
context->Message_Block[59] = (uint8_t)(context->Length_High);
context->Message_Block[60] = (uint8_t)(context->Length_Low >> 24);
context->Message_Block[61] = (uint8_t)(context->Length_Low >> 16);
context->Message_Block[62] = (uint8_t)(context->Length_Low >> 8);
context->Message_Block[63] = (uint8_t)(context->Length_Low);
SHA224_256ProcessMessageBlock(context);
}
/*
* SHA224_256ResultN
*
* Description:
* This helper function will return the 224-bit or 256-bit message
* digest into the Message_Digest array provided by the caller.
* NOTE:
* The first octet of hash is stored in the element with index 0,
* the last octet of hash in the element with index 27/31.
*
* Parameters:
* context: [in/out]
* The context to use to calculate the SHA hash.
* Message_Digest[ ]: [out]
* Where the digest is returned.
* HashSize: [in]
* The size of the hash, either 28 or 32.
*
* Returns:
* sha Error Code.
*/
static int SHA224_256ResultN(SHA256Context *context,
uint8_t Message_Digest[ ], int HashSize)
{
int i;
if (!context) return shaNull;
if (!Message_Digest) return shaNull;
if (context->Corrupted) return context->Corrupted;
if (!context->Computed)
SHA224_256Finalize(context, 0x80);
for (i = 0; i < HashSize; ++i)
Message_Digest[i] = (uint8_t)
(context->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ));
return shaSuccess;
}
| libgit2-main | src/util/hash/rfc6234/sha224-256.c |
/***
* Copyright 2017 Marc Stevens <marc@marc-stevens.nl>, Dan Shumow (danshu@microsoft.com)
* Distributed under the MIT Software License.
* See accompanying file LICENSE.txt or copy at
* https://opensource.org/licenses/MIT
***/
#ifndef SHA1DC_NO_STANDARD_INCLUDES
#include <string.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h> /* make sure macros like _BIG_ENDIAN visible */
#endif
#ifdef SHA1DC_CUSTOM_INCLUDE_SHA1_C
#include SHA1DC_CUSTOM_INCLUDE_SHA1_C
#endif
#ifndef SHA1DC_INIT_SAFE_HASH_DEFAULT
#define SHA1DC_INIT_SAFE_HASH_DEFAULT 1
#endif
#include "sha1.h"
#include "ubc_check.h"
#if (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || \
defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || \
defined(__i586__) || defined(__i686__) || defined(_M_IX86) || defined(__X86__) || \
defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__) || defined(__INTEL__) || \
defined(__386) || defined(_M_X64) || defined(_M_AMD64))
#define SHA1DC_ON_INTEL_LIKE_PROCESSOR
#endif
/*
Because Little-Endian architectures are most common,
we only set SHA1DC_BIGENDIAN if one of these conditions is met.
Note that all MSFT platforms are little endian,
so none of these will be defined under the MSC compiler.
If you are compiling on a big endian platform and your compiler does not define one of these,
you will have to add whatever macros your tool chain defines to indicate Big-Endianness.
*/
#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
/*
* Should detect Big Endian under GCC since at least 4.6.0 (gcc svn
* rev #165881). See
* https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
*
* This also works under clang since 3.2, it copied the GCC-ism. See
* clang.git's 3b198a97d2 ("Preprocessor: add __BYTE_ORDER__
* predefined macro", 2012-07-27)
*/
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define SHA1DC_BIGENDIAN
#endif
/* Not under GCC-alike */
#elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN)
/*
* Should detect Big Endian under glibc.git since 14245eb70e ("entered
* into RCS", 1992-11-25). Defined in <endian.h> which will have been
* brought in by standard headers. See glibc.git and
* https://sourceforge.net/p/predef/wiki/Endianness/
*/
#if __BYTE_ORDER == __BIG_ENDIAN
#define SHA1DC_BIGENDIAN
#endif
/* Not under GCC-alike or glibc */
#elif defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)
/*
* *BSD and newlib (embedded linux, cygwin, etc).
* the defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN) part prevents
* this condition from matching with Solaris/sparc.
* (Solaris defines only one endian macro)
*/
#if _BYTE_ORDER == _BIG_ENDIAN
#define SHA1DC_BIGENDIAN
#endif
/* Not under GCC-alike or glibc or *BSD or newlib */
#elif (defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || \
defined(__sparc))
/*
* Should define Big Endian for a whitelist of known processors. See
* https://sourceforge.net/p/predef/wiki/Endianness/ and
* http://www.oracle.com/technetwork/server-storage/solaris/portingtosolaris-138514.html
*/
#define SHA1DC_BIGENDIAN
/* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> */
#elif (defined(_AIX) || defined(__hpux))
/*
* Defines Big Endian on a whitelist of OSs that are known to be Big
* Endian-only. See
* https://public-inbox.org/git/93056823-2740-d072-1ebd-46b440b33d7e@felt.demon.nl/
*/
#define SHA1DC_BIGENDIAN
/* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> or <os whitelist> */
#elif defined(SHA1DC_ON_INTEL_LIKE_PROCESSOR)
/*
* As a last resort before we do anything else we're not 100% sure
* about below, we blacklist specific processors here. We could add
* more, see e.g. https://wiki.debian.org/ArchitectureSpecificsMemo
*/
#else /* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> or <os whitelist> or <processor blacklist> */
/* We do nothing more here for now */
/*#error "Uncomment this to see if you fall through all the detection"*/
#endif /* Big Endian detection */
#if (defined(SHA1DC_FORCE_LITTLEENDIAN) && defined(SHA1DC_BIGENDIAN))
#undef SHA1DC_BIGENDIAN
#endif
#if (defined(SHA1DC_FORCE_BIGENDIAN) && !defined(SHA1DC_BIGENDIAN))
#define SHA1DC_BIGENDIAN
#endif
/*ENDIANNESS SELECTION*/
#ifndef SHA1DC_FORCE_ALIGNED_ACCESS
#if defined(SHA1DC_FORCE_UNALIGNED_ACCESS) || defined(SHA1DC_ON_INTEL_LIKE_PROCESSOR)
#define SHA1DC_ALLOW_UNALIGNED_ACCESS
#endif /*UNALIGNED ACCESS DETECTION*/
#endif /*FORCE ALIGNED ACCESS*/
#define rotate_right(x,n) (((x)>>(n))|((x)<<(32-(n))))
#define rotate_left(x,n) (((x)<<(n))|((x)>>(32-(n))))
#define sha1_bswap32(x) \
{x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0xFF00FF); x = (x << 16) | (x >> 16);}
#define sha1_mix(W, t) (rotate_left(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1))
#ifdef SHA1DC_BIGENDIAN
#define sha1_load(m, t, temp) { temp = m[t]; }
#else
#define sha1_load(m, t, temp) { temp = m[t]; sha1_bswap32(temp); }
#endif
#define sha1_store(W, t, x) *(volatile uint32_t *)&W[t] = x
#define sha1_f1(b,c,d) ((d)^((b)&((c)^(d))))
#define sha1_f2(b,c,d) ((b)^(c)^(d))
#define sha1_f3(b,c,d) (((b)&(c))+((d)&((b)^(c))))
#define sha1_f4(b,c,d) ((b)^(c)^(d))
#define HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, m, t) \
{ e += rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, m, t) \
{ e += rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, m, t) \
{ e += rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, m, t) \
{ e += rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; b = rotate_left(b, 30); }
#define HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, m, t) \
{ b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, m, t) \
{ b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, m, t) \
{ b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; }
#define HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, m, t) \
{ b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; }
#define SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, t, temp) \
{sha1_load(m, t, temp); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_left(b, 30);}
#define SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(a, b, c, d, e, W, t, temp) \
{temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_left(b, 30); }
#define SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, t, temp) \
{temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1; b = rotate_left(b, 30); }
#define SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, t, temp) \
{temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC; b = rotate_left(b, 30); }
#define SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, t, temp) \
{temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6; b = rotate_left(b, 30); }
#define SHA1_STORE_STATE(i) states[i][0] = a; states[i][1] = b; states[i][2] = c; states[i][3] = d; states[i][4] = e;
#ifdef BUILDNOCOLLDETECTSHA1COMPRESSION
void sha1_compression(uint32_t ihv[5], const uint32_t m[16])
{
uint32_t W[80];
uint32_t a,b,c,d,e;
unsigned i;
memcpy(W, m, 16 * 4);
for (i = 16; i < 80; ++i)
W[i] = sha1_mix(W, i);
a = ihv[0]; b = ihv[1]; c = ihv[2]; d = ihv[3]; e = ihv[4];
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 0);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 1);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 2);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 3);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 4);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 5);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 6);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 7);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 8);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 9);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 10);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 11);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 12);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 13);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 14);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 15);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 16);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 17);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 18);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 19);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 20);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 21);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 22);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 23);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 24);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 25);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 26);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 27);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 28);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 29);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 30);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 31);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 32);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 33);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 34);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 35);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 36);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 37);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 38);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 39);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 40);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 41);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 42);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 43);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 44);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 45);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 46);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 47);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 48);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 49);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 50);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 51);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 52);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 53);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 54);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 55);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 56);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 57);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 58);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 59);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 60);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 61);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 62);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 63);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 64);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 65);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 66);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 67);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 68);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 69);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 70);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 71);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 72);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 73);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 74);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 75);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 76);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 77);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 78);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 79);
ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e;
}
#endif /*BUILDNOCOLLDETECTSHA1COMPRESSION*/
static void sha1_compression_W(uint32_t ihv[5], const uint32_t W[80])
{
uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4];
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 0);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 1);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 2);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 3);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 4);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 5);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 6);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 7);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 8);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 9);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 10);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 11);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 12);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 13);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 14);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 15);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 16);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 17);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 18);
HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 19);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 20);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 21);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 22);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 23);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 24);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 25);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 26);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 27);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 28);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 29);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 30);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 31);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 32);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 33);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 34);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 35);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 36);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 37);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 38);
HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 39);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 40);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 41);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 42);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 43);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 44);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 45);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 46);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 47);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 48);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 49);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 50);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 51);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 52);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 53);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 54);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 55);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 56);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 57);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 58);
HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 59);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 60);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 61);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 62);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 63);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 64);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 65);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 66);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 67);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 68);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 69);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 70);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 71);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 72);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 73);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 74);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 75);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 76);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 77);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 78);
HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 79);
ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e;
}
void sha1_compression_states(uint32_t ihv[5], const uint32_t m[16], uint32_t W[80], uint32_t states[80][5])
{
uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4];
uint32_t temp;
#ifdef DOSTORESTATE00
SHA1_STORE_STATE(0)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 0, temp);
#ifdef DOSTORESTATE01
SHA1_STORE_STATE(1)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 1, temp);
#ifdef DOSTORESTATE02
SHA1_STORE_STATE(2)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 2, temp);
#ifdef DOSTORESTATE03
SHA1_STORE_STATE(3)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 3, temp);
#ifdef DOSTORESTATE04
SHA1_STORE_STATE(4)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 4, temp);
#ifdef DOSTORESTATE05
SHA1_STORE_STATE(5)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 5, temp);
#ifdef DOSTORESTATE06
SHA1_STORE_STATE(6)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 6, temp);
#ifdef DOSTORESTATE07
SHA1_STORE_STATE(7)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 7, temp);
#ifdef DOSTORESTATE08
SHA1_STORE_STATE(8)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 8, temp);
#ifdef DOSTORESTATE09
SHA1_STORE_STATE(9)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 9, temp);
#ifdef DOSTORESTATE10
SHA1_STORE_STATE(10)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 10, temp);
#ifdef DOSTORESTATE11
SHA1_STORE_STATE(11)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 11, temp);
#ifdef DOSTORESTATE12
SHA1_STORE_STATE(12)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 12, temp);
#ifdef DOSTORESTATE13
SHA1_STORE_STATE(13)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 13, temp);
#ifdef DOSTORESTATE14
SHA1_STORE_STATE(14)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 14, temp);
#ifdef DOSTORESTATE15
SHA1_STORE_STATE(15)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 15, temp);
#ifdef DOSTORESTATE16
SHA1_STORE_STATE(16)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(e, a, b, c, d, W, 16, temp);
#ifdef DOSTORESTATE17
SHA1_STORE_STATE(17)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(d, e, a, b, c, W, 17, temp);
#ifdef DOSTORESTATE18
SHA1_STORE_STATE(18)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(c, d, e, a, b, W, 18, temp);
#ifdef DOSTORESTATE19
SHA1_STORE_STATE(19)
#endif
SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(b, c, d, e, a, W, 19, temp);
#ifdef DOSTORESTATE20
SHA1_STORE_STATE(20)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 20, temp);
#ifdef DOSTORESTATE21
SHA1_STORE_STATE(21)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 21, temp);
#ifdef DOSTORESTATE22
SHA1_STORE_STATE(22)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 22, temp);
#ifdef DOSTORESTATE23
SHA1_STORE_STATE(23)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 23, temp);
#ifdef DOSTORESTATE24
SHA1_STORE_STATE(24)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 24, temp);
#ifdef DOSTORESTATE25
SHA1_STORE_STATE(25)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 25, temp);
#ifdef DOSTORESTATE26
SHA1_STORE_STATE(26)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 26, temp);
#ifdef DOSTORESTATE27
SHA1_STORE_STATE(27)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 27, temp);
#ifdef DOSTORESTATE28
SHA1_STORE_STATE(28)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 28, temp);
#ifdef DOSTORESTATE29
SHA1_STORE_STATE(29)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 29, temp);
#ifdef DOSTORESTATE30
SHA1_STORE_STATE(30)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 30, temp);
#ifdef DOSTORESTATE31
SHA1_STORE_STATE(31)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 31, temp);
#ifdef DOSTORESTATE32
SHA1_STORE_STATE(32)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 32, temp);
#ifdef DOSTORESTATE33
SHA1_STORE_STATE(33)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 33, temp);
#ifdef DOSTORESTATE34
SHA1_STORE_STATE(34)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 34, temp);
#ifdef DOSTORESTATE35
SHA1_STORE_STATE(35)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 35, temp);
#ifdef DOSTORESTATE36
SHA1_STORE_STATE(36)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 36, temp);
#ifdef DOSTORESTATE37
SHA1_STORE_STATE(37)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 37, temp);
#ifdef DOSTORESTATE38
SHA1_STORE_STATE(38)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 38, temp);
#ifdef DOSTORESTATE39
SHA1_STORE_STATE(39)
#endif
SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 39, temp);
#ifdef DOSTORESTATE40
SHA1_STORE_STATE(40)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 40, temp);
#ifdef DOSTORESTATE41
SHA1_STORE_STATE(41)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 41, temp);
#ifdef DOSTORESTATE42
SHA1_STORE_STATE(42)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 42, temp);
#ifdef DOSTORESTATE43
SHA1_STORE_STATE(43)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 43, temp);
#ifdef DOSTORESTATE44
SHA1_STORE_STATE(44)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 44, temp);
#ifdef DOSTORESTATE45
SHA1_STORE_STATE(45)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 45, temp);
#ifdef DOSTORESTATE46
SHA1_STORE_STATE(46)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 46, temp);
#ifdef DOSTORESTATE47
SHA1_STORE_STATE(47)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 47, temp);
#ifdef DOSTORESTATE48
SHA1_STORE_STATE(48)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 48, temp);
#ifdef DOSTORESTATE49
SHA1_STORE_STATE(49)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 49, temp);
#ifdef DOSTORESTATE50
SHA1_STORE_STATE(50)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 50, temp);
#ifdef DOSTORESTATE51
SHA1_STORE_STATE(51)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 51, temp);
#ifdef DOSTORESTATE52
SHA1_STORE_STATE(52)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 52, temp);
#ifdef DOSTORESTATE53
SHA1_STORE_STATE(53)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 53, temp);
#ifdef DOSTORESTATE54
SHA1_STORE_STATE(54)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 54, temp);
#ifdef DOSTORESTATE55
SHA1_STORE_STATE(55)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 55, temp);
#ifdef DOSTORESTATE56
SHA1_STORE_STATE(56)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 56, temp);
#ifdef DOSTORESTATE57
SHA1_STORE_STATE(57)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 57, temp);
#ifdef DOSTORESTATE58
SHA1_STORE_STATE(58)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 58, temp);
#ifdef DOSTORESTATE59
SHA1_STORE_STATE(59)
#endif
SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 59, temp);
#ifdef DOSTORESTATE60
SHA1_STORE_STATE(60)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 60, temp);
#ifdef DOSTORESTATE61
SHA1_STORE_STATE(61)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 61, temp);
#ifdef DOSTORESTATE62
SHA1_STORE_STATE(62)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 62, temp);
#ifdef DOSTORESTATE63
SHA1_STORE_STATE(63)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 63, temp);
#ifdef DOSTORESTATE64
SHA1_STORE_STATE(64)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 64, temp);
#ifdef DOSTORESTATE65
SHA1_STORE_STATE(65)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 65, temp);
#ifdef DOSTORESTATE66
SHA1_STORE_STATE(66)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 66, temp);
#ifdef DOSTORESTATE67
SHA1_STORE_STATE(67)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 67, temp);
#ifdef DOSTORESTATE68
SHA1_STORE_STATE(68)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 68, temp);
#ifdef DOSTORESTATE69
SHA1_STORE_STATE(69)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 69, temp);
#ifdef DOSTORESTATE70
SHA1_STORE_STATE(70)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 70, temp);
#ifdef DOSTORESTATE71
SHA1_STORE_STATE(71)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 71, temp);
#ifdef DOSTORESTATE72
SHA1_STORE_STATE(72)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 72, temp);
#ifdef DOSTORESTATE73
SHA1_STORE_STATE(73)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 73, temp);
#ifdef DOSTORESTATE74
SHA1_STORE_STATE(74)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 74, temp);
#ifdef DOSTORESTATE75
SHA1_STORE_STATE(75)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 75, temp);
#ifdef DOSTORESTATE76
SHA1_STORE_STATE(76)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 76, temp);
#ifdef DOSTORESTATE77
SHA1_STORE_STATE(77)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 77, temp);
#ifdef DOSTORESTATE78
SHA1_STORE_STATE(78)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 78, temp);
#ifdef DOSTORESTATE79
SHA1_STORE_STATE(79)
#endif
SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 79, temp);
ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e;
}
#define SHA1_RECOMPRESS(t) \
static void sha1recompress_fast_ ## t (uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5]) \
{ \
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; \
if (t > 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 79); \
if (t > 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 78); \
if (t > 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 77); \
if (t > 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 76); \
if (t > 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 75); \
if (t > 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 74); \
if (t > 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 73); \
if (t > 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 72); \
if (t > 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 71); \
if (t > 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 70); \
if (t > 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 69); \
if (t > 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 68); \
if (t > 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 67); \
if (t > 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 66); \
if (t > 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 65); \
if (t > 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 64); \
if (t > 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 63); \
if (t > 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 62); \
if (t > 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 61); \
if (t > 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 60); \
if (t > 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 59); \
if (t > 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 58); \
if (t > 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 57); \
if (t > 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 56); \
if (t > 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 55); \
if (t > 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 54); \
if (t > 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 53); \
if (t > 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 52); \
if (t > 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 51); \
if (t > 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 50); \
if (t > 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 49); \
if (t > 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 48); \
if (t > 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 47); \
if (t > 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 46); \
if (t > 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 45); \
if (t > 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 44); \
if (t > 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 43); \
if (t > 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 42); \
if (t > 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 41); \
if (t > 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 40); \
if (t > 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 39); \
if (t > 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 38); \
if (t > 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 37); \
if (t > 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 36); \
if (t > 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 35); \
if (t > 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 34); \
if (t > 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 33); \
if (t > 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 32); \
if (t > 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 31); \
if (t > 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 30); \
if (t > 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 29); \
if (t > 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 28); \
if (t > 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 27); \
if (t > 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 26); \
if (t > 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 25); \
if (t > 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 24); \
if (t > 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 23); \
if (t > 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 22); \
if (t > 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 21); \
if (t > 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 20); \
if (t > 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 19); \
if (t > 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 18); \
if (t > 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 17); \
if (t > 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 16); \
if (t > 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 15); \
if (t > 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 14); \
if (t > 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 13); \
if (t > 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 12); \
if (t > 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 11); \
if (t > 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 10); \
if (t > 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 9); \
if (t > 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 8); \
if (t > 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 7); \
if (t > 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 6); \
if (t > 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 5); \
if (t > 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 4); \
if (t > 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 3); \
if (t > 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 2); \
if (t > 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 1); \
if (t > 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 0); \
ihvin[0] = a; ihvin[1] = b; ihvin[2] = c; ihvin[3] = d; ihvin[4] = e; \
a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; \
if (t <= 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 0); \
if (t <= 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 1); \
if (t <= 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 2); \
if (t <= 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 3); \
if (t <= 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 4); \
if (t <= 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 5); \
if (t <= 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 6); \
if (t <= 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 7); \
if (t <= 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 8); \
if (t <= 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 9); \
if (t <= 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 10); \
if (t <= 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 11); \
if (t <= 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 12); \
if (t <= 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 13); \
if (t <= 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 14); \
if (t <= 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 15); \
if (t <= 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 16); \
if (t <= 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 17); \
if (t <= 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 18); \
if (t <= 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 19); \
if (t <= 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 20); \
if (t <= 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 21); \
if (t <= 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 22); \
if (t <= 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 23); \
if (t <= 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 24); \
if (t <= 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 25); \
if (t <= 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 26); \
if (t <= 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 27); \
if (t <= 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 28); \
if (t <= 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 29); \
if (t <= 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 30); \
if (t <= 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 31); \
if (t <= 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 32); \
if (t <= 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 33); \
if (t <= 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 34); \
if (t <= 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 35); \
if (t <= 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 36); \
if (t <= 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 37); \
if (t <= 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 38); \
if (t <= 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 39); \
if (t <= 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 40); \
if (t <= 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 41); \
if (t <= 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 42); \
if (t <= 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 43); \
if (t <= 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 44); \
if (t <= 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 45); \
if (t <= 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 46); \
if (t <= 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 47); \
if (t <= 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 48); \
if (t <= 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 49); \
if (t <= 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 50); \
if (t <= 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 51); \
if (t <= 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 52); \
if (t <= 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 53); \
if (t <= 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 54); \
if (t <= 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 55); \
if (t <= 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 56); \
if (t <= 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 57); \
if (t <= 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 58); \
if (t <= 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 59); \
if (t <= 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 60); \
if (t <= 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 61); \
if (t <= 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 62); \
if (t <= 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 63); \
if (t <= 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 64); \
if (t <= 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 65); \
if (t <= 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 66); \
if (t <= 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 67); \
if (t <= 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 68); \
if (t <= 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 69); \
if (t <= 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 70); \
if (t <= 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 71); \
if (t <= 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 72); \
if (t <= 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 73); \
if (t <= 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 74); \
if (t <= 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 75); \
if (t <= 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 76); \
if (t <= 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 77); \
if (t <= 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 78); \
if (t <= 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 79); \
ihvout[0] = ihvin[0] + a; ihvout[1] = ihvin[1] + b; ihvout[2] = ihvin[2] + c; ihvout[3] = ihvin[3] + d; ihvout[4] = ihvin[4] + e; \
}
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127) /* Compiler complains about the checks in the above macro being constant. */
#endif
#ifdef DOSTORESTATE0
SHA1_RECOMPRESS(0)
#endif
#ifdef DOSTORESTATE1
SHA1_RECOMPRESS(1)
#endif
#ifdef DOSTORESTATE2
SHA1_RECOMPRESS(2)
#endif
#ifdef DOSTORESTATE3
SHA1_RECOMPRESS(3)
#endif
#ifdef DOSTORESTATE4
SHA1_RECOMPRESS(4)
#endif
#ifdef DOSTORESTATE5
SHA1_RECOMPRESS(5)
#endif
#ifdef DOSTORESTATE6
SHA1_RECOMPRESS(6)
#endif
#ifdef DOSTORESTATE7
SHA1_RECOMPRESS(7)
#endif
#ifdef DOSTORESTATE8
SHA1_RECOMPRESS(8)
#endif
#ifdef DOSTORESTATE9
SHA1_RECOMPRESS(9)
#endif
#ifdef DOSTORESTATE10
SHA1_RECOMPRESS(10)
#endif
#ifdef DOSTORESTATE11
SHA1_RECOMPRESS(11)
#endif
#ifdef DOSTORESTATE12
SHA1_RECOMPRESS(12)
#endif
#ifdef DOSTORESTATE13
SHA1_RECOMPRESS(13)
#endif
#ifdef DOSTORESTATE14
SHA1_RECOMPRESS(14)
#endif
#ifdef DOSTORESTATE15
SHA1_RECOMPRESS(15)
#endif
#ifdef DOSTORESTATE16
SHA1_RECOMPRESS(16)
#endif
#ifdef DOSTORESTATE17
SHA1_RECOMPRESS(17)
#endif
#ifdef DOSTORESTATE18
SHA1_RECOMPRESS(18)
#endif
#ifdef DOSTORESTATE19
SHA1_RECOMPRESS(19)
#endif
#ifdef DOSTORESTATE20
SHA1_RECOMPRESS(20)
#endif
#ifdef DOSTORESTATE21
SHA1_RECOMPRESS(21)
#endif
#ifdef DOSTORESTATE22
SHA1_RECOMPRESS(22)
#endif
#ifdef DOSTORESTATE23
SHA1_RECOMPRESS(23)
#endif
#ifdef DOSTORESTATE24
SHA1_RECOMPRESS(24)
#endif
#ifdef DOSTORESTATE25
SHA1_RECOMPRESS(25)
#endif
#ifdef DOSTORESTATE26
SHA1_RECOMPRESS(26)
#endif
#ifdef DOSTORESTATE27
SHA1_RECOMPRESS(27)
#endif
#ifdef DOSTORESTATE28
SHA1_RECOMPRESS(28)
#endif
#ifdef DOSTORESTATE29
SHA1_RECOMPRESS(29)
#endif
#ifdef DOSTORESTATE30
SHA1_RECOMPRESS(30)
#endif
#ifdef DOSTORESTATE31
SHA1_RECOMPRESS(31)
#endif
#ifdef DOSTORESTATE32
SHA1_RECOMPRESS(32)
#endif
#ifdef DOSTORESTATE33
SHA1_RECOMPRESS(33)
#endif
#ifdef DOSTORESTATE34
SHA1_RECOMPRESS(34)
#endif
#ifdef DOSTORESTATE35
SHA1_RECOMPRESS(35)
#endif
#ifdef DOSTORESTATE36
SHA1_RECOMPRESS(36)
#endif
#ifdef DOSTORESTATE37
SHA1_RECOMPRESS(37)
#endif
#ifdef DOSTORESTATE38
SHA1_RECOMPRESS(38)
#endif
#ifdef DOSTORESTATE39
SHA1_RECOMPRESS(39)
#endif
#ifdef DOSTORESTATE40
SHA1_RECOMPRESS(40)
#endif
#ifdef DOSTORESTATE41
SHA1_RECOMPRESS(41)
#endif
#ifdef DOSTORESTATE42
SHA1_RECOMPRESS(42)
#endif
#ifdef DOSTORESTATE43
SHA1_RECOMPRESS(43)
#endif
#ifdef DOSTORESTATE44
SHA1_RECOMPRESS(44)
#endif
#ifdef DOSTORESTATE45
SHA1_RECOMPRESS(45)
#endif
#ifdef DOSTORESTATE46
SHA1_RECOMPRESS(46)
#endif
#ifdef DOSTORESTATE47
SHA1_RECOMPRESS(47)
#endif
#ifdef DOSTORESTATE48
SHA1_RECOMPRESS(48)
#endif
#ifdef DOSTORESTATE49
SHA1_RECOMPRESS(49)
#endif
#ifdef DOSTORESTATE50
SHA1_RECOMPRESS(50)
#endif
#ifdef DOSTORESTATE51
SHA1_RECOMPRESS(51)
#endif
#ifdef DOSTORESTATE52
SHA1_RECOMPRESS(52)
#endif
#ifdef DOSTORESTATE53
SHA1_RECOMPRESS(53)
#endif
#ifdef DOSTORESTATE54
SHA1_RECOMPRESS(54)
#endif
#ifdef DOSTORESTATE55
SHA1_RECOMPRESS(55)
#endif
#ifdef DOSTORESTATE56
SHA1_RECOMPRESS(56)
#endif
#ifdef DOSTORESTATE57
SHA1_RECOMPRESS(57)
#endif
#ifdef DOSTORESTATE58
SHA1_RECOMPRESS(58)
#endif
#ifdef DOSTORESTATE59
SHA1_RECOMPRESS(59)
#endif
#ifdef DOSTORESTATE60
SHA1_RECOMPRESS(60)
#endif
#ifdef DOSTORESTATE61
SHA1_RECOMPRESS(61)
#endif
#ifdef DOSTORESTATE62
SHA1_RECOMPRESS(62)
#endif
#ifdef DOSTORESTATE63
SHA1_RECOMPRESS(63)
#endif
#ifdef DOSTORESTATE64
SHA1_RECOMPRESS(64)
#endif
#ifdef DOSTORESTATE65
SHA1_RECOMPRESS(65)
#endif
#ifdef DOSTORESTATE66
SHA1_RECOMPRESS(66)
#endif
#ifdef DOSTORESTATE67
SHA1_RECOMPRESS(67)
#endif
#ifdef DOSTORESTATE68
SHA1_RECOMPRESS(68)
#endif
#ifdef DOSTORESTATE69
SHA1_RECOMPRESS(69)
#endif
#ifdef DOSTORESTATE70
SHA1_RECOMPRESS(70)
#endif
#ifdef DOSTORESTATE71
SHA1_RECOMPRESS(71)
#endif
#ifdef DOSTORESTATE72
SHA1_RECOMPRESS(72)
#endif
#ifdef DOSTORESTATE73
SHA1_RECOMPRESS(73)
#endif
#ifdef DOSTORESTATE74
SHA1_RECOMPRESS(74)
#endif
#ifdef DOSTORESTATE75
SHA1_RECOMPRESS(75)
#endif
#ifdef DOSTORESTATE76
SHA1_RECOMPRESS(76)
#endif
#ifdef DOSTORESTATE77
SHA1_RECOMPRESS(77)
#endif
#ifdef DOSTORESTATE78
SHA1_RECOMPRESS(78)
#endif
#ifdef DOSTORESTATE79
SHA1_RECOMPRESS(79)
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
static void sha1_recompression_step(uint32_t step, uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5])
{
switch (step)
{
#ifdef DOSTORESTATE0
case 0:
sha1recompress_fast_0(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE1
case 1:
sha1recompress_fast_1(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE2
case 2:
sha1recompress_fast_2(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE3
case 3:
sha1recompress_fast_3(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE4
case 4:
sha1recompress_fast_4(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE5
case 5:
sha1recompress_fast_5(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE6
case 6:
sha1recompress_fast_6(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE7
case 7:
sha1recompress_fast_7(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE8
case 8:
sha1recompress_fast_8(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE9
case 9:
sha1recompress_fast_9(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE10
case 10:
sha1recompress_fast_10(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE11
case 11:
sha1recompress_fast_11(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE12
case 12:
sha1recompress_fast_12(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE13
case 13:
sha1recompress_fast_13(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE14
case 14:
sha1recompress_fast_14(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE15
case 15:
sha1recompress_fast_15(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE16
case 16:
sha1recompress_fast_16(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE17
case 17:
sha1recompress_fast_17(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE18
case 18:
sha1recompress_fast_18(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE19
case 19:
sha1recompress_fast_19(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE20
case 20:
sha1recompress_fast_20(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE21
case 21:
sha1recompress_fast_21(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE22
case 22:
sha1recompress_fast_22(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE23
case 23:
sha1recompress_fast_23(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE24
case 24:
sha1recompress_fast_24(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE25
case 25:
sha1recompress_fast_25(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE26
case 26:
sha1recompress_fast_26(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE27
case 27:
sha1recompress_fast_27(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE28
case 28:
sha1recompress_fast_28(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE29
case 29:
sha1recompress_fast_29(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE30
case 30:
sha1recompress_fast_30(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE31
case 31:
sha1recompress_fast_31(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE32
case 32:
sha1recompress_fast_32(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE33
case 33:
sha1recompress_fast_33(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE34
case 34:
sha1recompress_fast_34(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE35
case 35:
sha1recompress_fast_35(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE36
case 36:
sha1recompress_fast_36(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE37
case 37:
sha1recompress_fast_37(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE38
case 38:
sha1recompress_fast_38(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE39
case 39:
sha1recompress_fast_39(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE40
case 40:
sha1recompress_fast_40(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE41
case 41:
sha1recompress_fast_41(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE42
case 42:
sha1recompress_fast_42(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE43
case 43:
sha1recompress_fast_43(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE44
case 44:
sha1recompress_fast_44(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE45
case 45:
sha1recompress_fast_45(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE46
case 46:
sha1recompress_fast_46(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE47
case 47:
sha1recompress_fast_47(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE48
case 48:
sha1recompress_fast_48(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE49
case 49:
sha1recompress_fast_49(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE50
case 50:
sha1recompress_fast_50(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE51
case 51:
sha1recompress_fast_51(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE52
case 52:
sha1recompress_fast_52(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE53
case 53:
sha1recompress_fast_53(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE54
case 54:
sha1recompress_fast_54(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE55
case 55:
sha1recompress_fast_55(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE56
case 56:
sha1recompress_fast_56(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE57
case 57:
sha1recompress_fast_57(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE58
case 58:
sha1recompress_fast_58(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE59
case 59:
sha1recompress_fast_59(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE60
case 60:
sha1recompress_fast_60(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE61
case 61:
sha1recompress_fast_61(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE62
case 62:
sha1recompress_fast_62(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE63
case 63:
sha1recompress_fast_63(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE64
case 64:
sha1recompress_fast_64(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE65
case 65:
sha1recompress_fast_65(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE66
case 66:
sha1recompress_fast_66(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE67
case 67:
sha1recompress_fast_67(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE68
case 68:
sha1recompress_fast_68(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE69
case 69:
sha1recompress_fast_69(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE70
case 70:
sha1recompress_fast_70(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE71
case 71:
sha1recompress_fast_71(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE72
case 72:
sha1recompress_fast_72(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE73
case 73:
sha1recompress_fast_73(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE74
case 74:
sha1recompress_fast_74(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE75
case 75:
sha1recompress_fast_75(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE76
case 76:
sha1recompress_fast_76(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE77
case 77:
sha1recompress_fast_77(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE78
case 78:
sha1recompress_fast_78(ihvin, ihvout, me2, state);
break;
#endif
#ifdef DOSTORESTATE79
case 79:
sha1recompress_fast_79(ihvin, ihvout, me2, state);
break;
#endif
default:
abort();
}
}
static void sha1_process(SHA1_CTX *ctx, const uint32_t block[16])
{
unsigned i, j;
uint32_t ubc_dv_mask[DVMASKSIZE] = { 0xFFFFFFFF };
uint32_t ihvtmp[5];
ctx->ihv1[0] = ctx->ihv[0];
ctx->ihv1[1] = ctx->ihv[1];
ctx->ihv1[2] = ctx->ihv[2];
ctx->ihv1[3] = ctx->ihv[3];
ctx->ihv1[4] = ctx->ihv[4];
sha1_compression_states(ctx->ihv, block, ctx->m1, ctx->states);
if (ctx->detect_coll)
{
if (ctx->ubc_check)
{
ubc_check(ctx->m1, ubc_dv_mask);
}
if (ubc_dv_mask[0] != 0)
{
for (i = 0; sha1_dvs[i].dvType != 0; ++i)
{
if (ubc_dv_mask[0] & ((uint32_t)(1) << sha1_dvs[i].maskb))
{
for (j = 0; j < 80; ++j)
ctx->m2[j] = ctx->m1[j] ^ sha1_dvs[i].dm[j];
sha1_recompression_step(sha1_dvs[i].testt, ctx->ihv2, ihvtmp, ctx->m2, ctx->states[sha1_dvs[i].testt]);
/* to verify SHA-1 collision detection code with collisions for reduced-step SHA-1 */
if ((0 == ((ihvtmp[0] ^ ctx->ihv[0]) | (ihvtmp[1] ^ ctx->ihv[1]) | (ihvtmp[2] ^ ctx->ihv[2]) | (ihvtmp[3] ^ ctx->ihv[3]) | (ihvtmp[4] ^ ctx->ihv[4])))
|| (ctx->reduced_round_coll && 0==((ctx->ihv1[0] ^ ctx->ihv2[0]) | (ctx->ihv1[1] ^ ctx->ihv2[1]) | (ctx->ihv1[2] ^ ctx->ihv2[2]) | (ctx->ihv1[3] ^ ctx->ihv2[3]) | (ctx->ihv1[4] ^ ctx->ihv2[4]))))
{
ctx->found_collision = 1;
if (ctx->safe_hash)
{
sha1_compression_W(ctx->ihv, ctx->m1);
sha1_compression_W(ctx->ihv, ctx->m1);
}
break;
}
}
}
}
}
}
void SHA1DCInit(SHA1_CTX *ctx)
{
ctx->total = 0;
ctx->ihv[0] = 0x67452301;
ctx->ihv[1] = 0xEFCDAB89;
ctx->ihv[2] = 0x98BADCFE;
ctx->ihv[3] = 0x10325476;
ctx->ihv[4] = 0xC3D2E1F0;
ctx->found_collision = 0;
ctx->safe_hash = SHA1DC_INIT_SAFE_HASH_DEFAULT;
ctx->ubc_check = 1;
ctx->detect_coll = 1;
ctx->reduced_round_coll = 0;
ctx->callback = NULL;
}
void SHA1DCSetSafeHash(SHA1_CTX *ctx, int safehash)
{
if (safehash)
ctx->safe_hash = 1;
else
ctx->safe_hash = 0;
}
void SHA1DCSetUseUBC(SHA1_CTX *ctx, int ubc_check)
{
if (ubc_check)
ctx->ubc_check = 1;
else
ctx->ubc_check = 0;
}
void SHA1DCSetUseDetectColl(SHA1_CTX *ctx, int detect_coll)
{
if (detect_coll)
ctx->detect_coll = 1;
else
ctx->detect_coll = 0;
}
void SHA1DCSetDetectReducedRoundCollision(SHA1_CTX *ctx, int reduced_round_coll)
{
if (reduced_round_coll)
ctx->reduced_round_coll = 1;
else
ctx->reduced_round_coll = 0;
}
void SHA1DCSetCallback(SHA1_CTX *ctx, collision_block_callback callback)
{
ctx->callback = callback;
}
void SHA1DCUpdate(SHA1_CTX *ctx, const char *buf, size_t len)
{
unsigned left, fill;
if (len == 0)
return;
left = ctx->total & 63;
fill = 64 - left;
if (left && len >= fill)
{
ctx->total += fill;
memcpy(ctx->buffer + left, buf, fill);
sha1_process(ctx, (uint32_t*)(ctx->buffer));
buf += fill;
len -= fill;
left = 0;
}
while (len >= 64)
{
ctx->total += 64;
#if defined(SHA1DC_ALLOW_UNALIGNED_ACCESS)
sha1_process(ctx, (uint32_t*)(buf));
#else
memcpy(ctx->buffer, buf, 64);
sha1_process(ctx, (uint32_t*)(ctx->buffer));
#endif /* defined(SHA1DC_ALLOW_UNALIGNED_ACCESS) */
buf += 64;
len -= 64;
}
if (len > 0)
{
ctx->total += len;
memcpy(ctx->buffer + left, buf, len);
}
}
static const unsigned char sha1_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
int SHA1DCFinal(unsigned char output[20], SHA1_CTX *ctx)
{
uint32_t last = ctx->total & 63;
uint32_t padn = (last < 56) ? (56 - last) : (120 - last);
uint64_t total;
SHA1DCUpdate(ctx, (const char*)(sha1_padding), padn);
total = ctx->total - padn;
total <<= 3;
ctx->buffer[56] = (unsigned char)(total >> 56);
ctx->buffer[57] = (unsigned char)(total >> 48);
ctx->buffer[58] = (unsigned char)(total >> 40);
ctx->buffer[59] = (unsigned char)(total >> 32);
ctx->buffer[60] = (unsigned char)(total >> 24);
ctx->buffer[61] = (unsigned char)(total >> 16);
ctx->buffer[62] = (unsigned char)(total >> 8);
ctx->buffer[63] = (unsigned char)(total);
sha1_process(ctx, (uint32_t*)(ctx->buffer));
output[0] = (unsigned char)(ctx->ihv[0] >> 24);
output[1] = (unsigned char)(ctx->ihv[0] >> 16);
output[2] = (unsigned char)(ctx->ihv[0] >> 8);
output[3] = (unsigned char)(ctx->ihv[0]);
output[4] = (unsigned char)(ctx->ihv[1] >> 24);
output[5] = (unsigned char)(ctx->ihv[1] >> 16);
output[6] = (unsigned char)(ctx->ihv[1] >> 8);
output[7] = (unsigned char)(ctx->ihv[1]);
output[8] = (unsigned char)(ctx->ihv[2] >> 24);
output[9] = (unsigned char)(ctx->ihv[2] >> 16);
output[10] = (unsigned char)(ctx->ihv[2] >> 8);
output[11] = (unsigned char)(ctx->ihv[2]);
output[12] = (unsigned char)(ctx->ihv[3] >> 24);
output[13] = (unsigned char)(ctx->ihv[3] >> 16);
output[14] = (unsigned char)(ctx->ihv[3] >> 8);
output[15] = (unsigned char)(ctx->ihv[3]);
output[16] = (unsigned char)(ctx->ihv[4] >> 24);
output[17] = (unsigned char)(ctx->ihv[4] >> 16);
output[18] = (unsigned char)(ctx->ihv[4] >> 8);
output[19] = (unsigned char)(ctx->ihv[4]);
return ctx->found_collision;
}
#ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_C
#include SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_C
#endif
| libgit2-main | src/util/hash/sha1dc/sha1.c |
/***
* Copyright 2017 Marc Stevens <marc@marc-stevens.nl>, Dan Shumow <danshu@microsoft.com>
* Distributed under the MIT Software License.
* See accompanying file LICENSE.txt or copy at
* https://opensource.org/licenses/MIT
***/
/*
// this file was generated by the 'parse_bitrel' program in the tools section
// using the data files from directory 'tools/data/3565'
//
// sha1_dvs contains a list of SHA-1 Disturbance Vectors (DV) to check
// dvType, dvK and dvB define the DV: I(K,B) or II(K,B) (see the paper)
// dm[80] is the expanded message block XOR-difference defined by the DV
// testt is the step to do the recompression from for collision detection
// maski and maskb define the bit to check for each DV in the dvmask returned by ubc_check
//
// ubc_check takes as input an expanded message block and verifies the unavoidable bitconditions for all listed DVs
// it returns a dvmask where each bit belonging to a DV is set if all unavoidable bitconditions for that DV have been met
// thus one needs to do the recompression check for each DV that has its bit set
//
// ubc_check is programmatically generated and the unavoidable bitconditions have been hardcoded
// a directly verifiable version named ubc_check_verify can be found in ubc_check_verify.c
// ubc_check has been verified against ubc_check_verify using the 'ubc_check_test' program in the tools section
*/
#ifndef SHA1DC_NO_STANDARD_INCLUDES
#include <stdint.h>
#endif
#ifdef SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C
#include SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C
#endif
#include "ubc_check.h"
static const uint32_t DV_I_43_0_bit = (uint32_t)(1) << 0;
static const uint32_t DV_I_44_0_bit = (uint32_t)(1) << 1;
static const uint32_t DV_I_45_0_bit = (uint32_t)(1) << 2;
static const uint32_t DV_I_46_0_bit = (uint32_t)(1) << 3;
static const uint32_t DV_I_46_2_bit = (uint32_t)(1) << 4;
static const uint32_t DV_I_47_0_bit = (uint32_t)(1) << 5;
static const uint32_t DV_I_47_2_bit = (uint32_t)(1) << 6;
static const uint32_t DV_I_48_0_bit = (uint32_t)(1) << 7;
static const uint32_t DV_I_48_2_bit = (uint32_t)(1) << 8;
static const uint32_t DV_I_49_0_bit = (uint32_t)(1) << 9;
static const uint32_t DV_I_49_2_bit = (uint32_t)(1) << 10;
static const uint32_t DV_I_50_0_bit = (uint32_t)(1) << 11;
static const uint32_t DV_I_50_2_bit = (uint32_t)(1) << 12;
static const uint32_t DV_I_51_0_bit = (uint32_t)(1) << 13;
static const uint32_t DV_I_51_2_bit = (uint32_t)(1) << 14;
static const uint32_t DV_I_52_0_bit = (uint32_t)(1) << 15;
static const uint32_t DV_II_45_0_bit = (uint32_t)(1) << 16;
static const uint32_t DV_II_46_0_bit = (uint32_t)(1) << 17;
static const uint32_t DV_II_46_2_bit = (uint32_t)(1) << 18;
static const uint32_t DV_II_47_0_bit = (uint32_t)(1) << 19;
static const uint32_t DV_II_48_0_bit = (uint32_t)(1) << 20;
static const uint32_t DV_II_49_0_bit = (uint32_t)(1) << 21;
static const uint32_t DV_II_49_2_bit = (uint32_t)(1) << 22;
static const uint32_t DV_II_50_0_bit = (uint32_t)(1) << 23;
static const uint32_t DV_II_50_2_bit = (uint32_t)(1) << 24;
static const uint32_t DV_II_51_0_bit = (uint32_t)(1) << 25;
static const uint32_t DV_II_51_2_bit = (uint32_t)(1) << 26;
static const uint32_t DV_II_52_0_bit = (uint32_t)(1) << 27;
static const uint32_t DV_II_53_0_bit = (uint32_t)(1) << 28;
static const uint32_t DV_II_54_0_bit = (uint32_t)(1) << 29;
static const uint32_t DV_II_55_0_bit = (uint32_t)(1) << 30;
static const uint32_t DV_II_56_0_bit = (uint32_t)(1) << 31;
dv_info_t sha1_dvs[] =
{
{1,43,0,58,0,0, { 0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161,0x80000599 } }
, {1,44,0,58,0,1, { 0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161 } }
, {1,45,0,58,0,2, { 0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803 } }
, {1,46,0,58,0,3, { 0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c } }
, {1,46,2,58,0,4, { 0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a,0x00000132 } }
, {1,47,0,58,0,5, { 0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6 } }
, {1,47,2,58,0,6, { 0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a } }
, {1,48,0,58,0,7, { 0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408 } }
, {1,48,2,58,0,8, { 0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020 } }
, {1,49,0,58,0,9, { 0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164 } }
, {1,49,2,58,0,10, { 0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590 } }
, {1,50,0,65,0,11, { 0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018 } }
, {1,50,2,65,0,12, { 0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060 } }
, {1,51,0,65,0,13, { 0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202 } }
, {1,51,2,65,0,14, { 0xa0000003,0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a } }
, {1,52,0,65,0,15, { 0x04000010,0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012 } }
, {2,45,0,58,0,16, { 0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054,0x00000967 } }
, {2,46,0,58,0,17, { 0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054 } }
, {2,46,2,58,0,18, { 0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6,0x0000106a,0x00000b90,0x00000152 } }
, {2,47,0,58,0,19, { 0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4 } }
, {2,48,0,58,0,20, { 0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a } }
, {2,49,0,58,0,21, { 0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d } }
, {2,49,2,58,0,22, { 0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6 } }
, {2,50,0,65,0,23, { 0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b } }
, {2,50,2,65,0,24, { 0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c } }
, {2,51,0,65,0,25, { 0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b } }
, {2,51,2,65,0,26, { 0x00000043,0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e } }
, {2,52,0,65,0,27, { 0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014 } }
, {2,53,0,65,0,28, { 0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089 } }
, {2,54,0,65,0,29, { 0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107 } }
, {2,55,0,65,0,30, { 0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b } }
, {2,56,0,65,0,31, { 0x2600001a,0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046 } }
, {0,0,0,0,0,0, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}
};
void ubc_check(const uint32_t W[80], uint32_t dvmask[1])
{
uint32_t mask = ~((uint32_t)(0));
mask &= (((((W[44]^W[45])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_I_51_0_bit|DV_I_52_0_bit|DV_II_45_0_bit|DV_II_46_0_bit|DV_II_50_0_bit|DV_II_51_0_bit));
mask &= (((((W[49]^W[50])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_II_45_0_bit|DV_II_50_0_bit|DV_II_51_0_bit|DV_II_55_0_bit|DV_II_56_0_bit));
mask &= (((((W[48]^W[49])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_52_0_bit|DV_II_49_0_bit|DV_II_50_0_bit|DV_II_54_0_bit|DV_II_55_0_bit));
mask &= ((((W[47]^(W[50]>>25))&(1<<4))-(1<<4)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_51_0_bit|DV_II_56_0_bit));
mask &= (((((W[47]^W[48])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_51_0_bit|DV_II_48_0_bit|DV_II_49_0_bit|DV_II_53_0_bit|DV_II_54_0_bit));
mask &= (((((W[46]>>4)^(W[49]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_50_0_bit|DV_II_55_0_bit));
mask &= (((((W[46]^W[47])>>29)&1)-1) | ~(DV_I_43_0_bit|DV_I_50_0_bit|DV_II_47_0_bit|DV_II_48_0_bit|DV_II_52_0_bit|DV_II_53_0_bit));
mask &= (((((W[45]>>4)^(W[48]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_49_0_bit|DV_II_54_0_bit));
mask &= (((((W[45]^W[46])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_51_0_bit|DV_II_52_0_bit));
mask &= (((((W[44]>>4)^(W[47]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_53_0_bit));
mask &= (((((W[43]>>4)^(W[46]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_52_0_bit));
mask &= (((((W[43]^W[44])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_I_50_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_49_0_bit|DV_II_50_0_bit));
mask &= (((((W[42]>>4)^(W[45]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_51_0_bit));
mask &= (((((W[41]>>4)^(W[44]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_50_0_bit));
mask &= (((((W[40]^W[41])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_47_0_bit|DV_I_48_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_56_0_bit));
mask &= (((((W[54]^W[55])>>29)&1)-1) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_50_0_bit|DV_II_55_0_bit|DV_II_56_0_bit));
mask &= (((((W[53]^W[54])>>29)&1)-1) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_49_0_bit|DV_II_54_0_bit|DV_II_55_0_bit));
mask &= (((((W[52]^W[53])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit|DV_II_53_0_bit|DV_II_54_0_bit));
mask &= ((((W[50]^(W[53]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_48_0_bit|DV_II_54_0_bit));
mask &= (((((W[50]^W[51])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_II_46_0_bit|DV_II_51_0_bit|DV_II_52_0_bit|DV_II_56_0_bit));
mask &= ((((W[49]^(W[52]>>25))&(1<<4))-(1<<4)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_47_0_bit|DV_II_53_0_bit));
mask &= ((((W[48]^(W[51]>>25))&(1<<4))-(1<<4)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_52_0_bit));
mask &= (((((W[42]^W[43])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_49_0_bit));
mask &= (((((W[41]^W[42])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_48_0_bit));
mask &= (((((W[40]>>4)^(W[43]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_50_0_bit|DV_II_49_0_bit|DV_II_56_0_bit));
mask &= (((((W[39]>>4)^(W[42]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_49_0_bit|DV_II_48_0_bit|DV_II_55_0_bit));
if (mask & (DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit))
mask &= (((((W[38]>>4)^(W[41]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit));
mask &= (((((W[37]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_47_0_bit|DV_II_46_0_bit|DV_II_53_0_bit|DV_II_55_0_bit));
if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit))
mask &= (((((W[55]^W[56])>>29)&1)-1) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit));
if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit))
mask &= ((((W[52]^(W[55]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit));
if (mask & (DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit))
mask &= ((((W[51]^(W[54]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit));
if (mask & (DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit))
mask &= (((((W[51]^W[52])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit));
if (mask & (DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit))
mask &= (((((W[36]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit));
if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit))
mask &= ((0-(((W[53]^W[56])>>29)&1)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit));
if (mask & (DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit))
mask &= ((0-(((W[51]^W[54])>>29)&1)) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit));
if (mask & (DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit))
mask &= ((0-(((W[50]^W[52])>>29)&1)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit));
if (mask & (DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit))
mask &= ((0-(((W[49]^W[51])>>29)&1)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit));
if (mask & (DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit))
mask &= ((0-(((W[48]^W[50])>>29)&1)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit));
if (mask & (DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit))
mask &= ((0-(((W[47]^W[49])>>29)&1)) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit));
if (mask & (DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit))
mask &= ((0-(((W[46]^W[48])>>29)&1)) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit));
mask &= ((((W[45]^W[47])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit|DV_I_51_2_bit));
if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit))
mask &= ((0-(((W[45]^W[47])>>29)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit));
mask &= (((((W[44]^W[46])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit|DV_I_50_2_bit));
if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit))
mask &= ((0-(((W[44]^W[46])>>29)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit));
mask &= ((0-((W[41]^(W[42]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_II_46_2_bit|DV_II_51_2_bit));
mask &= ((0-((W[40]^(W[41]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_51_2_bit|DV_II_50_2_bit));
if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit))
mask &= ((0-(((W[40]^W[42])>>4)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit));
mask &= ((0-((W[39]^(W[40]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_50_2_bit|DV_II_49_2_bit));
if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit))
mask &= ((0-(((W[39]^W[41])>>4)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit));
if (mask & (DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit))
mask &= ((0-(((W[38]^W[40])>>4)&1)) | ~(DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit));
if (mask & (DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit))
mask &= ((0-(((W[37]^W[39])>>4)&1)) | ~(DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit));
mask &= ((0-((W[36]^(W[37]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_50_2_bit|DV_II_46_2_bit));
if (mask & (DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit))
mask &= (((((W[35]>>4)^(W[39]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit));
if (mask & (DV_I_48_0_bit|DV_II_48_0_bit))
mask &= ((0-((W[63]^(W[64]>>5))&(1<<0))) | ~(DV_I_48_0_bit|DV_II_48_0_bit));
if (mask & (DV_I_45_0_bit|DV_II_45_0_bit))
mask &= ((0-((W[63]^(W[64]>>5))&(1<<1))) | ~(DV_I_45_0_bit|DV_II_45_0_bit));
if (mask & (DV_I_47_0_bit|DV_II_47_0_bit))
mask &= ((0-((W[62]^(W[63]>>5))&(1<<0))) | ~(DV_I_47_0_bit|DV_II_47_0_bit));
if (mask & (DV_I_46_0_bit|DV_II_46_0_bit))
mask &= ((0-((W[61]^(W[62]>>5))&(1<<0))) | ~(DV_I_46_0_bit|DV_II_46_0_bit));
mask &= ((0-((W[61]^(W[62]>>5))&(1<<2))) | ~(DV_I_46_2_bit|DV_II_46_2_bit));
if (mask & (DV_I_45_0_bit|DV_II_45_0_bit))
mask &= ((0-((W[60]^(W[61]>>5))&(1<<0))) | ~(DV_I_45_0_bit|DV_II_45_0_bit));
if (mask & (DV_II_51_0_bit|DV_II_54_0_bit))
mask &= (((((W[58]^W[59])>>29)&1)-1) | ~(DV_II_51_0_bit|DV_II_54_0_bit));
if (mask & (DV_II_50_0_bit|DV_II_53_0_bit))
mask &= (((((W[57]^W[58])>>29)&1)-1) | ~(DV_II_50_0_bit|DV_II_53_0_bit));
if (mask & (DV_II_52_0_bit|DV_II_54_0_bit))
mask &= ((((W[56]^(W[59]>>25))&(1<<4))-(1<<4)) | ~(DV_II_52_0_bit|DV_II_54_0_bit));
if (mask & (DV_II_51_0_bit|DV_II_52_0_bit))
mask &= ((0-(((W[56]^W[59])>>29)&1)) | ~(DV_II_51_0_bit|DV_II_52_0_bit));
if (mask & (DV_II_49_0_bit|DV_II_52_0_bit))
mask &= (((((W[56]^W[57])>>29)&1)-1) | ~(DV_II_49_0_bit|DV_II_52_0_bit));
if (mask & (DV_II_51_0_bit|DV_II_53_0_bit))
mask &= ((((W[55]^(W[58]>>25))&(1<<4))-(1<<4)) | ~(DV_II_51_0_bit|DV_II_53_0_bit));
if (mask & (DV_II_50_0_bit|DV_II_52_0_bit))
mask &= ((((W[54]^(W[57]>>25))&(1<<4))-(1<<4)) | ~(DV_II_50_0_bit|DV_II_52_0_bit));
if (mask & (DV_II_49_0_bit|DV_II_51_0_bit))
mask &= ((((W[53]^(W[56]>>25))&(1<<4))-(1<<4)) | ~(DV_II_49_0_bit|DV_II_51_0_bit));
mask &= ((((W[51]^(W[50]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_46_2_bit));
mask &= ((((W[48]^W[50])&(1<<6))-(1<<6)) | ~(DV_I_50_2_bit|DV_II_46_2_bit));
if (mask & (DV_I_51_0_bit|DV_I_52_0_bit))
mask &= ((0-(((W[48]^W[55])>>29)&1)) | ~(DV_I_51_0_bit|DV_I_52_0_bit));
mask &= ((((W[47]^W[49])&(1<<6))-(1<<6)) | ~(DV_I_49_2_bit|DV_I_51_2_bit));
mask &= ((((W[48]^(W[47]>>5))&(1<<1))-(1<<1)) | ~(DV_I_47_2_bit|DV_II_51_2_bit));
mask &= ((((W[46]^W[48])&(1<<6))-(1<<6)) | ~(DV_I_48_2_bit|DV_I_50_2_bit));
mask &= ((((W[47]^(W[46]>>5))&(1<<1))-(1<<1)) | ~(DV_I_46_2_bit|DV_II_50_2_bit));
mask &= ((0-((W[44]^(W[45]>>5))&(1<<1))) | ~(DV_I_51_2_bit|DV_II_49_2_bit));
mask &= ((((W[43]^W[45])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit));
mask &= (((((W[42]^W[44])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit));
mask &= ((((W[43]^(W[42]>>5))&(1<<1))-(1<<1)) | ~(DV_II_46_2_bit|DV_II_51_2_bit));
mask &= ((((W[42]^(W[41]>>5))&(1<<1))-(1<<1)) | ~(DV_I_51_2_bit|DV_II_50_2_bit));
mask &= ((((W[41]^(W[40]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_49_2_bit));
if (mask & (DV_I_52_0_bit|DV_II_51_0_bit))
mask &= ((((W[39]^(W[43]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_51_0_bit));
if (mask & (DV_I_51_0_bit|DV_II_50_0_bit))
mask &= ((((W[38]^(W[42]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_50_0_bit));
if (mask & (DV_I_48_2_bit|DV_I_51_2_bit))
mask &= ((0-((W[37]^(W[38]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_I_51_2_bit));
if (mask & (DV_I_50_0_bit|DV_II_49_0_bit))
mask &= ((((W[37]^(W[41]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_II_49_0_bit));
if (mask & (DV_II_52_0_bit|DV_II_54_0_bit))
mask &= ((0-((W[36]^W[38])&(1<<4))) | ~(DV_II_52_0_bit|DV_II_54_0_bit));
mask &= ((0-((W[35]^(W[36]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_49_2_bit));
if (mask & (DV_I_51_0_bit|DV_II_47_0_bit))
mask &= ((((W[35]^(W[39]>>25))&(1<<3))-(1<<3)) | ~(DV_I_51_0_bit|DV_II_47_0_bit));
if (mask) {
if (mask & DV_I_43_0_bit)
if (
!((W[61]^(W[62]>>5)) & (1<<1))
|| !(!((W[59]^(W[63]>>25)) & (1<<5)))
|| !((W[58]^(W[63]>>30)) & (1<<0))
) mask &= ~DV_I_43_0_bit;
if (mask & DV_I_44_0_bit)
if (
!((W[62]^(W[63]>>5)) & (1<<1))
|| !(!((W[60]^(W[64]>>25)) & (1<<5)))
|| !((W[59]^(W[64]>>30)) & (1<<0))
) mask &= ~DV_I_44_0_bit;
if (mask & DV_I_46_2_bit)
mask &= ((~((W[40]^W[42])>>2)) | ~DV_I_46_2_bit);
if (mask & DV_I_47_2_bit)
if (
!((W[62]^(W[63]>>5)) & (1<<2))
|| !(!((W[41]^W[43]) & (1<<6)))
) mask &= ~DV_I_47_2_bit;
if (mask & DV_I_48_2_bit)
if (
!((W[63]^(W[64]>>5)) & (1<<2))
|| !(!((W[48]^(W[49]<<5)) & (1<<6)))
) mask &= ~DV_I_48_2_bit;
if (mask & DV_I_49_2_bit)
if (
!(!((W[49]^(W[50]<<5)) & (1<<6)))
|| !((W[42]^W[50]) & (1<<1))
|| !(!((W[39]^(W[40]<<5)) & (1<<6)))
|| !((W[38]^W[40]) & (1<<1))
) mask &= ~DV_I_49_2_bit;
if (mask & DV_I_50_0_bit)
mask &= ((((W[36]^W[37])<<7)) | ~DV_I_50_0_bit);
if (mask & DV_I_50_2_bit)
mask &= ((((W[43]^W[51])<<11)) | ~DV_I_50_2_bit);
if (mask & DV_I_51_0_bit)
mask &= ((((W[37]^W[38])<<9)) | ~DV_I_51_0_bit);
if (mask & DV_I_51_2_bit)
if (
!(!((W[51]^(W[52]<<5)) & (1<<6)))
|| !(!((W[49]^W[51]) & (1<<6)))
|| !(!((W[37]^(W[37]>>5)) & (1<<1)))
|| !(!((W[35]^(W[39]>>25)) & (1<<5)))
) mask &= ~DV_I_51_2_bit;
if (mask & DV_I_52_0_bit)
mask &= ((((W[38]^W[39])<<11)) | ~DV_I_52_0_bit);
if (mask & DV_II_46_2_bit)
mask &= ((((W[47]^W[51])<<17)) | ~DV_II_46_2_bit);
if (mask & DV_II_48_0_bit)
if (
!(!((W[36]^(W[40]>>25)) & (1<<3)))
|| !((W[35]^(W[40]<<2)) & (1<<30))
) mask &= ~DV_II_48_0_bit;
if (mask & DV_II_49_0_bit)
if (
!(!((W[37]^(W[41]>>25)) & (1<<3)))
|| !((W[36]^(W[41]<<2)) & (1<<30))
) mask &= ~DV_II_49_0_bit;
if (mask & DV_II_49_2_bit)
if (
!(!((W[53]^(W[54]<<5)) & (1<<6)))
|| !(!((W[51]^W[53]) & (1<<6)))
|| !((W[50]^W[54]) & (1<<1))
|| !(!((W[45]^(W[46]<<5)) & (1<<6)))
|| !(!((W[37]^(W[41]>>25)) & (1<<5)))
|| !((W[36]^(W[41]>>30)) & (1<<0))
) mask &= ~DV_II_49_2_bit;
if (mask & DV_II_50_0_bit)
if (
!((W[55]^W[58]) & (1<<29))
|| !(!((W[38]^(W[42]>>25)) & (1<<3)))
|| !((W[37]^(W[42]<<2)) & (1<<30))
) mask &= ~DV_II_50_0_bit;
if (mask & DV_II_50_2_bit)
if (
!(!((W[54]^(W[55]<<5)) & (1<<6)))
|| !(!((W[52]^W[54]) & (1<<6)))
|| !((W[51]^W[55]) & (1<<1))
|| !((W[45]^W[47]) & (1<<1))
|| !(!((W[38]^(W[42]>>25)) & (1<<5)))
|| !((W[37]^(W[42]>>30)) & (1<<0))
) mask &= ~DV_II_50_2_bit;
if (mask & DV_II_51_0_bit)
if (
!(!((W[39]^(W[43]>>25)) & (1<<3)))
|| !((W[38]^(W[43]<<2)) & (1<<30))
) mask &= ~DV_II_51_0_bit;
if (mask & DV_II_51_2_bit)
if (
!(!((W[55]^(W[56]<<5)) & (1<<6)))
|| !(!((W[53]^W[55]) & (1<<6)))
|| !((W[52]^W[56]) & (1<<1))
|| !((W[46]^W[48]) & (1<<1))
|| !(!((W[39]^(W[43]>>25)) & (1<<5)))
|| !((W[38]^(W[43]>>30)) & (1<<0))
) mask &= ~DV_II_51_2_bit;
if (mask & DV_II_52_0_bit)
if (
!(!((W[59]^W[60]) & (1<<29)))
|| !(!((W[40]^(W[44]>>25)) & (1<<3)))
|| !(!((W[40]^(W[44]>>25)) & (1<<4)))
|| !((W[39]^(W[44]<<2)) & (1<<30))
) mask &= ~DV_II_52_0_bit;
if (mask & DV_II_53_0_bit)
if (
!((W[58]^W[61]) & (1<<29))
|| !(!((W[57]^(W[61]>>25)) & (1<<4)))
|| !(!((W[41]^(W[45]>>25)) & (1<<3)))
|| !(!((W[41]^(W[45]>>25)) & (1<<4)))
) mask &= ~DV_II_53_0_bit;
if (mask & DV_II_54_0_bit)
if (
!(!((W[58]^(W[62]>>25)) & (1<<4)))
|| !(!((W[42]^(W[46]>>25)) & (1<<3)))
|| !(!((W[42]^(W[46]>>25)) & (1<<4)))
) mask &= ~DV_II_54_0_bit;
if (mask & DV_II_55_0_bit)
if (
!(!((W[59]^(W[63]>>25)) & (1<<4)))
|| !(!((W[57]^(W[59]>>25)) & (1<<4)))
|| !(!((W[43]^(W[47]>>25)) & (1<<3)))
|| !(!((W[43]^(W[47]>>25)) & (1<<4)))
) mask &= ~DV_II_55_0_bit;
if (mask & DV_II_56_0_bit)
if (
!(!((W[60]^(W[64]>>25)) & (1<<4)))
|| !(!((W[44]^(W[48]>>25)) & (1<<3)))
|| !(!((W[44]^(W[48]>>25)) & (1<<4)))
) mask &= ~DV_II_56_0_bit;
}
dvmask[0]=mask;
}
#ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_C
#include SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_C
#endif
| libgit2-main | src/util/hash/sha1dc/ubc_check.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#ifndef GIT_WIN32
#include <limits.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
char *p_realpath(const char *pathname, char *resolved)
{
char *ret;
if ((ret = realpath(pathname, resolved)) == NULL)
return NULL;
#ifdef __OpenBSD__
/* The OpenBSD realpath function behaves differently,
* figure out if the file exists */
if (access(ret, F_OK) < 0)
ret = NULL;
#endif
return ret;
}
#endif
| libgit2-main | src/util/unix/realpath.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#if !defined(GIT_WIN32) && !defined(NO_MMAP)
#include "map.h"
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
int git__page_size(size_t *page_size)
{
long sc_page_size = sysconf(_SC_PAGE_SIZE);
if (sc_page_size < 0) {
git_error_set(GIT_ERROR_OS, "can't determine system page size");
return -1;
}
*page_size = (size_t) sc_page_size;
return 0;
}
int git__mmap_alignment(size_t *alignment)
{
return git__page_size(alignment);
}
int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset)
{
int mprot = PROT_READ;
int mflag = 0;
GIT_MMAP_VALIDATE(out, len, prot, flags);
out->data = NULL;
out->len = 0;
if (prot & GIT_PROT_WRITE)
mprot |= PROT_WRITE;
if ((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED)
mflag = MAP_SHARED;
else if ((flags & GIT_MAP_TYPE) == GIT_MAP_PRIVATE)
mflag = MAP_PRIVATE;
else
mflag = MAP_SHARED;
out->data = mmap(NULL, len, mprot, mflag, fd, offset);
if (!out->data || out->data == MAP_FAILED) {
git_error_set(GIT_ERROR_OS, "failed to mmap. Could not write data");
return -1;
}
out->len = len;
return 0;
}
int p_munmap(git_map *map)
{
GIT_ASSERT_ARG(map);
munmap(map->data, map->len);
map->data = NULL;
map->len = 0;
return 0;
}
#endif
| libgit2-main | src/util/unix/map.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "win32_leakcheck.h"
#if defined(GIT_WIN32_LEAKCHECK)
#include "win32/w32_leakcheck.h"
static void *leakcheck_malloc(size_t len, const char *file, int line)
{
void *ptr = _malloc_dbg(len, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line);
if (!ptr) git_error_set_oom();
return ptr;
}
static void *leakcheck_calloc(size_t nelem, size_t elsize, const char *file, int line)
{
void *ptr = _calloc_dbg(nelem, elsize, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line);
if (!ptr) git_error_set_oom();
return ptr;
}
static char *leakcheck_strdup(const char *str, const char *file, int line)
{
char *ptr = _strdup_dbg(str, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line);
if (!ptr) git_error_set_oom();
return ptr;
}
static char *leakcheck_strndup(const char *str, size_t n, const char *file, int line)
{
size_t length = 0, alloclength;
char *ptr;
length = p_strnlen(str, n);
if (GIT_ADD_SIZET_OVERFLOW(&alloclength, length, 1) ||
!(ptr = leakcheck_malloc(alloclength, file, line)))
return NULL;
if (length)
memcpy(ptr, str, length);
ptr[length] = '\0';
return ptr;
}
static char *leakcheck_substrdup(const char *start, size_t n, const char *file, int line)
{
char *ptr;
size_t alloclen;
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, n, 1) ||
!(ptr = leakcheck_malloc(alloclen, file, line)))
return NULL;
memcpy(ptr, start, n);
ptr[n] = '\0';
return ptr;
}
static void *leakcheck_realloc(void *ptr, size_t size, const char *file, int line)
{
void *new_ptr = _realloc_dbg(ptr, size, _NORMAL_BLOCK, git_win32_leakcheck_stacktrace(1,file), line);
if (!new_ptr) git_error_set_oom();
return new_ptr;
}
static void *leakcheck_reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line)
{
size_t newsize;
if (GIT_MULTIPLY_SIZET_OVERFLOW(&newsize, nelem, elsize))
return NULL;
return leakcheck_realloc(ptr, newsize, file, line);
}
static void *leakcheck_mallocarray(size_t nelem, size_t elsize, const char *file, int line)
{
return leakcheck_reallocarray(NULL, nelem, elsize, file, line);
}
static void leakcheck_free(void *ptr)
{
free(ptr);
}
int git_win32_leakcheck_init_allocator(git_allocator *allocator)
{
allocator->gmalloc = leakcheck_malloc;
allocator->gcalloc = leakcheck_calloc;
allocator->gstrdup = leakcheck_strdup;
allocator->gstrndup = leakcheck_strndup;
allocator->gsubstrdup = leakcheck_substrdup;
allocator->grealloc = leakcheck_realloc;
allocator->greallocarray = leakcheck_reallocarray;
allocator->gmallocarray = leakcheck_mallocarray;
allocator->gfree = leakcheck_free;
return 0;
}
#else
int git_win32_leakcheck_init_allocator(git_allocator *allocator)
{
GIT_UNUSED(allocator);
git_error_set(GIT_EINVALID, "leakcheck memory allocator not available");
return -1;
}
#endif
| libgit2-main | src/util/allocators/win32_leakcheck.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "stdalloc.h"
static void *stdalloc__malloc(size_t len, const char *file, int line)
{
void *ptr;
GIT_UNUSED(file);
GIT_UNUSED(line);
#ifdef GIT_DEBUG_STRICT_ALLOC
if (!len)
return NULL;
#endif
ptr = malloc(len);
if (!ptr)
git_error_set_oom();
return ptr;
}
static void *stdalloc__calloc(size_t nelem, size_t elsize, const char *file, int line)
{
void *ptr;
GIT_UNUSED(file);
GIT_UNUSED(line);
#ifdef GIT_DEBUG_STRICT_ALLOC
if (!elsize || !nelem)
return NULL;
#endif
ptr = calloc(nelem, elsize);
if (!ptr)
git_error_set_oom();
return ptr;
}
static char *stdalloc__strdup(const char *str, const char *file, int line)
{
char *ptr;
GIT_UNUSED(file);
GIT_UNUSED(line);
ptr = strdup(str);
if (!ptr)
git_error_set_oom();
return ptr;
}
static char *stdalloc__strndup(const char *str, size_t n, const char *file, int line)
{
size_t length = 0, alloclength;
char *ptr;
length = p_strnlen(str, n);
if (GIT_ADD_SIZET_OVERFLOW(&alloclength, length, 1) ||
!(ptr = stdalloc__malloc(alloclength, file, line)))
return NULL;
if (length)
memcpy(ptr, str, length);
ptr[length] = '\0';
return ptr;
}
static char *stdalloc__substrdup(const char *start, size_t n, const char *file, int line)
{
char *ptr;
size_t alloclen;
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, n, 1) ||
!(ptr = stdalloc__malloc(alloclen, file, line)))
return NULL;
memcpy(ptr, start, n);
ptr[n] = '\0';
return ptr;
}
static void *stdalloc__realloc(void *ptr, size_t size, const char *file, int line)
{
void *new_ptr;
GIT_UNUSED(file);
GIT_UNUSED(line);
#ifdef GIT_DEBUG_STRICT_ALLOC
if (!size)
return NULL;
#endif
new_ptr = realloc(ptr, size);
if (!new_ptr)
git_error_set_oom();
return new_ptr;
}
static void *stdalloc__reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line)
{
size_t newsize;
if (GIT_MULTIPLY_SIZET_OVERFLOW(&newsize, nelem, elsize))
return NULL;
return stdalloc__realloc(ptr, newsize, file, line);
}
static void *stdalloc__mallocarray(size_t nelem, size_t elsize, const char *file, int line)
{
return stdalloc__reallocarray(NULL, nelem, elsize, file, line);
}
static void stdalloc__free(void *ptr)
{
free(ptr);
}
int git_stdalloc_init_allocator(git_allocator *allocator)
{
allocator->gmalloc = stdalloc__malloc;
allocator->gcalloc = stdalloc__calloc;
allocator->gstrdup = stdalloc__strdup;
allocator->gstrndup = stdalloc__strndup;
allocator->gsubstrdup = stdalloc__substrdup;
allocator->grealloc = stdalloc__realloc;
allocator->greallocarray = stdalloc__reallocarray;
allocator->gmallocarray = stdalloc__mallocarray;
allocator->gfree = stdalloc__free;
return 0;
}
| libgit2-main | src/util/allocators/stdalloc.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "failalloc.h"
void *git_failalloc_malloc(size_t len, const char *file, int line)
{
GIT_UNUSED(len);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
void *git_failalloc_calloc(size_t nelem, size_t elsize, const char *file, int line)
{
GIT_UNUSED(nelem);
GIT_UNUSED(elsize);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
char *git_failalloc_strdup(const char *str, const char *file, int line)
{
GIT_UNUSED(str);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
char *git_failalloc_strndup(const char *str, size_t n, const char *file, int line)
{
GIT_UNUSED(str);
GIT_UNUSED(n);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
char *git_failalloc_substrdup(const char *start, size_t n, const char *file, int line)
{
GIT_UNUSED(start);
GIT_UNUSED(n);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
void *git_failalloc_realloc(void *ptr, size_t size, const char *file, int line)
{
GIT_UNUSED(ptr);
GIT_UNUSED(size);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
void *git_failalloc_reallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line)
{
GIT_UNUSED(ptr);
GIT_UNUSED(nelem);
GIT_UNUSED(elsize);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
void *git_failalloc_mallocarray(size_t nelem, size_t elsize, const char *file, int line)
{
GIT_UNUSED(nelem);
GIT_UNUSED(elsize);
GIT_UNUSED(file);
GIT_UNUSED(line);
return NULL;
}
void git_failalloc_free(void *ptr)
{
GIT_UNUSED(ptr);
}
| libgit2-main | src/util/allocators/failalloc.c |
#include "precompiled.h"
| libgit2-main | src/util/win32/precompiled.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "thread.h"
#include "runtime.h"
#define CLEAN_THREAD_EXIT 0x6F012842
typedef void (WINAPI *win32_srwlock_fn)(GIT_SRWLOCK *);
static win32_srwlock_fn win32_srwlock_initialize;
static win32_srwlock_fn win32_srwlock_acquire_shared;
static win32_srwlock_fn win32_srwlock_release_shared;
static win32_srwlock_fn win32_srwlock_acquire_exclusive;
static win32_srwlock_fn win32_srwlock_release_exclusive;
static DWORD fls_index;
/* The thread procedure stub used to invoke the caller's procedure
* and capture the return value for later collection. Windows will
* only hold a DWORD, but we need to be able to store an entire
* void pointer. This requires the indirection. */
static DWORD WINAPI git_win32__threadproc(LPVOID lpParameter)
{
git_thread *thread = lpParameter;
/* Set the current thread for `git_thread_exit` */
FlsSetValue(fls_index, thread);
thread->result = thread->proc(thread->param);
return CLEAN_THREAD_EXIT;
}
static void git_threads_global_shutdown(void)
{
FlsFree(fls_index);
}
int git_threads_global_init(void)
{
HMODULE hModule = GetModuleHandleW(L"kernel32");
if (hModule) {
win32_srwlock_initialize = (win32_srwlock_fn)(void *)
GetProcAddress(hModule, "InitializeSRWLock");
win32_srwlock_acquire_shared = (win32_srwlock_fn)(void *)
GetProcAddress(hModule, "AcquireSRWLockShared");
win32_srwlock_release_shared = (win32_srwlock_fn)(void *)
GetProcAddress(hModule, "ReleaseSRWLockShared");
win32_srwlock_acquire_exclusive = (win32_srwlock_fn)(void *)
GetProcAddress(hModule, "AcquireSRWLockExclusive");
win32_srwlock_release_exclusive = (win32_srwlock_fn)(void *)
GetProcAddress(hModule, "ReleaseSRWLockExclusive");
}
if ((fls_index = FlsAlloc(NULL)) == FLS_OUT_OF_INDEXES)
return -1;
return git_runtime_shutdown_register(git_threads_global_shutdown);
}
int git_thread_create(
git_thread *GIT_RESTRICT thread,
void *(*start_routine)(void*),
void *GIT_RESTRICT arg)
{
thread->result = NULL;
thread->param = arg;
thread->proc = start_routine;
thread->thread = CreateThread(
NULL, 0, git_win32__threadproc, thread, 0, NULL);
return thread->thread ? 0 : -1;
}
int git_thread_join(
git_thread *thread,
void **value_ptr)
{
DWORD exit;
if (WaitForSingleObject(thread->thread, INFINITE) != WAIT_OBJECT_0)
return -1;
if (!GetExitCodeThread(thread->thread, &exit)) {
CloseHandle(thread->thread);
return -1;
}
/* Check for the thread having exited uncleanly. If exit was unclean,
* then we don't have a return value to give back to the caller. */
GIT_ASSERT(exit == CLEAN_THREAD_EXIT);
if (value_ptr)
*value_ptr = thread->result;
CloseHandle(thread->thread);
return 0;
}
void git_thread_exit(void *value)
{
git_thread *thread = FlsGetValue(fls_index);
if (thread)
thread->result = value;
ExitThread(CLEAN_THREAD_EXIT);
}
size_t git_thread_currentid(void)
{
return GetCurrentThreadId();
}
int git_mutex_init(git_mutex *GIT_RESTRICT mutex)
{
InitializeCriticalSection(mutex);
return 0;
}
int git_mutex_free(git_mutex *mutex)
{
DeleteCriticalSection(mutex);
return 0;
}
int git_mutex_lock(git_mutex *mutex)
{
EnterCriticalSection(mutex);
return 0;
}
int git_mutex_unlock(git_mutex *mutex)
{
LeaveCriticalSection(mutex);
return 0;
}
int git_cond_init(git_cond *cond)
{
/* This is an auto-reset event. */
*cond = CreateEventW(NULL, FALSE, FALSE, NULL);
GIT_ASSERT(*cond);
/* If we can't create the event, claim that the reason was out-of-memory.
* The actual reason can be fetched with GetLastError(). */
return *cond ? 0 : ENOMEM;
}
int git_cond_free(git_cond *cond)
{
BOOL closed;
if (!cond)
return EINVAL;
closed = CloseHandle(*cond);
GIT_ASSERT(closed);
GIT_UNUSED(closed);
*cond = NULL;
return 0;
}
int git_cond_wait(git_cond *cond, git_mutex *mutex)
{
int error;
DWORD wait_result;
if (!cond || !mutex)
return EINVAL;
/* The caller must be holding the mutex. */
error = git_mutex_unlock(mutex);
if (error)
return error;
wait_result = WaitForSingleObject(*cond, INFINITE);
GIT_ASSERT(WAIT_OBJECT_0 == wait_result);
GIT_UNUSED(wait_result);
return git_mutex_lock(mutex);
}
int git_cond_signal(git_cond *cond)
{
BOOL signaled;
if (!cond)
return EINVAL;
signaled = SetEvent(*cond);
GIT_ASSERT(signaled);
GIT_UNUSED(signaled);
return 0;
}
int git_rwlock_init(git_rwlock *GIT_RESTRICT lock)
{
if (win32_srwlock_initialize)
win32_srwlock_initialize(&lock->native.srwl);
else
InitializeCriticalSection(&lock->native.csec);
return 0;
}
int git_rwlock_rdlock(git_rwlock *lock)
{
if (win32_srwlock_acquire_shared)
win32_srwlock_acquire_shared(&lock->native.srwl);
else
EnterCriticalSection(&lock->native.csec);
return 0;
}
int git_rwlock_rdunlock(git_rwlock *lock)
{
if (win32_srwlock_release_shared)
win32_srwlock_release_shared(&lock->native.srwl);
else
LeaveCriticalSection(&lock->native.csec);
return 0;
}
int git_rwlock_wrlock(git_rwlock *lock)
{
if (win32_srwlock_acquire_exclusive)
win32_srwlock_acquire_exclusive(&lock->native.srwl);
else
EnterCriticalSection(&lock->native.csec);
return 0;
}
int git_rwlock_wrunlock(git_rwlock *lock)
{
if (win32_srwlock_release_exclusive)
win32_srwlock_release_exclusive(&lock->native.srwl);
else
LeaveCriticalSection(&lock->native.csec);
return 0;
}
int git_rwlock_free(git_rwlock *lock)
{
if (!win32_srwlock_initialize)
DeleteCriticalSection(&lock->native.csec);
git__memzero(lock, sizeof(*lock));
return 0;
}
| libgit2-main | src/util/win32/thread.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "w32_util.h"
/**
* Creates a FindFirstFile(Ex) filter string from a UTF-8 path.
* The filter string enumerates all items in the directory.
*
* @param dest The buffer to receive the filter string.
* @param src The UTF-8 path of the directory to enumerate.
* @return True if the filter string was created successfully; false otherwise
*/
bool git_win32__findfirstfile_filter(git_win32_path dest, const char *src)
{
static const wchar_t suffix[] = L"\\*";
int len = git_win32_path_from_utf8(dest, src);
/* Ensure the path was converted */
if (len < 0)
return false;
/* Ensure that the path does not end with a trailing slash,
* because we're about to add one. Don't rely our trim_end
* helper, because we want to remove the backslash even for
* drive letter paths, in this case. */
if (len > 0 &&
(dest[len - 1] == L'/' || dest[len - 1] == L'\\')) {
dest[len - 1] = L'\0';
len--;
}
/* Ensure we have enough room to add the suffix */
if ((size_t)len >= GIT_WIN_PATH_UTF16 - CONST_STRLEN(suffix))
return false;
wcscat(dest, suffix);
return true;
}
/**
* Ensures the given path (file or folder) has the +H (hidden) attribute set.
*
* @param path The path which should receive the +H bit.
* @return 0 on success; -1 on failure
*/
int git_win32__set_hidden(const char *path, bool hidden)
{
git_win32_path buf;
DWORD attrs, newattrs;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
attrs = GetFileAttributesW(buf);
/* Ensure the path exists */
if (attrs == INVALID_FILE_ATTRIBUTES)
return -1;
if (hidden)
newattrs = attrs | FILE_ATTRIBUTE_HIDDEN;
else
newattrs = attrs & ~FILE_ATTRIBUTE_HIDDEN;
if (attrs != newattrs && !SetFileAttributesW(buf, newattrs)) {
git_error_set(GIT_ERROR_OS, "failed to %s hidden bit for '%s'",
hidden ? "set" : "unset", path);
return -1;
}
return 0;
}
int git_win32__hidden(bool *out, const char *path)
{
git_win32_path buf;
DWORD attrs;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
attrs = GetFileAttributesW(buf);
/* Ensure the path exists */
if (attrs == INVALID_FILE_ATTRIBUTES)
return -1;
*out = (attrs & FILE_ATTRIBUTE_HIDDEN) ? true : false;
return 0;
}
int git_win32__file_attribute_to_stat(
struct stat *st,
const WIN32_FILE_ATTRIBUTE_DATA *attrdata,
const wchar_t *path)
{
git_win32__stat_init(st,
attrdata->dwFileAttributes,
attrdata->nFileSizeHigh,
attrdata->nFileSizeLow,
attrdata->ftCreationTime,
attrdata->ftLastAccessTime,
attrdata->ftLastWriteTime);
if (attrdata->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT && path) {
git_win32_path target;
if (git_win32_path_readlink_w(target, path) >= 0) {
st->st_mode = (st->st_mode & ~S_IFMT) | S_IFLNK;
/* st_size gets the UTF-8 length of the target name, in bytes,
* not counting the NULL terminator */
if ((st->st_size = git__utf16_to_8(NULL, 0, target)) < 0) {
git_error_set(GIT_ERROR_OS, "could not convert reparse point name for '%ls'", path);
return -1;
}
}
}
return 0;
}
| libgit2-main | src/util/win32/w32_util.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "utf-conv.h"
GIT_INLINE(void) git__set_errno(void)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
errno = ENAMETOOLONG;
else
errno = EINVAL;
}
/**
* Converts a UTF-8 string to wide characters.
*
* @param dest The buffer to receive the wide string.
* @param dest_size The size of the buffer, in characters.
* @param src The UTF-8 string to convert.
* @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure
*/
int git__utf8_to_16(wchar_t *dest, size_t dest_size, const char *src)
{
int len;
/* Length of -1 indicates NULL termination of the input string. Subtract 1 from the result to
* turn 0 into -1 (an error code) and to not count the NULL terminator as part of the string's
* length. MultiByteToWideChar never returns int's minvalue, so underflow is not possible */
if ((len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, dest, (int)dest_size) - 1) < 0)
git__set_errno();
return len;
}
/**
* Converts a wide string to UTF-8.
*
* @param dest The buffer to receive the UTF-8 string.
* @param dest_size The size of the buffer, in bytes.
* @param src The wide string to convert.
* @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure
*/
int git__utf16_to_8(char *dest, size_t dest_size, const wchar_t *src)
{
int len;
/* Length of -1 indicates NULL termination of the input string. Subtract 1 from the result to
* turn 0 into -1 (an error code) and to not count the NULL terminator as part of the string's
* length. WideCharToMultiByte never returns int's minvalue, so underflow is not possible */
if ((len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dest, (int)dest_size, NULL, NULL) - 1) < 0)
git__set_errno();
return len;
}
/**
* Converts a UTF-8 string to wide characters.
* Memory is allocated to hold the converted string.
* The caller is responsible for freeing the string with git__free.
*
* @param dest Receives a pointer to the wide string.
* @param src The UTF-8 string to convert.
* @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure
*/
int git__utf8_to_16_alloc(wchar_t **dest, const char *src)
{
int utf16_size;
*dest = NULL;
/* Length of -1 indicates NULL termination of the input string */
utf16_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0);
if (!utf16_size) {
git__set_errno();
return -1;
}
if (!(*dest = git__mallocarray(utf16_size, sizeof(wchar_t)))) {
errno = ENOMEM;
return -1;
}
utf16_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, *dest, utf16_size);
if (!utf16_size) {
git__set_errno();
git__free(*dest);
*dest = NULL;
}
/* Subtract 1 from the result to turn 0 into -1 (an error code) and to not count the NULL
* terminator as part of the string's length. MultiByteToWideChar never returns int's minvalue,
* so underflow is not possible */
return utf16_size - 1;
}
/**
* Converts a wide string to UTF-8.
* Memory is allocated to hold the converted string.
* The caller is responsible for freeing the string with git__free.
*
* @param dest Receives a pointer to the UTF-8 string.
* @param src The wide string to convert.
* @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure
*/
int git__utf16_to_8_alloc(char **dest, const wchar_t *src)
{
int utf8_size;
*dest = NULL;
/* Length of -1 indicates NULL termination of the input string */
utf8_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL);
if (!utf8_size) {
git__set_errno();
return -1;
}
*dest = git__malloc(utf8_size);
if (!*dest) {
errno = ENOMEM;
return -1;
}
utf8_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, *dest, utf8_size, NULL, NULL);
if (!utf8_size) {
git__set_errno();
git__free(*dest);
*dest = NULL;
}
/* Subtract 1 from the result to turn 0 into -1 (an error code) and to not count the NULL
* terminator as part of the string's length. MultiByteToWideChar never returns int's minvalue,
* so underflow is not possible */
return utf8_size - 1;
}
| libgit2-main | src/util/win32/utf-conv.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "findfile.h"
#include "path_w32.h"
#include "utf-conv.h"
#include "fs_path.h"
#define REG_GITFORWINDOWS_KEY L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
#define REG_GITFORWINDOWS_KEY_WOW64 L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
static int git_win32__expand_path(git_win32_path dest, const wchar_t *src)
{
DWORD len = ExpandEnvironmentStringsW(src, dest, GIT_WIN_PATH_UTF16);
if (!len || len > GIT_WIN_PATH_UTF16)
return -1;
return 0;
}
static int win32_path_to_8(git_str *dest, const wchar_t *src)
{
git_win32_utf8_path utf8_path;
if (git_win32_path_to_utf8(utf8_path, src) < 0) {
git_error_set(GIT_ERROR_OS, "unable to convert path to UTF-8");
return -1;
}
/* Convert backslashes to forward slashes */
git_fs_path_mkposix(utf8_path);
return git_str_sets(dest, utf8_path);
}
static git_win32_path mock_registry;
static bool mock_registry_set;
extern int git_win32__set_registry_system_dir(const wchar_t *mock_sysdir)
{
if (!mock_sysdir) {
mock_registry[0] = L'\0';
mock_registry_set = false;
} else {
size_t len = wcslen(mock_sysdir);
if (len > GIT_WIN_PATH_MAX) {
git_error_set(GIT_ERROR_INVALID, "mock path too long");
return -1;
}
wcscpy(mock_registry, mock_sysdir);
mock_registry_set = true;
}
return 0;
}
static int lookup_registry_key(
git_win32_path out,
const HKEY hive,
const wchar_t* key,
const wchar_t *value)
{
HKEY hkey;
DWORD type, size;
int error = GIT_ENOTFOUND;
/*
* Registry data may not be NUL terminated, provide room to do
* it ourselves.
*/
size = (DWORD)((sizeof(git_win32_path) - 1) * sizeof(wchar_t));
if (RegOpenKeyExW(hive, key, 0, KEY_READ, &hkey) != 0)
return GIT_ENOTFOUND;
if (RegQueryValueExW(hkey, value, NULL, &type, (LPBYTE)out, &size) == 0 &&
type == REG_SZ &&
size > 0 &&
size < sizeof(git_win32_path)) {
size_t wsize = size / sizeof(wchar_t);
size_t len = wsize - 1;
if (out[wsize - 1] != L'\0') {
len = wsize;
out[wsize] = L'\0';
}
if (out[len - 1] == L'\\')
out[len - 1] = L'\0';
if (_waccess(out, F_OK) == 0)
error = 0;
}
RegCloseKey(hkey);
return error;
}
static int find_sysdir_in_registry(git_win32_path out)
{
if (mock_registry_set) {
if (mock_registry[0] == L'\0')
return GIT_ENOTFOUND;
wcscpy(out, mock_registry);
return 0;
}
if (lookup_registry_key(out, HKEY_CURRENT_USER, REG_GITFORWINDOWS_KEY, L"InstallLocation") == 0 ||
lookup_registry_key(out, HKEY_CURRENT_USER, REG_GITFORWINDOWS_KEY_WOW64, L"InstallLocation") == 0 ||
lookup_registry_key(out, HKEY_LOCAL_MACHINE, REG_GITFORWINDOWS_KEY, L"InstallLocation") == 0 ||
lookup_registry_key(out, HKEY_LOCAL_MACHINE, REG_GITFORWINDOWS_KEY_WOW64, L"InstallLocation") == 0)
return 0;
return GIT_ENOTFOUND;
}
static int find_sysdir_in_path(git_win32_path out)
{
size_t out_len;
if (git_win32_path_find_executable(out, L"git.exe") < 0 &&
git_win32_path_find_executable(out, L"git.cmd") < 0)
return GIT_ENOTFOUND;
out_len = wcslen(out);
/* Trim the file name */
if (out_len <= CONST_STRLEN(L"git.exe"))
return GIT_ENOTFOUND;
out_len -= CONST_STRLEN(L"git.exe");
if (out_len && out[out_len - 1] == L'\\')
out_len--;
/*
* Git for Windows usually places the command in a 'bin' or
* 'cmd' directory, trim that.
*/
if (out_len >= CONST_STRLEN(L"\\bin") &&
wcsncmp(&out[out_len - CONST_STRLEN(L"\\bin")], L"\\bin", CONST_STRLEN(L"\\bin")) == 0)
out_len -= CONST_STRLEN(L"\\bin");
else if (out_len >= CONST_STRLEN(L"\\cmd") &&
wcsncmp(&out[out_len - CONST_STRLEN(L"\\cmd")], L"\\cmd", CONST_STRLEN(L"\\cmd")) == 0)
out_len -= CONST_STRLEN(L"\\cmd");
if (!out_len)
return GIT_ENOTFOUND;
out[out_len] = L'\0';
return 0;
}
static int win32_find_existing_dirs(
git_str* out,
const wchar_t* tmpl[])
{
git_win32_path path16;
git_str buf = GIT_STR_INIT;
git_str_clear(out);
for (; *tmpl != NULL; tmpl++) {
if (!git_win32__expand_path(path16, *tmpl) &&
path16[0] != L'%' &&
!_waccess(path16, F_OK)) {
win32_path_to_8(&buf, path16);
if (buf.size)
git_str_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr);
}
}
git_str_dispose(&buf);
return (git_str_oom(out) ? -1 : 0);
}
static int append_subdir(git_str *out, git_str *path, const char *subdir)
{
static const char* architecture_roots[] = {
"",
"mingw64",
"mingw32",
NULL
};
const char **root;
size_t orig_path_len = path->size;
for (root = architecture_roots; *root; root++) {
if ((*root[0] && git_str_joinpath(path, path->ptr, *root) < 0) ||
git_str_joinpath(path, path->ptr, subdir) < 0)
return -1;
if (git_fs_path_exists(path->ptr) &&
git_str_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, path->ptr) < 0)
return -1;
git_str_truncate(path, orig_path_len);
}
return 0;
}
int git_win32__find_system_dirs(git_str *out, const char *subdir)
{
git_win32_path pathdir, regdir;
git_str path8 = GIT_STR_INIT;
bool has_pathdir, has_regdir;
int error;
has_pathdir = (find_sysdir_in_path(pathdir) == 0);
has_regdir = (find_sysdir_in_registry(regdir) == 0);
if (!has_pathdir && !has_regdir)
return 0;
/*
* Usually the git in the path is the same git in the registry,
* in this case there's no need to duplicate the paths.
*/
if (has_pathdir && has_regdir && wcscmp(pathdir, regdir) == 0)
has_regdir = false;
if (has_pathdir) {
if ((error = win32_path_to_8(&path8, pathdir)) < 0 ||
(error = append_subdir(out, &path8, subdir)) < 0)
goto done;
}
if (has_regdir) {
if ((error = win32_path_to_8(&path8, regdir)) < 0 ||
(error = append_subdir(out, &path8, subdir)) < 0)
goto done;
}
done:
git_str_dispose(&path8);
return error;
}
int git_win32__find_global_dirs(git_str *out)
{
static const wchar_t *global_tmpls[4] = {
L"%HOME%\\",
L"%HOMEDRIVE%%HOMEPATH%\\",
L"%USERPROFILE%\\",
NULL,
};
return win32_find_existing_dirs(out, global_tmpls);
}
int git_win32__find_xdg_dirs(git_str *out)
{
static const wchar_t *global_tmpls[7] = {
L"%XDG_CONFIG_HOME%\\git",
L"%APPDATA%\\git",
L"%LOCALAPPDATA%\\git",
L"%HOME%\\.config\\git",
L"%HOMEDRIVE%%HOMEPATH%\\.config\\git",
L"%USERPROFILE%\\.config\\git",
NULL,
};
return win32_find_existing_dirs(out, global_tmpls);
}
int git_win32__find_programdata_dirs(git_str *out)
{
static const wchar_t *programdata_tmpls[2] = {
L"%PROGRAMDATA%\\Git",
NULL,
};
return win32_find_existing_dirs(out, programdata_tmpls);
}
| libgit2-main | src/util/win32/findfile.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#include "../posix.h"
#include "../futils.h"
#include "fs_path.h"
#include "path_w32.h"
#include "utf-conv.h"
#include "reparse.h"
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <ws2tcpip.h>
#ifndef FILE_NAME_NORMALIZED
# define FILE_NAME_NORMALIZED 0
#endif
#ifndef IO_REPARSE_TAG_SYMLINK
#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
#endif
#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
# define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x02
#endif
#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
# define SYMBOLIC_LINK_FLAG_DIRECTORY 0x01
#endif
/* Allowable mode bits on Win32. Using mode bits that are not supported on
* Win32 (eg S_IRWXU) is generally ignored, but Wine warns loudly about it
* so we simply remove them.
*/
#define WIN32_MODE_MASK (_S_IREAD | _S_IWRITE)
unsigned long git_win32__createfile_sharemode =
FILE_SHARE_READ | FILE_SHARE_WRITE;
int git_win32__retries = 10;
GIT_INLINE(void) set_errno(void)
{
switch (GetLastError()) {
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_INVALID_DRIVE:
case ERROR_NO_MORE_FILES:
case ERROR_BAD_NETPATH:
case ERROR_BAD_NET_NAME:
case ERROR_BAD_PATHNAME:
case ERROR_FILENAME_EXCED_RANGE:
errno = ENOENT;
break;
case ERROR_BAD_ENVIRONMENT:
errno = E2BIG;
break;
case ERROR_BAD_FORMAT:
case ERROR_INVALID_STARTING_CODESEG:
case ERROR_INVALID_STACKSEG:
case ERROR_INVALID_MODULETYPE:
case ERROR_INVALID_EXE_SIGNATURE:
case ERROR_EXE_MARKED_INVALID:
case ERROR_BAD_EXE_FORMAT:
case ERROR_ITERATED_DATA_EXCEEDS_64k:
case ERROR_INVALID_MINALLOCSIZE:
case ERROR_DYNLINK_FROM_INVALID_RING:
case ERROR_IOPL_NOT_ENABLED:
case ERROR_INVALID_SEGDPL:
case ERROR_AUTODATASEG_EXCEEDS_64k:
case ERROR_RING2SEG_MUST_BE_MOVABLE:
case ERROR_RELOC_CHAIN_XEEDS_SEGLIM:
case ERROR_INFLOOP_IN_RELOC_CHAIN:
errno = ENOEXEC;
break;
case ERROR_INVALID_HANDLE:
case ERROR_INVALID_TARGET_HANDLE:
case ERROR_DIRECT_ACCESS_HANDLE:
errno = EBADF;
break;
case ERROR_WAIT_NO_CHILDREN:
case ERROR_CHILD_NOT_COMPLETE:
errno = ECHILD;
break;
case ERROR_NO_PROC_SLOTS:
case ERROR_MAX_THRDS_REACHED:
case ERROR_NESTING_NOT_ALLOWED:
errno = EAGAIN;
break;
case ERROR_ARENA_TRASHED:
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_INVALID_BLOCK:
case ERROR_NOT_ENOUGH_QUOTA:
errno = ENOMEM;
break;
case ERROR_ACCESS_DENIED:
case ERROR_CURRENT_DIRECTORY:
case ERROR_WRITE_PROTECT:
case ERROR_BAD_UNIT:
case ERROR_NOT_READY:
case ERROR_BAD_COMMAND:
case ERROR_CRC:
case ERROR_BAD_LENGTH:
case ERROR_SEEK:
case ERROR_NOT_DOS_DISK:
case ERROR_SECTOR_NOT_FOUND:
case ERROR_OUT_OF_PAPER:
case ERROR_WRITE_FAULT:
case ERROR_READ_FAULT:
case ERROR_GEN_FAILURE:
case ERROR_SHARING_VIOLATION:
case ERROR_LOCK_VIOLATION:
case ERROR_WRONG_DISK:
case ERROR_SHARING_BUFFER_EXCEEDED:
case ERROR_NETWORK_ACCESS_DENIED:
case ERROR_CANNOT_MAKE:
case ERROR_FAIL_I24:
case ERROR_DRIVE_LOCKED:
case ERROR_SEEK_ON_DEVICE:
case ERROR_NOT_LOCKED:
case ERROR_LOCK_FAILED:
errno = EACCES;
break;
case ERROR_FILE_EXISTS:
case ERROR_ALREADY_EXISTS:
errno = EEXIST;
break;
case ERROR_NOT_SAME_DEVICE:
errno = EXDEV;
break;
case ERROR_INVALID_FUNCTION:
case ERROR_INVALID_ACCESS:
case ERROR_INVALID_DATA:
case ERROR_INVALID_PARAMETER:
case ERROR_NEGATIVE_SEEK:
errno = EINVAL;
break;
case ERROR_TOO_MANY_OPEN_FILES:
errno = EMFILE;
break;
case ERROR_DISK_FULL:
errno = ENOSPC;
break;
case ERROR_BROKEN_PIPE:
errno = EPIPE;
break;
case ERROR_DIR_NOT_EMPTY:
errno = ENOTEMPTY;
break;
default:
errno = EINVAL;
}
}
GIT_INLINE(bool) last_error_retryable(void)
{
int os_error = GetLastError();
return (os_error == ERROR_SHARING_VIOLATION ||
os_error == ERROR_ACCESS_DENIED);
}
#define do_with_retries(fn, remediation) \
do { \
int __retry, __ret; \
for (__retry = git_win32__retries; __retry; __retry--) { \
if ((__ret = (fn)) != GIT_RETRY) \
return __ret; \
if (__retry > 1 && (__ret = (remediation)) != 0) { \
if (__ret == GIT_RETRY) \
continue; \
return __ret; \
} \
Sleep(5); \
} \
return -1; \
} while (0) \
static int ensure_writable(wchar_t *path)
{
DWORD attrs;
if ((attrs = GetFileAttributesW(path)) == INVALID_FILE_ATTRIBUTES)
goto on_error;
if ((attrs & FILE_ATTRIBUTE_READONLY) == 0)
return 0;
if (!SetFileAttributesW(path, (attrs & ~FILE_ATTRIBUTE_READONLY)))
goto on_error;
return GIT_RETRY;
on_error:
set_errno();
return -1;
}
/**
* Truncate or extend file.
*
* We now take a "git_off_t" rather than "long" because
* files may be longer than 2Gb.
*/
int p_ftruncate(int fd, off64_t size)
{
if (size < 0) {
errno = EINVAL;
return -1;
}
#if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
return ((_chsize_s(fd, size) == 0) ? 0 : -1);
#else
/* TODO MINGW32 Find a replacement for _chsize() that handles big files. */
if (size > INT32_MAX) {
errno = EFBIG;
return -1;
}
return _chsize(fd, (long)size);
#endif
}
int p_mkdir(const char *path, mode_t mode)
{
git_win32_path buf;
GIT_UNUSED(mode);
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
return _wmkdir(buf);
}
int p_link(const char *old, const char *new)
{
GIT_UNUSED(old);
GIT_UNUSED(new);
errno = ENOSYS;
return -1;
}
GIT_INLINE(int) unlink_once(const wchar_t *path)
{
DWORD error;
if (DeleteFileW(path))
return 0;
if ((error = GetLastError()) == ERROR_ACCESS_DENIED) {
WIN32_FILE_ATTRIBUTE_DATA fdata;
if (!GetFileAttributesExW(path, GetFileExInfoStandard, &fdata) ||
!(fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
!(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
goto out;
if (RemoveDirectoryW(path))
return 0;
}
out:
SetLastError(error);
if (last_error_retryable())
return GIT_RETRY;
set_errno();
return -1;
}
int p_unlink(const char *path)
{
git_win32_path wpath;
if (git_win32_path_from_utf8(wpath, path) < 0)
return -1;
do_with_retries(unlink_once(wpath), ensure_writable(wpath));
}
int p_fsync(int fd)
{
HANDLE fh = (HANDLE)_get_osfhandle(fd);
p_fsync__cnt++;
if (fh == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
if (!FlushFileBuffers(fh)) {
DWORD code = GetLastError();
if (code == ERROR_INVALID_HANDLE)
errno = EINVAL;
else
errno = EIO;
return -1;
}
return 0;
}
#define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\')
static int lstat_w(
wchar_t *path,
struct stat *buf,
bool posix_enotdir)
{
WIN32_FILE_ATTRIBUTE_DATA fdata;
if (GetFileAttributesExW(path, GetFileExInfoStandard, &fdata)) {
if (!buf)
return 0;
return git_win32__file_attribute_to_stat(buf, &fdata, path);
}
switch (GetLastError()) {
case ERROR_ACCESS_DENIED:
errno = EACCES;
break;
default:
errno = ENOENT;
break;
}
/* To match POSIX behavior, set ENOTDIR when any of the folders in the
* file path is a regular file, otherwise set ENOENT.
*/
if (errno == ENOENT && posix_enotdir) {
size_t path_len = wcslen(path);
/* scan up path until we find an existing item */
while (1) {
DWORD attrs;
/* remove last directory component */
for (path_len--; path_len > 0 && !WIN32_IS_WSEP(path[path_len]); path_len--);
if (path_len <= 0)
break;
path[path_len] = L'\0';
attrs = GetFileAttributesW(path);
if (attrs != INVALID_FILE_ATTRIBUTES) {
if (!(attrs & FILE_ATTRIBUTE_DIRECTORY))
errno = ENOTDIR;
break;
}
}
}
return -1;
}
static int do_lstat(const char *path, struct stat *buf, bool posixly_correct)
{
git_win32_path path_w;
int len;
if ((len = git_win32_path_from_utf8(path_w, path)) < 0)
return -1;
git_win32_path_trim_end(path_w, len);
return lstat_w(path_w, buf, posixly_correct);
}
int p_lstat(const char *filename, struct stat *buf)
{
return do_lstat(filename, buf, false);
}
int p_lstat_posixly(const char *filename, struct stat *buf)
{
return do_lstat(filename, buf, true);
}
int p_readlink(const char *path, char *buf, size_t bufsiz)
{
git_win32_path path_w, target_w;
git_win32_utf8_path target;
int len;
/* readlink(2) does not NULL-terminate the string written
* to the target buffer. Furthermore, the target buffer need
* not be large enough to hold the entire result. A truncated
* result should be written in this case. Since this truncation
* could occur in the middle of the encoding of a code point,
* we need to buffer the result on the stack. */
if (git_win32_path_from_utf8(path_w, path) < 0 ||
git_win32_path_readlink_w(target_w, path_w) < 0 ||
(len = git_win32_path_to_utf8(target, target_w)) < 0)
return -1;
bufsiz = min((size_t)len, bufsiz);
memcpy(buf, target, bufsiz);
return (int)bufsiz;
}
static bool target_is_dir(const char *target, const char *path)
{
git_str resolved = GIT_STR_INIT;
git_win32_path resolved_w;
bool isdir = true;
if (git_fs_path_is_absolute(target))
git_win32_path_from_utf8(resolved_w, target);
else if (git_fs_path_dirname_r(&resolved, path) < 0 ||
git_fs_path_apply_relative(&resolved, target) < 0 ||
git_win32_path_from_utf8(resolved_w, resolved.ptr) < 0)
goto out;
isdir = GetFileAttributesW(resolved_w) & FILE_ATTRIBUTE_DIRECTORY;
out:
git_str_dispose(&resolved);
return isdir;
}
int p_symlink(const char *target, const char *path)
{
git_win32_path target_w, path_w;
DWORD dwFlags;
/*
* Convert both target and path to Windows-style paths. Note that we do
* not want to use `git_win32_path_from_utf8` for converting the target,
* as that function will automatically pre-pend the current working
* directory in case the path is not absolute. As Git will instead use
* relative symlinks, this is not something we want.
*/
if (git_win32_path_from_utf8(path_w, path) < 0 ||
git_win32_path_relative_from_utf8(target_w, target) < 0)
return -1;
dwFlags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
if (target_is_dir(target, path))
dwFlags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
if (!CreateSymbolicLinkW(path_w, target_w, dwFlags))
return -1;
return 0;
}
struct open_opts {
DWORD access;
DWORD sharing;
SECURITY_ATTRIBUTES security;
DWORD creation_disposition;
DWORD attributes;
int osf_flags;
};
GIT_INLINE(void) open_opts_from_posix(struct open_opts *opts, int flags, mode_t mode)
{
memset(opts, 0, sizeof(struct open_opts));
switch (flags & (O_WRONLY | O_RDWR)) {
case O_WRONLY:
opts->access = GENERIC_WRITE;
break;
case O_RDWR:
opts->access = GENERIC_READ | GENERIC_WRITE;
break;
default:
opts->access = GENERIC_READ;
break;
}
opts->sharing = (DWORD)git_win32__createfile_sharemode;
switch (flags & (O_CREAT | O_TRUNC | O_EXCL)) {
case O_CREAT | O_EXCL:
case O_CREAT | O_TRUNC | O_EXCL:
opts->creation_disposition = CREATE_NEW;
break;
case O_CREAT | O_TRUNC:
opts->creation_disposition = CREATE_ALWAYS;
break;
case O_TRUNC:
opts->creation_disposition = TRUNCATE_EXISTING;
break;
case O_CREAT:
opts->creation_disposition = OPEN_ALWAYS;
break;
default:
opts->creation_disposition = OPEN_EXISTING;
break;
}
opts->attributes = ((flags & O_CREAT) && !(mode & S_IWRITE)) ?
FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL;
opts->osf_flags = flags & (O_RDONLY | O_APPEND);
opts->security.nLength = sizeof(SECURITY_ATTRIBUTES);
opts->security.lpSecurityDescriptor = NULL;
opts->security.bInheritHandle = 0;
}
GIT_INLINE(int) open_once(
const wchar_t *path,
struct open_opts *opts)
{
int fd;
HANDLE handle = CreateFileW(path, opts->access, opts->sharing,
&opts->security, opts->creation_disposition, opts->attributes, 0);
if (handle == INVALID_HANDLE_VALUE) {
if (last_error_retryable())
return GIT_RETRY;
set_errno();
return -1;
}
if ((fd = _open_osfhandle((intptr_t)handle, opts->osf_flags)) < 0)
CloseHandle(handle);
return fd;
}
int p_open(const char *path, int flags, ...)
{
git_win32_path wpath;
mode_t mode = 0;
struct open_opts opts = {0};
#ifdef GIT_DEBUG_STRICT_OPEN
if (strstr(path, "//") != NULL) {
errno = EACCES;
return -1;
}
#endif
if (git_win32_path_from_utf8(wpath, path) < 0)
return -1;
if (flags & O_CREAT) {
va_list arg_list;
va_start(arg_list, flags);
mode = (mode_t)va_arg(arg_list, int);
va_end(arg_list);
}
open_opts_from_posix(&opts, flags, mode);
do_with_retries(
open_once(wpath, &opts),
0);
}
int p_creat(const char *path, mode_t mode)
{
return p_open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
}
int p_utimes(const char *path, const struct p_timeval times[2])
{
git_win32_path wpath;
int fd, error;
DWORD attrs_orig, attrs_new = 0;
struct open_opts opts = { 0 };
if (git_win32_path_from_utf8(wpath, path) < 0)
return -1;
attrs_orig = GetFileAttributesW(wpath);
if (attrs_orig & FILE_ATTRIBUTE_READONLY) {
attrs_new = attrs_orig & ~FILE_ATTRIBUTE_READONLY;
if (!SetFileAttributesW(wpath, attrs_new)) {
git_error_set(GIT_ERROR_OS, "failed to set attributes");
return -1;
}
}
open_opts_from_posix(&opts, O_RDWR, 0);
if ((fd = open_once(wpath, &opts)) < 0) {
error = -1;
goto done;
}
error = p_futimes(fd, times);
close(fd);
done:
if (attrs_orig != attrs_new) {
DWORD os_error = GetLastError();
SetFileAttributesW(wpath, attrs_orig);
SetLastError(os_error);
}
return error;
}
int p_futimes(int fd, const struct p_timeval times[2])
{
HANDLE handle;
FILETIME atime = { 0 }, mtime = { 0 };
if (times == NULL) {
SYSTEMTIME st;
GetSystemTime(&st);
SystemTimeToFileTime(&st, &atime);
SystemTimeToFileTime(&st, &mtime);
}
else {
git_win32__timeval_to_filetime(&atime, times[0]);
git_win32__timeval_to_filetime(&mtime, times[1]);
}
if ((handle = (HANDLE)_get_osfhandle(fd)) == INVALID_HANDLE_VALUE)
return -1;
if (SetFileTime(handle, NULL, &atime, &mtime) == 0)
return -1;
return 0;
}
int p_getcwd(char *buffer_out, size_t size)
{
git_win32_path buf;
wchar_t *cwd = _wgetcwd(buf, GIT_WIN_PATH_UTF16);
if (!cwd)
return -1;
git_win32_path_remove_namespace(cwd, wcslen(cwd));
/* Convert the working directory back to UTF-8 */
if (git__utf16_to_8(buffer_out, size, cwd) < 0) {
DWORD code = GetLastError();
if (code == ERROR_INSUFFICIENT_BUFFER)
errno = ERANGE;
else
errno = EINVAL;
return -1;
}
git_fs_path_mkposix(buffer_out);
return 0;
}
static int getfinalpath_w(
git_win32_path dest,
const wchar_t *path)
{
HANDLE hFile;
DWORD dwChars;
/* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not
* specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the
* target of the link. */
hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == hFile)
return -1;
/* Call GetFinalPathNameByHandle */
dwChars = GetFinalPathNameByHandleW(hFile, dest, GIT_WIN_PATH_UTF16, FILE_NAME_NORMALIZED);
CloseHandle(hFile);
if (!dwChars || dwChars >= GIT_WIN_PATH_UTF16)
return -1;
/* The path may be delivered to us with a namespace prefix; remove */
return (int)git_win32_path_remove_namespace(dest, dwChars);
}
static int follow_and_lstat_link(git_win32_path path, struct stat *buf)
{
git_win32_path target_w;
if (getfinalpath_w(target_w, path) < 0)
return -1;
return lstat_w(target_w, buf, false);
}
int p_fstat(int fd, struct stat *buf)
{
BY_HANDLE_FILE_INFORMATION fhInfo;
HANDLE fh = (HANDLE)_get_osfhandle(fd);
if (fh == INVALID_HANDLE_VALUE ||
!GetFileInformationByHandle(fh, &fhInfo)) {
errno = EBADF;
return -1;
}
git_win32__file_information_to_stat(buf, &fhInfo);
return 0;
}
int p_stat(const char *path, struct stat *buf)
{
git_win32_path path_w;
int len;
if ((len = git_win32_path_from_utf8(path_w, path)) < 0 ||
lstat_w(path_w, buf, false) < 0)
return -1;
/* The item is a symbolic link or mount point. No need to iterate
* to follow multiple links; use GetFinalPathNameFromHandle. */
if (S_ISLNK(buf->st_mode))
return follow_and_lstat_link(path_w, buf);
return 0;
}
int p_chdir(const char *path)
{
git_win32_path buf;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
return _wchdir(buf);
}
int p_chmod(const char *path, mode_t mode)
{
git_win32_path buf;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
return _wchmod(buf, mode);
}
int p_rmdir(const char *path)
{
git_win32_path buf;
int error;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
error = _wrmdir(buf);
if (error == -1) {
switch (GetLastError()) {
/* _wrmdir() is documented to return EACCES if "A program has an open
* handle to the directory." This sounds like what everybody else calls
* EBUSY. Let's convert appropriate error codes.
*/
case ERROR_SHARING_VIOLATION:
errno = EBUSY;
break;
/* This error can be returned when trying to rmdir an extant file. */
case ERROR_DIRECTORY:
errno = ENOTDIR;
break;
}
}
return error;
}
char *p_realpath(const char *orig_path, char *buffer)
{
git_win32_path orig_path_w, buffer_w;
if (git_win32_path_from_utf8(orig_path_w, orig_path) < 0)
return NULL;
/* Note that if the path provided is a relative path, then the current directory
* is used to resolve the path -- which is a concurrency issue because the current
* directory is a process-wide variable. */
if (!GetFullPathNameW(orig_path_w, GIT_WIN_PATH_UTF16, buffer_w, NULL)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
errno = ENAMETOOLONG;
else
errno = EINVAL;
return NULL;
}
/* The path must exist. */
if (GetFileAttributesW(buffer_w) == INVALID_FILE_ATTRIBUTES) {
errno = ENOENT;
return NULL;
}
if (!buffer && !(buffer = git__malloc(GIT_WIN_PATH_UTF8))) {
errno = ENOMEM;
return NULL;
}
/* Convert the path to UTF-8. If the caller provided a buffer, then it
* is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't,
* then we may overflow. */
if (git_win32_path_to_utf8(buffer, buffer_w) < 0)
return NULL;
git_fs_path_mkposix(buffer);
return buffer;
}
int p_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr)
{
#if defined(_MSC_VER)
int len;
if (count == 0)
return _vscprintf(format, argptr);
#if _MSC_VER >= 1500
len = _vsnprintf_s(buffer, count, _TRUNCATE, format, argptr);
#else
len = _vsnprintf(buffer, count, format, argptr);
#endif
if (len < 0)
return _vscprintf(format, argptr);
return len;
#else /* MinGW */
return vsnprintf(buffer, count, format, argptr);
#endif
}
int p_snprintf(char *buffer, size_t count, const char *format, ...)
{
va_list va;
int r;
va_start(va, format);
r = p_vsnprintf(buffer, count, format, va);
va_end(va);
return r;
}
int p_access(const char *path, mode_t mode)
{
git_win32_path buf;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
return _waccess(buf, mode & WIN32_MODE_MASK);
}
GIT_INLINE(int) rename_once(const wchar_t *from, const wchar_t *to)
{
if (MoveFileExW(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
return 0;
if (last_error_retryable())
return GIT_RETRY;
set_errno();
return -1;
}
int p_rename(const char *from, const char *to)
{
git_win32_path wfrom, wto;
if (git_win32_path_from_utf8(wfrom, from) < 0 ||
git_win32_path_from_utf8(wto, to) < 0)
return -1;
do_with_retries(rename_once(wfrom, wto), ensure_writable(wto));
}
int p_recv(GIT_SOCKET socket, void *buffer, size_t length, int flags)
{
if ((size_t)((int)length) != length)
return -1; /* git_error_set will be done by caller */
return recv(socket, buffer, (int)length, flags);
}
int p_send(GIT_SOCKET socket, const void *buffer, size_t length, int flags)
{
if ((size_t)((int)length) != length)
return -1; /* git_error_set will be done by caller */
return send(socket, buffer, (int)length, flags);
}
/**
* Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html
* On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that
*/
struct tm *
p_localtime_r (const time_t *timer, struct tm *result)
{
struct tm *local_result;
local_result = localtime (timer);
if (local_result == NULL || result == NULL)
return NULL;
memcpy (result, local_result, sizeof (struct tm));
return result;
}
struct tm *
p_gmtime_r (const time_t *timer, struct tm *result)
{
struct tm *local_result;
local_result = gmtime (timer);
if (local_result == NULL || result == NULL)
return NULL;
memcpy (result, local_result, sizeof (struct tm));
return result;
}
int p_inet_pton(int af, const char *src, void *dst)
{
struct sockaddr_storage sin;
void *addr;
int sin_len = sizeof(struct sockaddr_storage), addr_len;
int error = 0;
if (af == AF_INET) {
addr = &((struct sockaddr_in *)&sin)->sin_addr;
addr_len = sizeof(struct in_addr);
} else if (af == AF_INET6) {
addr = &((struct sockaddr_in6 *)&sin)->sin6_addr;
addr_len = sizeof(struct in6_addr);
} else {
errno = EAFNOSUPPORT;
return -1;
}
if ((error = WSAStringToAddressA((LPSTR)src, af, NULL, (LPSOCKADDR)&sin, &sin_len)) == 0) {
memcpy(dst, addr, addr_len);
return 1;
}
switch(WSAGetLastError()) {
case WSAEINVAL:
return 0;
case WSAEFAULT:
errno = ENOSPC;
return -1;
case WSA_NOT_ENOUGH_MEMORY:
errno = ENOMEM;
return -1;
}
errno = EINVAL;
return -1;
}
ssize_t p_pread(int fd, void *data, size_t size, off64_t offset)
{
HANDLE fh;
DWORD rsize = 0;
OVERLAPPED ov = {0};
LARGE_INTEGER pos = {0};
off64_t final_offset = 0;
/* Fail if the final offset would have overflowed to match POSIX semantics. */
if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) {
errno = EINVAL;
return -1;
}
/*
* Truncate large writes to the maximum allowable size: the caller
* needs to always call this in a loop anyways.
*/
if (size > INT32_MAX) {
size = INT32_MAX;
}
pos.QuadPart = offset;
ov.Offset = pos.LowPart;
ov.OffsetHigh = pos.HighPart;
fh = (HANDLE)_get_osfhandle(fd);
if (ReadFile(fh, data, (DWORD)size, &rsize, &ov)) {
return (ssize_t)rsize;
}
set_errno();
return -1;
}
ssize_t p_pwrite(int fd, const void *data, size_t size, off64_t offset)
{
HANDLE fh;
DWORD wsize = 0;
OVERLAPPED ov = {0};
LARGE_INTEGER pos = {0};
off64_t final_offset = 0;
/* Fail if the final offset would have overflowed to match POSIX semantics. */
if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) {
errno = EINVAL;
return -1;
}
/*
* Truncate large writes to the maximum allowable size: the caller
* needs to always call this in a loop anyways.
*/
if (size > INT32_MAX) {
size = INT32_MAX;
}
pos.QuadPart = offset;
ov.Offset = pos.LowPart;
ov.OffsetHigh = pos.HighPart;
fh = (HANDLE)_get_osfhandle(fd);
if (WriteFile(fh, data, (DWORD)size, &wsize, &ov)) {
return (ssize_t)wsize;
}
set_errno();
return -1;
}
| libgit2-main | src/util/win32/posix_w32.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "w32_leakcheck.h"
#if defined(GIT_WIN32_LEAKCHECK)
#include "Windows.h"
#include "Dbghelp.h"
#include "win32/posix.h"
#include "hash.h"
#include "runtime.h"
/* Stack frames (for stack tracing, below) */
static bool g_win32_stack_initialized = false;
static HANDLE g_win32_stack_process = INVALID_HANDLE_VALUE;
static git_win32_leakcheck_stack_aux_cb_alloc g_aux_cb_alloc = NULL;
static git_win32_leakcheck_stack_aux_cb_lookup g_aux_cb_lookup = NULL;
int git_win32_leakcheck_stack_set_aux_cb(
git_win32_leakcheck_stack_aux_cb_alloc cb_alloc,
git_win32_leakcheck_stack_aux_cb_lookup cb_lookup)
{
g_aux_cb_alloc = cb_alloc;
g_aux_cb_lookup = cb_lookup;
return 0;
}
/**
* Load symbol table data. This should be done in the primary
* thread at startup (under a lock if there are other threads
* active).
*/
void git_win32_leakcheck_stack_init(void)
{
if (!g_win32_stack_initialized) {
g_win32_stack_process = GetCurrentProcess();
SymSetOptions(SYMOPT_LOAD_LINES);
SymInitialize(g_win32_stack_process, NULL, TRUE);
g_win32_stack_initialized = true;
}
}
/**
* Cleanup symbol table data. This should be done in the
* primary thead at shutdown (under a lock if there are other
* threads active).
*/
void git_win32_leakcheck_stack_cleanup(void)
{
if (g_win32_stack_initialized) {
SymCleanup(g_win32_stack_process);
g_win32_stack_process = INVALID_HANDLE_VALUE;
g_win32_stack_initialized = false;
}
}
int git_win32_leakcheck_stack_capture(git_win32_leakcheck_stack_raw_data *pdata, int skip)
{
if (!g_win32_stack_initialized) {
git_error_set(GIT_ERROR_INVALID, "git_win32_stack not initialized.");
return GIT_ERROR;
}
memset(pdata, 0, sizeof(*pdata));
pdata->nr_frames = RtlCaptureStackBackTrace(
skip+1, GIT_WIN32_LEAKCHECK_STACK_MAX_FRAMES, pdata->frames, NULL);
/* If an "aux" data provider was registered, ask it to capture
* whatever data it needs and give us an "aux_id" to it so that
* we can refer to it later when reporting.
*/
if (g_aux_cb_alloc)
(g_aux_cb_alloc)(&pdata->aux_id);
return 0;
}
int git_win32_leakcheck_stack_compare(
git_win32_leakcheck_stack_raw_data *d1,
git_win32_leakcheck_stack_raw_data *d2)
{
return memcmp(d1, d2, sizeof(*d1));
}
int git_win32_leakcheck_stack_format(
char *pbuf, size_t buf_len,
const git_win32_leakcheck_stack_raw_data *pdata,
const char *prefix, const char *suffix)
{
#define MY_MAX_FILENAME 255
/* SYMBOL_INFO has char FileName[1] at the end. The docs say to
* to malloc it with extra space for your desired max filename.
*/
struct {
SYMBOL_INFO symbol;
char extra[MY_MAX_FILENAME + 1];
} s;
IMAGEHLP_LINE64 line;
size_t buf_used = 0;
unsigned int k;
char detail[MY_MAX_FILENAME * 2]; /* filename plus space for function name and formatting */
size_t detail_len;
if (!g_win32_stack_initialized) {
git_error_set(GIT_ERROR_INVALID, "git_win32_stack not initialized.");
return GIT_ERROR;
}
if (!prefix)
prefix = "\t";
if (!suffix)
suffix = "\n";
memset(pbuf, 0, buf_len);
memset(&s, 0, sizeof(s));
s.symbol.MaxNameLen = MY_MAX_FILENAME;
s.symbol.SizeOfStruct = sizeof(SYMBOL_INFO);
memset(&line, 0, sizeof(line));
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
for (k=0; k < pdata->nr_frames; k++) {
DWORD64 frame_k = (DWORD64)pdata->frames[k];
DWORD dwUnused;
if (SymFromAddr(g_win32_stack_process, frame_k, 0, &s.symbol) &&
SymGetLineFromAddr64(g_win32_stack_process, frame_k, &dwUnused, &line)) {
const char *pslash;
const char *pfile;
pslash = strrchr(line.FileName, '\\');
pfile = ((pslash) ? (pslash+1) : line.FileName);
p_snprintf(detail, sizeof(detail), "%s%s:%d> %s%s",
prefix, pfile, line.LineNumber, s.symbol.Name, suffix);
} else {
/* This happens when we cross into another module.
* For example, in CLAR tests, this is typically
* the CRT startup code. Just print an unknown
* frame and continue.
*/
p_snprintf(detail, sizeof(detail), "%s??%s", prefix, suffix);
}
detail_len = strlen(detail);
if (buf_len < (buf_used + detail_len + 1)) {
/* we don't have room for this frame in the buffer, so just stop. */
break;
}
memcpy(&pbuf[buf_used], detail, detail_len);
buf_used += detail_len;
}
/* "aux_id" 0 is reserved to mean no aux data. This is needed to handle
* allocs that occur before the aux callbacks were registered.
*/
if (pdata->aux_id > 0) {
p_snprintf(detail, sizeof(detail), "%saux_id: %d%s",
prefix, pdata->aux_id, suffix);
detail_len = strlen(detail);
if ((buf_used + detail_len + 1) < buf_len) {
memcpy(&pbuf[buf_used], detail, detail_len);
buf_used += detail_len;
}
/* If an "aux" data provider is still registered, ask it to append its detailed
* data to the end of ours using the "aux_id" it gave us when this de-duped
* item was created.
*/
if (g_aux_cb_lookup)
(g_aux_cb_lookup)(pdata->aux_id, &pbuf[buf_used], (buf_len - buf_used - 1));
}
return GIT_OK;
}
int git_win32_leakcheck_stack(
char * pbuf, size_t buf_len,
int skip,
const char *prefix, const char *suffix)
{
git_win32_leakcheck_stack_raw_data data;
int error;
if ((error = git_win32_leakcheck_stack_capture(&data, skip)) < 0)
return error;
if ((error = git_win32_leakcheck_stack_format(pbuf, buf_len, &data, prefix, suffix)) < 0)
return error;
return 0;
}
/* Stack tracing */
#define STACKTRACE_UID_LEN (15)
/**
* The stacktrace of an allocation can be distilled
* to a unique id based upon the stackframe pointers
* and ignoring any size arguments. We will use these
* UIDs as the (char const*) __FILE__ argument we
* give to the CRT malloc routines.
*/
typedef struct {
char uid[STACKTRACE_UID_LEN + 1];
} git_win32_leakcheck_stacktrace_uid;
/**
* All mallocs with the same stacktrace will be de-duped
* and aggregated into this row.
*/
typedef struct {
git_win32_leakcheck_stacktrace_uid uid; /* must be first */
git_win32_leakcheck_stack_raw_data raw_data;
unsigned int count_allocs; /* times this alloc signature seen since init */
unsigned int count_allocs_at_last_checkpoint; /* times since last mark */
unsigned int transient_count_leaks; /* sum of leaks */
} git_win32_leakcheck_stacktrace_row;
static CRITICAL_SECTION g_crtdbg_stacktrace_cs;
/**
* CRTDBG memory leak tracking takes a "char const * const file_name"
* and stores the pointer in the heap data (instead of allocing a copy
* for itself). Normally, this is not a problem, since we usually pass
* in __FILE__. But I'm going to lie to it and pass in the address of
* the UID in place of the file_name. Also, I do not want to alloc the
* stacktrace data (because we are called from inside our alloc routines).
* Therefore, I'm creating a very large static pool array to store row
* data. This also eliminates the temptation to realloc it (and move the
* UID pointers).
*
* And to efficiently look for duplicates we need an index on the rows
* so we can bsearch it. Again, without mallocing.
*
* If we observe more than MY_ROW_LIMIT unique malloc signatures, we
* fall through and use the traditional __FILE__ processing and don't
* try to de-dup them. If your testing hits this limit, just increase
* it and try again.
*/
#define MY_ROW_LIMIT (2 * 1024 * 1024)
static git_win32_leakcheck_stacktrace_row g_cs_rows[MY_ROW_LIMIT];
static git_win32_leakcheck_stacktrace_row *g_cs_index[MY_ROW_LIMIT];
static unsigned int g_cs_end = MY_ROW_LIMIT;
static unsigned int g_cs_ins = 0; /* insertion point == unique allocs seen */
static unsigned int g_count_total_allocs = 0; /* number of allocs seen */
static unsigned int g_transient_count_total_leaks = 0; /* number of total leaks */
static unsigned int g_transient_count_dedup_leaks = 0; /* number of unique leaks */
static bool g_limit_reached = false; /* had allocs after we filled row table */
static unsigned int g_checkpoint_id = 0; /* to better label leak checkpoints */
static bool g_transient_leaks_since_mark = false; /* payload for hook */
/**
* Compare function for bsearch on g_cs_index table.
*/
static int row_cmp(const void *v1, const void *v2)
{
git_win32_leakcheck_stack_raw_data *d1 = (git_win32_leakcheck_stack_raw_data*)v1;
git_win32_leakcheck_stacktrace_row *r2 = (git_win32_leakcheck_stacktrace_row *)v2;
return (git_win32_leakcheck_stack_compare(d1, &r2->raw_data));
}
/**
* Unique insert the new data into the row and index tables.
* We have to sort by the stackframe data itself, not the uid.
*/
static git_win32_leakcheck_stacktrace_row * insert_unique(
const git_win32_leakcheck_stack_raw_data *pdata)
{
size_t pos;
if (git__bsearch(g_cs_index, g_cs_ins, pdata, row_cmp, &pos) < 0) {
/* Append new unique item to row table. */
memcpy(&g_cs_rows[g_cs_ins].raw_data, pdata, sizeof(*pdata));
sprintf(g_cs_rows[g_cs_ins].uid.uid, "##%08lx", g_cs_ins);
/* Insert pointer to it into the proper place in the index table. */
if (pos < g_cs_ins)
memmove(&g_cs_index[pos+1], &g_cs_index[pos], (g_cs_ins - pos)*sizeof(g_cs_index[0]));
g_cs_index[pos] = &g_cs_rows[g_cs_ins];
g_cs_ins++;
}
g_cs_index[pos]->count_allocs++;
return g_cs_index[pos];
}
/**
* Hook function to receive leak data from the CRT. (This includes
* both "<file_name>:(<line_number>)" data, but also each of the
* various headers and fields.
*
* Scan this for the special "##<pos>" UID forms that we substituted
* for the "<file_name>". Map <pos> back to the row data and
* increment its leak count.
*
* See https://msdn.microsoft.com/en-us/library/74kabxyx.aspx
*
* We suppress the actual crtdbg output.
*/
static int __cdecl report_hook(int nRptType, char *szMsg, int *retVal)
{
static int hook_result = TRUE; /* FALSE to get stock dump; TRUE to suppress. */
unsigned int pos;
*retVal = 0; /* do not invoke debugger */
if ((szMsg[0] != '#') || (szMsg[1] != '#'))
return hook_result;
if (sscanf(&szMsg[2], "%08lx", &pos) < 1)
return hook_result;
if (pos >= g_cs_ins)
return hook_result;
if (g_transient_leaks_since_mark) {
if (g_cs_rows[pos].count_allocs == g_cs_rows[pos].count_allocs_at_last_checkpoint)
return hook_result;
}
g_cs_rows[pos].transient_count_leaks++;
if (g_cs_rows[pos].transient_count_leaks == 1)
g_transient_count_dedup_leaks++;
g_transient_count_total_leaks++;
return hook_result;
}
/**
* Write leak data to all of the various places we need.
* We force the caller to sprintf() the message first
* because we want to avoid fprintf() because it allocs.
*/
static void my_output(const char *buf)
{
fwrite(buf, strlen(buf), 1, stderr);
OutputDebugString(buf);
}
/**
* For each row with leaks, dump a stacktrace for it.
*/
static void dump_summary(const char *label)
{
unsigned int k;
char buf[10 * 1024];
if (g_transient_count_total_leaks == 0)
return;
fflush(stdout);
fflush(stderr);
my_output("\n");
if (g_limit_reached) {
sprintf(buf,
"LEAK SUMMARY: de-dup row table[%d] filled. Increase MY_ROW_LIMIT.\n",
MY_ROW_LIMIT);
my_output(buf);
}
if (!label)
label = "";
if (g_transient_leaks_since_mark) {
sprintf(buf, "LEAK CHECKPOINT %d: leaks %d unique %d: %s\n",
g_checkpoint_id, g_transient_count_total_leaks, g_transient_count_dedup_leaks, label);
my_output(buf);
} else {
sprintf(buf, "LEAK SUMMARY: TOTAL leaks %d de-duped %d: %s\n",
g_transient_count_total_leaks, g_transient_count_dedup_leaks, label);
my_output(buf);
}
my_output("\n");
for (k = 0; k < g_cs_ins; k++) {
if (g_cs_rows[k].transient_count_leaks > 0) {
sprintf(buf, "LEAK: %s leaked %d of %d times:\n",
g_cs_rows[k].uid.uid,
g_cs_rows[k].transient_count_leaks,
g_cs_rows[k].count_allocs);
my_output(buf);
if (git_win32_leakcheck_stack_format(
buf, sizeof(buf), &g_cs_rows[k].raw_data,
NULL, NULL) >= 0) {
my_output(buf);
}
my_output("\n");
}
}
fflush(stderr);
}
/**
* Initialize our memory leak tracking and de-dup data structures.
* This should ONLY be called by git_libgit2_init().
*/
void git_win32_leakcheck_stacktrace_init(void)
{
InitializeCriticalSection(&g_crtdbg_stacktrace_cs);
EnterCriticalSection(&g_crtdbg_stacktrace_cs);
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
LeaveCriticalSection(&g_crtdbg_stacktrace_cs);
}
int git_win32_leakcheck_stacktrace_dump(
git_win32_leakcheck_stacktrace_options opt,
const char *label)
{
_CRT_REPORT_HOOK old;
unsigned int k;
int r = 0;
#define IS_BIT_SET(o,b) (((o) & (b)) != 0)
bool b_set_mark = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_SET_MARK);
bool b_leaks_since_mark = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK);
bool b_leaks_total = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL);
bool b_quiet = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET);
if (b_leaks_since_mark && b_leaks_total) {
git_error_set(GIT_ERROR_INVALID, "cannot combine LEAKS_SINCE_MARK and LEAKS_TOTAL.");
return GIT_ERROR;
}
if (!b_set_mark && !b_leaks_since_mark && !b_leaks_total) {
git_error_set(GIT_ERROR_INVALID, "nothing to do.");
return GIT_ERROR;
}
EnterCriticalSection(&g_crtdbg_stacktrace_cs);
if (b_leaks_since_mark || b_leaks_total) {
/* All variables with "transient" in the name are per-dump counters
* and reset before each dump. This lets us handle checkpoints.
*/
g_transient_count_total_leaks = 0;
g_transient_count_dedup_leaks = 0;
for (k = 0; k < g_cs_ins; k++) {
g_cs_rows[k].transient_count_leaks = 0;
}
}
g_transient_leaks_since_mark = b_leaks_since_mark;
old = _CrtSetReportHook(report_hook);
_CrtDumpMemoryLeaks();
_CrtSetReportHook(old);
if (b_leaks_since_mark || b_leaks_total) {
r = g_transient_count_dedup_leaks;
if (!b_quiet)
dump_summary(label);
}
if (b_set_mark) {
for (k = 0; k < g_cs_ins; k++) {
g_cs_rows[k].count_allocs_at_last_checkpoint = g_cs_rows[k].count_allocs;
}
g_checkpoint_id++;
}
LeaveCriticalSection(&g_crtdbg_stacktrace_cs);
return r;
}
/**
* Shutdown our memory leak tracking and dump summary data.
* This should ONLY be called by git_libgit2_shutdown().
*
* We explicitly call _CrtDumpMemoryLeaks() during here so
* that we can compute summary data for the leaks. We print
* the stacktrace of each unique leak.
*
* This cleanup does not happen if the app calls exit()
* without calling the libgit2 shutdown code.
*
* This info we print here is independent of any automatic
* reporting during exit() caused by _CRTDBG_LEAK_CHECK_DF.
* Set it in your app if you also want traditional reporting.
*/
void git_win32_leakcheck_stacktrace_cleanup(void)
{
/* At shutdown/cleanup, dump cumulative leak info
* with everything since startup. This might generate
* extra noise if the caller has been doing checkpoint
* dumps, but it might also eliminate some false
* positives for resources previously reported during
* checkpoints.
*/
git_win32_leakcheck_stacktrace_dump(
GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL,
"CLEANUP");
DeleteCriticalSection(&g_crtdbg_stacktrace_cs);
}
const char *git_win32_leakcheck_stacktrace(int skip, const char *file)
{
git_win32_leakcheck_stack_raw_data new_data;
git_win32_leakcheck_stacktrace_row *row;
const char * result = file;
if (git_win32_leakcheck_stack_capture(&new_data, skip+1) < 0)
return result;
EnterCriticalSection(&g_crtdbg_stacktrace_cs);
if (g_cs_ins < g_cs_end) {
row = insert_unique(&new_data);
result = row->uid.uid;
} else {
g_limit_reached = true;
}
g_count_total_allocs++;
LeaveCriticalSection(&g_crtdbg_stacktrace_cs);
return result;
}
static void git_win32_leakcheck_global_shutdown(void)
{
git_win32_leakcheck_stacktrace_cleanup();
git_win32_leakcheck_stack_cleanup();
}
bool git_win32_leakcheck_has_leaks(void)
{
return (g_transient_count_total_leaks > 0);
}
int git_win32_leakcheck_global_init(void)
{
git_win32_leakcheck_stacktrace_init();
git_win32_leakcheck_stack_init();
return git_runtime_shutdown_register(git_win32_leakcheck_global_shutdown);
}
#else
int git_win32_leakcheck_global_init(void)
{
return 0;
}
#endif
| libgit2-main | src/util/win32/w32_leakcheck.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "dir.h"
#define GIT__WIN32_NO_WRAP_DIR
#include "posix.h"
git__DIR *git__opendir(const char *dir)
{
git_win32_path filter_w;
git__DIR *new = NULL;
size_t dirlen, alloclen;
if (!dir || !git_win32__findfirstfile_filter(filter_w, dir))
return NULL;
dirlen = strlen(dir);
if (GIT_ADD_SIZET_OVERFLOW(&alloclen, sizeof(*new), dirlen) ||
GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1) ||
!(new = git__calloc(1, alloclen)))
return NULL;
memcpy(new->dir, dir, dirlen);
new->h = FindFirstFileW(filter_w, &new->f);
if (new->h == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", dir);
git__free(new);
return NULL;
}
new->first = 1;
return new;
}
int git__readdir_ext(
git__DIR *d,
struct git__dirent *entry,
struct git__dirent **result,
int *is_dir)
{
if (!d || !entry || !result || d->h == INVALID_HANDLE_VALUE)
return -1;
*result = NULL;
if (d->first)
d->first = 0;
else if (!FindNextFileW(d->h, &d->f)) {
if (GetLastError() == ERROR_NO_MORE_FILES)
return 0;
git_error_set(GIT_ERROR_OS, "could not read from directory '%s'", d->dir);
return -1;
}
/* Convert the path to UTF-8 */
if (git_win32_path_to_utf8(entry->d_name, d->f.cFileName) < 0)
return -1;
entry->d_ino = 0;
*result = entry;
if (is_dir != NULL)
*is_dir = ((d->f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
return 0;
}
struct git__dirent *git__readdir(git__DIR *d)
{
struct git__dirent *result;
if (git__readdir_ext(d, &d->entry, &result, NULL) < 0)
return NULL;
return result;
}
void git__rewinddir(git__DIR *d)
{
git_win32_path filter_w;
if (!d)
return;
if (d->h != INVALID_HANDLE_VALUE) {
FindClose(d->h);
d->h = INVALID_HANDLE_VALUE;
d->first = 0;
}
if (!git_win32__findfirstfile_filter(filter_w, d->dir))
return;
d->h = FindFirstFileW(filter_w, &d->f);
if (d->h == INVALID_HANDLE_VALUE)
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", d->dir);
else
d->first = 1;
}
int git__closedir(git__DIR *d)
{
if (!d)
return 0;
if (d->h != INVALID_HANDLE_VALUE) {
FindClose(d->h);
d->h = INVALID_HANDLE_VALUE;
}
git__free(d);
return 0;
}
| libgit2-main | src/util/win32/dir.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "error.h"
#include "utf-conv.h"
#ifdef GIT_WINHTTP
# include <winhttp.h>
#endif
char *git_win32_get_error_message(DWORD error_code)
{
LPWSTR lpMsgBuf = NULL;
HMODULE hModule = NULL;
char *utf8_msg = NULL;
DWORD dwFlags =
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
if (!error_code)
return NULL;
#ifdef GIT_WINHTTP
/* Errors raised by WinHTTP are not in the system resource table */
if (error_code >= WINHTTP_ERROR_BASE &&
error_code <= WINHTTP_ERROR_LAST)
hModule = GetModuleHandleW(L"winhttp");
#endif
GIT_UNUSED(hModule);
if (hModule)
dwFlags |= FORMAT_MESSAGE_FROM_HMODULE;
else
dwFlags |= FORMAT_MESSAGE_FROM_SYSTEM;
if (FormatMessageW(dwFlags, hModule, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpMsgBuf, 0, NULL)) {
/* Convert the message to UTF-8. If this fails, we will
* return NULL, which is a condition expected by the caller */
if (git__utf16_to_8_alloc(&utf8_msg, lpMsgBuf) < 0)
utf8_msg = NULL;
LocalFree(lpMsgBuf);
}
return utf8_msg;
}
| libgit2-main | src/util/win32/error.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#include "map.h"
#include <errno.h>
#ifndef NO_MMAP
static DWORD get_page_size(void)
{
static DWORD page_size;
SYSTEM_INFO sys;
if (!page_size) {
GetSystemInfo(&sys);
page_size = sys.dwPageSize;
}
return page_size;
}
static DWORD get_allocation_granularity(void)
{
static DWORD granularity;
SYSTEM_INFO sys;
if (!granularity) {
GetSystemInfo(&sys);
granularity = sys.dwAllocationGranularity;
}
return granularity;
}
int git__page_size(size_t *page_size)
{
*page_size = get_page_size();
return 0;
}
int git__mmap_alignment(size_t *page_size)
{
*page_size = get_allocation_granularity();
return 0;
}
int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset)
{
HANDLE fh = (HANDLE)_get_osfhandle(fd);
DWORD alignment = get_allocation_granularity();
DWORD fmap_prot = 0;
DWORD view_prot = 0;
DWORD off_low = 0;
DWORD off_hi = 0;
off64_t page_start;
off64_t page_offset;
GIT_MMAP_VALIDATE(out, len, prot, flags);
out->data = NULL;
out->len = 0;
out->fmh = NULL;
if (fh == INVALID_HANDLE_VALUE) {
errno = EBADF;
git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value");
return -1;
}
if (prot & GIT_PROT_WRITE)
fmap_prot |= PAGE_READWRITE;
else if (prot & GIT_PROT_READ)
fmap_prot |= PAGE_READONLY;
if (prot & GIT_PROT_WRITE)
view_prot |= FILE_MAP_WRITE;
if (prot & GIT_PROT_READ)
view_prot |= FILE_MAP_READ;
page_start = (offset / alignment) * alignment;
page_offset = offset - page_start;
if (page_offset != 0) { /* offset must be multiple of the allocation granularity */
errno = EINVAL;
git_error_set(GIT_ERROR_OS, "failed to mmap. Offset must be multiple of allocation granularity");
return -1;
}
out->fmh = CreateFileMapping(fh, NULL, fmap_prot, 0, 0, NULL);
if (!out->fmh || out->fmh == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value");
out->fmh = NULL;
return -1;
}
off_low = (DWORD)(page_start);
off_hi = (DWORD)(page_start >> 32);
out->data = MapViewOfFile(out->fmh, view_prot, off_hi, off_low, len);
if (!out->data) {
git_error_set(GIT_ERROR_OS, "failed to mmap. No data written");
CloseHandle(out->fmh);
out->fmh = NULL;
return -1;
}
out->len = len;
return 0;
}
int p_munmap(git_map *map)
{
int error = 0;
GIT_ASSERT_ARG(map);
if (map->data) {
if (!UnmapViewOfFile(map->data)) {
git_error_set(GIT_ERROR_OS, "failed to munmap. Could not unmap view of file");
error = -1;
}
map->data = NULL;
}
if (map->fmh) {
if (!CloseHandle(map->fmh)) {
git_error_set(GIT_ERROR_OS, "failed to munmap. Could not close handle");
error = -1;
}
map->fmh = NULL;
}
return error;
}
#endif
| libgit2-main | src/util/win32/map.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "path_w32.h"
#include "fs_path.h"
#include "utf-conv.h"
#include "posix.h"
#include "reparse.h"
#include "dir.h"
#define PATH__NT_NAMESPACE L"\\\\?\\"
#define PATH__NT_NAMESPACE_LEN 4
#define PATH__ABSOLUTE_LEN 3
#define path__is_nt_namespace(p) \
(((p)[0] == '\\' && (p)[1] == '\\' && (p)[2] == '?' && (p)[3] == '\\') || \
((p)[0] == '/' && (p)[1] == '/' && (p)[2] == '?' && (p)[3] == '/'))
#define path__is_unc(p) \
(((p)[0] == '\\' && (p)[1] == '\\') || ((p)[0] == '/' && (p)[1] == '/'))
#define path__startswith_slash(p) \
((p)[0] == '\\' || (p)[0] == '/')
GIT_INLINE(int) path__cwd(wchar_t *path, int size)
{
int len;
if ((len = GetCurrentDirectoryW(size, path)) == 0) {
errno = GetLastError() == ERROR_ACCESS_DENIED ? EACCES : ENOENT;
return -1;
} else if (len > size) {
errno = ENAMETOOLONG;
return -1;
}
/* The Win32 APIs may return "\\?\" once you've used it first.
* But it may not. What a gloriously predictable API!
*/
if (wcsncmp(path, PATH__NT_NAMESPACE, PATH__NT_NAMESPACE_LEN))
return len;
len -= PATH__NT_NAMESPACE_LEN;
memmove(path, path + PATH__NT_NAMESPACE_LEN, sizeof(wchar_t) * len);
return len;
}
static wchar_t *path__skip_server(wchar_t *path)
{
wchar_t *c;
for (c = path; *c; c++) {
if (git_fs_path_is_dirsep(*c))
return c + 1;
}
return c;
}
static wchar_t *path__skip_prefix(wchar_t *path)
{
if (path__is_nt_namespace(path)) {
path += PATH__NT_NAMESPACE_LEN;
if (wcsncmp(path, L"UNC\\", 4) == 0)
path = path__skip_server(path + 4);
else if (git_fs_path_is_absolute(path))
path += PATH__ABSOLUTE_LEN;
} else if (git_fs_path_is_absolute(path)) {
path += PATH__ABSOLUTE_LEN;
} else if (path__is_unc(path)) {
path = path__skip_server(path + 2);
}
return path;
}
int git_win32_path_canonicalize(git_win32_path path)
{
wchar_t *base, *from, *to, *next;
size_t len;
base = to = path__skip_prefix(path);
/* Unposixify if the prefix */
for (from = path; from < to; from++) {
if (*from == L'/')
*from = L'\\';
}
while (*from) {
for (next = from; *next; ++next) {
if (*next == L'/') {
*next = L'\\';
break;
}
if (*next == L'\\')
break;
}
len = next - from;
if (len == 1 && from[0] == L'.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == L'.' && from[1] == L'.') {
if (to == base) {
/* no more path segments to strip, eat the "../" */
if (*next == L'\\')
len++;
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == L'\\') to--;
while (to > base && to[-1] != L'\\') to--;
}
} else {
if (*next == L'\\' && *from != L'\\')
len++;
if (to != from)
memmove(to, from, sizeof(wchar_t) * len);
to += len;
}
from += len;
while (*from == L'\\') from++;
}
/* Strip trailing backslashes */
while (to > base && to[-1] == L'\\') to--;
*to = L'\0';
if ((to - path) > INT_MAX) {
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return -1;
}
return (int)(to - path);
}
static int git_win32_path_join(
git_win32_path dest,
const wchar_t *one,
size_t one_len,
const wchar_t *two,
size_t two_len)
{
size_t backslash = 0;
if (one_len && two_len && one[one_len - 1] != L'\\')
backslash = 1;
if (one_len + two_len + backslash > MAX_PATH) {
git_error_set(GIT_ERROR_INVALID, "path too long");
return -1;
}
memmove(dest, one, one_len * sizeof(wchar_t));
if (backslash)
dest[one_len] = L'\\';
memcpy(dest + one_len + backslash, two, two_len * sizeof(wchar_t));
dest[one_len + backslash + two_len] = L'\0';
return 0;
}
struct win32_path_iter {
wchar_t *env;
const wchar_t *current_dir;
};
static int win32_path_iter_init(struct win32_path_iter *iter)
{
DWORD len = GetEnvironmentVariableW(L"PATH", NULL, 0);
if (!len && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
iter->env = NULL;
iter->current_dir = NULL;
return 0;
} else if (!len) {
git_error_set(GIT_ERROR_OS, "could not load PATH");
return -1;
}
iter->env = git__malloc(len * sizeof(wchar_t));
GIT_ERROR_CHECK_ALLOC(iter->env);
len = GetEnvironmentVariableW(L"PATH", iter->env, len);
if (len == 0) {
git_error_set(GIT_ERROR_OS, "could not load PATH");
return -1;
}
iter->current_dir = iter->env;
return 0;
}
static int win32_path_iter_next(
const wchar_t **out,
size_t *out_len,
struct win32_path_iter *iter)
{
const wchar_t *start;
wchar_t term;
size_t len = 0;
if (!iter->current_dir || !*iter->current_dir)
return GIT_ITEROVER;
term = (*iter->current_dir == L'"') ? *iter->current_dir++ : L';';
start = iter->current_dir;
while (*iter->current_dir && *iter->current_dir != term) {
iter->current_dir++;
len++;
}
*out = start;
*out_len = len;
if (term == L'"' && *iter->current_dir)
iter->current_dir++;
while (*iter->current_dir == L';')
iter->current_dir++;
return 0;
}
static void win32_path_iter_dispose(struct win32_path_iter *iter)
{
if (!iter)
return;
git__free(iter->env);
iter->env = NULL;
iter->current_dir = NULL;
}
int git_win32_path_find_executable(git_win32_path fullpath, wchar_t *exe)
{
struct win32_path_iter path_iter;
const wchar_t *dir;
size_t dir_len, exe_len = wcslen(exe);
bool found = false;
if (win32_path_iter_init(&path_iter) < 0)
return -1;
while (win32_path_iter_next(&dir, &dir_len, &path_iter) != GIT_ITEROVER) {
if (git_win32_path_join(fullpath, dir, dir_len, exe, exe_len) < 0)
continue;
if (_waccess(fullpath, 0) == 0) {
found = true;
break;
}
}
win32_path_iter_dispose(&path_iter);
if (found)
return 0;
fullpath[0] = L'\0';
return GIT_ENOTFOUND;
}
static int win32_path_cwd(wchar_t *out, size_t len)
{
int cwd_len;
if (len > INT_MAX) {
errno = ENAMETOOLONG;
return -1;
}
if ((cwd_len = path__cwd(out, (int)len)) < 0)
return -1;
/* UNC paths */
if (wcsncmp(L"\\\\", out, 2) == 0) {
/* Our buffer must be at least 5 characters larger than the
* current working directory: we swallow one of the leading
* '\'s, but we we add a 'UNC' specifier to the path, plus
* a trailing directory separator, plus a NUL.
*/
if (cwd_len > GIT_WIN_PATH_MAX - 4) {
errno = ENAMETOOLONG;
return -1;
}
memmove(out+2, out, sizeof(wchar_t) * cwd_len);
out[0] = L'U';
out[1] = L'N';
out[2] = L'C';
cwd_len += 2;
}
/* Our buffer must be at least 2 characters larger than the current
* working directory. (One character for the directory separator,
* one for the null.
*/
else if (cwd_len > GIT_WIN_PATH_MAX - 2) {
errno = ENAMETOOLONG;
return -1;
}
return cwd_len;
}
int git_win32_path_from_utf8(git_win32_path out, const char *src)
{
wchar_t *dest = out;
/* All win32 paths are in NT-prefixed format, beginning with "\\?\". */
memcpy(dest, PATH__NT_NAMESPACE, sizeof(wchar_t) * PATH__NT_NAMESPACE_LEN);
dest += PATH__NT_NAMESPACE_LEN;
/* See if this is an absolute path (beginning with a drive letter) */
if (git_fs_path_is_absolute(src)) {
if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src) < 0)
goto on_error;
}
/* File-prefixed NT-style paths beginning with \\?\ */
else if (path__is_nt_namespace(src)) {
/* Skip the NT prefix, the destination already contains it */
if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src + PATH__NT_NAMESPACE_LEN) < 0)
goto on_error;
}
/* UNC paths */
else if (path__is_unc(src)) {
memcpy(dest, L"UNC\\", sizeof(wchar_t) * 4);
dest += 4;
/* Skip the leading "\\" */
if (git__utf8_to_16(dest, GIT_WIN_PATH_MAX - 2, src + 2) < 0)
goto on_error;
}
/* Absolute paths omitting the drive letter */
else if (path__startswith_slash(src)) {
if (path__cwd(dest, GIT_WIN_PATH_MAX) < 0)
goto on_error;
if (!git_fs_path_is_absolute(dest)) {
errno = ENOENT;
goto on_error;
}
/* Skip the drive letter specification ("C:") */
if (git__utf8_to_16(dest + 2, GIT_WIN_PATH_MAX - 2, src) < 0)
goto on_error;
}
/* Relative paths */
else {
int cwd_len;
if ((cwd_len = win32_path_cwd(dest, GIT_WIN_PATH_MAX)) < 0)
goto on_error;
dest[cwd_len++] = L'\\';
if (git__utf8_to_16(dest + cwd_len, GIT_WIN_PATH_MAX - cwd_len, src) < 0)
goto on_error;
}
return git_win32_path_canonicalize(out);
on_error:
/* set windows error code so we can use its error message */
if (errno == ENAMETOOLONG)
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return -1;
}
int git_win32_path_relative_from_utf8(git_win32_path out, const char *src)
{
wchar_t *dest = out, *p;
int len;
/* Handle absolute paths */
if (git_fs_path_is_absolute(src) ||
path__is_nt_namespace(src) ||
path__is_unc(src) ||
path__startswith_slash(src)) {
return git_win32_path_from_utf8(out, src);
}
if ((len = git__utf8_to_16(dest, GIT_WIN_PATH_MAX, src)) < 0)
return -1;
for (p = dest; p < (dest + len); p++) {
if (*p == L'/')
*p = L'\\';
}
return len;
}
int git_win32_path_to_utf8(git_win32_utf8_path dest, const wchar_t *src)
{
char *out = dest;
int len;
/* Strip NT namespacing "\\?\" */
if (path__is_nt_namespace(src)) {
src += 4;
/* "\\?\UNC\server\share" -> "\\server\share" */
if (wcsncmp(src, L"UNC\\", 4) == 0) {
src += 4;
memcpy(dest, "\\\\", 2);
out = dest + 2;
}
}
if ((len = git__utf16_to_8(out, GIT_WIN_PATH_UTF8, src)) < 0)
return len;
git_fs_path_mkposix(dest);
return len;
}
char *git_win32_path_8dot3_name(const char *path)
{
git_win32_path longpath, shortpath;
wchar_t *start;
char *shortname;
int len, namelen = 1;
if (git_win32_path_from_utf8(longpath, path) < 0)
return NULL;
len = GetShortPathNameW(longpath, shortpath, GIT_WIN_PATH_UTF16);
while (len && shortpath[len-1] == L'\\')
shortpath[--len] = L'\0';
if (len == 0 || len >= GIT_WIN_PATH_UTF16)
return NULL;
for (start = shortpath + (len - 1);
start > shortpath && *(start-1) != '/' && *(start-1) != '\\';
start--)
namelen++;
/* We may not have actually been given a short name. But if we have,
* it will be in the ASCII byte range, so we don't need to worry about
* multi-byte sequences and can allocate naively.
*/
if (namelen > 12 || (shortname = git__malloc(namelen + 1)) == NULL)
return NULL;
if ((len = git__utf16_to_8(shortname, namelen + 1, start)) < 0)
return NULL;
return shortname;
}
static bool path_is_volume(wchar_t *target, size_t target_len)
{
return (target_len && wcsncmp(target, L"\\??\\Volume{", 11) == 0);
}
/* On success, returns the length, in characters, of the path stored in dest.
* On failure, returns a negative value. */
int git_win32_path_readlink_w(git_win32_path dest, const git_win32_path path)
{
BYTE buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
GIT_REPARSE_DATA_BUFFER *reparse_buf = (GIT_REPARSE_DATA_BUFFER *)buf;
HANDLE handle = NULL;
DWORD ioctl_ret;
wchar_t *target;
size_t target_len;
int error = -1;
handle = CreateFileW(path, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (handle == INVALID_HANDLE_VALUE) {
errno = ENOENT;
return -1;
}
if (!DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0,
reparse_buf, sizeof(buf), &ioctl_ret, NULL)) {
errno = EINVAL;
goto on_error;
}
switch (reparse_buf->ReparseTag) {
case IO_REPARSE_TAG_SYMLINK:
target = reparse_buf->ReparseBuffer.SymbolicLink.PathBuffer +
(reparse_buf->ReparseBuffer.SymbolicLink.SubstituteNameOffset / sizeof(WCHAR));
target_len = reparse_buf->ReparseBuffer.SymbolicLink.SubstituteNameLength / sizeof(WCHAR);
break;
case IO_REPARSE_TAG_MOUNT_POINT:
target = reparse_buf->ReparseBuffer.MountPoint.PathBuffer +
(reparse_buf->ReparseBuffer.MountPoint.SubstituteNameOffset / sizeof(WCHAR));
target_len = reparse_buf->ReparseBuffer.MountPoint.SubstituteNameLength / sizeof(WCHAR);
break;
default:
errno = EINVAL;
goto on_error;
}
if (path_is_volume(target, target_len)) {
/* This path is a reparse point that represents another volume mounted
* at this location, it is not a symbolic link our input was canonical.
*/
errno = EINVAL;
error = -1;
} else if (target_len) {
/* The path may need to have a namespace prefix removed. */
target_len = git_win32_path_remove_namespace(target, target_len);
/* Need one additional character in the target buffer
* for the terminating NULL. */
if (GIT_WIN_PATH_UTF16 > target_len) {
wcscpy(dest, target);
error = (int)target_len;
}
}
on_error:
CloseHandle(handle);
return error;
}
/**
* Removes any trailing backslashes from a path, except in the case of a drive
* letter path (C:\, D:\, etc.). This function cannot fail.
*
* @param path The path which should be trimmed.
* @return The length of the modified string (<= the input length)
*/
size_t git_win32_path_trim_end(wchar_t *str, size_t len)
{
while (1) {
if (!len || str[len - 1] != L'\\')
break;
/*
* Don't trim backslashes from drive letter paths, which
* are 3 characters long and of the form C:\, D:\, etc.
*/
if (len == 3 && git_win32__isalpha(str[0]) && str[1] == ':')
break;
len--;
}
str[len] = L'\0';
return len;
}
/**
* Removes any of the following namespace prefixes from a path,
* if found: "\??\", "\\?\", "\\?\UNC\". This function cannot fail.
*
* @param path The path which should be converted.
* @return The length of the modified string (<= the input length)
*/
size_t git_win32_path_remove_namespace(wchar_t *str, size_t len)
{
static const wchar_t dosdevices_namespace[] = L"\\\?\?\\";
static const wchar_t nt_namespace[] = L"\\\\?\\";
static const wchar_t unc_namespace_remainder[] = L"UNC\\";
static const wchar_t unc_prefix[] = L"\\\\";
const wchar_t *prefix = NULL, *remainder = NULL;
size_t prefix_len = 0, remainder_len = 0;
/* "\??\" -- DOS Devices prefix */
if (len >= CONST_STRLEN(dosdevices_namespace) &&
!wcsncmp(str, dosdevices_namespace, CONST_STRLEN(dosdevices_namespace))) {
remainder = str + CONST_STRLEN(dosdevices_namespace);
remainder_len = len - CONST_STRLEN(dosdevices_namespace);
}
/* "\\?\" -- NT namespace prefix */
else if (len >= CONST_STRLEN(nt_namespace) &&
!wcsncmp(str, nt_namespace, CONST_STRLEN(nt_namespace))) {
remainder = str + CONST_STRLEN(nt_namespace);
remainder_len = len - CONST_STRLEN(nt_namespace);
}
/* "\??\UNC\", "\\?\UNC\" -- UNC prefix */
if (remainder_len >= CONST_STRLEN(unc_namespace_remainder) &&
!wcsncmp(remainder, unc_namespace_remainder, CONST_STRLEN(unc_namespace_remainder))) {
/*
* The proper Win32 path for a UNC share has "\\" at beginning of it
* and looks like "\\server\share\<folderStructure>". So remove the
* UNC namespace and add a prefix of "\\" in its place.
*/
remainder += CONST_STRLEN(unc_namespace_remainder);
remainder_len -= CONST_STRLEN(unc_namespace_remainder);
prefix = unc_prefix;
prefix_len = CONST_STRLEN(unc_prefix);
}
/*
* Sanity check that the new string isn't longer than the old one.
* (This could only happen due to programmer error introducing a
* prefix longer than the namespace it replaces.)
*/
if (remainder && len >= remainder_len + prefix_len) {
if (prefix)
memmove(str, prefix, prefix_len * sizeof(wchar_t));
memmove(str + prefix_len, remainder, remainder_len * sizeof(wchar_t));
len = remainder_len + prefix_len;
str[len] = L'\0';
}
return git_win32_path_trim_end(str, len);
}
| libgit2-main | src/util/win32/path_w32.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "w32_buffer.h"
#include "utf-conv.h"
GIT_INLINE(int) handle_wc_error(void)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
errno = ENAMETOOLONG;
else
errno = EINVAL;
return -1;
}
int git_str_put_w(git_str *buf, const wchar_t *string_w, size_t len_w)
{
int utf8_len, utf8_write_len;
size_t new_size;
if (!len_w) {
return 0;
} else if (len_w > INT_MAX) {
git_error_set_oom();
return -1;
}
GIT_ASSERT(string_w);
/* Measure the string necessary for conversion */
if ((utf8_len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, NULL, 0, NULL, NULL)) == 0)
return 0;
GIT_ASSERT(utf8_len > 0);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, buf->size, (size_t)utf8_len);
GIT_ERROR_CHECK_ALLOC_ADD(&new_size, new_size, 1);
if (git_str_grow(buf, new_size) < 0)
return -1;
if ((utf8_write_len = WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, string_w, (int)len_w, &buf->ptr[buf->size], utf8_len, NULL, NULL)) == 0)
return handle_wc_error();
GIT_ASSERT(utf8_write_len == utf8_len);
buf->size += utf8_write_len;
buf->ptr[buf->size] = '\0';
return 0;
}
| libgit2-main | src/util/win32/w32_buffer.c |
/*
* Copyright (c), Edward Thomson <ethomson@edwardthomson.com>
* All rights reserved.
*
* This file is part of adopt, distributed under the MIT license.
* For full terms and conditions, see the included LICENSE file.
*
* THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT.
*
* This file was produced by using the `rename.pl` script included with
* adopt. The command-line specified was:
*
* ./rename.pl cli_opt --filename=opt --include=cli.h --inline=GIT_INLINE --header-guard=CLI_opt_h__ --lowercase-status --without-usage
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <assert.h>
#include "cli.h"
#include "opt.h"
#ifdef _WIN32
# include <Windows.h>
#else
# include <fcntl.h>
# include <sys/ioctl.h>
#endif
#ifdef _MSC_VER
# define alloca _alloca
#endif
#define spec_is_option_type(x) \
((x)->type == CLI_OPT_TYPE_BOOL || \
(x)->type == CLI_OPT_TYPE_SWITCH || \
(x)->type == CLI_OPT_TYPE_VALUE)
GIT_INLINE(const cli_opt_spec *) spec_for_long(
int *is_negated,
int *has_value,
const char **value,
const cli_opt_parser *parser,
const char *arg)
{
const cli_opt_spec *spec;
char *eql;
size_t eql_pos;
eql = strchr(arg, '=');
eql_pos = (eql = strchr(arg, '=')) ? (size_t)(eql - arg) : strlen(arg);
for (spec = parser->specs; spec->type; ++spec) {
/* Handle -- (everything after this is literal) */
if (spec->type == CLI_OPT_TYPE_LITERAL && arg[0] == '\0')
return spec;
/* Handle --no-option arguments for bool types */
if (spec->type == CLI_OPT_TYPE_BOOL &&
strncmp(arg, "no-", 3) == 0 &&
strcmp(arg + 3, spec->name) == 0) {
*is_negated = 1;
return spec;
}
/* Handle the typical --option arguments */
if (spec_is_option_type(spec) &&
spec->name &&
strcmp(arg, spec->name) == 0)
return spec;
/* Handle --option=value arguments */
if (spec->type == CLI_OPT_TYPE_VALUE &&
eql &&
strncmp(arg, spec->name, eql_pos) == 0 &&
spec->name[eql_pos] == '\0') {
*has_value = 1;
*value = arg[eql_pos + 1] ? &arg[eql_pos + 1] : NULL;
return spec;
}
}
return NULL;
}
GIT_INLINE(const cli_opt_spec *) spec_for_short(
const char **value,
const cli_opt_parser *parser,
const char *arg)
{
const cli_opt_spec *spec;
for (spec = parser->specs; spec->type; ++spec) {
/* Handle -svalue short options with a value */
if (spec->type == CLI_OPT_TYPE_VALUE &&
arg[0] == spec->alias &&
arg[1] != '\0') {
*value = &arg[1];
return spec;
}
/* Handle typical -s short options */
if (arg[0] == spec->alias) {
*value = NULL;
return spec;
}
}
return NULL;
}
GIT_INLINE(const cli_opt_spec *) spec_for_arg(cli_opt_parser *parser)
{
const cli_opt_spec *spec;
size_t args = 0;
for (spec = parser->specs; spec->type; ++spec) {
if (spec->type == CLI_OPT_TYPE_ARG) {
if (args == parser->arg_idx) {
parser->arg_idx++;
return spec;
}
args++;
}
if (spec->type == CLI_OPT_TYPE_ARGS && args == parser->arg_idx)
return spec;
}
return NULL;
}
GIT_INLINE(int) spec_is_choice(const cli_opt_spec *spec)
{
return ((spec + 1)->type &&
((spec + 1)->usage & CLI_OPT_USAGE_CHOICE));
}
/*
* If we have a choice with switches and bare arguments, and we see
* the switch, then we no longer expect the bare argument.
*/
GIT_INLINE(void) consume_choices(const cli_opt_spec *spec, cli_opt_parser *parser)
{
/* back up to the beginning of the choices */
while (spec->type && (spec->usage & CLI_OPT_USAGE_CHOICE))
--spec;
if (!spec_is_choice(spec))
return;
do {
if (spec->type == CLI_OPT_TYPE_ARG)
parser->arg_idx++;
++spec;
} while(spec->type && (spec->usage & CLI_OPT_USAGE_CHOICE));
}
static cli_opt_status_t parse_long(cli_opt *opt, cli_opt_parser *parser)
{
const cli_opt_spec *spec;
char *arg = parser->args[parser->idx++];
const char *value = NULL;
int is_negated = 0, has_value = 0;
opt->arg = arg;
if ((spec = spec_for_long(&is_negated, &has_value, &value, parser, &arg[2])) == NULL) {
opt->spec = NULL;
opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
goto done;
}
opt->spec = spec;
/* Future options parsed as literal */
if (spec->type == CLI_OPT_TYPE_LITERAL)
parser->in_literal = 1;
/* --bool or --no-bool */
else if (spec->type == CLI_OPT_TYPE_BOOL && spec->value)
*((int *)spec->value) = !is_negated;
/* --accumulate */
else if (spec->type == CLI_OPT_TYPE_ACCUMULATOR && spec->value)
*((int *)spec->value) += spec->switch_value ? spec->switch_value : 1;
/* --switch */
else if (spec->type == CLI_OPT_TYPE_SWITCH && spec->value)
*((int *)spec->value) = spec->switch_value;
/* Parse values as "--foo=bar" or "--foo bar" */
else if (spec->type == CLI_OPT_TYPE_VALUE) {
if (has_value)
opt->value = (char *)value;
else if ((parser->idx + 1) <= parser->args_len)
opt->value = parser->args[parser->idx++];
if (spec->value)
*((char **)spec->value) = opt->value;
}
/* Required argument was not provided */
if (spec->type == CLI_OPT_TYPE_VALUE &&
!opt->value &&
!(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL))
opt->status = CLI_OPT_STATUS_MISSING_VALUE;
else
opt->status = CLI_OPT_STATUS_OK;
consume_choices(opt->spec, parser);
done:
return opt->status;
}
static cli_opt_status_t parse_short(cli_opt *opt, cli_opt_parser *parser)
{
const cli_opt_spec *spec;
char *arg = parser->args[parser->idx++];
const char *value;
opt->arg = arg;
if ((spec = spec_for_short(&value, parser, &arg[1 + parser->in_short])) == NULL) {
opt->spec = NULL;
opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
goto done;
}
opt->spec = spec;
if (spec->type == CLI_OPT_TYPE_BOOL && spec->value)
*((int *)spec->value) = 1;
else if (spec->type == CLI_OPT_TYPE_ACCUMULATOR && spec->value)
*((int *)spec->value) += spec->switch_value ? spec->switch_value : 1;
else if (spec->type == CLI_OPT_TYPE_SWITCH && spec->value)
*((int *)spec->value) = spec->switch_value;
/* Parse values as "-ifoo" or "-i foo" */
else if (spec->type == CLI_OPT_TYPE_VALUE) {
if (value)
opt->value = (char *)value;
else if ((parser->idx + 1) <= parser->args_len)
opt->value = parser->args[parser->idx++];
if (spec->value)
*((char **)spec->value) = opt->value;
}
/*
* Handle compressed short arguments, like "-fbcd"; see if there's
* another character after the one we processed. If not, advance
* the parser index.
*/
if (spec->type != CLI_OPT_TYPE_VALUE && arg[2 + parser->in_short] != '\0') {
parser->in_short++;
parser->idx--;
} else {
parser->in_short = 0;
}
/* Required argument was not provided */
if (spec->type == CLI_OPT_TYPE_VALUE && !opt->value)
opt->status = CLI_OPT_STATUS_MISSING_VALUE;
else
opt->status = CLI_OPT_STATUS_OK;
consume_choices(opt->spec, parser);
done:
return opt->status;
}
static cli_opt_status_t parse_arg(cli_opt *opt, cli_opt_parser *parser)
{
const cli_opt_spec *spec = spec_for_arg(parser);
opt->spec = spec;
opt->arg = parser->args[parser->idx];
if (!spec) {
parser->idx++;
opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
} else if (spec->type == CLI_OPT_TYPE_ARGS) {
if (spec->value)
*((char ***)spec->value) = &parser->args[parser->idx];
/*
* We have started a list of arguments; the remainder of
* given arguments need not be examined.
*/
parser->in_args = (parser->args_len - parser->idx);
parser->idx = parser->args_len;
opt->args_len = parser->in_args;
opt->status = CLI_OPT_STATUS_OK;
} else {
if (spec->value)
*((char **)spec->value) = parser->args[parser->idx];
parser->idx++;
opt->status = CLI_OPT_STATUS_OK;
}
return opt->status;
}
static int support_gnu_style(unsigned int flags)
{
if ((flags & CLI_OPT_PARSE_FORCE_GNU) != 0)
return 1;
if ((flags & CLI_OPT_PARSE_GNU) == 0)
return 0;
/* TODO: Windows */
#if defined(_WIN32) && defined(UNICODE)
if (_wgetenv(L"POSIXLY_CORRECT") != NULL)
return 0;
#else
if (getenv("POSIXLY_CORRECT") != NULL)
return 0;
#endif
return 1;
}
void cli_opt_parser_init(
cli_opt_parser *parser,
const cli_opt_spec specs[],
char **args,
size_t args_len,
unsigned int flags)
{
assert(parser);
memset(parser, 0x0, sizeof(cli_opt_parser));
parser->specs = specs;
parser->args = args;
parser->args_len = args_len;
parser->flags = flags;
parser->needs_sort = support_gnu_style(flags);
}
GIT_INLINE(const cli_opt_spec *) spec_for_sort(
int *needs_value,
const cli_opt_parser *parser,
const char *arg)
{
int is_negated, has_value = 0;
const char *value;
const cli_opt_spec *spec = NULL;
size_t idx = 0;
*needs_value = 0;
if (strncmp(arg, "--", 2) == 0) {
spec = spec_for_long(&is_negated, &has_value, &value, parser, &arg[2]);
*needs_value = !has_value;
}
else if (strncmp(arg, "-", 1) == 0) {
spec = spec_for_short(&value, parser, &arg[1]);
/*
* Advance through compressed short arguments to see if
* the last one has a value, eg "-xvffilename".
*/
while (spec && !value && arg[1 + ++idx] != '\0')
spec = spec_for_short(&value, parser, &arg[1 + idx]);
*needs_value = (value == NULL);
}
return spec;
}
/*
* Some parsers allow for handling arguments like "file1 --help file2";
* this is done by re-sorting the arguments in-place; emulate that.
*/
static int sort_gnu_style(cli_opt_parser *parser)
{
size_t i, j, insert_idx = parser->idx, offset;
const cli_opt_spec *spec;
char *option, *value;
int needs_value, changed = 0;
parser->needs_sort = 0;
for (i = parser->idx; i < parser->args_len; i++) {
spec = spec_for_sort(&needs_value, parser, parser->args[i]);
/* Not a "-" or "--" prefixed option. No change. */
if (!spec)
continue;
/* A "--" alone means remaining args are literal. */
if (spec->type == CLI_OPT_TYPE_LITERAL)
break;
option = parser->args[i];
/*
* If the argument is a value type and doesn't already
* have a value (eg "--foo=bar" or "-fbar") then we need
* to copy the next argument as its value.
*/
if (spec->type == CLI_OPT_TYPE_VALUE && needs_value) {
/*
* A required value is not provided; set parser
* index to this value so that we fail on it.
*/
if (i + 1 >= parser->args_len) {
parser->idx = i;
return 1;
}
value = parser->args[i + 1];
offset = 1;
} else {
value = NULL;
offset = 0;
}
/* Caller error if args[0] is an option. */
if (i == 0)
return 0;
/* Shift args up one (or two) and insert the option */
for (j = i; j > insert_idx; j--)
parser->args[j + offset] = parser->args[j - 1];
parser->args[insert_idx] = option;
if (value)
parser->args[insert_idx + 1] = value;
insert_idx += (1 + offset);
i += offset;
changed = 1;
}
return changed;
}
cli_opt_status_t cli_opt_parser_next(cli_opt *opt, cli_opt_parser *parser)
{
assert(opt && parser);
memset(opt, 0x0, sizeof(cli_opt));
if (parser->idx >= parser->args_len) {
opt->args_len = parser->in_args;
return CLI_OPT_STATUS_DONE;
}
/* Handle options in long form, those beginning with "--" */
if (strncmp(parser->args[parser->idx], "--", 2) == 0 &&
!parser->in_short &&
!parser->in_literal)
return parse_long(opt, parser);
/* Handle options in short form, those beginning with "-" */
else if (parser->in_short ||
(strncmp(parser->args[parser->idx], "-", 1) == 0 &&
!parser->in_literal))
return parse_short(opt, parser);
/*
* We've reached the first "bare" argument. In POSIX mode, all
* remaining items on the command line are arguments. In GNU
* mode, there may be long or short options after this. Sort any
* options up to this position then re-parse the current position.
*/
if (parser->needs_sort && sort_gnu_style(parser))
return cli_opt_parser_next(opt, parser);
return parse_arg(opt, parser);
}
GIT_INLINE(int) spec_included(const cli_opt_spec **specs, const cli_opt_spec *spec)
{
const cli_opt_spec **i;
for (i = specs; *i; ++i) {
if (spec == *i)
return 1;
}
return 0;
}
static cli_opt_status_t validate_required(
cli_opt *opt,
const cli_opt_spec specs[],
const cli_opt_spec **given_specs)
{
const cli_opt_spec *spec, *required;
int given;
/*
* Iterate over the possible specs to identify requirements and
* ensure that those have been given on the command-line.
* Note that we can have required *choices*, where one in a
* list of choices must be specified.
*/
for (spec = specs, required = NULL, given = 0; spec->type; ++spec) {
if (!required && (spec->usage & CLI_OPT_USAGE_REQUIRED)) {
required = spec;
given = 0;
} else if (!required) {
continue;
}
if (!given)
given = spec_included(given_specs, spec);
/*
* Validate the requirement unless we're in a required
* choice. In that case, keep the required state and
* validate at the end of the choice list.
*/
if (!spec_is_choice(spec)) {
if (!given) {
opt->spec = required;
opt->status = CLI_OPT_STATUS_MISSING_ARGUMENT;
break;
}
required = NULL;
given = 0;
}
}
return opt->status;
}
cli_opt_status_t cli_opt_parse(
cli_opt *opt,
const cli_opt_spec specs[],
char **args,
size_t args_len,
unsigned int flags)
{
cli_opt_parser parser;
const cli_opt_spec **given_specs;
size_t given_idx = 0;
cli_opt_parser_init(&parser, specs, args, args_len, flags);
given_specs = alloca(sizeof(const cli_opt_spec *) * (args_len + 1));
while (cli_opt_parser_next(opt, &parser)) {
if (opt->status != CLI_OPT_STATUS_OK &&
opt->status != CLI_OPT_STATUS_DONE)
return opt->status;
if ((opt->spec->usage & CLI_OPT_USAGE_STOP_PARSING))
return (opt->status = CLI_OPT_STATUS_DONE);
given_specs[given_idx++] = opt->spec;
}
given_specs[given_idx] = NULL;
return validate_required(opt, specs, given_specs);
}
static int spec_name_fprint(FILE *file, const cli_opt_spec *spec)
{
int error;
if (spec->type == CLI_OPT_TYPE_ARG)
error = fprintf(file, "%s", spec->value_name);
else if (spec->type == CLI_OPT_TYPE_ARGS)
error = fprintf(file, "%s", spec->value_name);
else if (spec->alias && !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
error = fprintf(file, "-%c", spec->alias);
else
error = fprintf(file, "--%s", spec->name);
return error;
}
int cli_opt_status_fprint(
FILE *file,
const char *command,
const cli_opt *opt)
{
const cli_opt_spec *choice;
int error;
if (command && (error = fprintf(file, "%s: ", command)) < 0)
return error;
switch (opt->status) {
case CLI_OPT_STATUS_DONE:
error = fprintf(file, "finished processing arguments (no error)\n");
break;
case CLI_OPT_STATUS_OK:
error = fprintf(file, "no error\n");
break;
case CLI_OPT_STATUS_UNKNOWN_OPTION:
error = fprintf(file, "unknown option: %s\n", opt->arg);
break;
case CLI_OPT_STATUS_MISSING_VALUE:
if ((error = fprintf(file, "argument '")) < 0 ||
(error = spec_name_fprint(file, opt->spec)) < 0 ||
(error = fprintf(file, "' requires a value.\n")) < 0)
break;
break;
case CLI_OPT_STATUS_MISSING_ARGUMENT:
if (spec_is_choice(opt->spec)) {
int is_choice = 1;
if (spec_is_choice((opt->spec)+1))
error = fprintf(file, "one of");
else
error = fprintf(file, "either");
if (error < 0)
break;
for (choice = opt->spec; is_choice; ++choice) {
is_choice = spec_is_choice(choice);
if (!is_choice)
error = fprintf(file, " or");
else if (choice != opt->spec)
error = fprintf(file, ",");
if ((error < 0) ||
(error = fprintf(file, " '")) < 0 ||
(error = spec_name_fprint(file, choice)) < 0 ||
(error = fprintf(file, "'")) < 0)
break;
if (!spec_is_choice(choice))
break;
}
if ((error < 0) ||
(error = fprintf(file, " is required.\n")) < 0)
break;
} else {
if ((error = fprintf(file, "argument '")) < 0 ||
(error = spec_name_fprint(file, opt->spec)) < 0 ||
(error = fprintf(file, "' is required.\n")) < 0)
break;
}
break;
default:
error = fprintf(file, "unknown status: %d\n", opt->status);
break;
}
return error;
}
| libgit2-main | src/cli/opt.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "cli.h"
#include "str.h"
static int print_spec_name(git_str *out, const cli_opt_spec *spec)
{
if (spec->type == CLI_OPT_TYPE_VALUE && spec->alias &&
!(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL) &&
!(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
return git_str_printf(out, "-%c <%s>", spec->alias, spec->value_name);
if (spec->type == CLI_OPT_TYPE_VALUE && spec->alias &&
!(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
return git_str_printf(out, "-%c [<%s>]", spec->alias, spec->value_name);
if (spec->type == CLI_OPT_TYPE_VALUE &&
!(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL))
return git_str_printf(out, "--%s[=<%s>]", spec->name, spec->value_name);
if (spec->type == CLI_OPT_TYPE_VALUE)
return git_str_printf(out, "--%s=<%s>", spec->name, spec->value_name);
if (spec->type == CLI_OPT_TYPE_ARG)
return git_str_printf(out, "<%s>", spec->value_name);
if (spec->type == CLI_OPT_TYPE_ARGS)
return git_str_printf(out, "<%s>...", spec->value_name);
if (spec->type == CLI_OPT_TYPE_LITERAL)
return git_str_printf(out, "--");
if (spec->alias && !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
return git_str_printf(out, "-%c", spec->alias);
if (spec->name)
return git_str_printf(out, "--%s", spec->name);
GIT_ASSERT(0);
}
/*
* This is similar to adopt's function, but modified to understand
* that we have a command ("git") and a "subcommand" ("checkout").
* It also understands a terminal's line length and wrap appropriately,
* using a `git_str` for storage.
*/
int cli_opt_usage_fprint(
FILE *file,
const char *command,
const char *subcommand,
const cli_opt_spec specs[])
{
git_str usage = GIT_BUF_INIT, opt = GIT_BUF_INIT;
const cli_opt_spec *spec;
size_t i, prefixlen, linelen;
bool choice = false, next_choice = false, optional = false;
int error;
/* TODO: query actual console width. */
int console_width = 80;
if ((error = git_str_printf(&usage, "usage: %s", command)) < 0)
goto done;
if (subcommand &&
(error = git_str_printf(&usage, " %s", subcommand)) < 0)
goto done;
linelen = git_str_len(&usage);
prefixlen = linelen + 1;
for (spec = specs; spec->type; ++spec) {
if (!choice)
optional = !(spec->usage & CLI_OPT_USAGE_REQUIRED);
next_choice = !!((spec + 1)->usage & CLI_OPT_USAGE_CHOICE);
if (spec->usage & CLI_OPT_USAGE_HIDDEN)
continue;
if (choice)
git_str_putc(&opt, '|');
else
git_str_clear(&opt);
if (optional && !choice)
git_str_putc(&opt, '[');
if (!optional && !choice && next_choice)
git_str_putc(&opt, '(');
if ((error = print_spec_name(&opt, spec)) < 0)
goto done;
if (!optional && choice && !next_choice)
git_str_putc(&opt, ')');
else if (optional && !next_choice)
git_str_putc(&opt, ']');
if ((choice = next_choice))
continue;
if (git_str_oom(&opt)) {
error = -1;
goto done;
}
if (linelen > prefixlen &&
console_width > 0 &&
linelen + git_str_len(&opt) + 1 > (size_t)console_width) {
git_str_putc(&usage, '\n');
for (i = 0; i < prefixlen; i++)
git_str_putc(&usage, ' ');
linelen = prefixlen;
} else {
git_str_putc(&usage, ' ');
linelen += git_str_len(&opt) + 1;
}
git_str_puts(&usage, git_str_cstr(&opt));
if (git_str_oom(&usage)) {
error = -1;
goto done;
}
}
error = fprintf(file, "%s\n", git_str_cstr(&usage));
done:
error = (error < 0) ? -1 : 0;
git_str_dispose(&usage);
git_str_dispose(&opt);
return error;
}
int cli_opt_usage_error(
const char *subcommand,
const cli_opt_spec specs[],
const cli_opt *invalid_opt)
{
cli_opt_status_fprint(stderr, PROGRAM_NAME, invalid_opt);
cli_opt_usage_fprint(stderr, PROGRAM_NAME, subcommand, specs);
return CLI_EXIT_USAGE;
}
int cli_opt_help_fprint(
FILE *file,
const cli_opt_spec specs[])
{
git_str help = GIT_BUF_INIT;
const cli_opt_spec *spec;
int error = 0;
/* Display required arguments first */
for (spec = specs; spec->type; ++spec) {
if (! (spec->usage & CLI_OPT_USAGE_REQUIRED) ||
(spec->usage & CLI_OPT_USAGE_HIDDEN))
continue;
git_str_printf(&help, " ");
if ((error = print_spec_name(&help, spec)) < 0)
goto done;
git_str_printf(&help, ": %s\n", spec->help);
}
/* Display the remaining arguments */
for (spec = specs; spec->type; ++spec) {
if ((spec->usage & CLI_OPT_USAGE_REQUIRED) ||
(spec->usage & CLI_OPT_USAGE_HIDDEN))
continue;
git_str_printf(&help, " ");
if ((error = print_spec_name(&help, spec)) < 0)
goto done;
git_str_printf(&help, ": %s\n", spec->help);
}
if (git_str_oom(&help) ||
p_write(fileno(file), help.ptr, help.size) < 0)
error = -1;
done:
error = (error < 0) ? -1 : 0;
git_str_dispose(&help);
return error;
}
| libgit2-main | src/cli/opt_usage.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include <git2.h>
#include "cli.h"
#include "cmd.h"
#define COMMAND_NAME "help"
static char *command;
static int show_help;
static const cli_opt_spec opts[] = {
{ CLI_OPT_TYPE_SWITCH, "help", 0, &show_help, 1,
CLI_OPT_USAGE_HIDDEN, NULL, "display help about the help command" },
{ CLI_OPT_TYPE_ARG, "command", 0, &command, 0,
CLI_OPT_USAGE_DEFAULT, "command", "the command to show help for" },
{ 0 },
};
static int print_help(void)
{
cli_opt_usage_fprint(stdout, PROGRAM_NAME, COMMAND_NAME, opts);
printf("\n");
printf("Display help information about %s. If a command is specified, help\n", PROGRAM_NAME);
printf("about that command will be shown. Otherwise, general information about\n");
printf("%s will be shown, including the commands available.\n", PROGRAM_NAME);
return 0;
}
static int print_commands(void)
{
const cli_cmd_spec *cmd;
cli_opt_usage_fprint(stdout, PROGRAM_NAME, NULL, cli_common_opts);
printf("\n");
printf("These are the %s commands available:\n\n", PROGRAM_NAME);
for (cmd = cli_cmds; cmd->name; cmd++)
printf(" %-11s %s\n", cmd->name, cmd->desc);
printf("\nSee '%s help <command>' for more information on a specific command.\n", PROGRAM_NAME);
return 0;
}
int cmd_help(int argc, char **argv)
{
char *fake_args[2];
const cli_cmd_spec *cmd;
cli_opt invalid_opt;
if (cli_opt_parse(&invalid_opt, opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU))
return cli_opt_usage_error(COMMAND_NAME, opts, &invalid_opt);
/* Show the meta-help */
if (show_help)
return print_help();
/* We were not asked to show help for a specific command. */
if (!command)
return print_commands();
/*
* If we were asked for help for a command (eg, `help <command>`),
* delegate back to that command's `--help` option. This lets
* commands own their help. Emulate the command-line arguments
* that would invoke `<command> --help` and invoke that command.
*/
fake_args[0] = command;
fake_args[1] = "--help";
if ((cmd = cli_cmd_spec_byname(command)) == NULL)
return cli_error("'%s' is not a %s command. See '%s help'.",
command, PROGRAM_NAME, PROGRAM_NAME);
return cmd->fn(2, fake_args);
}
| libgit2-main | src/cli/cmd_help.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "cli.h"
#include "cmd.h"
const cli_cmd_spec *cli_cmd_spec_byname(const char *name)
{
const cli_cmd_spec *cmd;
for (cmd = cli_cmds; cmd->name; cmd++) {
if (!strcmp(cmd->name, name))
return cmd;
}
return NULL;
}
| libgit2-main | src/cli/cmd.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include <git2.h>
#include "cli.h"
#include "cmd.h"
static int show_help = 0;
static int show_version = 0;
static char *command = NULL;
static char **args = NULL;
const cli_opt_spec cli_common_opts[] = {
{ CLI_OPT_TYPE_SWITCH, "help", 0, &show_help, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "display help information" },
{ CLI_OPT_TYPE_SWITCH, "version", 0, &show_version, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "display the version" },
{ CLI_OPT_TYPE_ARG, "command", 0, &command, 0,
CLI_OPT_USAGE_REQUIRED, "command", "the command to run" },
{ CLI_OPT_TYPE_ARGS, "args", 0, &args, 0,
CLI_OPT_USAGE_DEFAULT, "args", "arguments for the command" },
{ 0 }
};
const cli_cmd_spec cli_cmds[] = {
{ "cat-file", cmd_cat_file, "Display an object in the repository" },
{ "clone", cmd_clone, "Clone a repository into a new directory" },
{ "hash-object", cmd_hash_object, "Hash a raw object and product its object ID" },
{ "help", cmd_help, "Display help information" },
{ NULL }
};
int main(int argc, char **argv)
{
const cli_cmd_spec *cmd;
cli_opt_parser optparser;
cli_opt opt;
char *help_args[3] = { NULL };
int help_args_len;
int args_len = 0;
int ret = 0;
if (git_libgit2_init() < 0) {
cli_error("failed to initialize libgit2");
exit(CLI_EXIT_GIT);
}
cli_opt_parser_init(&optparser, cli_common_opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU);
/* Parse the top-level (common) options and command information */
while (cli_opt_parser_next(&opt, &optparser)) {
if (!opt.spec) {
cli_opt_status_fprint(stderr, PROGRAM_NAME, &opt);
cli_opt_usage_fprint(stderr, PROGRAM_NAME, NULL, cli_common_opts);
ret = CLI_EXIT_USAGE;
goto done;
}
/*
* When we see a command, stop parsing and capture the
* remaining arguments as args for the command itself.
*/
if (command) {
args = &argv[optparser.idx];
args_len = (int)(argc - optparser.idx);
break;
}
}
if (show_version) {
printf("%s version %s\n", PROGRAM_NAME, LIBGIT2_VERSION);
goto done;
}
/*
* If `--help <command>` is specified, delegate to that command's
* `--help` option. If no command is specified, run the `help`
* command. Do this by updating the args to emulate that behavior.
*/
if (!command || show_help) {
help_args[0] = command ? (char *)command : "help";
help_args[1] = command ? "--help" : NULL;
help_args_len = command ? 2 : 1;
command = help_args[0];
args = help_args;
args_len = help_args_len;
}
if ((cmd = cli_cmd_spec_byname(command)) == NULL) {
ret = cli_error("'%s' is not a %s command. See '%s help'.",
command, PROGRAM_NAME, PROGRAM_NAME);
goto done;
}
ret = cmd->fn(args_len, args);
done:
git_libgit2_shutdown();
return ret;
}
| libgit2-main | src/cli/main.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include "progress.h"
#include "error.h"
/*
* Show updates to the percentage and number of objects received
* separately from the throughput to give an accurate progress while
* avoiding too much noise on the screen.
*/
#define PROGRESS_UPDATE_TIME 0.10
#define THROUGHPUT_UPDATE_TIME 1.00
#define is_nl(c) ((c) == '\r' || (c) == '\n')
#define return_os_error(msg) do { \
git_error_set(GIT_ERROR_OS, "%s", msg); return -1; } while(0)
GIT_INLINE(size_t) no_nl_len(const char *str, size_t len)
{
size_t i = 0;
while (i < len && !is_nl(str[i]))
i++;
return i;
}
GIT_INLINE(size_t) nl_len(bool *has_nl, const char *str, size_t len)
{
size_t i = no_nl_len(str, len);
*has_nl = false;
while (i < len && is_nl(str[i])) {
*has_nl = true;
i++;
}
return i;
}
static int progress_write(cli_progress *progress, bool force, git_str *line)
{
bool has_nl;
size_t no_nl = no_nl_len(line->ptr, line->size);
size_t nl = nl_len(&has_nl, line->ptr + no_nl, line->size - no_nl);
double now = git__timer();
size_t i;
/* Avoid spamming the console with progress updates */
if (!force && line->ptr[line->size - 1] != '\n' && progress->last_update) {
if (now - progress->last_update < PROGRESS_UPDATE_TIME) {
git_str_clear(&progress->deferred);
git_str_put(&progress->deferred, line->ptr, line->size);
return git_str_oom(&progress->deferred) ? -1 : 0;
}
}
/*
* If there's something on this line already (eg, a progress line
* with only a trailing `\r` that we'll print over) then we need
* to really print over it in case we're writing a shorter line.
*/
if (printf("%.*s", (int)no_nl, line->ptr) < 0)
return_os_error("could not print status");
if (progress->onscreen.size) {
for (i = no_nl; i < progress->onscreen.size; i++) {
if (printf(" ") < 0)
return_os_error("could not print status");
}
}
if (printf("%.*s", (int)nl, line->ptr + no_nl) < 0 ||
fflush(stdout) != 0)
return_os_error("could not print status");
git_str_clear(&progress->onscreen);
if (line->ptr[line->size - 1] == '\n') {
progress->last_update = 0;
} else {
git_str_put(&progress->onscreen, line->ptr, line->size);
progress->last_update = now;
}
git_str_clear(&progress->deferred);
return git_str_oom(&progress->onscreen) ? -1 : 0;
}
static int progress_printf(cli_progress *progress, bool force, const char *fmt, ...)
GIT_FORMAT_PRINTF(3, 4);
int progress_printf(cli_progress *progress, bool force, const char *fmt, ...)
{
git_str buf = GIT_BUF_INIT;
va_list ap;
int error;
va_start(ap, fmt);
error = git_str_vprintf(&buf, fmt, ap);
va_end(ap);
if (error < 0)
return error;
error = progress_write(progress, force, &buf);
git_str_dispose(&buf);
return error;
}
static int progress_complete(cli_progress *progress)
{
if (progress->deferred.size)
progress_write(progress, true, &progress->deferred);
if (progress->onscreen.size)
if (printf("\n") < 0)
return_os_error("could not print status");
git_str_clear(&progress->deferred);
git_str_clear(&progress->onscreen);
progress->last_update = 0;
progress->action_start = 0;
progress->action_finish = 0;
return 0;
}
GIT_INLINE(int) percent(size_t completed, size_t total)
{
if (total == 0)
return (completed == 0) ? 100 : 0;
return (int)(((double)completed / (double)total) * 100);
}
int cli_progress_fetch_sideband(const char *str, int len, void *payload)
{
cli_progress *progress = (cli_progress *)payload;
size_t remain;
if (len <= 0)
return 0;
/* Accumulate the sideband data, then print it line-at-a-time. */
if (git_str_put(&progress->sideband, str, len) < 0)
return -1;
str = progress->sideband.ptr;
remain = progress->sideband.size;
while (remain) {
bool has_nl;
size_t line_len = nl_len(&has_nl, str, remain);
if (!has_nl)
break;
if (line_len < INT_MAX) {
int error = progress_printf(progress, true,
"remote: %.*s", (int)line_len, str);
if (error < 0)
return error;
}
str += line_len;
remain -= line_len;
}
git_str_consume_bytes(&progress->sideband, (progress->sideband.size - remain));
return 0;
}
static int fetch_receiving(
cli_progress *progress,
const git_indexer_progress *stats)
{
char *recv_units[] = { "B", "KiB", "MiB", "GiB", "TiB", NULL };
char *rate_units[] = { "B/s", "KiB/s", "MiB/s", "GiB/s", "TiB/s", NULL };
double now, recv_len, rate, elapsed;
size_t recv_unit_idx = 0, rate_unit_idx = 0;
bool done = (stats->received_objects == stats->total_objects);
if (!progress->action_start)
progress->action_start = git__timer();
if (done && progress->action_finish)
now = progress->action_finish;
else if (done)
progress->action_finish = now = git__timer();
else
now = git__timer();
if (progress->throughput_update &&
now - progress->throughput_update < THROUGHPUT_UPDATE_TIME) {
elapsed = progress->throughput_update -
progress->action_start;
recv_len = progress->throughput_bytes;
} else {
elapsed = now - progress->action_start;
recv_len = (double)stats->received_bytes;
progress->throughput_update = now;
progress->throughput_bytes = recv_len;
}
rate = elapsed ? recv_len / elapsed : 0;
while (recv_len > 1024 && recv_units[recv_unit_idx+1]) {
recv_len /= 1024;
recv_unit_idx++;
}
while (rate > 1024 && rate_units[rate_unit_idx+1]) {
rate /= 1024;
rate_unit_idx++;
}
return progress_printf(progress, false,
"Receiving objects: %3d%% (%d/%d), %.2f %s | %.2f %s%s\r",
percent(stats->received_objects, stats->total_objects),
stats->received_objects,
stats->total_objects,
recv_len, recv_units[recv_unit_idx],
rate, rate_units[rate_unit_idx],
done ? ", done." : "");
}
static int fetch_resolving(
cli_progress *progress,
const git_indexer_progress *stats)
{
bool done = (stats->indexed_deltas == stats->total_deltas);
return progress_printf(progress, false,
"Resolving deltas: %3d%% (%d/%d)%s\r",
percent(stats->indexed_deltas, stats->total_deltas),
stats->indexed_deltas, stats->total_deltas,
done ? ", done." : "");
}
int cli_progress_fetch_transfer(const git_indexer_progress *stats, void *payload)
{
cli_progress *progress = (cli_progress *)payload;
int error = 0;
switch (progress->action) {
case CLI_PROGRESS_NONE:
progress->action = CLI_PROGRESS_RECEIVING;
/* fall through */
case CLI_PROGRESS_RECEIVING:
if ((error = fetch_receiving(progress, stats)) < 0)
break;
/*
* Upgrade from receiving to resolving; do this after the
* final call to cli_progress_fetch_receiving (above) to
* ensure that we've printed a final "done" string after
* any sideband data.
*/
if (!stats->indexed_deltas)
break;
progress_complete(progress);
progress->action = CLI_PROGRESS_RESOLVING;
/* fall through */
case CLI_PROGRESS_RESOLVING:
error = fetch_resolving(progress, stats);
break;
default:
/* should not be reached */
GIT_ASSERT(!"unexpected progress state");
}
return error;
}
void cli_progress_checkout(
const char *path,
size_t completed_steps,
size_t total_steps,
void *payload)
{
cli_progress *progress = (cli_progress *)payload;
bool done = (completed_steps == total_steps);
GIT_UNUSED(path);
if (progress->action != CLI_PROGRESS_CHECKING_OUT) {
progress_complete(progress);
progress->action = CLI_PROGRESS_CHECKING_OUT;
}
progress_printf(progress, false,
"Checking out files: %3d%% (%" PRIuZ "/%" PRIuZ ")%s\r",
percent(completed_steps, total_steps),
completed_steps, total_steps,
done ? ", done." : "");
}
int cli_progress_abort(cli_progress *progress)
{
if (progress->onscreen.size > 0 && printf("\n") < 0)
return_os_error("could not print status");
return 0;
}
int cli_progress_finish(cli_progress *progress)
{
int error = progress->action ? progress_complete(progress) : 0;
progress->action = 0;
return error;
}
void cli_progress_dispose(cli_progress *progress)
{
if (progress == NULL)
return;
git_str_dispose(&progress->sideband);
git_str_dispose(&progress->onscreen);
git_str_dispose(&progress->deferred);
memset(progress, 0, sizeof(cli_progress));
}
| libgit2-main | src/cli/progress.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdio.h>
#include <git2.h>
#include "cli.h"
#include "cmd.h"
#include "error.h"
#include "sighandler.h"
#include "progress.h"
#include "fs_path.h"
#include "futils.h"
#define COMMAND_NAME "clone"
static char *branch, *remote_path, *local_path;
static int show_help, quiet, checkout = 1, bare;
static bool local_path_exists;
static cli_progress progress = CLI_PROGRESS_INIT;
static const cli_opt_spec opts[] = {
{ CLI_OPT_TYPE_SWITCH, "help", 0, &show_help, 1,
CLI_OPT_USAGE_HIDDEN | CLI_OPT_USAGE_STOP_PARSING, NULL,
"display help about the " COMMAND_NAME " command" },
{ CLI_OPT_TYPE_SWITCH, "quiet", 'q', &quiet, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "display the type of the object" },
{ CLI_OPT_TYPE_SWITCH, "no-checkout", 'n', &checkout, 0,
CLI_OPT_USAGE_DEFAULT, NULL, "don't checkout HEAD" },
{ CLI_OPT_TYPE_SWITCH, "bare", 0, &bare, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "don't create a working directory" },
{ CLI_OPT_TYPE_VALUE, "branch", 'b', &branch, 0,
CLI_OPT_USAGE_DEFAULT, "name", "branch to check out" },
{ CLI_OPT_TYPE_LITERAL },
{ CLI_OPT_TYPE_ARG, "repository", 0, &remote_path, 0,
CLI_OPT_USAGE_REQUIRED, "repository", "repository path" },
{ CLI_OPT_TYPE_ARG, "directory", 0, &local_path, 0,
CLI_OPT_USAGE_DEFAULT, "directory", "directory to clone into" },
{ 0 }
};
static void print_help(void)
{
cli_opt_usage_fprint(stdout, PROGRAM_NAME, COMMAND_NAME, opts);
printf("\n");
printf("Clone a repository into a new directory.\n");
printf("\n");
printf("Options:\n");
cli_opt_help_fprint(stdout, opts);
}
static char *compute_local_path(const char *orig_path)
{
const char *slash;
char *local_path;
if ((slash = strrchr(orig_path, '/')) == NULL &&
(slash = strrchr(orig_path, '\\')) == NULL)
local_path = git__strdup(orig_path);
else
local_path = git__strdup(slash + 1);
return local_path;
}
static bool validate_local_path(const char *path)
{
if (!git_fs_path_exists(path))
return false;
if (!git_fs_path_isdir(path) || !git_fs_path_is_empty_dir(path)) {
fprintf(stderr, "fatal: destination path '%s' already exists and is not an empty directory.\n",
path);
exit(128);
}
return true;
}
static void cleanup(void)
{
int rmdir_flags = GIT_RMDIR_REMOVE_FILES;
cli_progress_abort(&progress);
if (local_path_exists)
rmdir_flags |= GIT_RMDIR_SKIP_ROOT;
if (!git_fs_path_isdir(local_path))
return;
git_futils_rmdir_r(local_path, NULL, rmdir_flags);
}
static void interrupt_cleanup(void)
{
cleanup();
exit(130);
}
int cmd_clone(int argc, char **argv)
{
git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
git_repository *repo = NULL;
cli_opt invalid_opt;
char *computed_path = NULL;
int ret = 0;
if (cli_opt_parse(&invalid_opt, opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU))
return cli_opt_usage_error(COMMAND_NAME, opts, &invalid_opt);
if (show_help) {
print_help();
return 0;
}
if (!remote_path) {
ret = cli_error_usage("you must specify a repository to clone");
goto done;
}
if (bare)
clone_opts.bare = 1;
if (branch)
clone_opts.checkout_branch = branch;
if (!checkout)
clone_opts.checkout_opts.checkout_strategy = GIT_CHECKOUT_NONE;
if (!local_path)
local_path = computed_path = compute_local_path(remote_path);
local_path_exists = validate_local_path(local_path);
cli_sighandler_set_interrupt(interrupt_cleanup);
if (!local_path_exists &&
git_futils_mkdir(local_path, 0777, 0) < 0) {
ret = cli_error_git();
goto done;
}
if (!quiet) {
clone_opts.fetch_opts.callbacks.sideband_progress = cli_progress_fetch_sideband;
clone_opts.fetch_opts.callbacks.transfer_progress = cli_progress_fetch_transfer;
clone_opts.fetch_opts.callbacks.payload = &progress;
clone_opts.checkout_opts.progress_cb = cli_progress_checkout;
clone_opts.checkout_opts.progress_payload = &progress;
printf("Cloning into '%s'...\n", local_path);
}
if (git_clone(&repo, remote_path, local_path, &clone_opts) < 0) {
cleanup();
ret = cli_error_git();
goto done;
}
cli_progress_finish(&progress);
done:
cli_progress_dispose(&progress);
git__free(computed_path);
git_repository_free(repo);
return ret;
}
| libgit2-main | src/cli/cmd_clone.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <git2.h>
#include "cli.h"
#include "cmd.h"
#define COMMAND_NAME "cat-file"
typedef enum {
DISPLAY_CONTENT = 0,
DISPLAY_EXISTS,
DISPLAY_PRETTY,
DISPLAY_SIZE,
DISPLAY_TYPE
} display_t;
static int show_help;
static int display = DISPLAY_CONTENT;
static char *type_name, *object_spec;
static const cli_opt_spec opts[] = {
{ CLI_OPT_TYPE_SWITCH, "help", 0, &show_help, 1,
CLI_OPT_USAGE_HIDDEN | CLI_OPT_USAGE_STOP_PARSING, NULL,
"display help about the " COMMAND_NAME " command" },
{ CLI_OPT_TYPE_SWITCH, NULL, 't', &display, DISPLAY_TYPE,
CLI_OPT_USAGE_REQUIRED, NULL, "display the type of the object" },
{ CLI_OPT_TYPE_SWITCH, NULL, 's', &display, DISPLAY_SIZE,
CLI_OPT_USAGE_CHOICE, NULL, "display the size of the object" },
{ CLI_OPT_TYPE_SWITCH, NULL, 'e', &display, DISPLAY_EXISTS,
CLI_OPT_USAGE_CHOICE, NULL, "displays nothing unless the object is corrupt" },
{ CLI_OPT_TYPE_SWITCH, NULL, 'p', &display, DISPLAY_PRETTY,
CLI_OPT_USAGE_CHOICE, NULL, "pretty-print the object" },
{ CLI_OPT_TYPE_ARG, "type", 0, &type_name, 0,
CLI_OPT_USAGE_CHOICE, "type", "the type of object to display" },
{ CLI_OPT_TYPE_ARG, "object", 0, &object_spec, 0,
CLI_OPT_USAGE_REQUIRED, "object", "the object to display" },
{ 0 },
};
static void print_help(void)
{
cli_opt_usage_fprint(stdout, PROGRAM_NAME, COMMAND_NAME, opts);
printf("\n");
printf("Display the content for the given object in the repository.\n");
printf("\n");
printf("Options:\n");
cli_opt_help_fprint(stdout, opts);
}
static int print_odb(git_object *object, display_t display)
{
git_odb *odb = NULL;
git_odb_object *odb_object = NULL;
const unsigned char *content;
git_object_size_t size;
int ret = 0;
/*
* Our parsed blobs retain the raw content; all other objects are
* parsed into a working representation. To get the raw content,
* we need to do an ODB lookup. (Thankfully, this should be cached
* in-memory from our last call.)
*/
if (git_object_type(object) == GIT_OBJECT_BLOB) {
content = git_blob_rawcontent((git_blob *)object);
size = git_blob_rawsize((git_blob *)object);
} else {
if (git_repository_odb(&odb, git_object_owner(object)) < 0 ||
git_odb_read(&odb_object, odb, git_object_id(object)) < 0) {
ret = cli_error_git();
goto done;
}
content = git_odb_object_data(odb_object);
size = git_odb_object_size(odb_object);
}
switch (display) {
case DISPLAY_SIZE:
if (printf("%" PRIu64 "\n", size) < 0)
ret = cli_error_os();
break;
case DISPLAY_CONTENT:
if (p_write(fileno(stdout), content, (size_t)size) < 0)
ret = cli_error_os();
break;
default:
GIT_ASSERT(0);
}
done:
git_odb_object_free(odb_object);
git_odb_free(odb);
return ret;
}
static int print_type(git_object *object)
{
if (printf("%s\n", git_object_type2string(git_object_type(object))) < 0)
return cli_error_os();
return 0;
}
static int print_pretty(git_object *object)
{
const git_tree_entry *entry;
size_t i, count;
/*
* Only trees are stored in an unreadable format and benefit from
* pretty-printing.
*/
if (git_object_type(object) != GIT_OBJECT_TREE)
return print_odb(object, DISPLAY_CONTENT);
for (i = 0, count = git_tree_entrycount((git_tree *)object); i < count; i++) {
entry = git_tree_entry_byindex((git_tree *)object, i);
if (printf("%06o %s %s\t%s\n",
git_tree_entry_filemode_raw(entry),
git_object_type2string(git_tree_entry_type(entry)),
git_oid_tostr_s(git_tree_entry_id(entry)),
git_tree_entry_name(entry)) < 0)
return cli_error_os();
}
return 0;
}
int cmd_cat_file(int argc, char **argv)
{
git_repository *repo = NULL;
git_object *object = NULL;
git_object_t type;
cli_opt invalid_opt;
int giterr, ret = 0;
if (cli_opt_parse(&invalid_opt, opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU))
return cli_opt_usage_error(COMMAND_NAME, opts, &invalid_opt);
if (show_help) {
print_help();
return 0;
}
if (git_repository_open_ext(&repo, ".", GIT_REPOSITORY_OPEN_FROM_ENV, NULL) < 0)
return cli_error_git();
if ((giterr = git_revparse_single(&object, repo, object_spec)) < 0) {
if (display == DISPLAY_EXISTS && giterr == GIT_ENOTFOUND)
ret = 1;
else
ret = cli_error_git();
goto done;
}
if (type_name) {
git_object *peeled;
if ((type = git_object_string2type(type_name)) == GIT_OBJECT_INVALID) {
ret = cli_error_usage("invalid object type '%s'", type_name);
goto done;
}
if (git_object_peel(&peeled, object, type) < 0) {
ret = cli_error_git();
goto done;
}
git_object_free(object);
object = peeled;
}
switch (display) {
case DISPLAY_EXISTS:
ret = 0;
break;
case DISPLAY_TYPE:
ret = print_type(object);
break;
case DISPLAY_PRETTY:
ret = print_pretty(object);
break;
default:
ret = print_odb(object, display);
break;
}
done:
git_object_free(object);
git_repository_free(repo);
return ret;
}
| libgit2-main | src/cli/cmd_cat_file.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <git2.h>
#include "cli.h"
#include "cmd.h"
#include "futils.h"
#define COMMAND_NAME "hash-object"
static int show_help;
static char *type_name;
static int write_object, read_stdin, literally;
static char **filenames;
static const cli_opt_spec opts[] = {
{ CLI_OPT_TYPE_SWITCH, "help", 0, &show_help, 1,
CLI_OPT_USAGE_HIDDEN | CLI_OPT_USAGE_STOP_PARSING, NULL,
"display help about the " COMMAND_NAME " command" },
{ CLI_OPT_TYPE_VALUE, NULL, 't', &type_name, 0,
CLI_OPT_USAGE_DEFAULT, "type", "the type of object to hash (default: \"blob\")" },
{ CLI_OPT_TYPE_SWITCH, NULL, 'w', &write_object, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "write the object to the object database" },
{ CLI_OPT_TYPE_SWITCH, "literally", 0, &literally, 1,
CLI_OPT_USAGE_DEFAULT, NULL, "do not validate the object contents" },
{ CLI_OPT_TYPE_SWITCH, "stdin", 0, &read_stdin, 1,
CLI_OPT_USAGE_REQUIRED, NULL, "read content from stdin" },
{ CLI_OPT_TYPE_ARGS, "file", 0, &filenames, 0,
CLI_OPT_USAGE_CHOICE, "file", "the file (or files) to read and hash" },
{ 0 },
};
static void print_help(void)
{
cli_opt_usage_fprint(stdout, PROGRAM_NAME, COMMAND_NAME, opts);
printf("\n");
printf("Compute the object ID for a given file and optionally write that file\nto the object database.\n");
printf("\n");
printf("Options:\n");
cli_opt_help_fprint(stdout, opts);
}
static int hash_buf(git_odb *odb, git_str *buf, git_object_t type)
{
git_oid oid;
if (!literally) {
int valid = 0;
if (git_object_rawcontent_is_valid(&valid, buf->ptr, buf->size, type) < 0 || !valid)
return cli_error_git();
}
if (write_object) {
if (git_odb_write(&oid, odb, buf->ptr, buf->size, type) < 0)
return cli_error_git();
} else {
#ifdef GIT_EXPERIMENTAL_SHA256
if (git_odb_hash(&oid, buf->ptr, buf->size, type, GIT_OID_SHA1) < 0)
return cli_error_git();
#else
if (git_odb_hash(&oid, buf->ptr, buf->size, type) < 0)
return cli_error_git();
#endif
}
if (printf("%s\n", git_oid_tostr_s(&oid)) < 0)
return cli_error_os();
return 0;
}
int cmd_hash_object(int argc, char **argv)
{
git_repository *repo = NULL;
git_odb *odb = NULL;
git_str buf = GIT_STR_INIT;
cli_opt invalid_opt;
git_object_t type = GIT_OBJECT_BLOB;
char **filename;
int ret = 0;
if (cli_opt_parse(&invalid_opt, opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU))
return cli_opt_usage_error(COMMAND_NAME, opts, &invalid_opt);
if (show_help) {
print_help();
return 0;
}
if (type_name && (type = git_object_string2type(type_name)) == GIT_OBJECT_INVALID)
return cli_error_usage("invalid object type '%s'", type_name);
if (write_object &&
(git_repository_open_ext(&repo, ".", GIT_REPOSITORY_OPEN_FROM_ENV, NULL) < 0 ||
git_repository_odb(&odb, repo) < 0)) {
ret = cli_error_git();
goto done;
}
/*
* TODO: we're reading blobs, we shouldn't pull them all into main
* memory, we should just stream them into the odb instead.
* (Or create a `git_odb_writefile` API.)
*/
if (read_stdin) {
if (git_futils_readbuffer_fd_full(&buf, fileno(stdin)) < 0) {
ret = cli_error_git();
goto done;
}
if ((ret = hash_buf(odb, &buf, type)) != 0)
goto done;
} else {
for (filename = filenames; *filename; filename++) {
if (git_futils_readbuffer(&buf, *filename) < 0) {
ret = cli_error_git();
goto done;
}
if ((ret = hash_buf(odb, &buf, type)) != 0)
goto done;
}
}
done:
git_str_dispose(&buf);
git_odb_free(odb);
git_repository_free(repo);
return ret;
}
| libgit2-main | src/cli/cmd_hash_object.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include <stdint.h>
#include <signal.h>
#include "git2_util.h"
#include "cli.h"
static void (*interrupt_handler)(void) = NULL;
static void interrupt_proxy(int signal)
{
GIT_UNUSED(signal);
interrupt_handler();
}
int cli_sighandler_set_interrupt(void (*handler)(void))
{
void (*result)(int);
if ((interrupt_handler = handler) != NULL)
result = signal(SIGINT, interrupt_proxy);
else
result = signal(SIGINT, SIG_DFL);
if (result == SIG_ERR) {
git_error_set(GIT_ERROR_OS, "could not set signal handler");
return -1;
}
return 0;
}
| libgit2-main | src/cli/unix/sighandler.c |
#include "precompiled.h"
| libgit2-main | src/cli/win32/precompiled.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "git2_util.h"
#include <windows.h>
#include "cli.h"
static void (*interrupt_handler)(void) = NULL;
static BOOL WINAPI interrupt_proxy(DWORD signal)
{
GIT_UNUSED(signal);
interrupt_handler();
return TRUE;
}
int cli_sighandler_set_interrupt(void (*handler)(void))
{
BOOL result;
if ((interrupt_handler = handler) != NULL)
result = SetConsoleCtrlHandler(interrupt_proxy, FALSE);
else
result = SetConsoleCtrlHandler(NULL, FALSE);
if (!result) {
git_error_set(GIT_ERROR_OS, "could not set control control handler");
return -1;
}
return 0;
}
| libgit2-main | src/cli/win32/sighandler.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "commit_graph.h"
#include "array.h"
#include "buf.h"
#include "filebuf.h"
#include "futils.h"
#include "hash.h"
#include "oidarray.h"
#include "oidmap.h"
#include "pack.h"
#include "repository.h"
#include "revwalk.h"
#define GIT_COMMIT_GRAPH_MISSING_PARENT 0x70000000
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX 0x3FFFFFFF
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_INFINITY 0xFFFFFFFF
#define COMMIT_GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
#define COMMIT_GRAPH_VERSION 1
#define COMMIT_GRAPH_OBJECT_ID_VERSION 1
struct git_commit_graph_header {
uint32_t signature;
uint8_t version;
uint8_t object_id_version;
uint8_t chunks;
uint8_t base_graph_files;
};
#define COMMIT_GRAPH_OID_FANOUT_ID 0x4f494446 /* "OIDF" */
#define COMMIT_GRAPH_OID_LOOKUP_ID 0x4f49444c /* "OIDL" */
#define COMMIT_GRAPH_COMMIT_DATA_ID 0x43444154 /* "CDAT" */
#define COMMIT_GRAPH_EXTRA_EDGE_LIST_ID 0x45444745 /* "EDGE" */
#define COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID 0x42494458 /* "BIDX" */
#define COMMIT_GRAPH_BLOOM_FILTER_DATA_ID 0x42444154 /* "BDAT" */
struct git_commit_graph_chunk {
off64_t offset;
size_t length;
};
typedef git_array_t(size_t) parent_index_array_t;
struct packed_commit {
size_t index;
git_oid sha1;
git_oid tree_oid;
uint32_t generation;
git_time_t commit_time;
git_array_oid_t parents;
parent_index_array_t parent_indices;
};
static void packed_commit_free(struct packed_commit *p)
{
if (!p)
return;
git_array_clear(p->parents);
git_array_clear(p->parent_indices);
git__free(p);
}
static struct packed_commit *packed_commit_new(git_commit *commit)
{
unsigned int i, parentcount = git_commit_parentcount(commit);
struct packed_commit *p = git__calloc(1, sizeof(struct packed_commit));
if (!p)
goto cleanup;
git_array_init_to_size(p->parents, parentcount);
if (parentcount && !p->parents.ptr)
goto cleanup;
if (git_oid_cpy(&p->sha1, git_commit_id(commit)) < 0)
goto cleanup;
if (git_oid_cpy(&p->tree_oid, git_commit_tree_id(commit)) < 0)
goto cleanup;
p->commit_time = git_commit_time(commit);
for (i = 0; i < parentcount; ++i) {
git_oid *parent_id = git_array_alloc(p->parents);
if (!parent_id)
goto cleanup;
if (git_oid_cpy(parent_id, git_commit_parent_id(commit, i)) < 0)
goto cleanup;
}
return p;
cleanup:
packed_commit_free(p);
return NULL;
}
typedef int (*commit_graph_write_cb)(const char *buf, size_t size, void *cb_data);
static int commit_graph_error(const char *message)
{
git_error_set(GIT_ERROR_ODB, "invalid commit-graph file - %s", message);
return -1;
}
static int commit_graph_parse_oid_fanout(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_oid_fanout)
{
uint32_t i, nr;
if (chunk_oid_fanout->offset == 0)
return commit_graph_error("missing OID Fanout chunk");
if (chunk_oid_fanout->length == 0)
return commit_graph_error("empty OID Fanout chunk");
if (chunk_oid_fanout->length != 256 * 4)
return commit_graph_error("OID Fanout chunk has wrong length");
file->oid_fanout = (const uint32_t *)(data + chunk_oid_fanout->offset);
nr = 0;
for (i = 0; i < 256; ++i) {
uint32_t n = ntohl(file->oid_fanout[i]);
if (n < nr)
return commit_graph_error("index is non-monotonic");
nr = n;
}
file->num_commits = nr;
return 0;
}
static int commit_graph_parse_oid_lookup(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_oid_lookup)
{
uint32_t i;
unsigned char *oid, *prev_oid, zero_oid[GIT_OID_SHA1_SIZE] = {0};
if (chunk_oid_lookup->offset == 0)
return commit_graph_error("missing OID Lookup chunk");
if (chunk_oid_lookup->length == 0)
return commit_graph_error("empty OID Lookup chunk");
if (chunk_oid_lookup->length != file->num_commits * GIT_OID_SHA1_SIZE)
return commit_graph_error("OID Lookup chunk has wrong length");
file->oid_lookup = oid = (unsigned char *)(data + chunk_oid_lookup->offset);
prev_oid = zero_oid;
for (i = 0; i < file->num_commits; ++i, oid += GIT_OID_SHA1_SIZE) {
if (git_oid_raw_cmp(prev_oid, oid, GIT_OID_SHA1_SIZE) >= 0)
return commit_graph_error("OID Lookup index is non-monotonic");
prev_oid = oid;
}
return 0;
}
static int commit_graph_parse_commit_data(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_commit_data)
{
if (chunk_commit_data->offset == 0)
return commit_graph_error("missing Commit Data chunk");
if (chunk_commit_data->length == 0)
return commit_graph_error("empty Commit Data chunk");
if (chunk_commit_data->length != file->num_commits * (GIT_OID_SHA1_SIZE + 16))
return commit_graph_error("Commit Data chunk has wrong length");
file->commit_data = data + chunk_commit_data->offset;
return 0;
}
static int commit_graph_parse_extra_edge_list(
git_commit_graph_file *file,
const unsigned char *data,
struct git_commit_graph_chunk *chunk_extra_edge_list)
{
if (chunk_extra_edge_list->length == 0)
return 0;
if (chunk_extra_edge_list->length % 4 != 0)
return commit_graph_error("malformed Extra Edge List chunk");
file->extra_edge_list = data + chunk_extra_edge_list->offset;
file->num_extra_edge_list = chunk_extra_edge_list->length / 4;
return 0;
}
int git_commit_graph_file_parse(
git_commit_graph_file *file,
const unsigned char *data,
size_t size)
{
struct git_commit_graph_header *hdr;
const unsigned char *chunk_hdr;
struct git_commit_graph_chunk *last_chunk;
uint32_t i;
off64_t last_chunk_offset, chunk_offset, trailer_offset;
unsigned char checksum[GIT_HASH_SHA1_SIZE];
size_t checksum_size;
int error;
struct git_commit_graph_chunk chunk_oid_fanout = {0}, chunk_oid_lookup = {0},
chunk_commit_data = {0}, chunk_extra_edge_list = {0},
chunk_unsupported = {0};
GIT_ASSERT_ARG(file);
if (size < sizeof(struct git_commit_graph_header) + GIT_OID_SHA1_SIZE)
return commit_graph_error("commit-graph is too short");
hdr = ((struct git_commit_graph_header *)data);
if (hdr->signature != htonl(COMMIT_GRAPH_SIGNATURE) || hdr->version != COMMIT_GRAPH_VERSION
|| hdr->object_id_version != COMMIT_GRAPH_OBJECT_ID_VERSION) {
return commit_graph_error("unsupported commit-graph version");
}
if (hdr->chunks == 0)
return commit_graph_error("no chunks in commit-graph");
/*
* The very first chunk's offset should be after the header, all the chunk
* headers, and a special zero chunk.
*/
last_chunk_offset = sizeof(struct git_commit_graph_header) + (1 + hdr->chunks) * 12;
trailer_offset = size - GIT_OID_SHA1_SIZE;
checksum_size = GIT_HASH_SHA1_SIZE;
if (trailer_offset < last_chunk_offset)
return commit_graph_error("wrong commit-graph size");
memcpy(file->checksum, (data + trailer_offset), checksum_size);
if (git_hash_buf(checksum, data, (size_t)trailer_offset, GIT_HASH_ALGORITHM_SHA1) < 0)
return commit_graph_error("could not calculate signature");
if (memcmp(checksum, file->checksum, checksum_size) != 0)
return commit_graph_error("index signature mismatch");
chunk_hdr = data + sizeof(struct git_commit_graph_header);
last_chunk = NULL;
for (i = 0; i < hdr->chunks; ++i, chunk_hdr += 12) {
chunk_offset = ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 4)))) << 32
| ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 8))));
if (chunk_offset < last_chunk_offset)
return commit_graph_error("chunks are non-monotonic");
if (chunk_offset >= trailer_offset)
return commit_graph_error("chunks extend beyond the trailer");
if (last_chunk != NULL)
last_chunk->length = (size_t)(chunk_offset - last_chunk_offset);
last_chunk_offset = chunk_offset;
switch (ntohl(*((uint32_t *)(chunk_hdr + 0)))) {
case COMMIT_GRAPH_OID_FANOUT_ID:
chunk_oid_fanout.offset = last_chunk_offset;
last_chunk = &chunk_oid_fanout;
break;
case COMMIT_GRAPH_OID_LOOKUP_ID:
chunk_oid_lookup.offset = last_chunk_offset;
last_chunk = &chunk_oid_lookup;
break;
case COMMIT_GRAPH_COMMIT_DATA_ID:
chunk_commit_data.offset = last_chunk_offset;
last_chunk = &chunk_commit_data;
break;
case COMMIT_GRAPH_EXTRA_EDGE_LIST_ID:
chunk_extra_edge_list.offset = last_chunk_offset;
last_chunk = &chunk_extra_edge_list;
break;
case COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID:
case COMMIT_GRAPH_BLOOM_FILTER_DATA_ID:
chunk_unsupported.offset = last_chunk_offset;
last_chunk = &chunk_unsupported;
break;
default:
return commit_graph_error("unrecognized chunk ID");
}
}
last_chunk->length = (size_t)(trailer_offset - last_chunk_offset);
error = commit_graph_parse_oid_fanout(file, data, &chunk_oid_fanout);
if (error < 0)
return error;
error = commit_graph_parse_oid_lookup(file, data, &chunk_oid_lookup);
if (error < 0)
return error;
error = commit_graph_parse_commit_data(file, data, &chunk_commit_data);
if (error < 0)
return error;
error = commit_graph_parse_extra_edge_list(file, data, &chunk_extra_edge_list);
if (error < 0)
return error;
return 0;
}
int git_commit_graph_new(git_commit_graph **cgraph_out, const char *objects_dir, bool open_file)
{
git_commit_graph *cgraph = NULL;
int error = 0;
GIT_ASSERT_ARG(cgraph_out);
GIT_ASSERT_ARG(objects_dir);
cgraph = git__calloc(1, sizeof(git_commit_graph));
GIT_ERROR_CHECK_ALLOC(cgraph);
error = git_str_joinpath(&cgraph->filename, objects_dir, "info/commit-graph");
if (error < 0)
goto error;
if (open_file) {
error = git_commit_graph_file_open(&cgraph->file, git_str_cstr(&cgraph->filename));
if (error < 0)
goto error;
cgraph->checked = 1;
}
*cgraph_out = cgraph;
return 0;
error:
git_commit_graph_free(cgraph);
return error;
}
int git_commit_graph_open(git_commit_graph **cgraph_out, const char *objects_dir)
{
return git_commit_graph_new(cgraph_out, objects_dir, true);
}
int git_commit_graph_file_open(git_commit_graph_file **file_out, const char *path)
{
git_commit_graph_file *file;
git_file fd = -1;
size_t cgraph_size;
struct stat st;
int error;
/* TODO: properly open the file without access time using O_NOATIME */
fd = git_futils_open_ro(path);
if (fd < 0)
return fd;
if (p_fstat(fd, &st) < 0) {
p_close(fd);
git_error_set(GIT_ERROR_ODB, "commit-graph file not found - '%s'", path);
return GIT_ENOTFOUND;
}
if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)) {
p_close(fd);
git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path);
return GIT_ENOTFOUND;
}
cgraph_size = (size_t)st.st_size;
file = git__calloc(1, sizeof(git_commit_graph_file));
GIT_ERROR_CHECK_ALLOC(file);
error = git_futils_mmap_ro(&file->graph_map, fd, 0, cgraph_size);
p_close(fd);
if (error < 0) {
git_commit_graph_file_free(file);
return error;
}
if ((error = git_commit_graph_file_parse(file, file->graph_map.data, cgraph_size)) < 0) {
git_commit_graph_file_free(file);
return error;
}
*file_out = file;
return 0;
}
int git_commit_graph_get_file(git_commit_graph_file **file_out, git_commit_graph *cgraph)
{
if (!cgraph->checked) {
int error = 0;
git_commit_graph_file *result = NULL;
/* We only check once, no matter the result. */
cgraph->checked = 1;
/* Best effort */
error = git_commit_graph_file_open(&result, git_str_cstr(&cgraph->filename));
if (error < 0)
return error;
cgraph->file = result;
}
if (!cgraph->file)
return GIT_ENOTFOUND;
*file_out = cgraph->file;
return 0;
}
void git_commit_graph_refresh(git_commit_graph *cgraph)
{
if (!cgraph->checked)
return;
if (cgraph->file
&& git_commit_graph_file_needs_refresh(cgraph->file, git_str_cstr(&cgraph->filename))) {
/* We just free the commit graph. The next time it is requested, it will be
* re-loaded. */
git_commit_graph_file_free(cgraph->file);
cgraph->file = NULL;
}
/* Force a lazy re-check next time it is needed. */
cgraph->checked = 0;
}
static int git_commit_graph_entry_get_byindex(
git_commit_graph_entry *e,
const git_commit_graph_file *file,
size_t pos)
{
const unsigned char *commit_data;
GIT_ASSERT_ARG(e);
GIT_ASSERT_ARG(file);
if (pos >= file->num_commits) {
git_error_set(GIT_ERROR_INVALID, "commit index %zu does not exist", pos);
return GIT_ENOTFOUND;
}
commit_data = file->commit_data + pos * (GIT_OID_SHA1_SIZE + 4 * sizeof(uint32_t));
git_oid__fromraw(&e->tree_oid, commit_data, GIT_OID_SHA1);
e->parent_indices[0] = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE)));
e->parent_indices[1] = ntohl(
*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + sizeof(uint32_t))));
e->parent_count = (e->parent_indices[0] != GIT_COMMIT_GRAPH_MISSING_PARENT)
+ (e->parent_indices[1] != GIT_COMMIT_GRAPH_MISSING_PARENT);
e->generation = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + 2 * sizeof(uint32_t))));
e->commit_time = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + 3 * sizeof(uint32_t))));
e->commit_time |= (e->generation & UINT64_C(0x3)) << UINT64_C(32);
e->generation >>= 2u;
if (e->parent_indices[1] & 0x80000000u) {
uint32_t extra_edge_list_pos = e->parent_indices[1] & 0x7fffffff;
/* Make sure we're not being sent out of bounds */
if (extra_edge_list_pos >= file->num_extra_edge_list) {
git_error_set(GIT_ERROR_INVALID,
"commit %u does not exist",
extra_edge_list_pos);
return GIT_ENOTFOUND;
}
e->extra_parents_index = extra_edge_list_pos;
while (extra_edge_list_pos < file->num_extra_edge_list
&& (ntohl(*(
(uint32_t *)(file->extra_edge_list
+ extra_edge_list_pos * sizeof(uint32_t))))
& 0x80000000u)
== 0) {
extra_edge_list_pos++;
e->parent_count++;
}
}
git_oid__fromraw(&e->sha1, &file->oid_lookup[pos * GIT_OID_SHA1_SIZE], GIT_OID_SHA1);
return 0;
}
bool git_commit_graph_file_needs_refresh(const git_commit_graph_file *file, const char *path)
{
git_file fd = -1;
struct stat st;
ssize_t bytes_read;
unsigned char checksum[GIT_HASH_SHA1_SIZE];
size_t checksum_size = GIT_HASH_SHA1_SIZE;
/* TODO: properly open the file without access time using O_NOATIME */
fd = git_futils_open_ro(path);
if (fd < 0)
return true;
if (p_fstat(fd, &st) < 0) {
p_close(fd);
return true;
}
if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)
|| (size_t)st.st_size != file->graph_map.len) {
p_close(fd);
return true;
}
bytes_read = p_pread(fd, checksum, checksum_size, st.st_size - checksum_size);
p_close(fd);
if (bytes_read != (ssize_t)checksum_size)
return true;
return (memcmp(checksum, file->checksum, checksum_size) != 0);
}
int git_commit_graph_entry_find(
git_commit_graph_entry *e,
const git_commit_graph_file *file,
const git_oid *short_oid,
size_t len)
{
int pos, found = 0;
uint32_t hi, lo;
const unsigned char *current = NULL;
GIT_ASSERT_ARG(e);
GIT_ASSERT_ARG(file);
GIT_ASSERT_ARG(short_oid);
hi = ntohl(file->oid_fanout[(int)short_oid->id[0]]);
lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(file->oid_fanout[(int)short_oid->id[0] - 1]));
pos = git_pack__lookup_sha1(file->oid_lookup, GIT_OID_SHA1_SIZE, lo, hi, short_oid->id);
if (pos >= 0) {
/* An object matching exactly the oid was found */
found = 1;
current = file->oid_lookup + (pos * GIT_OID_SHA1_SIZE);
} else {
/* No object was found */
/* pos refers to the object with the "closest" oid to short_oid */
pos = -1 - pos;
if (pos < (int)file->num_commits) {
current = file->oid_lookup + (pos * GIT_OID_SHA1_SIZE);
if (!git_oid_raw_ncmp(short_oid->id, current, len))
found = 1;
}
}
if (found && len != GIT_OID_SHA1_HEXSIZE && pos + 1 < (int)file->num_commits) {
/* Check for ambiguousity */
const unsigned char *next = current + GIT_OID_SHA1_SIZE;
if (!git_oid_raw_ncmp(short_oid->id, next, len))
found = 2;
}
if (!found)
return git_odb__error_notfound(
"failed to find offset for commit-graph index entry", short_oid, len);
if (found > 1)
return git_odb__error_ambiguous(
"found multiple offsets for commit-graph index entry");
return git_commit_graph_entry_get_byindex(e, file, pos);
}
int git_commit_graph_entry_parent(
git_commit_graph_entry *parent,
const git_commit_graph_file *file,
const git_commit_graph_entry *entry,
size_t n)
{
GIT_ASSERT_ARG(parent);
GIT_ASSERT_ARG(file);
if (n >= entry->parent_count) {
git_error_set(GIT_ERROR_INVALID, "parent index %zu does not exist", n);
return GIT_ENOTFOUND;
}
if (n == 0 || (n == 1 && entry->parent_count == 2))
return git_commit_graph_entry_get_byindex(parent, file, entry->parent_indices[n]);
return git_commit_graph_entry_get_byindex(
parent,
file,
ntohl(
*(uint32_t *)(file->extra_edge_list
+ (entry->extra_parents_index + n - 1)
* sizeof(uint32_t)))
& 0x7fffffff);
}
int git_commit_graph_file_close(git_commit_graph_file *file)
{
GIT_ASSERT_ARG(file);
if (file->graph_map.data)
git_futils_mmap_free(&file->graph_map);
return 0;
}
void git_commit_graph_free(git_commit_graph *cgraph)
{
if (!cgraph)
return;
git_str_dispose(&cgraph->filename);
git_commit_graph_file_free(cgraph->file);
git__free(cgraph);
}
void git_commit_graph_file_free(git_commit_graph_file *file)
{
if (!file)
return;
git_commit_graph_file_close(file);
git__free(file);
}
static int packed_commit__cmp(const void *a_, const void *b_)
{
const struct packed_commit *a = a_;
const struct packed_commit *b = b_;
return git_oid_cmp(&a->sha1, &b->sha1);
}
int git_commit_graph_writer_new(git_commit_graph_writer **out, const char *objects_info_dir)
{
git_commit_graph_writer *w = git__calloc(1, sizeof(git_commit_graph_writer));
GIT_ERROR_CHECK_ALLOC(w);
if (git_str_sets(&w->objects_info_dir, objects_info_dir) < 0) {
git__free(w);
return -1;
}
if (git_vector_init(&w->commits, 0, packed_commit__cmp) < 0) {
git_str_dispose(&w->objects_info_dir);
git__free(w);
return -1;
}
*out = w;
return 0;
}
void git_commit_graph_writer_free(git_commit_graph_writer *w)
{
struct packed_commit *packed_commit;
size_t i;
if (!w)
return;
git_vector_foreach (&w->commits, i, packed_commit)
packed_commit_free(packed_commit);
git_vector_free(&w->commits);
git_str_dispose(&w->objects_info_dir);
git__free(w);
}
struct object_entry_cb_state {
git_repository *repo;
git_odb *db;
git_vector *commits;
};
static int object_entry__cb(const git_oid *id, void *data)
{
struct object_entry_cb_state *state = (struct object_entry_cb_state *)data;
git_commit *commit = NULL;
struct packed_commit *packed_commit = NULL;
size_t header_len;
git_object_t header_type;
int error = 0;
error = git_odb_read_header(&header_len, &header_type, state->db, id);
if (error < 0)
return error;
if (header_type != GIT_OBJECT_COMMIT)
return 0;
error = git_commit_lookup(&commit, state->repo, id);
if (error < 0)
return error;
packed_commit = packed_commit_new(commit);
git_commit_free(commit);
GIT_ERROR_CHECK_ALLOC(packed_commit);
error = git_vector_insert(state->commits, packed_commit);
if (error < 0) {
packed_commit_free(packed_commit);
return error;
}
return 0;
}
int git_commit_graph_writer_add_index_file(
git_commit_graph_writer *w,
git_repository *repo,
const char *idx_path)
{
int error;
struct git_pack_file *p = NULL;
struct object_entry_cb_state state = {0};
state.repo = repo;
state.commits = &w->commits;
error = git_repository_odb(&state.db, repo);
if (error < 0)
goto cleanup;
error = git_mwindow_get_pack(&p, idx_path);
if (error < 0)
goto cleanup;
error = git_pack_foreach_entry(p, object_entry__cb, &state);
if (error < 0)
goto cleanup;
cleanup:
if (p)
git_mwindow_put_pack(p);
git_odb_free(state.db);
return error;
}
int git_commit_graph_writer_add_revwalk(git_commit_graph_writer *w, git_revwalk *walk)
{
int error;
git_oid id;
git_repository *repo = git_revwalk_repository(walk);
git_commit *commit;
struct packed_commit *packed_commit;
while ((git_revwalk_next(&id, walk)) == 0) {
error = git_commit_lookup(&commit, repo, &id);
if (error < 0)
return error;
packed_commit = packed_commit_new(commit);
git_commit_free(commit);
GIT_ERROR_CHECK_ALLOC(packed_commit);
error = git_vector_insert(&w->commits, packed_commit);
if (error < 0) {
packed_commit_free(packed_commit);
return error;
}
}
return 0;
}
enum generation_number_commit_state {
GENERATION_NUMBER_COMMIT_STATE_UNVISITED = 0,
GENERATION_NUMBER_COMMIT_STATE_ADDED = 1,
GENERATION_NUMBER_COMMIT_STATE_EXPANDED = 2,
GENERATION_NUMBER_COMMIT_STATE_VISITED = 3
};
static int compute_generation_numbers(git_vector *commits)
{
git_array_t(size_t) index_stack = GIT_ARRAY_INIT;
size_t i, j;
size_t *parent_idx;
enum generation_number_commit_state *commit_states = NULL;
struct packed_commit *child_packed_commit;
git_oidmap *packed_commit_map = NULL;
int error = 0;
/* First populate the parent indices fields */
error = git_oidmap_new(&packed_commit_map);
if (error < 0)
goto cleanup;
git_vector_foreach (commits, i, child_packed_commit) {
child_packed_commit->index = i;
error = git_oidmap_set(
packed_commit_map, &child_packed_commit->sha1, child_packed_commit);
if (error < 0)
goto cleanup;
}
git_vector_foreach (commits, i, child_packed_commit) {
size_t parent_i, *parent_idx_ptr;
struct packed_commit *parent_packed_commit;
git_oid *parent_id;
git_array_init_to_size(
child_packed_commit->parent_indices,
git_array_size(child_packed_commit->parents));
if (git_array_size(child_packed_commit->parents)
&& !child_packed_commit->parent_indices.ptr) {
error = -1;
goto cleanup;
}
git_array_foreach (child_packed_commit->parents, parent_i, parent_id) {
parent_packed_commit = git_oidmap_get(packed_commit_map, parent_id);
if (!parent_packed_commit) {
git_error_set(GIT_ERROR_ODB,
"parent commit %s not found in commit graph",
git_oid_tostr_s(parent_id));
error = GIT_ENOTFOUND;
goto cleanup;
}
parent_idx_ptr = git_array_alloc(child_packed_commit->parent_indices);
if (!parent_idx_ptr) {
error = -1;
goto cleanup;
}
*parent_idx_ptr = parent_packed_commit->index;
}
}
/*
* We copy all the commits to the stack and then during visitation,
* each node can be added up to two times to the stack.
*/
git_array_init_to_size(index_stack, 3 * git_vector_length(commits));
if (!index_stack.ptr) {
error = -1;
goto cleanup;
}
commit_states = (enum generation_number_commit_state *)git__calloc(
git_vector_length(commits), sizeof(enum generation_number_commit_state));
if (!commit_states) {
error = -1;
goto cleanup;
}
/*
* Perform a Post-Order traversal so that all parent nodes are fully
* visited before the child node.
*/
git_vector_foreach (commits, i, child_packed_commit)
*(size_t *)git_array_alloc(index_stack) = i;
while (git_array_size(index_stack)) {
size_t *index_ptr = git_array_pop(index_stack);
i = *index_ptr;
child_packed_commit = git_vector_get(commits, i);
if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_VISITED) {
/* This commit has already been fully visited. */
continue;
}
if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_EXPANDED) {
/* All of the commits parents have been visited. */
child_packed_commit->generation = 0;
git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
struct packed_commit *parent = git_vector_get(commits, *parent_idx);
if (child_packed_commit->generation < parent->generation)
child_packed_commit->generation = parent->generation;
}
if (child_packed_commit->generation
< GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX) {
++child_packed_commit->generation;
}
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
continue;
}
/*
* This is the first time we see this commit. We need
* to visit all its parents before we can fully visit
* it.
*/
if (git_array_size(child_packed_commit->parent_indices) == 0) {
/*
* Special case: if the commit has no parents, there's
* no need to add it to the stack just to immediately
* remove it.
*/
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
child_packed_commit->generation = 1;
continue;
}
/*
* Add this current commit again so that it is visited
* again once all its children have been visited.
*/
*(size_t *)git_array_alloc(index_stack) = i;
git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
if (commit_states[*parent_idx]
!= GENERATION_NUMBER_COMMIT_STATE_UNVISITED) {
/* This commit has already been considered. */
continue;
}
commit_states[*parent_idx] = GENERATION_NUMBER_COMMIT_STATE_ADDED;
*(size_t *)git_array_alloc(index_stack) = *parent_idx;
}
commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_EXPANDED;
}
cleanup:
git_oidmap_free(packed_commit_map);
git__free(commit_states);
git_array_clear(index_stack);
return error;
}
static int write_offset(off64_t offset, commit_graph_write_cb write_cb, void *cb_data)
{
int error;
uint32_t word;
word = htonl((uint32_t)((offset >> 32) & 0xffffffffu));
error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
word = htonl((uint32_t)((offset >> 0) & 0xffffffffu));
error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
return 0;
}
static int write_chunk_header(
int chunk_id,
off64_t offset,
commit_graph_write_cb write_cb,
void *cb_data)
{
uint32_t word = htonl(chunk_id);
int error = write_cb((const char *)&word, sizeof(word), cb_data);
if (error < 0)
return error;
return write_offset(offset, write_cb, cb_data);
}
static int commit_graph_write_buf(const char *buf, size_t size, void *data)
{
git_str *b = (git_str *)data;
return git_str_put(b, buf, size);
}
struct commit_graph_write_hash_context {
commit_graph_write_cb write_cb;
void *cb_data;
git_hash_ctx *ctx;
};
static int commit_graph_write_hash(const char *buf, size_t size, void *data)
{
struct commit_graph_write_hash_context *ctx = data;
int error;
error = git_hash_update(ctx->ctx, buf, size);
if (error < 0)
return error;
return ctx->write_cb(buf, size, ctx->cb_data);
}
static void packed_commit_free_dup(void *packed_commit)
{
packed_commit_free(packed_commit);
}
static int commit_graph_write(
git_commit_graph_writer *w,
commit_graph_write_cb write_cb,
void *cb_data)
{
int error = 0;
size_t i;
struct packed_commit *packed_commit;
struct git_commit_graph_header hdr = {0};
uint32_t oid_fanout_count;
uint32_t extra_edge_list_count;
uint32_t oid_fanout[256];
off64_t offset;
git_str oid_lookup = GIT_STR_INIT, commit_data = GIT_STR_INIT,
extra_edge_list = GIT_STR_INIT;
unsigned char checksum[GIT_HASH_SHA1_SIZE];
size_t checksum_size;
git_hash_ctx ctx;
struct commit_graph_write_hash_context hash_cb_data = {0};
hdr.signature = htonl(COMMIT_GRAPH_SIGNATURE);
hdr.version = COMMIT_GRAPH_VERSION;
hdr.object_id_version = COMMIT_GRAPH_OBJECT_ID_VERSION;
hdr.chunks = 0;
hdr.base_graph_files = 0;
hash_cb_data.write_cb = write_cb;
hash_cb_data.cb_data = cb_data;
hash_cb_data.ctx = &ctx;
checksum_size = GIT_HASH_SHA1_SIZE;
error = git_hash_ctx_init(&ctx, GIT_HASH_ALGORITHM_SHA1);
if (error < 0)
return error;
cb_data = &hash_cb_data;
write_cb = commit_graph_write_hash;
/* Sort the commits. */
git_vector_sort(&w->commits);
git_vector_uniq(&w->commits, packed_commit_free_dup);
error = compute_generation_numbers(&w->commits);
if (error < 0)
goto cleanup;
/* Fill the OID Fanout table. */
oid_fanout_count = 0;
for (i = 0; i < 256; i++) {
while (oid_fanout_count < git_vector_length(&w->commits) &&
(packed_commit = (struct packed_commit *)git_vector_get(&w->commits, oid_fanout_count)) &&
packed_commit->sha1.id[0] <= i)
++oid_fanout_count;
oid_fanout[i] = htonl(oid_fanout_count);
}
/* Fill the OID Lookup table. */
git_vector_foreach (&w->commits, i, packed_commit) {
error = git_str_put(&oid_lookup,
(const char *)&packed_commit->sha1.id,
GIT_OID_SHA1_SIZE);
if (error < 0)
goto cleanup;
}
/* Fill the Commit Data and Extra Edge List tables. */
extra_edge_list_count = 0;
git_vector_foreach (&w->commits, i, packed_commit) {
uint64_t commit_time;
uint32_t generation;
uint32_t word;
size_t *packed_index;
unsigned int parentcount = (unsigned int)git_array_size(packed_commit->parents);
error = git_str_put(&commit_data,
(const char *)&packed_commit->tree_oid.id,
GIT_OID_SHA1_SIZE);
if (error < 0)
goto cleanup;
if (parentcount == 0) {
word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
} else {
packed_index = git_array_get(packed_commit->parent_indices, 0);
word = htonl((uint32_t)*packed_index);
}
error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
if (parentcount < 2) {
word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
} else if (parentcount == 2) {
packed_index = git_array_get(packed_commit->parent_indices, 1);
word = htonl((uint32_t)*packed_index);
} else {
word = htonl(0x80000000u | extra_edge_list_count);
}
error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
if (parentcount > 2) {
unsigned int parent_i;
for (parent_i = 1; parent_i < parentcount; ++parent_i) {
packed_index = git_array_get(
packed_commit->parent_indices, parent_i);
word = htonl((uint32_t)(*packed_index | (parent_i + 1 == parentcount ? 0x80000000u : 0)));
error = git_str_put(&extra_edge_list,
(const char *)&word,
sizeof(word));
if (error < 0)
goto cleanup;
}
extra_edge_list_count += parentcount - 1;
}
generation = packed_commit->generation;
commit_time = (uint64_t)packed_commit->commit_time;
if (generation > GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX)
generation = GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX;
word = ntohl((uint32_t)((generation << 2) | (((uint32_t)(commit_time >> 32)) & 0x3) ));
error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
word = ntohl((uint32_t)(commit_time & 0xfffffffful));
error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
if (error < 0)
goto cleanup;
}
/* Write the header. */
hdr.chunks = 3;
if (git_str_len(&extra_edge_list) > 0)
hdr.chunks++;
error = write_cb((const char *)&hdr, sizeof(hdr), cb_data);
if (error < 0)
goto cleanup;
/* Write the chunk headers. */
offset = sizeof(hdr) + (hdr.chunks + 1) * 12;
error = write_chunk_header(COMMIT_GRAPH_OID_FANOUT_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += sizeof(oid_fanout);
error = write_chunk_header(COMMIT_GRAPH_OID_LOOKUP_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_str_len(&oid_lookup);
error = write_chunk_header(COMMIT_GRAPH_COMMIT_DATA_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_str_len(&commit_data);
if (git_str_len(&extra_edge_list) > 0) {
error = write_chunk_header(
COMMIT_GRAPH_EXTRA_EDGE_LIST_ID, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
offset += git_str_len(&extra_edge_list);
}
error = write_chunk_header(0, offset, write_cb, cb_data);
if (error < 0)
goto cleanup;
/* Write all the chunks. */
error = write_cb((const char *)oid_fanout, sizeof(oid_fanout), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_str_cstr(&oid_lookup), git_str_len(&oid_lookup), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_str_cstr(&commit_data), git_str_len(&commit_data), cb_data);
if (error < 0)
goto cleanup;
error = write_cb(git_str_cstr(&extra_edge_list), git_str_len(&extra_edge_list), cb_data);
if (error < 0)
goto cleanup;
/* Finalize the checksum and write the trailer. */
error = git_hash_final(checksum, &ctx);
if (error < 0)
goto cleanup;
error = write_cb((char *)checksum, checksum_size, cb_data);
if (error < 0)
goto cleanup;
cleanup:
git_str_dispose(&oid_lookup);
git_str_dispose(&commit_data);
git_str_dispose(&extra_edge_list);
git_hash_ctx_cleanup(&ctx);
return error;
}
static int commit_graph_write_filebuf(const char *buf, size_t size, void *data)
{
git_filebuf *f = (git_filebuf *)data;
return git_filebuf_write(f, buf, size);
}
int git_commit_graph_writer_options_init(
git_commit_graph_writer_options *opts,
unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts,
version,
git_commit_graph_writer_options,
GIT_COMMIT_GRAPH_WRITER_OPTIONS_INIT);
return 0;
}
int git_commit_graph_writer_commit(
git_commit_graph_writer *w,
git_commit_graph_writer_options *opts)
{
int error;
int filebuf_flags = GIT_FILEBUF_DO_NOT_BUFFER;
git_str commit_graph_path = GIT_STR_INIT;
git_filebuf output = GIT_FILEBUF_INIT;
/* TODO: support options and fill in defaults. */
GIT_UNUSED(opts);
error = git_str_joinpath(
&commit_graph_path, git_str_cstr(&w->objects_info_dir), "commit-graph");
if (error < 0)
return error;
if (git_repository__fsync_gitdir)
filebuf_flags |= GIT_FILEBUF_FSYNC;
error = git_filebuf_open(&output, git_str_cstr(&commit_graph_path), filebuf_flags, 0644);
git_str_dispose(&commit_graph_path);
if (error < 0)
return error;
error = commit_graph_write(w, commit_graph_write_filebuf, &output);
if (error < 0) {
git_filebuf_cleanup(&output);
return error;
}
return git_filebuf_commit(&output);
}
int git_commit_graph_writer_dump(
git_buf *cgraph,
git_commit_graph_writer *w,
git_commit_graph_writer_options *opts)
{
GIT_BUF_WRAP_PRIVATE(cgraph, git_commit_graph__writer_dump, w, opts);
}
int git_commit_graph__writer_dump(
git_str *cgraph,
git_commit_graph_writer *w,
git_commit_graph_writer_options *opts)
{
/* TODO: support options. */
GIT_UNUSED(opts);
return commit_graph_write(w, commit_graph_write_buf, cgraph);
}
| libgit2-main | src/libgit2/commit_graph.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "commit_list.h"
#include "revwalk.h"
#include "pool.h"
#include "odb.h"
#include "commit.h"
int git_commit_list_generation_cmp(const void *a, const void *b)
{
uint32_t generation_a = ((git_commit_list_node *) a)->generation;
uint32_t generation_b = ((git_commit_list_node *) b)->generation;
if (!generation_a || !generation_b) {
/* Fall back to comparing by timestamps if at least one commit lacks a generation. */
return git_commit_list_time_cmp(a, b);
}
if (generation_a < generation_b)
return 1;
if (generation_a > generation_b)
return -1;
return 0;
}
int git_commit_list_time_cmp(const void *a, const void *b)
{
int64_t time_a = ((git_commit_list_node *) a)->time;
int64_t time_b = ((git_commit_list_node *) b)->time;
if (time_a < time_b)
return 1;
if (time_a > time_b)
return -1;
return 0;
}
git_commit_list *git_commit_list_insert(git_commit_list_node *item, git_commit_list **list_p)
{
git_commit_list *new_list = git__malloc(sizeof(git_commit_list));
if (new_list != NULL) {
new_list->item = item;
new_list->next = *list_p;
}
*list_p = new_list;
return new_list;
}
git_commit_list *git_commit_list_insert_by_date(git_commit_list_node *item, git_commit_list **list_p)
{
git_commit_list **pp = list_p;
git_commit_list *p;
while ((p = *pp) != NULL) {
if (git_commit_list_time_cmp(p->item, item) > 0)
break;
pp = &p->next;
}
return git_commit_list_insert(item, pp);
}
git_commit_list_node *git_commit_list_alloc_node(git_revwalk *walk)
{
return (git_commit_list_node *)git_pool_mallocz(&walk->commit_pool, 1);
}
static git_commit_list_node **alloc_parents(
git_revwalk *walk, git_commit_list_node *commit, size_t n_parents)
{
size_t bytes;
if (n_parents <= PARENTS_PER_COMMIT)
return (git_commit_list_node **)((char *)commit + sizeof(git_commit_list_node));
if (git__multiply_sizet_overflow(&bytes, n_parents, sizeof(git_commit_list_node *)))
return NULL;
return (git_commit_list_node **)git_pool_malloc(&walk->commit_pool, bytes);
}
void git_commit_list_free(git_commit_list **list_p)
{
git_commit_list *list = *list_p;
if (list == NULL)
return;
while (list) {
git_commit_list *temp = list;
list = temp->next;
git__free(temp);
}
*list_p = NULL;
}
git_commit_list_node *git_commit_list_pop(git_commit_list **stack)
{
git_commit_list *top = *stack;
git_commit_list_node *item = top ? top->item : NULL;
if (top) {
*stack = top->next;
git__free(top);
}
return item;
}
static int commit_quick_parse(
git_revwalk *walk,
git_commit_list_node *node,
git_odb_object *obj)
{
git_oid *parent_oid;
git_commit *commit;
size_t i;
commit = git__calloc(1, sizeof(*commit));
GIT_ERROR_CHECK_ALLOC(commit);
commit->object.repo = walk->repo;
if (git_commit__parse_ext(commit, obj, GIT_COMMIT_PARSE_QUICK) < 0) {
git__free(commit);
return -1;
}
if (!git__is_uint16(git_array_size(commit->parent_ids))) {
git__free(commit);
git_error_set(GIT_ERROR_INVALID, "commit has more than 2^16 parents");
return -1;
}
node->generation = 0;
node->time = commit->committer->when.time;
node->out_degree = (uint16_t) git_array_size(commit->parent_ids);
node->parents = alloc_parents(walk, node, node->out_degree);
GIT_ERROR_CHECK_ALLOC(node->parents);
git_array_foreach(commit->parent_ids, i, parent_oid) {
node->parents[i] = git_revwalk__commit_lookup(walk, parent_oid);
}
git_commit__free(commit);
node->parsed = 1;
return 0;
}
int git_commit_list_parse(git_revwalk *walk, git_commit_list_node *commit)
{
git_odb_object *obj;
git_commit_graph_file *cgraph_file = NULL;
int error;
if (commit->parsed)
return 0;
/* Let's try to use the commit graph first. */
git_odb__get_commit_graph_file(&cgraph_file, walk->odb);
if (cgraph_file) {
git_commit_graph_entry e;
error = git_commit_graph_entry_find(&e, cgraph_file, &commit->oid, GIT_OID_SHA1_SIZE);
if (error == 0 && git__is_uint16(e.parent_count)) {
size_t i;
commit->generation = (uint32_t)e.generation;
commit->time = e.commit_time;
commit->out_degree = (uint16_t)e.parent_count;
commit->parents = alloc_parents(walk, commit, commit->out_degree);
GIT_ERROR_CHECK_ALLOC(commit->parents);
for (i = 0; i < commit->out_degree; ++i) {
git_commit_graph_entry parent;
error = git_commit_graph_entry_parent(&parent, cgraph_file, &e, i);
if (error < 0)
return error;
commit->parents[i] = git_revwalk__commit_lookup(walk, &parent.sha1);
}
commit->parsed = 1;
return 0;
}
}
if ((error = git_odb_read(&obj, walk->odb, &commit->oid)) < 0)
return error;
if (obj->cached.type != GIT_OBJECT_COMMIT) {
git_error_set(GIT_ERROR_INVALID, "object is no commit object");
error = -1;
} else
error = commit_quick_parse(walk, commit, obj);
git_odb_object_free(obj);
return error;
}
| libgit2-main | src/libgit2/commit_list.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "merge_driver.h"
#include "vector.h"
#include "runtime.h"
#include "merge.h"
#include "git2/merge.h"
#include "git2/sys/merge.h"
static const char *merge_driver_name__text = "text";
static const char *merge_driver_name__union = "union";
static const char *merge_driver_name__binary = "binary";
struct merge_driver_registry {
git_rwlock lock;
git_vector drivers;
};
typedef struct {
git_merge_driver *driver;
int initialized;
char name[GIT_FLEX_ARRAY];
} git_merge_driver_entry;
static struct merge_driver_registry merge_driver_registry;
static void git_merge_driver_global_shutdown(void);
git_repository *git_merge_driver_source_repo(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->repo;
}
const git_index_entry *git_merge_driver_source_ancestor(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->ancestor;
}
const git_index_entry *git_merge_driver_source_ours(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->ours;
}
const git_index_entry *git_merge_driver_source_theirs(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->theirs;
}
const git_merge_file_options *git_merge_driver_source_file_options(
const git_merge_driver_source *src)
{
GIT_ASSERT_ARG_WITH_RETVAL(src, NULL);
return src->file_opts;
}
int git_merge_driver__builtin_apply(
git_merge_driver *self,
const char **path_out,
uint32_t *mode_out,
git_buf *merged_out,
const char *filter_name,
const git_merge_driver_source *src)
{
git_merge_driver__builtin *driver = (git_merge_driver__builtin *)self;
git_merge_file_options file_opts = GIT_MERGE_FILE_OPTIONS_INIT;
git_merge_file_result result = {0};
int error;
GIT_UNUSED(filter_name);
if (src->file_opts)
memcpy(&file_opts, src->file_opts, sizeof(git_merge_file_options));
if (driver->favor)
file_opts.favor = driver->favor;
if ((error = git_merge_file_from_index(&result, src->repo,
src->ancestor, src->ours, src->theirs, &file_opts)) < 0)
goto done;
if (!result.automergeable &&
!(file_opts.flags & GIT_MERGE_FILE_ACCEPT_CONFLICTS)) {
error = GIT_EMERGECONFLICT;
goto done;
}
*path_out = git_merge_file__best_path(
src->ancestor ? src->ancestor->path : NULL,
src->ours ? src->ours->path : NULL,
src->theirs ? src->theirs->path : NULL);
*mode_out = git_merge_file__best_mode(
src->ancestor ? src->ancestor->mode : 0,
src->ours ? src->ours->mode : 0,
src->theirs ? src->theirs->mode : 0);
merged_out->ptr = (char *)result.ptr;
merged_out->size = result.len;
merged_out->reserved = 0;
result.ptr = NULL;
done:
git_merge_file_result_free(&result);
return error;
}
static int merge_driver_binary_apply(
git_merge_driver *self,
const char **path_out,
uint32_t *mode_out,
git_buf *merged_out,
const char *filter_name,
const git_merge_driver_source *src)
{
GIT_UNUSED(self);
GIT_UNUSED(path_out);
GIT_UNUSED(mode_out);
GIT_UNUSED(merged_out);
GIT_UNUSED(filter_name);
GIT_UNUSED(src);
return GIT_EMERGECONFLICT;
}
static int merge_driver_entry_cmp(const void *a, const void *b)
{
const git_merge_driver_entry *entry_a = a;
const git_merge_driver_entry *entry_b = b;
return strcmp(entry_a->name, entry_b->name);
}
static int merge_driver_entry_search(const void *a, const void *b)
{
const char *name_a = a;
const git_merge_driver_entry *entry_b = b;
return strcmp(name_a, entry_b->name);
}
git_merge_driver__builtin git_merge_driver__text = {
{
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
git_merge_driver__builtin_apply,
},
GIT_MERGE_FILE_FAVOR_NORMAL
};
git_merge_driver__builtin git_merge_driver__union = {
{
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
git_merge_driver__builtin_apply,
},
GIT_MERGE_FILE_FAVOR_UNION
};
git_merge_driver git_merge_driver__binary = {
GIT_MERGE_DRIVER_VERSION,
NULL,
NULL,
merge_driver_binary_apply
};
/* Note: callers must lock the registry before calling this function */
static int merge_driver_registry_insert(
const char *name, git_merge_driver *driver)
{
git_merge_driver_entry *entry;
entry = git__calloc(1, sizeof(git_merge_driver_entry) + strlen(name) + 1);
GIT_ERROR_CHECK_ALLOC(entry);
strcpy(entry->name, name);
entry->driver = driver;
return git_vector_insert_sorted(
&merge_driver_registry.drivers, entry, NULL);
}
int git_merge_driver_global_init(void)
{
int error;
if (git_rwlock_init(&merge_driver_registry.lock) < 0)
return -1;
if ((error = git_vector_init(&merge_driver_registry.drivers, 3,
merge_driver_entry_cmp)) < 0)
goto done;
if ((error = merge_driver_registry_insert(
merge_driver_name__text, &git_merge_driver__text.base)) < 0 ||
(error = merge_driver_registry_insert(
merge_driver_name__union, &git_merge_driver__union.base)) < 0 ||
(error = merge_driver_registry_insert(
merge_driver_name__binary, &git_merge_driver__binary)) < 0)
goto done;
error = git_runtime_shutdown_register(git_merge_driver_global_shutdown);
done:
if (error < 0)
git_vector_free_deep(&merge_driver_registry.drivers);
return error;
}
static void git_merge_driver_global_shutdown(void)
{
git_merge_driver_entry *entry;
size_t i;
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0)
return;
git_vector_foreach(&merge_driver_registry.drivers, i, entry) {
if (entry->driver->shutdown)
entry->driver->shutdown(entry->driver);
git__free(entry);
}
git_vector_free(&merge_driver_registry.drivers);
git_rwlock_wrunlock(&merge_driver_registry.lock);
git_rwlock_free(&merge_driver_registry.lock);
}
/* Note: callers must lock the registry before calling this function */
static int merge_driver_registry_find(size_t *pos, const char *name)
{
return git_vector_search2(pos, &merge_driver_registry.drivers,
merge_driver_entry_search, name);
}
/* Note: callers must lock the registry before calling this function */
static git_merge_driver_entry *merge_driver_registry_lookup(
size_t *pos, const char *name)
{
git_merge_driver_entry *entry = NULL;
if (!merge_driver_registry_find(pos, name))
entry = git_vector_get(&merge_driver_registry.drivers, *pos);
return entry;
}
int git_merge_driver_register(const char *name, git_merge_driver *driver)
{
int error;
GIT_ASSERT_ARG(name);
GIT_ASSERT_ARG(driver);
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return -1;
}
if (!merge_driver_registry_find(NULL, name)) {
git_error_set(GIT_ERROR_MERGE, "attempt to reregister existing driver '%s'",
name);
error = GIT_EEXISTS;
goto done;
}
error = merge_driver_registry_insert(name, driver);
done:
git_rwlock_wrunlock(&merge_driver_registry.lock);
return error;
}
int git_merge_driver_unregister(const char *name)
{
git_merge_driver_entry *entry;
size_t pos;
int error = 0;
if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return -1;
}
if ((entry = merge_driver_registry_lookup(&pos, name)) == NULL) {
git_error_set(GIT_ERROR_MERGE, "cannot find merge driver '%s' to unregister",
name);
error = GIT_ENOTFOUND;
goto done;
}
git_vector_remove(&merge_driver_registry.drivers, pos);
if (entry->initialized && entry->driver->shutdown) {
entry->driver->shutdown(entry->driver);
entry->initialized = false;
}
git__free(entry);
done:
git_rwlock_wrunlock(&merge_driver_registry.lock);
return error;
}
git_merge_driver *git_merge_driver_lookup(const char *name)
{
git_merge_driver_entry *entry;
size_t pos;
int error;
/* If we've decided the merge driver to use internally - and not
* based on user configuration (in merge_driver_name_for_path)
* then we can use a hardcoded name to compare instead of bothering
* to take a lock and look it up in the vector.
*/
if (name == merge_driver_name__text)
return &git_merge_driver__text.base;
else if (name == merge_driver_name__binary)
return &git_merge_driver__binary;
if (git_rwlock_rdlock(&merge_driver_registry.lock) < 0) {
git_error_set(GIT_ERROR_OS, "failed to lock merge driver registry");
return NULL;
}
entry = merge_driver_registry_lookup(&pos, name);
git_rwlock_rdunlock(&merge_driver_registry.lock);
if (entry == NULL) {
git_error_set(GIT_ERROR_MERGE, "cannot use an unregistered filter");
return NULL;
}
if (!entry->initialized) {
if (entry->driver->initialize &&
(error = entry->driver->initialize(entry->driver)) < 0)
return NULL;
entry->initialized = 1;
}
return entry->driver;
}
static int merge_driver_name_for_path(
const char **out,
git_repository *repo,
const char *path,
const char *default_driver)
{
const char *value;
int error;
*out = NULL;
if ((error = git_attr_get(&value, repo, 0, path, "merge")) < 0)
return error;
/* set: use the built-in 3-way merge driver ("text") */
if (GIT_ATTR_IS_TRUE(value))
*out = merge_driver_name__text;
/* unset: do not merge ("binary") */
else if (GIT_ATTR_IS_FALSE(value))
*out = merge_driver_name__binary;
else if (GIT_ATTR_IS_UNSPECIFIED(value) && default_driver)
*out = default_driver;
else if (GIT_ATTR_IS_UNSPECIFIED(value))
*out = merge_driver_name__text;
else
*out = value;
return 0;
}
GIT_INLINE(git_merge_driver *) merge_driver_lookup_with_wildcard(
const char *name)
{
git_merge_driver *driver = git_merge_driver_lookup(name);
if (driver == NULL)
driver = git_merge_driver_lookup("*");
return driver;
}
int git_merge_driver_for_source(
const char **name_out,
git_merge_driver **driver_out,
const git_merge_driver_source *src)
{
const char *path, *driver_name;
int error = 0;
path = git_merge_file__best_path(
src->ancestor ? src->ancestor->path : NULL,
src->ours ? src->ours->path : NULL,
src->theirs ? src->theirs->path : NULL);
if ((error = merge_driver_name_for_path(
&driver_name, src->repo, path, src->default_driver)) < 0)
return error;
*name_out = driver_name;
*driver_out = merge_driver_lookup_with_wildcard(driver_name);
return error;
}
| libgit2-main | src/libgit2/merge_driver.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "proxy.h"
#include "git2/proxy.h"
int git_proxy_options_init(git_proxy_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_proxy_options, GIT_PROXY_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_proxy_init_options(git_proxy_options *opts, unsigned int version)
{
return git_proxy_options_init(opts, version);
}
#endif
int git_proxy_options_dup(git_proxy_options *tgt, const git_proxy_options *src)
{
if (!src) {
git_proxy_options_init(tgt, GIT_PROXY_OPTIONS_VERSION);
return 0;
}
memcpy(tgt, src, sizeof(git_proxy_options));
if (src->url) {
tgt->url = git__strdup(src->url);
GIT_ERROR_CHECK_ALLOC(tgt->url);
}
return 0;
}
void git_proxy_options_dispose(git_proxy_options *opts)
{
if (!opts)
return;
git__free((char *) opts->url);
opts->url = NULL;
}
| libgit2-main | src/libgit2/proxy.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "diff.h"
#include "common.h"
#include "buf.h"
#include "patch.h"
#include "email.h"
#include "commit.h"
#include "index.h"
#include "diff_generate.h"
#include "git2/version.h"
#include "git2/email.h"
struct patch_id_args {
git_hash_ctx ctx;
git_oid result;
int first_file;
};
GIT_INLINE(const char *) diff_delta__path(const git_diff_delta *delta)
{
const char *str = delta->old_file.path;
if (!str ||
delta->status == GIT_DELTA_ADDED ||
delta->status == GIT_DELTA_RENAMED ||
delta->status == GIT_DELTA_COPIED)
str = delta->new_file.path;
return str;
}
int git_diff_delta__cmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcmp(diff_delta__path(da), diff_delta__path(db));
return val ? val : ((int)da->status - (int)db->status);
}
int git_diff_delta__casecmp(const void *a, const void *b)
{
const git_diff_delta *da = a, *db = b;
int val = strcasecmp(diff_delta__path(da), diff_delta__path(db));
return val ? val : ((int)da->status - (int)db->status);
}
int git_diff__entry_cmp(const void *a, const void *b)
{
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
return strcmp(entry_a->path, entry_b->path);
}
int git_diff__entry_icmp(const void *a, const void *b)
{
const git_index_entry *entry_a = a;
const git_index_entry *entry_b = b;
return strcasecmp(entry_a->path, entry_b->path);
}
void git_diff_free(git_diff *diff)
{
if (!diff)
return;
GIT_REFCOUNT_DEC(diff, diff->free_fn);
}
void git_diff_addref(git_diff *diff)
{
GIT_REFCOUNT_INC(diff);
}
size_t git_diff_num_deltas(const git_diff *diff)
{
GIT_ASSERT_ARG(diff);
return diff->deltas.length;
}
size_t git_diff_num_deltas_of_type(const git_diff *diff, git_delta_t type)
{
size_t i, count = 0;
const git_diff_delta *delta;
GIT_ASSERT_ARG(diff);
git_vector_foreach(&diff->deltas, i, delta) {
count += (delta->status == type);
}
return count;
}
const git_diff_delta *git_diff_get_delta(const git_diff *diff, size_t idx)
{
GIT_ASSERT_ARG_WITH_RETVAL(diff, NULL);
return git_vector_get(&diff->deltas, idx);
}
int git_diff_is_sorted_icase(const git_diff *diff)
{
return (diff->opts.flags & GIT_DIFF_IGNORE_CASE) != 0;
}
int git_diff_get_perfdata(git_diff_perfdata *out, const git_diff *diff)
{
GIT_ASSERT_ARG(out);
GIT_ERROR_CHECK_VERSION(out, GIT_DIFF_PERFDATA_VERSION, "git_diff_perfdata");
out->stat_calls = diff->perf.stat_calls;
out->oid_calculations = diff->perf.oid_calculations;
return 0;
}
int git_diff_foreach(
git_diff *diff,
git_diff_file_cb file_cb,
git_diff_binary_cb binary_cb,
git_diff_hunk_cb hunk_cb,
git_diff_line_cb data_cb,
void *payload)
{
int error = 0;
git_diff_delta *delta;
size_t idx;
GIT_ASSERT_ARG(diff);
git_vector_foreach(&diff->deltas, idx, delta) {
git_patch *patch;
/* check flags against patch status */
if (git_diff_delta__should_skip(&diff->opts, delta))
continue;
if ((error = git_patch_from_diff(&patch, diff, idx)) != 0)
break;
error = git_patch__invoke_callbacks(patch, file_cb, binary_cb,
hunk_cb, data_cb, payload);
git_patch_free(patch);
if (error)
break;
}
return error;
}
#ifndef GIT_DEPRECATE_HARD
int git_diff_format_email(
git_buf *out,
git_diff *diff,
const git_diff_format_email_options *opts)
{
git_email_create_options email_create_opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
git_str email = GIT_STR_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
GIT_ASSERT_ARG(opts && opts->summary && opts->id && opts->author);
GIT_ERROR_CHECK_VERSION(opts,
GIT_DIFF_FORMAT_EMAIL_OPTIONS_VERSION,
"git_format_email_options");
/* This is a `git_buf` special case; subsequent calls append. */
email.ptr = out->ptr;
email.asize = out->reserved;
email.size = out->size;
out->ptr = git_str__initstr;
out->reserved = 0;
out->size = 0;
if ((opts->flags & GIT_DIFF_FORMAT_EMAIL_EXCLUDE_SUBJECT_PATCH_MARKER) != 0)
email_create_opts.subject_prefix = "";
error = git_email__append_from_diff(&email, diff, opts->patch_no,
opts->total_patches, opts->id, opts->summary, opts->body,
opts->author, &email_create_opts);
if (error < 0)
goto done;
error = git_buf_fromstr(out, &email);
done:
git_str_dispose(&email);
return error;
}
int git_diff_commit_as_email(
git_buf *out,
git_repository *repo,
git_commit *commit,
size_t patch_no,
size_t total_patches,
uint32_t flags,
const git_diff_options *diff_opts)
{
git_diff *diff = NULL;
git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT;
const git_oid *commit_id;
const char *summary, *body;
const git_signature *author;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(commit);
commit_id = git_commit_id(commit);
summary = git_commit_summary(commit);
body = git_commit_body(commit);
author = git_commit_author(commit);
if ((flags & GIT_DIFF_FORMAT_EMAIL_EXCLUDE_SUBJECT_PATCH_MARKER) != 0)
opts.subject_prefix = "";
if ((error = git_diff__commit(&diff, repo, commit, diff_opts)) < 0)
return error;
error = git_email_create_from_diff(out, diff, patch_no, total_patches, commit_id, summary, body, author, &opts);
git_diff_free(diff);
return error;
}
int git_diff_init_options(git_diff_options *opts, unsigned int version)
{
return git_diff_options_init(opts, version);
}
int git_diff_find_init_options(
git_diff_find_options *opts, unsigned int version)
{
return git_diff_find_options_init(opts, version);
}
int git_diff_format_email_options_init(
git_diff_format_email_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_format_email_options,
GIT_DIFF_FORMAT_EMAIL_OPTIONS_INIT);
return 0;
}
int git_diff_format_email_init_options(
git_diff_format_email_options *opts, unsigned int version)
{
return git_diff_format_email_options_init(opts, version);
}
#endif
int git_diff_options_init(git_diff_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_options, GIT_DIFF_OPTIONS_INIT);
return 0;
}
int git_diff_find_options_init(
git_diff_find_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_find_options, GIT_DIFF_FIND_OPTIONS_INIT);
return 0;
}
static int flush_hunk(git_oid *result, git_hash_ctx *ctx)
{
git_oid hash;
unsigned short carry = 0;
int error, i;
if ((error = git_hash_final(hash.id, ctx)) < 0 ||
(error = git_hash_init(ctx)) < 0)
return error;
for (i = 0; i < GIT_OID_SHA1_SIZE; i++) {
carry += result->id[i] + hash.id[i];
result->id[i] = (unsigned char)carry;
carry >>= 8;
}
return 0;
}
static void strip_spaces(git_str *buf)
{
char *src = buf->ptr, *dst = buf->ptr;
char c;
size_t len = 0;
while ((c = *src++) != '\0') {
if (!git__isspace(c)) {
*dst++ = c;
len++;
}
}
git_str_truncate(buf, len);
}
static int diff_patchid_print_callback_to_buf(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
struct patch_id_args *args = (struct patch_id_args *) payload;
git_str buf = GIT_STR_INIT;
int error = 0;
if (line->origin == GIT_DIFF_LINE_CONTEXT_EOFNL ||
line->origin == GIT_DIFF_LINE_ADD_EOFNL ||
line->origin == GIT_DIFF_LINE_DEL_EOFNL)
goto out;
if ((error = git_diff_print_callback__to_buf(delta, hunk,
line, &buf)) < 0)
goto out;
strip_spaces(&buf);
if (line->origin == GIT_DIFF_LINE_FILE_HDR &&
!args->first_file &&
(error = flush_hunk(&args->result, &args->ctx) < 0))
goto out;
if ((error = git_hash_update(&args->ctx, buf.ptr, buf.size)) < 0)
goto out;
if (line->origin == GIT_DIFF_LINE_FILE_HDR && args->first_file)
args->first_file = 0;
out:
git_str_dispose(&buf);
return error;
}
int git_diff_patchid_options_init(git_diff_patchid_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_diff_patchid_options, GIT_DIFF_PATCHID_OPTIONS_INIT);
return 0;
}
int git_diff_patchid(git_oid *out, git_diff *diff, git_diff_patchid_options *opts)
{
struct patch_id_args args;
int error;
GIT_ERROR_CHECK_VERSION(
opts, GIT_DIFF_PATCHID_OPTIONS_VERSION, "git_diff_patchid_options");
memset(&args, 0, sizeof(args));
args.first_file = 1;
if ((error = git_hash_ctx_init(&args.ctx, GIT_HASH_ALGORITHM_SHA1)) < 0)
goto out;
if ((error = git_diff_print(diff,
GIT_DIFF_FORMAT_PATCH_ID,
diff_patchid_print_callback_to_buf,
&args)) < 0)
goto out;
if ((error = (flush_hunk(&args.result, &args.ctx))) < 0)
goto out;
#ifdef GIT_EXPERIMENTAL_SHA256
args.result.type = GIT_OID_SHA1;
#endif
git_oid_cpy(out, &args.result);
out:
git_hash_ctx_cleanup(&args.ctx);
return error;
}
| libgit2-main | src/libgit2/diff.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "offmap.h"
#define kmalloc git__malloc
#define kcalloc git__calloc
#define krealloc git__realloc
#define kreallocarray git__reallocarray
#define kfree git__free
#include "khash.h"
__KHASH_TYPE(off, off64_t, void *)
__KHASH_IMPL(off, static kh_inline, off64_t, void *, 1, kh_int64_hash_func, kh_int64_hash_equal)
int git_offmap_new(git_offmap **out)
{
*out = kh_init(off);
GIT_ERROR_CHECK_ALLOC(*out);
return 0;
}
void git_offmap_free(git_offmap *map)
{
kh_destroy(off, map);
}
void git_offmap_clear(git_offmap *map)
{
kh_clear(off, map);
}
size_t git_offmap_size(git_offmap *map)
{
return kh_size(map);
}
void *git_offmap_get(git_offmap *map, const off64_t key)
{
size_t idx = kh_get(off, map, key);
if (idx == kh_end(map) || !kh_exist(map, idx))
return NULL;
return kh_val(map, idx);
}
int git_offmap_set(git_offmap *map, const off64_t key, void *value)
{
size_t idx;
int rval;
idx = kh_put(off, map, key, &rval);
if (rval < 0)
return -1;
if (rval == 0)
kh_key(map, idx) = key;
kh_val(map, idx) = value;
return 0;
}
int git_offmap_delete(git_offmap *map, const off64_t key)
{
khiter_t idx = kh_get(off, map, key);
if (idx == kh_end(map))
return GIT_ENOTFOUND;
kh_del(off, map, idx);
return 0;
}
int git_offmap_exists(git_offmap *map, const off64_t key)
{
return kh_get(off, map, key) != kh_end(map);
}
int git_offmap_iterate(void **value, git_offmap *map, size_t *iter, off64_t *key)
{
size_t i = *iter;
while (i < map->n_buckets && !kh_exist(map, i))
i++;
if (i >= map->n_buckets)
return GIT_ITEROVER;
if (key)
*key = kh_key(map, i);
if (value)
*value = kh_value(map, i);
*iter = ++i;
return 0;
}
| libgit2-main | src/libgit2/offmap.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "buf.h"
#include "diff.h"
#include "diff_file.h"
#include "patch_generate.h"
#include "futils.h"
#include "zstream.h"
#include "blob.h"
#include "delta.h"
#include "git2/sys/diff.h"
typedef struct {
git_diff_format_t format;
git_diff_line_cb print_cb;
void *payload;
git_str *buf;
git_diff_line line;
const char *old_prefix;
const char *new_prefix;
uint32_t flags;
int id_strlen;
int (*strcomp)(const char *, const char *);
} diff_print_info;
static int diff_print_info_init__common(
diff_print_info *pi,
git_str *out,
git_repository *repo,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
pi->format = format;
pi->print_cb = cb;
pi->payload = payload;
pi->buf = out;
if (!pi->id_strlen) {
if (!repo)
pi->id_strlen = GIT_ABBREV_DEFAULT;
else if (git_repository__configmap_lookup(&pi->id_strlen, repo, GIT_CONFIGMAP_ABBREV) < 0)
return -1;
}
if (pi->id_strlen > GIT_OID_SHA1_HEXSIZE)
pi->id_strlen = GIT_OID_SHA1_HEXSIZE;
memset(&pi->line, 0, sizeof(pi->line));
pi->line.old_lineno = -1;
pi->line.new_lineno = -1;
pi->line.num_lines = 1;
return 0;
}
static int diff_print_info_init_fromdiff(
diff_print_info *pi,
git_str *out,
git_diff *diff,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
git_repository *repo = diff ? diff->repo : NULL;
memset(pi, 0, sizeof(diff_print_info));
if (diff) {
pi->flags = diff->opts.flags;
pi->id_strlen = diff->opts.id_abbrev;
pi->old_prefix = diff->opts.old_prefix;
pi->new_prefix = diff->opts.new_prefix;
pi->strcomp = diff->strcomp;
}
return diff_print_info_init__common(pi, out, repo, format, cb, payload);
}
static int diff_print_info_init_frompatch(
diff_print_info *pi,
git_str *out,
git_patch *patch,
git_diff_format_t format,
git_diff_line_cb cb,
void *payload)
{
GIT_ASSERT_ARG(patch);
memset(pi, 0, sizeof(diff_print_info));
pi->flags = patch->diff_opts.flags;
pi->id_strlen = patch->diff_opts.id_abbrev;
pi->old_prefix = patch->diff_opts.old_prefix;
pi->new_prefix = patch->diff_opts.new_prefix;
return diff_print_info_init__common(pi, out, patch->repo, format, cb, payload);
}
static char diff_pick_suffix(int mode)
{
if (S_ISDIR(mode))
return '/';
else if (GIT_PERMS_IS_EXEC(mode)) /* -V536 */
/* in git, modes are very regular, so we must have 0100755 mode */
return '*';
else
return ' ';
}
char git_diff_status_char(git_delta_t status)
{
char code;
switch (status) {
case GIT_DELTA_ADDED: code = 'A'; break;
case GIT_DELTA_DELETED: code = 'D'; break;
case GIT_DELTA_MODIFIED: code = 'M'; break;
case GIT_DELTA_RENAMED: code = 'R'; break;
case GIT_DELTA_COPIED: code = 'C'; break;
case GIT_DELTA_IGNORED: code = 'I'; break;
case GIT_DELTA_UNTRACKED: code = '?'; break;
case GIT_DELTA_TYPECHANGE: code = 'T'; break;
case GIT_DELTA_UNREADABLE: code = 'X'; break;
default: code = ' '; break;
}
return code;
}
static int diff_print_one_name_only(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_str *out = pi->buf;
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 &&
delta->status == GIT_DELTA_UNMODIFIED)
return 0;
git_str_clear(out);
git_str_puts(out, delta->new_file.path);
git_str_putc(out, '\n');
if (git_str_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_str_cstr(out);
pi->line.content_len = git_str_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_one_name_status(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_str *out = pi->buf;
char old_suffix, new_suffix, code = git_diff_status_char(delta->status);
int(*strcomp)(const char *, const char *) = pi->strcomp ?
pi->strcomp : git__strcmp;
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
return 0;
old_suffix = diff_pick_suffix(delta->old_file.mode);
new_suffix = diff_pick_suffix(delta->new_file.mode);
git_str_clear(out);
if (delta->old_file.path != delta->new_file.path &&
strcomp(delta->old_file.path,delta->new_file.path) != 0)
git_str_printf(out, "%c\t%s%c %s%c\n", code,
delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
else if (delta->old_file.mode != delta->new_file.mode &&
delta->old_file.mode != 0 && delta->new_file.mode != 0)
git_str_printf(out, "%c\t%s%c %s%c\n", code,
delta->old_file.path, old_suffix, delta->new_file.path, new_suffix);
else if (old_suffix != ' ')
git_str_printf(out, "%c\t%s%c\n", code, delta->old_file.path, old_suffix);
else
git_str_printf(out, "%c\t%s\n", code, delta->old_file.path);
if (git_str_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_str_cstr(out);
pi->line.content_len = git_str_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_one_raw(
const git_diff_delta *delta, float progress, void *data)
{
diff_print_info *pi = data;
git_str *out = pi->buf;
int id_abbrev;
char code = git_diff_status_char(delta->status);
char start_oid[GIT_OID_SHA1_HEXSIZE+1], end_oid[GIT_OID_SHA1_HEXSIZE+1];
GIT_UNUSED(progress);
if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ')
return 0;
git_str_clear(out);
id_abbrev = delta->old_file.mode ? delta->old_file.id_abbrev :
delta->new_file.id_abbrev;
if (pi->id_strlen > id_abbrev) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
id_abbrev, pi->id_strlen);
return -1;
}
git_oid_tostr(start_oid, pi->id_strlen + 1, &delta->old_file.id);
git_oid_tostr(end_oid, pi->id_strlen + 1, &delta->new_file.id);
git_str_printf(
out, (pi->id_strlen <= GIT_OID_SHA1_HEXSIZE) ?
":%06o %06o %s... %s... %c" : ":%06o %06o %s %s %c",
delta->old_file.mode, delta->new_file.mode, start_oid, end_oid, code);
if (delta->similarity > 0)
git_str_printf(out, "%03u", delta->similarity);
if (delta->old_file.path != delta->new_file.path)
git_str_printf(
out, "\t%s %s\n", delta->old_file.path, delta->new_file.path);
else
git_str_printf(
out, "\t%s\n", delta->old_file.path ?
delta->old_file.path : delta->new_file.path);
if (git_str_oom(out))
return -1;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_str_cstr(out);
pi->line.content_len = git_str_len(out);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_modes(
git_str *out, const git_diff_delta *delta)
{
git_str_printf(out, "old mode %o\n", delta->old_file.mode);
git_str_printf(out, "new mode %o\n", delta->new_file.mode);
return git_str_oom(out) ? -1 : 0;
}
static int diff_print_oid_range(
git_str *out, const git_diff_delta *delta, int id_strlen,
bool print_index)
{
char start_oid[GIT_OID_SHA1_HEXSIZE+1], end_oid[GIT_OID_SHA1_HEXSIZE+1];
if (delta->old_file.mode &&
id_strlen > delta->old_file.id_abbrev) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
delta->old_file.id_abbrev, id_strlen);
return -1;
}
if ((delta->new_file.mode &&
id_strlen > delta->new_file.id_abbrev)) {
git_error_set(GIT_ERROR_PATCH,
"the patch input contains %d id characters (cannot print %d)",
delta->new_file.id_abbrev, id_strlen);
return -1;
}
git_oid_tostr(start_oid, id_strlen + 1, &delta->old_file.id);
git_oid_tostr(end_oid, id_strlen + 1, &delta->new_file.id);
if (delta->old_file.mode == delta->new_file.mode) {
if (print_index)
git_str_printf(out, "index %s..%s %o\n",
start_oid, end_oid, delta->old_file.mode);
} else {
if (delta->old_file.mode == 0)
git_str_printf(out, "new file mode %o\n", delta->new_file.mode);
else if (delta->new_file.mode == 0)
git_str_printf(out, "deleted file mode %o\n", delta->old_file.mode);
else
diff_print_modes(out, delta);
if (print_index)
git_str_printf(out, "index %s..%s\n", start_oid, end_oid);
}
return git_str_oom(out) ? -1 : 0;
}
static int diff_delta_format_path(
git_str *out, const char *prefix, const char *filename)
{
if (!filename) {
/* don't prefix "/dev/null" */
return git_str_puts(out, "/dev/null");
}
if (git_str_joinpath(out, prefix, filename) < 0)
return -1;
return git_str_quote(out);
}
static int diff_delta_format_with_paths(
git_str *out,
const git_diff_delta *delta,
const char *template,
const char *oldpath,
const char *newpath)
{
if (git_oid_is_zero(&delta->old_file.id))
oldpath = "/dev/null";
if (git_oid_is_zero(&delta->new_file.id))
newpath = "/dev/null";
return git_str_printf(out, template, oldpath, newpath);
}
static int diff_delta_format_similarity_header(
git_str *out,
const git_diff_delta *delta)
{
git_str old_path = GIT_STR_INIT, new_path = GIT_STR_INIT;
const char *type;
int error = 0;
if (delta->similarity > 100) {
git_error_set(GIT_ERROR_PATCH, "invalid similarity %d", delta->similarity);
error = -1;
goto done;
}
GIT_ASSERT(delta->status == GIT_DELTA_RENAMED || delta->status == GIT_DELTA_COPIED);
if (delta->status == GIT_DELTA_RENAMED)
type = "rename";
else
type = "copy";
if ((error = git_str_puts(&old_path, delta->old_file.path)) < 0 ||
(error = git_str_puts(&new_path, delta->new_file.path)) < 0 ||
(error = git_str_quote(&old_path)) < 0 ||
(error = git_str_quote(&new_path)) < 0)
goto done;
git_str_printf(out,
"similarity index %d%%\n"
"%s from %s\n"
"%s to %s\n",
delta->similarity,
type, old_path.ptr,
type, new_path.ptr);
if (git_str_oom(out))
error = -1;
done:
git_str_dispose(&old_path);
git_str_dispose(&new_path);
return error;
}
static bool delta_is_unchanged(const git_diff_delta *delta)
{
if (git_oid_is_zero(&delta->old_file.id) &&
git_oid_is_zero(&delta->new_file.id))
return true;
if (delta->old_file.mode == GIT_FILEMODE_COMMIT ||
delta->new_file.mode == GIT_FILEMODE_COMMIT)
return false;
if (git_oid_equal(&delta->old_file.id, &delta->new_file.id))
return true;
return false;
}
int git_diff_delta__format_file_header(
git_str *out,
const git_diff_delta *delta,
const char *oldpfx,
const char *newpfx,
int id_strlen,
bool print_index)
{
git_str old_path = GIT_STR_INIT, new_path = GIT_STR_INIT;
bool unchanged = delta_is_unchanged(delta);
int error = 0;
if (!oldpfx)
oldpfx = DIFF_OLD_PREFIX_DEFAULT;
if (!newpfx)
newpfx = DIFF_NEW_PREFIX_DEFAULT;
if (!id_strlen)
id_strlen = GIT_ABBREV_DEFAULT;
if ((error = diff_delta_format_path(
&old_path, oldpfx, delta->old_file.path)) < 0 ||
(error = diff_delta_format_path(
&new_path, newpfx, delta->new_file.path)) < 0)
goto done;
git_str_clear(out);
git_str_printf(out, "diff --git %s %s\n",
old_path.ptr, new_path.ptr);
if (unchanged && delta->old_file.mode != delta->new_file.mode)
diff_print_modes(out, delta);
if (delta->status == GIT_DELTA_RENAMED ||
(delta->status == GIT_DELTA_COPIED && unchanged)) {
if ((error = diff_delta_format_similarity_header(out, delta)) < 0)
goto done;
}
if (!unchanged) {
if ((error = diff_print_oid_range(out, delta,
id_strlen, print_index)) < 0)
goto done;
if ((delta->flags & GIT_DIFF_FLAG_BINARY) == 0)
diff_delta_format_with_paths(out, delta,
"--- %s\n+++ %s\n", old_path.ptr, new_path.ptr);
}
if (git_str_oom(out))
error = -1;
done:
git_str_dispose(&old_path);
git_str_dispose(&new_path);
return error;
}
static int format_binary(
diff_print_info *pi,
git_diff_binary_t type,
const char *data,
size_t datalen,
size_t inflatedlen)
{
const char *typename = type == GIT_DIFF_BINARY_DELTA ?
"delta" : "literal";
const char *scan, *end;
git_str_printf(pi->buf, "%s %" PRIuZ "\n", typename, inflatedlen);
pi->line.num_lines++;
for (scan = data, end = data + datalen; scan < end; ) {
size_t chunk_len = end - scan;
if (chunk_len > 52)
chunk_len = 52;
if (chunk_len <= 26)
git_str_putc(pi->buf, (char)chunk_len + 'A' - 1);
else
git_str_putc(pi->buf, (char)chunk_len - 26 + 'a' - 1);
git_str_encode_base85(pi->buf, scan, chunk_len);
git_str_putc(pi->buf, '\n');
if (git_str_oom(pi->buf))
return -1;
scan += chunk_len;
pi->line.num_lines++;
}
git_str_putc(pi->buf, '\n');
if (git_str_oom(pi->buf))
return -1;
return 0;
}
static int diff_print_patch_file_binary_noshow(
diff_print_info *pi, git_diff_delta *delta,
const char *old_pfx, const char *new_pfx)
{
git_str old_path = GIT_STR_INIT, new_path = GIT_STR_INIT;
int error;
if ((error = diff_delta_format_path(&old_path, old_pfx, delta->old_file.path)) < 0 ||
(error = diff_delta_format_path(&new_path, new_pfx, delta->new_file.path)) < 0 ||
(error = diff_delta_format_with_paths(pi->buf, delta, "Binary files %s and %s differ\n",
old_path.ptr, new_path.ptr)) < 0)
goto done;
pi->line.num_lines = 1;
done:
git_str_dispose(&old_path);
git_str_dispose(&new_path);
return error;
}
static int diff_print_patch_file_binary(
diff_print_info *pi, git_diff_delta *delta,
const char *old_pfx, const char *new_pfx,
const git_diff_binary *binary)
{
size_t pre_binary_size;
int error;
if (delta->status == GIT_DELTA_UNMODIFIED)
return 0;
if ((pi->flags & GIT_DIFF_SHOW_BINARY) == 0 || !binary->contains_data)
return diff_print_patch_file_binary_noshow(
pi, delta, old_pfx, new_pfx);
pre_binary_size = pi->buf->size;
git_str_printf(pi->buf, "GIT binary patch\n");
pi->line.num_lines++;
if ((error = format_binary(pi, binary->new_file.type, binary->new_file.data,
binary->new_file.datalen, binary->new_file.inflatedlen)) < 0 ||
(error = format_binary(pi, binary->old_file.type, binary->old_file.data,
binary->old_file.datalen, binary->old_file.inflatedlen)) < 0) {
if (error == GIT_EBUFS) {
git_error_clear();
git_str_truncate(pi->buf, pre_binary_size);
return diff_print_patch_file_binary_noshow(
pi, delta, old_pfx, new_pfx);
}
}
pi->line.num_lines++;
return error;
}
static int diff_print_patch_file(
const git_diff_delta *delta, float progress, void *data)
{
int error;
diff_print_info *pi = data;
const char *oldpfx =
pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT;
const char *newpfx =
pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT;
bool binary = (delta->flags & GIT_DIFF_FLAG_BINARY) ||
(pi->flags & GIT_DIFF_FORCE_BINARY);
bool show_binary = !!(pi->flags & GIT_DIFF_SHOW_BINARY);
int id_strlen = pi->id_strlen;
bool print_index = (pi->format != GIT_DIFF_FORMAT_PATCH_ID);
if (binary && show_binary)
id_strlen = delta->old_file.id_abbrev ? delta->old_file.id_abbrev :
delta->new_file.id_abbrev;
GIT_UNUSED(progress);
if (S_ISDIR(delta->new_file.mode) ||
delta->status == GIT_DELTA_UNMODIFIED ||
delta->status == GIT_DELTA_IGNORED ||
delta->status == GIT_DELTA_UNREADABLE ||
(delta->status == GIT_DELTA_UNTRACKED &&
(pi->flags & GIT_DIFF_SHOW_UNTRACKED_CONTENT) == 0))
return 0;
if ((error = git_diff_delta__format_file_header(pi->buf, delta, oldpfx, newpfx,
id_strlen, print_index)) < 0)
return error;
pi->line.origin = GIT_DIFF_LINE_FILE_HDR;
pi->line.content = git_str_cstr(pi->buf);
pi->line.content_len = git_str_len(pi->buf);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_patch_binary(
const git_diff_delta *delta,
const git_diff_binary *binary,
void *data)
{
diff_print_info *pi = data;
const char *old_pfx =
pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT;
const char *new_pfx =
pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT;
int error;
git_str_clear(pi->buf);
if ((error = diff_print_patch_file_binary(
pi, (git_diff_delta *)delta, old_pfx, new_pfx, binary)) < 0)
return error;
pi->line.origin = GIT_DIFF_LINE_BINARY;
pi->line.content = git_str_cstr(pi->buf);
pi->line.content_len = git_str_len(pi->buf);
return pi->print_cb(delta, NULL, &pi->line, pi->payload);
}
static int diff_print_patch_hunk(
const git_diff_delta *d,
const git_diff_hunk *h,
void *data)
{
diff_print_info *pi = data;
if (S_ISDIR(d->new_file.mode))
return 0;
pi->line.origin = GIT_DIFF_LINE_HUNK_HDR;
pi->line.content = h->header;
pi->line.content_len = h->header_len;
return pi->print_cb(d, h, &pi->line, pi->payload);
}
static int diff_print_patch_line(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *data)
{
diff_print_info *pi = data;
if (S_ISDIR(delta->new_file.mode))
return 0;
return pi->print_cb(delta, hunk, line, pi->payload);
}
/* print a git_diff to an output callback */
int git_diff_print(
git_diff *diff,
git_diff_format_t format,
git_diff_line_cb print_cb,
void *payload)
{
int error;
git_str buf = GIT_STR_INIT;
diff_print_info pi;
git_diff_file_cb print_file = NULL;
git_diff_binary_cb print_binary = NULL;
git_diff_hunk_cb print_hunk = NULL;
git_diff_line_cb print_line = NULL;
switch (format) {
case GIT_DIFF_FORMAT_PATCH:
print_file = diff_print_patch_file;
print_binary = diff_print_patch_binary;
print_hunk = diff_print_patch_hunk;
print_line = diff_print_patch_line;
break;
case GIT_DIFF_FORMAT_PATCH_ID:
print_file = diff_print_patch_file;
print_binary = diff_print_patch_binary;
print_line = diff_print_patch_line;
break;
case GIT_DIFF_FORMAT_PATCH_HEADER:
print_file = diff_print_patch_file;
break;
case GIT_DIFF_FORMAT_RAW:
print_file = diff_print_one_raw;
break;
case GIT_DIFF_FORMAT_NAME_ONLY:
print_file = diff_print_one_name_only;
break;
case GIT_DIFF_FORMAT_NAME_STATUS:
print_file = diff_print_one_name_status;
break;
default:
git_error_set(GIT_ERROR_INVALID, "unknown diff output format (%d)", format);
return -1;
}
if ((error = diff_print_info_init_fromdiff(&pi, &buf, diff, format, print_cb, payload)) < 0)
goto out;
if ((error = git_diff_foreach(diff, print_file, print_binary, print_hunk, print_line, &pi)) != 0) {
git_error_set_after_callback_function(error, "git_diff_print");
goto out;
}
out:
git_str_dispose(&buf);
return error;
}
int git_diff_print_callback__to_buf(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
git_str *output = payload;
GIT_UNUSED(delta); GIT_UNUSED(hunk);
if (!output) {
git_error_set(GIT_ERROR_INVALID, "buffer pointer must be provided");
return -1;
}
if (line->origin == GIT_DIFF_LINE_ADDITION ||
line->origin == GIT_DIFF_LINE_DELETION ||
line->origin == GIT_DIFF_LINE_CONTEXT)
git_str_putc(output, line->origin);
return git_str_put(output, line->content, line->content_len);
}
int git_diff_print_callback__to_file_handle(
const git_diff_delta *delta,
const git_diff_hunk *hunk,
const git_diff_line *line,
void *payload)
{
FILE *fp = payload ? payload : stdout;
int error;
GIT_UNUSED(delta);
GIT_UNUSED(hunk);
if (line->origin == GIT_DIFF_LINE_CONTEXT ||
line->origin == GIT_DIFF_LINE_ADDITION ||
line->origin == GIT_DIFF_LINE_DELETION) {
while ((error = fputc(line->origin, fp)) == EINTR)
continue;
if (error) {
git_error_set(GIT_ERROR_OS, "could not write status");
return -1;
}
}
if (fwrite(line->content, line->content_len, 1, fp) != 1) {
git_error_set(GIT_ERROR_OS, "could not write line");
return -1;
}
return 0;
}
/* print a git_diff to a git_str */
int git_diff_to_buf(git_buf *out, git_diff *diff, git_diff_format_t format)
{
git_str str = GIT_STR_INIT;
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(diff);
if ((error = git_buf_tostr(&str, out)) < 0 ||
(error = git_diff_print(diff, format, git_diff_print_callback__to_buf, &str)) < 0)
goto done;
error = git_buf_fromstr(out, &str);
done:
git_str_dispose(&str);
return error;
}
/* print a git_patch to an output callback */
int git_patch_print(
git_patch *patch,
git_diff_line_cb print_cb,
void *payload)
{
git_str temp = GIT_STR_INIT;
diff_print_info pi;
int error;
GIT_ASSERT_ARG(patch);
GIT_ASSERT_ARG(print_cb);
if ((error = diff_print_info_init_frompatch(&pi, &temp, patch,
GIT_DIFF_FORMAT_PATCH, print_cb, payload)) < 0)
goto out;
if ((error = git_patch__invoke_callbacks(patch, diff_print_patch_file, diff_print_patch_binary,
diff_print_patch_hunk, diff_print_patch_line, &pi)) < 0) {
git_error_set_after_callback_function(error, "git_patch_print");
goto out;
}
out:
git_str_dispose(&temp);
return error;
}
/* print a git_patch to a git_str */
int git_patch_to_buf(git_buf *out, git_patch *patch)
{
GIT_BUF_WRAP_PRIVATE(out, git_patch__to_buf, patch);
}
int git_patch__to_buf(git_str *out, git_patch *patch)
{
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(patch);
return git_patch_print(patch, git_diff_print_callback__to_buf, out);
}
| libgit2-main | src/libgit2/diff_print.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "trace.h"
#include "str.h"
#include "runtime.h"
#include "git2/trace.h"
struct git_trace_data git_trace__data = {0};
int git_trace_set(git_trace_level_t level, git_trace_cb callback)
{
GIT_ASSERT_ARG(level == 0 || callback != NULL);
git_trace__data.level = level;
git_trace__data.callback = callback;
GIT_MEMORY_BARRIER;
return 0;
}
| libgit2-main | src/libgit2/trace.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "fetch.h"
#include "git2/oid.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "git2/transport.h"
#include "git2/sys/remote.h"
#include "oid.h"
#include "remote.h"
#include "refspec.h"
#include "pack.h"
#include "netops.h"
#include "repository.h"
#include "refs.h"
static int maybe_want(git_remote *remote, git_remote_head *head, git_refspec *tagspec, git_remote_autotag_option_t tagopt)
{
int match = 0, valid;
if (git_reference_name_is_valid(&valid, head->name) < 0)
return -1;
if (!valid)
return 0;
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
/*
* If tagopt is --tags, always request tags
* in addition to the remote's refspecs
*/
if (git_refspec_src_matches(tagspec, head->name))
match = 1;
}
if (!match && git_remote__matching_refspec(remote, head->name))
match = 1;
if (!match)
return 0;
return git_vector_insert(&remote->refs, head);
}
static int mark_local(git_remote *remote)
{
git_remote_head *head;
git_odb *odb;
size_t i;
if (git_repository_odb__weakptr(&odb, remote->repo) < 0)
return -1;
git_vector_foreach(&remote->refs, i, head) {
/* If we have the object, mark it so we don't ask for it */
if (git_odb_exists(odb, &head->oid))
head->local = 1;
else
remote->need_pack = 1;
}
return 0;
}
static int maybe_want_oid(git_remote *remote, git_refspec *spec)
{
git_remote_head *oid_head;
oid_head = git__calloc(1, sizeof(git_remote_head));
GIT_ERROR_CHECK_ALLOC(oid_head);
git_oid__fromstr(&oid_head->oid, spec->src, GIT_OID_SHA1);
if (spec->dst) {
oid_head->name = git__strdup(spec->dst);
GIT_ERROR_CHECK_ALLOC(oid_head->name);
}
if (git_vector_insert(&remote->local_heads, oid_head) < 0 ||
git_vector_insert(&remote->refs, oid_head) < 0)
return -1;
return 0;
}
static int filter_wants(git_remote *remote, const git_fetch_options *opts)
{
git_remote_head **heads;
git_refspec tagspec, head, *spec;
int error = 0;
git_odb *odb;
size_t i, heads_len;
unsigned int remote_caps;
unsigned int oid_mask = GIT_REMOTE_CAPABILITY_TIP_OID |
GIT_REMOTE_CAPABILITY_REACHABLE_OID;
git_remote_autotag_option_t tagopt = remote->download_tags;
if (opts && opts->download_tags != GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED)
tagopt = opts->download_tags;
git_vector_clear(&remote->refs);
if ((error = git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true)) < 0)
return error;
/*
* The fetch refspec can be NULL, and what this means is that the
* user didn't specify one. This is fine, as it means that we're
* not interested in any particular branch but just the remote's
* HEAD, which will be stored in FETCH_HEAD after the fetch.
*/
if (remote->active_refspecs.length == 0) {
if ((error = git_refspec__parse(&head, "HEAD", true)) < 0)
goto cleanup;
error = git_refspec__dwim_one(&remote->active_refspecs, &head, &remote->refs);
git_refspec__dispose(&head);
if (error < 0)
goto cleanup;
}
if ((error = git_repository_odb__weakptr(&odb, remote->repo)) < 0)
goto cleanup;
if ((error = git_remote_ls((const git_remote_head ***)&heads, &heads_len, remote)) < 0 ||
(error = git_remote_capabilities(&remote_caps, remote)) < 0)
goto cleanup;
/* Handle remote heads */
for (i = 0; i < heads_len; i++) {
if ((error = maybe_want(remote, heads[i], &tagspec, tagopt)) < 0)
goto cleanup;
}
/* Handle explicitly specified OID specs */
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (!git_oid__is_hexstr(spec->src, GIT_OID_SHA1))
continue;
if (!(remote_caps & oid_mask)) {
git_error_set(GIT_ERROR_INVALID, "cannot fetch a specific object from the remote repository");
error = -1;
goto cleanup;
}
if ((error = maybe_want_oid(remote, spec)) < 0)
goto cleanup;
}
error = mark_local(remote);
cleanup:
git_refspec__dispose(&tagspec);
return error;
}
/*
* In this first version, we push all our refs in and start sending
* them out. When we get an ACK we hide that commit and continue
* traversing until we're done
*/
int git_fetch_negotiate(git_remote *remote, const git_fetch_options *opts)
{
git_transport *t = remote->transport;
remote->need_pack = 0;
if (filter_wants(remote, opts) < 0)
return -1;
/* Don't try to negotiate when we don't want anything */
if (!remote->need_pack)
return 0;
/*
* Now we have everything set up so we can start tell the
* server what we want and what we have.
*/
return t->negotiate_fetch(t,
remote->repo,
(const git_remote_head * const *)remote->refs.contents,
remote->refs.length);
}
int git_fetch_download_pack(git_remote *remote)
{
git_transport *t = remote->transport;
if (!remote->need_pack)
return 0;
return t->download_pack(t, remote->repo, &remote->stats);
}
int git_fetch_options_init(git_fetch_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_fetch_options, GIT_FETCH_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_fetch_init_options(git_fetch_options *opts, unsigned int version)
{
return git_fetch_options_init(opts, version);
}
#endif
| libgit2-main | src/libgit2/fetch.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "util.h"
#include "common.h"
int git_strarray_copy(git_strarray *tgt, const git_strarray *src)
{
size_t i;
GIT_ASSERT_ARG(tgt);
GIT_ASSERT_ARG(src);
memset(tgt, 0, sizeof(*tgt));
if (!src->count)
return 0;
tgt->strings = git__calloc(src->count, sizeof(char *));
GIT_ERROR_CHECK_ALLOC(tgt->strings);
for (i = 0; i < src->count; ++i) {
if (!src->strings[i])
continue;
tgt->strings[tgt->count] = git__strdup(src->strings[i]);
if (!tgt->strings[tgt->count]) {
git_strarray_dispose(tgt);
memset(tgt, 0, sizeof(*tgt));
return -1;
}
tgt->count++;
}
return 0;
}
void git_strarray_dispose(git_strarray *array)
{
size_t i;
if (array == NULL)
return;
for (i = 0; i < array->count; ++i)
git__free(array->strings[i]);
git__free(array->strings);
memset(array, 0, sizeof(*array));
}
#ifndef GIT_DEPRECATE_HARD
void git_strarray_free(git_strarray *array)
{
git_strarray_dispose(array);
}
#endif
| libgit2-main | src/libgit2/strarray.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "array.h"
#include "common.h"
#include "git2/message.h"
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#define COMMENT_LINE_CHAR '#'
#define TRAILER_SEPARATORS ":"
static const char *const git_generated_prefixes[] = {
"Signed-off-by: ",
"(cherry picked from commit ",
NULL
};
static int is_blank_line(const char *str)
{
const char *s = str;
while (*s && *s != '\n' && isspace(*s))
s++;
return !*s || *s == '\n';
}
static const char *next_line(const char *str)
{
const char *nl = strchr(str, '\n');
if (nl) {
return nl + 1;
} else {
/* return pointer to the NUL terminator: */
return str + strlen(str);
}
}
/*
* Return the position of the start of the last line. If len is 0, return 0.
*/
static bool last_line(size_t *out, const char *buf, size_t len)
{
size_t i;
*out = 0;
if (len == 0)
return false;
if (len == 1)
return true;
/*
* Skip the last character (in addition to the null terminator),
* because if the last character is a newline, it is considered as part
* of the last line anyway.
*/
i = len - 2;
for (; i > 0; i--) {
if (buf[i] == '\n') {
*out = i + 1;
return true;
}
}
return true;
}
/*
* If the given line is of the form
* "<token><optional whitespace><separator>..." or "<separator>...", sets out
* to the location of the separator and returns true. Otherwise, returns
* false. The optional whitespace is allowed there primarily to allow things
* like "Bug #43" where <token> is "Bug" and <separator> is "#".
*
* The separator-starts-line case (in which this function returns true and
* sets out to 0) is distinguished from the non-well-formed-line case (in
* which this function returns false) because some callers of this function
* need such a distinction.
*/
static bool find_separator(size_t *out, const char *line, const char *separators)
{
int whitespace_found = 0;
const char *c;
for (c = line; *c; c++) {
if (strchr(separators, *c)) {
*out = c - line;
return true;
}
if (!whitespace_found && (isalnum(*c) || *c == '-'))
continue;
if (c != line && (*c == ' ' || *c == '\t')) {
whitespace_found = 1;
continue;
}
break;
}
return false;
}
/*
* Inspect the given string and determine the true "end" of the log message, in
* order to find where to put a new Signed-off-by: line. Ignored are
* trailing comment lines and blank lines. To support "git commit -s
* --amend" on an existing commit, we also ignore "Conflicts:". To
* support "git commit -v", we truncate at cut lines.
*
* Returns the number of bytes from the tail to ignore, to be fed as
* the second parameter to append_signoff().
*/
static size_t ignore_non_trailer(const char *buf, size_t len)
{
size_t boc = 0, bol = 0;
int in_old_conflicts_block = 0;
size_t cutoff = len;
while (bol < cutoff) {
const char *next_line = memchr(buf + bol, '\n', len - bol);
if (!next_line)
next_line = buf + len;
else
next_line++;
if (buf[bol] == COMMENT_LINE_CHAR || buf[bol] == '\n') {
/* is this the first of the run of comments? */
if (!boc)
boc = bol;
/* otherwise, it is just continuing */
} else if (git__prefixcmp(buf + bol, "Conflicts:\n") == 0) {
in_old_conflicts_block = 1;
if (!boc)
boc = bol;
} else if (in_old_conflicts_block && buf[bol] == '\t') {
; /* a pathname in the conflicts block */
} else if (boc) {
/* the previous was not trailing comment */
boc = 0;
in_old_conflicts_block = 0;
}
bol = next_line - buf;
}
return boc ? len - boc : len - cutoff;
}
/*
* Return the position of the start of the patch or the length of str if there
* is no patch in the message.
*/
static size_t find_patch_start(const char *str)
{
const char *s;
for (s = str; *s; s = next_line(s)) {
if (git__prefixcmp(s, "---") == 0)
return s - str;
}
return s - str;
}
/*
* Return the position of the first trailer line or len if there are no
* trailers.
*/
static size_t find_trailer_start(const char *buf, size_t len)
{
const char *s;
size_t end_of_title, l;
int only_spaces = 1;
int recognized_prefix = 0, trailer_lines = 0, non_trailer_lines = 0;
/*
* Number of possible continuation lines encountered. This will be
* reset to 0 if we encounter a trailer (since those lines are to be
* considered continuations of that trailer), and added to
* non_trailer_lines if we encounter a non-trailer (since those lines
* are to be considered non-trailers).
*/
int possible_continuation_lines = 0;
/* The first paragraph is the title and cannot be trailers */
for (s = buf; s < buf + len; s = next_line(s)) {
if (s[0] == COMMENT_LINE_CHAR)
continue;
if (is_blank_line(s))
break;
}
end_of_title = s - buf;
/*
* Get the start of the trailers by looking starting from the end for a
* blank line before a set of non-blank lines that (i) are all
* trailers, or (ii) contains at least one Git-generated trailer and
* consists of at least 25% trailers.
*/
l = len;
while (last_line(&l, buf, l) && l >= end_of_title) {
const char *bol = buf + l;
const char *const *p;
size_t separator_pos = 0;
if (bol[0] == COMMENT_LINE_CHAR) {
non_trailer_lines += possible_continuation_lines;
possible_continuation_lines = 0;
continue;
}
if (is_blank_line(bol)) {
if (only_spaces)
continue;
non_trailer_lines += possible_continuation_lines;
if (recognized_prefix &&
trailer_lines * 3 >= non_trailer_lines)
return next_line(bol) - buf;
else if (trailer_lines && !non_trailer_lines)
return next_line(bol) - buf;
return len;
}
only_spaces = 0;
for (p = git_generated_prefixes; *p; p++) {
if (git__prefixcmp(bol, *p) == 0) {
trailer_lines++;
possible_continuation_lines = 0;
recognized_prefix = 1;
goto continue_outer_loop;
}
}
find_separator(&separator_pos, bol, TRAILER_SEPARATORS);
if (separator_pos >= 1 && !isspace(bol[0])) {
trailer_lines++;
possible_continuation_lines = 0;
if (recognized_prefix)
continue;
} else if (isspace(bol[0]))
possible_continuation_lines++;
else {
non_trailer_lines++;
non_trailer_lines += possible_continuation_lines;
possible_continuation_lines = 0;
}
continue_outer_loop:
;
}
return len;
}
/* Return the position of the end of the trailers. */
static size_t find_trailer_end(const char *buf, size_t len)
{
return len - ignore_non_trailer(buf, len);
}
static char *extract_trailer_block(const char *message, size_t *len)
{
size_t patch_start = find_patch_start(message);
size_t trailer_end = find_trailer_end(message, patch_start);
size_t trailer_start = find_trailer_start(message, trailer_end);
size_t trailer_len = trailer_end - trailer_start;
char *buffer = git__malloc(trailer_len + 1);
if (buffer == NULL)
return NULL;
memcpy(buffer, message + trailer_start, trailer_len);
buffer[trailer_len] = 0;
*len = trailer_len;
return buffer;
}
enum trailer_state {
S_START = 0,
S_KEY = 1,
S_KEY_WS = 2,
S_SEP_WS = 3,
S_VALUE = 4,
S_VALUE_NL = 5,
S_VALUE_END = 6,
S_IGNORE = 7
};
#define NEXT(st) { state = (st); ptr++; continue; }
#define GOTO(st) { state = (st); continue; }
typedef git_array_t(git_message_trailer) git_array_trailer_t;
int git_message_trailers(git_message_trailer_array *trailer_arr, const char *message)
{
enum trailer_state state = S_START;
int rc = 0;
char *ptr;
char *key = NULL;
char *value = NULL;
git_array_trailer_t arr = GIT_ARRAY_INIT;
size_t trailer_len;
char *trailer = extract_trailer_block(message, &trailer_len);
if (trailer == NULL)
return -1;
for (ptr = trailer;;) {
switch (state) {
case S_START: {
if (*ptr == 0) {
goto ret;
}
key = ptr;
GOTO(S_KEY);
}
case S_KEY: {
if (*ptr == 0) {
goto ret;
}
if (isalnum(*ptr) || *ptr == '-') {
/* legal key character */
NEXT(S_KEY);
}
if (*ptr == ' ' || *ptr == '\t') {
/* optional whitespace before separator */
*ptr = 0;
NEXT(S_KEY_WS);
}
if (strchr(TRAILER_SEPARATORS, *ptr)) {
*ptr = 0;
NEXT(S_SEP_WS);
}
/* illegal character */
GOTO(S_IGNORE);
}
case S_KEY_WS: {
if (*ptr == 0) {
goto ret;
}
if (*ptr == ' ' || *ptr == '\t') {
NEXT(S_KEY_WS);
}
if (strchr(TRAILER_SEPARATORS, *ptr)) {
NEXT(S_SEP_WS);
}
/* illegal character */
GOTO(S_IGNORE);
}
case S_SEP_WS: {
if (*ptr == 0) {
goto ret;
}
if (*ptr == ' ' || *ptr == '\t') {
NEXT(S_SEP_WS);
}
value = ptr;
NEXT(S_VALUE);
}
case S_VALUE: {
if (*ptr == 0) {
GOTO(S_VALUE_END);
}
if (*ptr == '\n') {
NEXT(S_VALUE_NL);
}
NEXT(S_VALUE);
}
case S_VALUE_NL: {
if (*ptr == ' ') {
/* continuation; */
NEXT(S_VALUE);
}
ptr[-1] = 0;
GOTO(S_VALUE_END);
}
case S_VALUE_END: {
git_message_trailer *t = git_array_alloc(arr);
t->key = key;
t->value = value;
key = NULL;
value = NULL;
GOTO(S_START);
}
case S_IGNORE: {
if (*ptr == 0) {
goto ret;
}
if (*ptr == '\n') {
NEXT(S_START);
}
NEXT(S_IGNORE);
}
}
}
ret:
trailer_arr->_trailer_block = trailer;
trailer_arr->trailers = arr.ptr;
trailer_arr->count = arr.size;
return rc;
}
void git_message_trailer_array_free(git_message_trailer_array *arr)
{
git__free(arr->_trailer_block);
git__free(arr->trailers);
}
| libgit2-main | src/libgit2/trailer.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "reflog.h"
#include "repository.h"
#include "filebuf.h"
#include "signature.h"
#include "refdb.h"
#include "git2/sys/refdb_backend.h"
#include "git2/sys/reflog.h"
void git_reflog_entry__free(git_reflog_entry *entry)
{
git_signature_free(entry->committer);
git__free(entry->msg);
git__free(entry);
}
void git_reflog_free(git_reflog *reflog)
{
size_t i;
git_reflog_entry *entry;
if (reflog == NULL)
return;
if (reflog->db)
GIT_REFCOUNT_DEC(reflog->db, git_refdb__free);
for (i=0; i < reflog->entries.length; i++) {
entry = git_vector_get(&reflog->entries, i);
git_reflog_entry__free(entry);
}
git_vector_free(&reflog->entries);
git__free(reflog->ref_name);
git__free(reflog);
}
int git_reflog_read(git_reflog **reflog, git_repository *repo, const char *name)
{
git_refdb *refdb;
int error;
GIT_ASSERT_ARG(reflog);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
return error;
return git_refdb_reflog_read(reflog, refdb, name);
}
int git_reflog_write(git_reflog *reflog)
{
git_refdb *db;
GIT_ASSERT_ARG(reflog);
GIT_ASSERT_ARG(reflog->db);
db = reflog->db;
return db->backend->reflog_write(db->backend, reflog);
}
int git_reflog_append(git_reflog *reflog, const git_oid *new_oid, const git_signature *committer, const char *msg)
{
const git_reflog_entry *previous;
git_reflog_entry *entry;
GIT_ASSERT_ARG(reflog);
GIT_ASSERT_ARG(new_oid);
GIT_ASSERT_ARG(committer);
entry = git__calloc(1, sizeof(git_reflog_entry));
GIT_ERROR_CHECK_ALLOC(entry);
if ((git_signature_dup(&entry->committer, committer)) < 0)
goto cleanup;
if (msg != NULL) {
size_t i, msglen = strlen(msg);
if ((entry->msg = git__strndup(msg, msglen)) == NULL)
goto cleanup;
/*
* Replace all newlines with spaces, except for
* the final trailing newline.
*/
for (i = 0; i < msglen; i++)
if (entry->msg[i] == '\n')
entry->msg[i] = ' ';
}
previous = git_reflog_entry_byindex(reflog, 0);
if (previous == NULL)
git_oid__fromstr(&entry->oid_old, GIT_OID_SHA1_HEXZERO, GIT_OID_SHA1);
else
git_oid_cpy(&entry->oid_old, &previous->oid_cur);
git_oid_cpy(&entry->oid_cur, new_oid);
if (git_vector_insert(&reflog->entries, entry) < 0)
goto cleanup;
return 0;
cleanup:
git_reflog_entry__free(entry);
return -1;
}
int git_reflog_rename(git_repository *repo, const char *old_name, const char *new_name)
{
git_refdb *refdb;
int error;
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
return -1;
return refdb->backend->reflog_rename(refdb->backend, old_name, new_name);
}
int git_reflog_delete(git_repository *repo, const char *name)
{
git_refdb *refdb;
int error;
if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
return -1;
return refdb->backend->reflog_delete(refdb->backend, name);
}
size_t git_reflog_entrycount(git_reflog *reflog)
{
GIT_ASSERT_ARG_WITH_RETVAL(reflog, 0);
return reflog->entries.length;
}
const git_reflog_entry *git_reflog_entry_byindex(const git_reflog *reflog, size_t idx)
{
GIT_ASSERT_ARG_WITH_RETVAL(reflog, NULL);
if (idx >= reflog->entries.length)
return NULL;
return git_vector_get(
&reflog->entries, reflog_inverse_index(idx, reflog->entries.length));
}
const git_oid *git_reflog_entry_id_old(const git_reflog_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return &entry->oid_old;
}
const git_oid *git_reflog_entry_id_new(const git_reflog_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return &entry->oid_cur;
}
const git_signature *git_reflog_entry_committer(const git_reflog_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return entry->committer;
}
const char *git_reflog_entry_message(const git_reflog_entry *entry)
{
GIT_ASSERT_ARG_WITH_RETVAL(entry, NULL);
return entry->msg;
}
int git_reflog_drop(git_reflog *reflog, size_t idx, int rewrite_previous_entry)
{
size_t entrycount;
git_reflog_entry *entry, *previous;
entrycount = git_reflog_entrycount(reflog);
entry = (git_reflog_entry *)git_reflog_entry_byindex(reflog, idx);
if (entry == NULL) {
git_error_set(GIT_ERROR_REFERENCE, "no reflog entry at index %"PRIuZ, idx);
return GIT_ENOTFOUND;
}
git_reflog_entry__free(entry);
if (git_vector_remove(
&reflog->entries, reflog_inverse_index(idx, entrycount)) < 0)
return -1;
if (!rewrite_previous_entry)
return 0;
/* No need to rewrite anything when removing the most recent entry */
if (idx == 0)
return 0;
/* Have the latest entry just been dropped? */
if (entrycount == 1)
return 0;
entry = (git_reflog_entry *)git_reflog_entry_byindex(reflog, idx - 1);
/* If the oldest entry has just been removed... */
if (idx == entrycount - 1) {
git_oid zero = GIT_OID_SHA1_ZERO;
/* ...clear the oid_old member of the "new" oldest entry */
if (git_oid_cpy(&entry->oid_old, &zero) < 0)
return -1;
return 0;
}
previous = (git_reflog_entry *)git_reflog_entry_byindex(reflog, idx);
git_oid_cpy(&entry->oid_old, &previous->oid_cur);
return 0;
}
| libgit2-main | src/libgit2/reflog.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "remote.h"
#include "buf.h"
#include "branch.h"
#include "config.h"
#include "repository.h"
#include "fetch.h"
#include "refs.h"
#include "refspec.h"
#include "fetchhead.h"
#include "push.h"
#include "proxy.h"
#include "git2/config.h"
#include "git2/types.h"
#include "git2/oid.h"
#include "git2/net.h"
#define CONFIG_URL_FMT "remote.%s.url"
#define CONFIG_PUSHURL_FMT "remote.%s.pushurl"
#define CONFIG_FETCH_FMT "remote.%s.fetch"
#define CONFIG_PUSH_FMT "remote.%s.push"
#define CONFIG_TAGOPT_FMT "remote.%s.tagopt"
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs);
static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name);
static int apply_insteadof(char **out, git_config *config, const char *url, int direction, bool use_default_if_empty);
static int add_refspec_to(git_vector *vector, const char *string, bool is_fetch)
{
git_refspec *spec;
spec = git__calloc(1, sizeof(git_refspec));
GIT_ERROR_CHECK_ALLOC(spec);
if (git_refspec__parse(spec, string, is_fetch) < 0) {
git__free(spec);
return -1;
}
spec->push = !is_fetch;
if (git_vector_insert(vector, spec) < 0) {
git_refspec__dispose(spec);
git__free(spec);
return -1;
}
return 0;
}
static int add_refspec(git_remote *remote, const char *string, bool is_fetch)
{
return add_refspec_to(&remote->refspecs, string, is_fetch);
}
static int download_tags_value(git_remote *remote, git_config *cfg)
{
git_config_entry *ce;
git_str buf = GIT_STR_INIT;
int error;
if (git_str_printf(&buf, "remote.%s.tagopt", remote->name) < 0)
return -1;
error = git_config__lookup_entry(&ce, cfg, git_str_cstr(&buf), false);
git_str_dispose(&buf);
if (!error && ce && ce->value) {
if (!strcmp(ce->value, "--no-tags"))
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
else if (!strcmp(ce->value, "--tags"))
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_ALL;
}
git_config_entry_free(ce);
return error;
}
static int ensure_remote_name_is_valid(const char *name)
{
int valid, error;
error = git_remote_name_is_valid(&valid, name);
if (!error && !valid) {
git_error_set(
GIT_ERROR_CONFIG,
"'%s' is not a valid remote name.", name ? name : "(null)");
error = GIT_EINVALIDSPEC;
}
return error;
}
static int write_add_refspec(git_repository *repo, const char *name, const char *refspec, bool fetch)
{
git_config *cfg;
git_str var = GIT_STR_INIT;
git_refspec spec;
const char *fmt;
int error;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
fmt = fetch ? CONFIG_FETCH_FMT : CONFIG_PUSH_FMT;
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if ((error = git_refspec__parse(&spec, refspec, fetch)) < 0)
return error;
git_refspec__dispose(&spec);
if ((error = git_str_printf(&var, fmt, name)) < 0)
return error;
/*
* "$^" is an unmatchable regexp: it will not match anything at all, so
* all values will be considered new and we will not replace any
* present value.
*/
if ((error = git_config_set_multivar(cfg, var.ptr, "$^", refspec)) < 0) {
goto cleanup;
}
cleanup:
git_str_dispose(&var);
return 0;
}
static int canonicalize_url(git_str *out, const char *in)
{
if (in == NULL || strlen(in) == 0) {
git_error_set(GIT_ERROR_INVALID, "cannot set empty URL");
return GIT_EINVALIDSPEC;
}
#ifdef GIT_WIN32
/* Given a UNC path like \\server\path, we need to convert this
* to //server/path for compatibility with core git.
*/
if (in[0] == '\\' && in[1] == '\\' &&
(git__isalpha(in[2]) || git__isdigit(in[2]))) {
const char *c;
for (c = in; *c; c++)
git_str_putc(out, *c == '\\' ? '/' : *c);
return git_str_oom(out) ? -1 : 0;
}
#endif
return git_str_puts(out, in);
}
static int default_fetchspec_for_name(git_str *buf, const char *name)
{
if (git_str_printf(buf, "+refs/heads/*:refs/remotes/%s/*", name) < 0)
return -1;
return 0;
}
static int ensure_remote_doesnot_exist(git_repository *repo, const char *name)
{
int error;
git_remote *remote;
error = git_remote_lookup(&remote, repo, name);
if (error == GIT_ENOTFOUND)
return 0;
if (error < 0)
return error;
git_remote_free(remote);
git_error_set(GIT_ERROR_CONFIG, "remote '%s' already exists", name);
return GIT_EEXISTS;
}
int git_remote_create_options_init(git_remote_create_options *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_remote_create_options, GIT_REMOTE_CREATE_OPTIONS_INIT);
return 0;
}
#ifndef GIT_DEPRECATE_HARD
int git_remote_create_init_options(git_remote_create_options *opts, unsigned int version)
{
return git_remote_create_options_init(opts, version);
}
#endif
int git_remote_create_with_opts(git_remote **out, const char *url, const git_remote_create_options *opts)
{
git_remote *remote = NULL;
git_config *config_ro = NULL, *config_rw;
git_str canonical_url = GIT_STR_INIT;
git_str var = GIT_STR_INIT;
git_str specbuf = GIT_STR_INIT;
const git_remote_create_options dummy_opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
int error = -1;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(url);
if (!opts) {
opts = &dummy_opts;
}
GIT_ERROR_CHECK_VERSION(opts, GIT_REMOTE_CREATE_OPTIONS_VERSION, "git_remote_create_options");
if (opts->name != NULL) {
if ((error = ensure_remote_name_is_valid(opts->name)) < 0)
return error;
if (opts->repository &&
(error = ensure_remote_doesnot_exist(opts->repository, opts->name)) < 0)
return error;
}
if (opts->repository) {
if ((error = git_repository_config_snapshot(&config_ro, opts->repository)) < 0)
goto on_error;
}
remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
remote->repo = opts->repository;
if ((error = git_vector_init(&remote->refs, 8, NULL)) < 0 ||
(error = canonicalize_url(&canonical_url, url)) < 0)
goto on_error;
if (opts->repository && !(opts->flags & GIT_REMOTE_CREATE_SKIP_INSTEADOF)) {
if ((error = apply_insteadof(&remote->url, config_ro, canonical_url.ptr, GIT_DIRECTION_FETCH, true)) < 0 ||
(error = apply_insteadof(&remote->pushurl, config_ro, canonical_url.ptr, GIT_DIRECTION_PUSH, false)) < 0)
goto on_error;
} else {
remote->url = git__strdup(canonical_url.ptr);
GIT_ERROR_CHECK_ALLOC(remote->url);
}
if (opts->name != NULL) {
remote->name = git__strdup(opts->name);
GIT_ERROR_CHECK_ALLOC(remote->name);
if (opts->repository &&
((error = git_str_printf(&var, CONFIG_URL_FMT, opts->name)) < 0 ||
(error = git_repository_config__weakptr(&config_rw, opts->repository)) < 0 ||
(error = git_config_set_string(config_rw, var.ptr, canonical_url.ptr)) < 0))
goto on_error;
}
if (opts->fetchspec != NULL ||
(opts->name && !(opts->flags & GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC))) {
const char *fetch = NULL;
if (opts->fetchspec) {
fetch = opts->fetchspec;
} else {
if ((error = default_fetchspec_for_name(&specbuf, opts->name)) < 0)
goto on_error;
fetch = git_str_cstr(&specbuf);
}
if ((error = add_refspec(remote, fetch, true)) < 0)
goto on_error;
/* only write for named remotes with a repository */
if (opts->repository && opts->name &&
((error = write_add_refspec(opts->repository, opts->name, fetch, true)) < 0 ||
(error = lookup_remote_prune_config(remote, config_ro, opts->name)) < 0))
goto on_error;
/* Move the data over to where the matching functions can find them */
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto on_error;
}
/* A remote without a name doesn't download tags */
if (!opts->name)
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
else
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;
git_str_dispose(&var);
*out = remote;
error = 0;
on_error:
if (error)
git_remote_free(remote);
git_config_free(config_ro);
git_str_dispose(&specbuf);
git_str_dispose(&canonical_url);
git_str_dispose(&var);
return error;
}
int git_remote_create(git_remote **out, git_repository *repo, const char *name, const char *url)
{
git_str buf = GIT_STR_INIT;
int error;
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
/* Those 2 tests are duplicated here because of backward-compatibility */
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if (canonicalize_url(&buf, url) < 0)
return GIT_ERROR;
git_str_clear(&buf);
opts.repository = repo;
opts.name = name;
error = git_remote_create_with_opts(out, url, &opts);
git_str_dispose(&buf);
return error;
}
int git_remote_create_with_fetchspec(git_remote **out, git_repository *repo, const char *name, const char *url, const char *fetch)
{
int error;
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
opts.repository = repo;
opts.name = name;
opts.fetchspec = fetch;
opts.flags = GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC;
return git_remote_create_with_opts(out, url, &opts);
}
int git_remote_create_anonymous(git_remote **out, git_repository *repo, const char *url)
{
git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
opts.repository = repo;
return git_remote_create_with_opts(out, url, &opts);
}
int git_remote_create_detached(git_remote **out, const char *url)
{
return git_remote_create_with_opts(out, url, NULL);
}
int git_remote_dup(git_remote **dest, git_remote *source)
{
size_t i;
int error = 0;
git_refspec *spec;
git_remote *remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
if (source->name != NULL) {
remote->name = git__strdup(source->name);
GIT_ERROR_CHECK_ALLOC(remote->name);
}
if (source->url != NULL) {
remote->url = git__strdup(source->url);
GIT_ERROR_CHECK_ALLOC(remote->url);
}
if (source->pushurl != NULL) {
remote->pushurl = git__strdup(source->pushurl);
GIT_ERROR_CHECK_ALLOC(remote->pushurl);
}
remote->repo = source->repo;
remote->download_tags = source->download_tags;
remote->prune_refs = source->prune_refs;
if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
error = -1;
goto cleanup;
}
git_vector_foreach(&source->refspecs, i, spec) {
if ((error = add_refspec(remote, spec->string, !spec->push)) < 0)
goto cleanup;
}
*dest = remote;
cleanup:
if (error < 0)
git__free(remote);
return error;
}
struct refspec_cb_data {
git_remote *remote;
int fetch;
};
static int refspec_cb(const git_config_entry *entry, void *payload)
{
struct refspec_cb_data *data = (struct refspec_cb_data *)payload;
return add_refspec(data->remote, entry->value, data->fetch);
}
static int get_optional_config(
bool *found, git_config *config, git_str *buf,
git_config_foreach_cb cb, void *payload)
{
int error = 0;
const char *key = git_str_cstr(buf);
if (git_str_oom(buf))
return -1;
if (cb != NULL)
error = git_config_get_multivar_foreach(config, key, NULL, cb, payload);
else
error = git_config_get_string(payload, config, key);
if (found)
*found = !error;
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
return error;
}
int git_remote_lookup(git_remote **out, git_repository *repo, const char *name)
{
git_remote *remote = NULL;
git_str buf = GIT_STR_INIT;
const char *val;
int error = 0;
git_config *config;
struct refspec_cb_data data = { NULL };
bool optional_setting_found = false, found;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = ensure_remote_name_is_valid(name)) < 0)
return error;
if ((error = git_repository_config_snapshot(&config, repo)) < 0)
return error;
remote = git__calloc(1, sizeof(git_remote));
GIT_ERROR_CHECK_ALLOC(remote);
remote->name = git__strdup(name);
GIT_ERROR_CHECK_ALLOC(remote->name);
if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->passive_refspecs, 2, NULL) < 0 ||
git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
error = -1;
goto cleanup;
}
if ((error = git_str_printf(&buf, "remote.%s.url", name)) < 0)
goto cleanup;
if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
goto cleanup;
optional_setting_found |= found;
remote->repo = repo;
remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;
if (found && strlen(val) > 0) {
if ((error = apply_insteadof(&remote->url, config, val, GIT_DIRECTION_FETCH, true)) < 0 ||
(error = apply_insteadof(&remote->pushurl, config, val, GIT_DIRECTION_PUSH, false)) < 0)
goto cleanup;
}
val = NULL;
git_str_clear(&buf);
git_str_printf(&buf, "remote.%s.pushurl", name);
if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
goto cleanup;
optional_setting_found |= found;
if (!optional_setting_found) {
error = GIT_ENOTFOUND;
git_error_set(GIT_ERROR_CONFIG, "remote '%s' does not exist", name);
goto cleanup;
}
if (found && strlen(val) > 0) {
if (remote->pushurl)
git__free(remote->pushurl);
if ((error = apply_insteadof(&remote->pushurl, config, val, GIT_DIRECTION_FETCH, true)) < 0)
goto cleanup;
}
data.remote = remote;
data.fetch = true;
git_str_clear(&buf);
git_str_printf(&buf, "remote.%s.fetch", name);
if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
goto cleanup;
data.fetch = false;
git_str_clear(&buf);
git_str_printf(&buf, "remote.%s.push", name);
if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
goto cleanup;
if ((error = download_tags_value(remote, config)) < 0)
goto cleanup;
if ((error = lookup_remote_prune_config(remote, config, name)) < 0)
goto cleanup;
/* Move the data over to where the matching functions can find them */
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto cleanup;
*out = remote;
cleanup:
git_config_free(config);
git_str_dispose(&buf);
if (error < 0)
git_remote_free(remote);
return error;
}
static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name)
{
git_str buf = GIT_STR_INIT;
int error = 0;
git_str_printf(&buf, "remote.%s.prune", name);
if ((error = git_config_get_bool(&remote->prune_refs, config, git_str_cstr(&buf))) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
if ((error = git_config_get_bool(&remote->prune_refs, config, "fetch.prune")) < 0) {
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
}
}
}
git_str_dispose(&buf);
return error;
}
const char *git_remote_name(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->name;
}
git_repository *git_remote_owner(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->repo;
}
const char *git_remote_url(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->url;
}
int git_remote_set_instance_url(git_remote *remote, const char *url)
{
char *tmp;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(url);
if ((tmp = git__strdup(url)) == NULL)
return -1;
git__free(remote->url);
remote->url = tmp;
return 0;
}
static int set_url(git_repository *repo, const char *remote, const char *pattern, const char *url)
{
git_config *cfg;
git_str buf = GIT_STR_INIT, canonical_url = GIT_STR_INIT;
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(remote);
if ((error = ensure_remote_name_is_valid(remote)) < 0)
return error;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if ((error = git_str_printf(&buf, pattern, remote)) < 0)
return error;
if (url) {
if ((error = canonicalize_url(&canonical_url, url)) < 0)
goto cleanup;
error = git_config_set_string(cfg, buf.ptr, url);
} else {
error = git_config_delete_entry(cfg, buf.ptr);
}
cleanup:
git_str_dispose(&canonical_url);
git_str_dispose(&buf);
return error;
}
int git_remote_set_url(git_repository *repo, const char *remote, const char *url)
{
return set_url(repo, remote, CONFIG_URL_FMT, url);
}
const char *git_remote_pushurl(const git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return remote->pushurl;
}
int git_remote_set_instance_pushurl(git_remote *remote, const char *url)
{
char *tmp;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(url);
if ((tmp = git__strdup(url)) == NULL)
return -1;
git__free(remote->pushurl);
remote->pushurl = tmp;
return 0;
}
int git_remote_set_pushurl(git_repository *repo, const char *remote, const char *url)
{
return set_url(repo, remote, CONFIG_PUSHURL_FMT, url);
}
static int resolve_url(
git_str *resolved_url,
const char *url,
int direction,
const git_remote_callbacks *callbacks)
{
#ifdef GIT_DEPRECATE_HARD
GIT_UNUSED(direction);
GIT_UNUSED(callbacks);
#else
git_buf buf = GIT_BUF_INIT;
int error;
if (callbacks && callbacks->resolve_url) {
error = callbacks->resolve_url(&buf, url, direction, callbacks->payload);
if (error != GIT_PASSTHROUGH) {
git_error_set_after_callback_function(error, "git_resolve_url_cb");
git_str_set(resolved_url, buf.ptr, buf.size);
git_buf_dispose(&buf);
return error;
}
}
#endif
return git_str_sets(resolved_url, url);
}
int git_remote__urlfordirection(
git_str *url_out,
struct git_remote *remote,
int direction,
const git_remote_callbacks *callbacks)
{
const char *url = NULL;
GIT_ASSERT_ARG(remote);
GIT_ASSERT_ARG(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH);
if (callbacks && callbacks->remote_ready) {
int status = callbacks->remote_ready(remote, direction, callbacks->payload);
if (status != 0 && status != GIT_PASSTHROUGH) {
git_error_set_after_callback_function(status, "git_remote_ready_cb");
return status;
}
}
if (direction == GIT_DIRECTION_FETCH)
url = remote->url;
else if (direction == GIT_DIRECTION_PUSH)
url = remote->pushurl ? remote->pushurl : remote->url;
if (!url) {
git_error_set(GIT_ERROR_INVALID,
"malformed remote '%s' - missing %s URL",
remote->name ? remote->name : "(anonymous)",
direction == GIT_DIRECTION_FETCH ? "fetch" : "push");
return GIT_EINVALID;
}
return resolve_url(url_out, url, direction, callbacks);
}
int git_remote_connect_options_init(
git_remote_connect_options *opts,
unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_remote_connect_options, GIT_REMOTE_CONNECT_OPTIONS_INIT);
return 0;
}
int git_remote_connect_options_dup(
git_remote_connect_options *dst,
const git_remote_connect_options *src)
{
memcpy(dst, src, sizeof(git_remote_connect_options));
if (git_proxy_options_dup(&dst->proxy_opts, &src->proxy_opts) < 0 ||
git_strarray_copy(&dst->custom_headers, &src->custom_headers) < 0)
return -1;
return 0;
}
void git_remote_connect_options_dispose(git_remote_connect_options *opts)
{
if (!opts)
return;
git_strarray_dispose(&opts->custom_headers);
git_proxy_options_dispose(&opts->proxy_opts);
}
static size_t http_header_name_length(const char *http_header)
{
const char *colon = strchr(http_header, ':');
if (!colon)
return 0;
return colon - http_header;
}
static bool is_malformed_http_header(const char *http_header)
{
const char *c;
size_t name_len;
/* Disallow \r and \n */
if ((c = strchr(http_header, '\r')) != NULL)
return true;
if ((c = strchr(http_header, '\n')) != NULL)
return true;
/* Require a header name followed by : */
if ((name_len = http_header_name_length(http_header)) < 1)
return true;
return false;
}
static char *forbidden_custom_headers[] = {
"User-Agent",
"Host",
"Accept",
"Content-Type",
"Transfer-Encoding",
"Content-Length",
};
static bool is_forbidden_custom_header(const char *custom_header)
{
unsigned long i;
size_t name_len = http_header_name_length(custom_header);
/* Disallow headers that we set */
for (i = 0; i < ARRAY_SIZE(forbidden_custom_headers); i++)
if (strncmp(forbidden_custom_headers[i], custom_header, name_len) == 0)
return true;
return false;
}
static int validate_custom_headers(const git_strarray *custom_headers)
{
size_t i;
if (!custom_headers)
return 0;
for (i = 0; i < custom_headers->count; i++) {
if (is_malformed_http_header(custom_headers->strings[i])) {
git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is malformed", custom_headers->strings[i]);
return -1;
}
if (is_forbidden_custom_header(custom_headers->strings[i])) {
git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is already set by libgit2", custom_headers->strings[i]);
return -1;
}
}
return 0;
}
static int lookup_redirect_config(
git_remote_redirect_t *out,
git_repository *repo)
{
git_config *config;
const char *value;
int bool_value, error = 0;
if (!repo) {
*out = GIT_REMOTE_REDIRECT_INITIAL;
return 0;
}
if ((error = git_repository_config_snapshot(&config, repo)) < 0)
goto done;
if ((error = git_config_get_string(&value, config, "http.followRedirects")) < 0) {
if (error == GIT_ENOTFOUND) {
*out = GIT_REMOTE_REDIRECT_INITIAL;
error = 0;
}
goto done;
}
if (git_config_parse_bool(&bool_value, value) == 0) {
*out = bool_value ? GIT_REMOTE_REDIRECT_ALL :
GIT_REMOTE_REDIRECT_NONE;
} else if (strcasecmp(value, "initial") == 0) {
*out = GIT_REMOTE_REDIRECT_INITIAL;
} else {
git_error_set(GIT_ERROR_CONFIG, "invalid configuration setting '%s' for 'http.followRedirects'", value);
error = -1;
}
done:
git_config_free(config);
return error;
}
int git_remote_connect_options_normalize(
git_remote_connect_options *dst,
git_repository *repo,
const git_remote_connect_options *src)
{
git_remote_connect_options_dispose(dst);
git_remote_connect_options_init(dst, GIT_REMOTE_CONNECT_OPTIONS_VERSION);
if (src) {
GIT_ERROR_CHECK_VERSION(src, GIT_REMOTE_CONNECT_OPTIONS_VERSION, "git_remote_connect_options");
GIT_ERROR_CHECK_VERSION(&src->callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
GIT_ERROR_CHECK_VERSION(&src->proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
if (validate_custom_headers(&src->custom_headers) < 0 ||
git_remote_connect_options_dup(dst, src) < 0)
return -1;
}
if (dst->follow_redirects == 0) {
if (lookup_redirect_config(&dst->follow_redirects, repo) < 0)
return -1;
}
return 0;
}
int git_remote_connect_ext(
git_remote *remote,
git_direction direction,
const git_remote_connect_options *given_opts)
{
git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
git_str url = GIT_STR_INIT;
git_transport *t;
int error;
GIT_ASSERT_ARG(remote);
if (given_opts)
memcpy(&opts, given_opts, sizeof(git_remote_connect_options));
GIT_ERROR_CHECK_VERSION(&opts.callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
GIT_ERROR_CHECK_VERSION(&opts.proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
t = remote->transport;
if ((error = git_remote__urlfordirection(&url, remote, direction, &opts.callbacks)) < 0)
goto on_error;
/* If we don't have a transport object yet, and the caller specified a
* custom transport factory, use that */
if (!t && opts.callbacks.transport &&
(error = opts.callbacks.transport(&t, remote, opts.callbacks.payload)) < 0)
goto on_error;
/* If we still don't have a transport, then use the global
* transport registrations which map URI schemes to transport factories */
if (!t && (error = git_transport_new(&t, remote, url.ptr)) < 0)
goto on_error;
if ((error = t->connect(t, url.ptr, direction, &opts)) != 0)
goto on_error;
remote->transport = t;
git_str_dispose(&url);
return 0;
on_error:
if (t)
t->free(t);
git_str_dispose(&url);
if (t == remote->transport)
remote->transport = NULL;
return error;
}
int git_remote_connect(
git_remote *remote,
git_direction direction,
const git_remote_callbacks *callbacks,
const git_proxy_options *proxy,
const git_strarray *custom_headers)
{
git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
if (callbacks)
memcpy(&opts.callbacks, callbacks, sizeof(git_remote_callbacks));
if (proxy)
memcpy(&opts.proxy_opts, proxy, sizeof(git_proxy_options));
if (custom_headers)
memcpy(&opts.custom_headers, custom_headers, sizeof(git_strarray));
return git_remote_connect_ext(remote, direction, &opts);
}
int git_remote_ls(const git_remote_head ***out, size_t *size, git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (!remote->transport) {
git_error_set(GIT_ERROR_NET, "this remote has never connected");
return -1;
}
return remote->transport->ls(out, size, remote->transport);
}
int git_remote_capabilities(unsigned int *out, git_remote *remote)
{
GIT_ASSERT_ARG(remote);
*out = 0;
if (!remote->transport) {
git_error_set(GIT_ERROR_NET, "this remote has never connected");
return -1;
}
return remote->transport->capabilities(out, remote->transport);
}
static int lookup_config(char **out, git_config *cfg, const char *name)
{
git_config_entry *ce = NULL;
int error;
if ((error = git_config__lookup_entry(&ce, cfg, name, false)) < 0)
return error;
if (ce && ce->value) {
*out = git__strdup(ce->value);
GIT_ERROR_CHECK_ALLOC(*out);
} else {
error = GIT_ENOTFOUND;
}
git_config_entry_free(ce);
return error;
}
static void url_config_trim(git_net_url *url)
{
size_t len = strlen(url->path);
if (url->path[len - 1] == '/') {
len--;
} else {
while (len && url->path[len - 1] != '/')
len--;
}
url->path[len] = '\0';
}
static int http_proxy_config(char **out, git_remote *remote, git_net_url *url)
{
git_config *cfg = NULL;
git_str buf = GIT_STR_INIT;
git_net_url lookup_url = GIT_NET_URL_INIT;
int error;
if ((error = git_net_url_dup(&lookup_url, url)) < 0)
goto done;
if (remote->repo) {
if ((error = git_repository_config(&cfg, remote->repo)) < 0)
goto done;
} else {
if ((error = git_config_open_default(&cfg)) < 0)
goto done;
}
/* remote.<name>.proxy config setting */
if (remote->name && remote->name[0]) {
git_str_clear(&buf);
if ((error = git_str_printf(&buf, "remote.%s.proxy", remote->name)) < 0 ||
(error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
goto done;
}
while (true) {
git_str_clear(&buf);
if ((error = git_str_puts(&buf, "http.")) < 0 ||
(error = git_net_url_fmt(&buf, &lookup_url)) < 0 ||
(error = git_str_puts(&buf, ".proxy")) < 0 ||
(error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
goto done;
if (! lookup_url.path[0])
break;
url_config_trim(&lookup_url);
}
git_str_clear(&buf);
error = lookup_config(out, cfg, "http.proxy");
done:
git_config_free(cfg);
git_str_dispose(&buf);
git_net_url_dispose(&lookup_url);
return error;
}
static int http_proxy_env(char **out, git_remote *remote, git_net_url *url)
{
git_str proxy_env = GIT_STR_INIT, no_proxy_env = GIT_STR_INIT;
bool use_ssl = (strcmp(url->scheme, "https") == 0);
int error;
GIT_UNUSED(remote);
/* http_proxy / https_proxy environment variables */
error = git__getenv(&proxy_env, use_ssl ? "https_proxy" : "http_proxy");
/* try uppercase environment variables */
if (error == GIT_ENOTFOUND)
error = git__getenv(&proxy_env, use_ssl ? "HTTPS_PROXY" : "HTTP_PROXY");
if (error)
goto done;
/* no_proxy/NO_PROXY environment variables */
error = git__getenv(&no_proxy_env, "no_proxy");
if (error == GIT_ENOTFOUND)
error = git__getenv(&no_proxy_env, "NO_PROXY");
if (error && error != GIT_ENOTFOUND)
goto done;
if (!git_net_url_matches_pattern_list(url, no_proxy_env.ptr))
*out = git_str_detach(&proxy_env);
else
error = GIT_ENOTFOUND;
done:
git_str_dispose(&proxy_env);
git_str_dispose(&no_proxy_env);
return error;
}
int git_remote__http_proxy(char **out, git_remote *remote, git_net_url *url)
{
int error;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(remote);
*out = NULL;
/*
* Go through the possible sources for proxy configuration,
* Examine the various git config options first, then
* consult environment variables.
*/
if ((error = http_proxy_config(out, remote, url)) != GIT_ENOTFOUND ||
(error = http_proxy_env(out, remote, url)) != GIT_ENOTFOUND)
return error;
return 0;
}
/* DWIM `refspecs` based on `refs` and append the output to `out` */
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs)
{
size_t i;
git_refspec *spec;
git_vector_foreach(refspecs, i, spec) {
if (git_refspec__dwim_one(out, spec, refs) < 0)
return -1;
}
return 0;
}
static void free_refspecs(git_vector *vec)
{
size_t i;
git_refspec *spec;
git_vector_foreach(vec, i, spec) {
git_refspec__dispose(spec);
git__free(spec);
}
git_vector_clear(vec);
}
static int remote_head_cmp(const void *_a, const void *_b)
{
const git_remote_head *a = (git_remote_head *) _a;
const git_remote_head *b = (git_remote_head *) _b;
return git__strcmp_cb(a->name, b->name);
}
static int ls_to_vector(git_vector *out, git_remote *remote)
{
git_remote_head **heads;
size_t heads_len, i;
if (git_remote_ls((const git_remote_head ***)&heads, &heads_len, remote) < 0)
return -1;
if (git_vector_init(out, heads_len, remote_head_cmp) < 0)
return -1;
for (i = 0; i < heads_len; i++) {
if (git_vector_insert(out, heads[i]) < 0)
return -1;
}
return 0;
}
#define copy_opts(out, in) \
if (in) { \
(out)->callbacks = (in)->callbacks; \
(out)->proxy_opts = (in)->proxy_opts; \
(out)->custom_headers = (in)->custom_headers; \
(out)->follow_redirects = (in)->follow_redirects; \
}
GIT_INLINE(int) connect_opts_from_fetch_opts(
git_remote_connect_options *out,
git_remote *remote,
const git_fetch_options *fetch_opts)
{
git_remote_connect_options tmp = GIT_REMOTE_CONNECT_OPTIONS_INIT;
copy_opts(&tmp, fetch_opts);
return git_remote_connect_options_normalize(out, remote->repo, &tmp);
}
static int connect_or_reset_options(
git_remote *remote,
int direction,
git_remote_connect_options *opts)
{
if (!git_remote_connected(remote)) {
return git_remote_connect_ext(remote, direction, opts);
} else {
return remote->transport->set_connect_opts(remote->transport, opts);
}
}
/* Download from an already connected remote. */
static int git_remote__download(
git_remote *remote,
const git_strarray *refspecs,
const git_fetch_options *opts)
{
git_vector *to_active, specs = GIT_VECTOR_INIT, refs = GIT_VECTOR_INIT;
size_t i;
int error;
if (ls_to_vector(&refs, remote) < 0)
return -1;
if ((error = git_vector_init(&specs, 0, NULL)) < 0)
goto on_error;
remote->passed_refspecs = 0;
if (!refspecs || !refspecs->count) {
to_active = &remote->refspecs;
} else {
for (i = 0; i < refspecs->count; i++) {
if ((error = add_refspec_to(&specs, refspecs->strings[i], true)) < 0)
goto on_error;
}
to_active = &specs;
remote->passed_refspecs = 1;
}
free_refspecs(&remote->passive_refspecs);
if ((error = dwim_refspecs(&remote->passive_refspecs, &remote->refspecs, &refs)) < 0)
goto on_error;
free_refspecs(&remote->active_refspecs);
error = dwim_refspecs(&remote->active_refspecs, to_active, &refs);
git_vector_free(&refs);
free_refspecs(&specs);
git_vector_free(&specs);
if (error < 0)
goto on_error;
if (remote->push) {
git_push_free(remote->push);
remote->push = NULL;
}
if ((error = git_fetch_negotiate(remote, opts)) < 0)
goto on_error;
error = git_fetch_download_pack(remote);
on_error:
git_vector_free(&refs);
free_refspecs(&specs);
git_vector_free(&specs);
return error;
}
int git_remote_download(
git_remote *remote,
const git_strarray *refspecs,
const git_fetch_options *opts)
{
git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
int error;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (connect_opts_from_fetch_opts(&connect_opts, remote, opts) < 0)
return -1;
if ((error = connect_or_reset_options(remote, GIT_DIRECTION_FETCH, &connect_opts)) < 0)
return error;
return git_remote__download(remote, refspecs, opts);
}
int git_remote_fetch(
git_remote *remote,
const git_strarray *refspecs,
const git_fetch_options *opts,
const char *reflog_message)
{
int error, update_fetchhead = 1;
git_remote_autotag_option_t tagopt = remote->download_tags;
bool prune = false;
git_str reflog_msg_buf = GIT_STR_INIT;
git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (connect_opts_from_fetch_opts(&connect_opts, remote, opts) < 0)
return -1;
if ((error = connect_or_reset_options(remote, GIT_DIRECTION_FETCH, &connect_opts)) < 0)
return error;
if (opts) {
update_fetchhead = opts->update_fetchhead;
tagopt = opts->download_tags;
}
/* Connect and download everything */
error = git_remote__download(remote, refspecs, opts);
/* We don't need to be connected anymore */
git_remote_disconnect(remote);
/* If the download failed, return the error */
if (error != 0)
goto done;
/* Default reflog message */
if (reflog_message)
git_str_sets(&reflog_msg_buf, reflog_message);
else {
git_str_printf(&reflog_msg_buf, "fetch %s",
remote->name ? remote->name : remote->url);
}
/* Create "remote/foo" branches for all remote branches */
error = git_remote_update_tips(remote, &connect_opts.callbacks, update_fetchhead, tagopt, git_str_cstr(&reflog_msg_buf));
git_str_dispose(&reflog_msg_buf);
if (error < 0)
goto done;
if (opts && opts->prune == GIT_FETCH_PRUNE)
prune = true;
else if (opts && opts->prune == GIT_FETCH_PRUNE_UNSPECIFIED && remote->prune_refs)
prune = true;
else if (opts && opts->prune == GIT_FETCH_NO_PRUNE)
prune = false;
else
prune = remote->prune_refs;
if (prune)
error = git_remote_prune(remote, &connect_opts.callbacks);
done:
git_remote_connect_options_dispose(&connect_opts);
return error;
}
static int remote_head_for_fetchspec_src(git_remote_head **out, git_vector *update_heads, const char *fetchspec_src)
{
unsigned int i;
git_remote_head *remote_ref;
GIT_ASSERT_ARG(update_heads);
GIT_ASSERT_ARG(fetchspec_src);
*out = NULL;
git_vector_foreach(update_heads, i, remote_ref) {
if (strcmp(remote_ref->name, fetchspec_src) == 0) {
*out = remote_ref;
break;
}
}
return 0;
}
static int ref_to_update(int *update, git_str *remote_name, git_remote *remote, git_refspec *spec, const char *ref_name)
{
int error = 0;
git_repository *repo;
git_str upstream_remote = GIT_STR_INIT;
git_str upstream_name = GIT_STR_INIT;
repo = git_remote_owner(remote);
if ((!git_reference__is_branch(ref_name)) ||
!git_remote_name(remote) ||
(error = git_branch__upstream_remote(&upstream_remote, repo, ref_name) < 0) ||
git__strcmp(git_remote_name(remote), git_str_cstr(&upstream_remote)) ||
(error = git_branch__upstream_name(&upstream_name, repo, ref_name)) < 0 ||
!git_refspec_dst_matches(spec, git_str_cstr(&upstream_name)) ||
(error = git_refspec__rtransform(remote_name, spec, upstream_name.ptr)) < 0) {
/* Not an error if there is no upstream */
if (error == GIT_ENOTFOUND) {
git_error_clear();
error = 0;
}
*update = 0;
} else {
*update = 1;
}
git_str_dispose(&upstream_remote);
git_str_dispose(&upstream_name);
return error;
}
static int remote_head_for_ref(git_remote_head **out, git_remote *remote, git_refspec *spec, git_vector *update_heads, git_reference *ref)
{
git_reference *resolved_ref = NULL;
git_str remote_name = GIT_STR_INIT;
git_config *config = NULL;
const char *ref_name;
int error = 0, update;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(spec);
GIT_ASSERT_ARG(ref);
*out = NULL;
error = git_reference_resolve(&resolved_ref, ref);
/* If we're in an unborn branch, let's pretend nothing happened */
if (error == GIT_ENOTFOUND && git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
ref_name = git_reference_symbolic_target(ref);
error = 0;
} else {
ref_name = git_reference_name(resolved_ref);
}
/*
* The ref name may be unresolvable - perhaps it's pointing to
* something invalid. In this case, there is no remote head for
* this ref.
*/
if (!ref_name) {
error = 0;
goto cleanup;
}
if ((error = ref_to_update(&update, &remote_name, remote, spec, ref_name)) < 0)
goto cleanup;
if (update)
error = remote_head_for_fetchspec_src(out, update_heads, git_str_cstr(&remote_name));
cleanup:
git_str_dispose(&remote_name);
git_reference_free(resolved_ref);
git_config_free(config);
return error;
}
static int git_remote_write_fetchhead(git_remote *remote, git_refspec *spec, git_vector *update_heads)
{
git_reference *head_ref = NULL;
git_fetchhead_ref *fetchhead_ref;
git_remote_head *remote_ref, *merge_remote_ref;
git_vector fetchhead_refs;
bool include_all_fetchheads;
unsigned int i = 0;
int error = 0;
GIT_ASSERT_ARG(remote);
/* no heads, nothing to do */
if (update_heads->length == 0)
return 0;
if (git_vector_init(&fetchhead_refs, update_heads->length, git_fetchhead_ref_cmp) < 0)
return -1;
/* Iff refspec is * (but not subdir slash star), include tags */
include_all_fetchheads = (strcmp(GIT_REFS_HEADS_DIR "*", git_refspec_src(spec)) == 0);
/* Determine what to merge: if refspec was a wildcard, just use HEAD */
if (git_refspec_is_wildcard(spec)) {
if ((error = git_reference_lookup(&head_ref, remote->repo, GIT_HEAD_FILE)) < 0 ||
(error = remote_head_for_ref(&merge_remote_ref, remote, spec, update_heads, head_ref)) < 0)
goto cleanup;
} else {
/* If we're fetching a single refspec, that's the only thing that should be in FETCH_HEAD. */
if ((error = remote_head_for_fetchspec_src(&merge_remote_ref, update_heads, git_refspec_src(spec))) < 0)
goto cleanup;
}
/* Create the FETCH_HEAD file */
git_vector_foreach(update_heads, i, remote_ref) {
int merge_this_fetchhead = (merge_remote_ref == remote_ref);
if (!include_all_fetchheads &&
!git_refspec_src_matches(spec, remote_ref->name) &&
!merge_this_fetchhead)
continue;
if (git_fetchhead_ref_create(&fetchhead_ref,
&remote_ref->oid,
merge_this_fetchhead,
remote_ref->name,
git_remote_url(remote)) < 0)
goto cleanup;
if (git_vector_insert(&fetchhead_refs, fetchhead_ref) < 0)
goto cleanup;
}
git_fetchhead_write(remote->repo, &fetchhead_refs);
cleanup:
for (i = 0; i < fetchhead_refs.length; ++i)
git_fetchhead_ref_free(fetchhead_refs.contents[i]);
git_vector_free(&fetchhead_refs);
git_reference_free(head_ref);
return error;
}
/**
* Generate a list of candidates for pruning by getting a list of
* references which match the rhs of an active refspec.
*/
static int prune_candidates(git_vector *candidates, git_remote *remote)
{
git_strarray arr = { 0 };
size_t i;
int error;
if ((error = git_reference_list(&arr, remote->repo)) < 0)
return error;
for (i = 0; i < arr.count; i++) {
const char *refname = arr.strings[i];
char *refname_dup;
if (!git_remote__matching_dst_refspec(remote, refname))
continue;
refname_dup = git__strdup(refname);
GIT_ERROR_CHECK_ALLOC(refname_dup);
if ((error = git_vector_insert(candidates, refname_dup)) < 0)
goto out;
}
out:
git_strarray_dispose(&arr);
return error;
}
static int find_head(const void *_a, const void *_b)
{
git_remote_head *a = (git_remote_head *) _a;
git_remote_head *b = (git_remote_head *) _b;
return strcmp(a->name, b->name);
}
int git_remote_prune(git_remote *remote, const git_remote_callbacks *callbacks)
{
size_t i, j;
git_vector remote_refs = GIT_VECTOR_INIT;
git_vector candidates = GIT_VECTOR_INIT;
const git_refspec *spec;
const char *refname;
int error;
git_oid zero_id = GIT_OID_SHA1_ZERO;
if (callbacks)
GIT_ERROR_CHECK_VERSION(callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
if ((error = ls_to_vector(&remote_refs, remote)) < 0)
goto cleanup;
git_vector_set_cmp(&remote_refs, find_head);
if ((error = prune_candidates(&candidates, remote)) < 0)
goto cleanup;
/*
* Remove those entries from the candidate list for which we
* can find a remote reference in at least one refspec.
*/
git_vector_foreach(&candidates, i, refname) {
git_vector_foreach(&remote->active_refspecs, j, spec) {
git_str buf = GIT_STR_INIT;
size_t pos;
char *src_name;
git_remote_head key = {0};
if (!git_refspec_dst_matches(spec, refname))
continue;
if ((error = git_refspec__rtransform(&buf, spec, refname)) < 0)
goto cleanup;
key.name = (char *) git_str_cstr(&buf);
error = git_vector_bsearch(&pos, &remote_refs, &key);
git_str_dispose(&buf);
if (error < 0 && error != GIT_ENOTFOUND)
goto cleanup;
if (error == GIT_ENOTFOUND)
continue;
/* If we did find a source, remove it from the candidates. */
if ((error = git_vector_set((void **) &src_name, &candidates, i, NULL)) < 0)
goto cleanup;
git__free(src_name);
break;
}
}
/*
* For those candidates still left in the list, we need to
* remove them. We do not remove symrefs, as those are for
* stuff like origin/HEAD which will never match, but we do
* not want to remove them.
*/
git_vector_foreach(&candidates, i, refname) {
git_reference *ref;
git_oid id;
if (refname == NULL)
continue;
error = git_reference_lookup(&ref, remote->repo, refname);
/* as we want it gone, let's not consider this an error */
if (error == GIT_ENOTFOUND)
continue;
if (error < 0)
goto cleanup;
if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
git_reference_free(ref);
continue;
}
git_oid_cpy(&id, git_reference_target(ref));
error = git_reference_delete(ref);
git_reference_free(ref);
if (error < 0)
goto cleanup;
if (callbacks && callbacks->update_tips)
error = callbacks->update_tips(refname, &id, &zero_id, callbacks->payload);
if (error < 0)
goto cleanup;
}
cleanup:
git_vector_free(&remote_refs);
git_vector_free_deep(&candidates);
return error;
}
static int update_ref(
const git_remote *remote,
const char *ref_name,
git_oid *id,
const char *msg,
const git_remote_callbacks *callbacks)
{
git_reference *ref;
git_oid old_id;
int error;
error = git_reference_name_to_id(&old_id, remote->repo, ref_name);
if (error < 0 && error != GIT_ENOTFOUND)
return error;
else if (error == 0 && git_oid_equal(&old_id, id))
return 0;
/* If we did find a current reference, make sure we haven't lost a race */
if (error)
error = git_reference_create(&ref, remote->repo, ref_name, id, true, msg);
else
error = git_reference_create_matching(&ref, remote->repo, ref_name, id, true, &old_id, msg);
git_reference_free(ref);
if (error < 0)
return error;
if (callbacks && callbacks->update_tips &&
(error = callbacks->update_tips(ref_name, &old_id, id, callbacks->payload)) < 0)
return error;
return 0;
}
static int update_one_tip(
git_vector *update_heads,
git_remote *remote,
git_refspec *spec,
git_remote_head *head,
git_refspec *tagspec,
git_remote_autotag_option_t tagopt,
const char *log_message,
const git_remote_callbacks *callbacks)
{
git_odb *odb;
git_str refname = GIT_STR_INIT;
git_reference *ref = NULL;
bool autotag = false;
git_oid old;
int valid;
int error;
if ((error = git_repository_odb__weakptr(&odb, remote->repo)) < 0)
goto done;
/* Ignore malformed ref names (which also saves us from tag^{} */
if ((error = git_reference_name_is_valid(&valid, head->name)) < 0)
goto done;
if (!valid)
goto done;
/* If we have a tag, see if the auto-follow rules say to update it */
if (git_refspec_src_matches(tagspec, head->name)) {
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_AUTO)
autotag = true;
if (tagopt != GIT_REMOTE_DOWNLOAD_TAGS_NONE) {
if (git_str_puts(&refname, head->name) < 0)
goto done;
}
}
/* If we didn't want to auto-follow the tag, check if the refspec matches */
if (!autotag && git_refspec_src_matches(spec, head->name)) {
if (spec->dst) {
if ((error = git_refspec__transform(&refname, spec, head->name)) < 0)
goto done;
} else {
/*
* no rhs means store it in FETCH_HEAD, even if we don't
* update anything else.
*/
error = git_vector_insert(update_heads, head);
goto done;
}
}
/* If we still don't have a refname, we don't want it */
if (git_str_len(&refname) == 0)
goto done;
/* In autotag mode, only create tags for objects already in db */
if (autotag && !git_odb_exists(odb, &head->oid))
goto done;
if (!autotag && (error = git_vector_insert(update_heads, head)) < 0)
goto done;
error = git_reference_name_to_id(&old, remote->repo, refname.ptr);
if (error < 0 && error != GIT_ENOTFOUND)
goto done;
if (!(error || error == GIT_ENOTFOUND) &&
!spec->force &&
!git_graph_descendant_of(remote->repo, &head->oid, &old)) {
error = 0;
goto done;
}
if (error == GIT_ENOTFOUND) {
git_oid_clear(&old, GIT_OID_SHA1);
error = 0;
if (autotag && (error = git_vector_insert(update_heads, head)) < 0)
goto done;
}
if (!git_oid__cmp(&old, &head->oid))
goto done;
/* In autotag mode, don't overwrite any locally-existing tags */
error = git_reference_create(&ref, remote->repo, refname.ptr, &head->oid, !autotag,
log_message);
if (error < 0) {
if (error == GIT_EEXISTS)
error = 0;
goto done;
}
if (callbacks && callbacks->update_tips != NULL &&
(error = callbacks->update_tips(refname.ptr, &old, &head->oid, callbacks->payload)) < 0)
git_error_set_after_callback_function(error, "git_remote_fetch");
done:
git_reference_free(ref);
git_str_dispose(&refname);
return error;
}
static int update_tips_for_spec(
git_remote *remote,
const git_remote_callbacks *callbacks,
int update_fetchhead,
git_remote_autotag_option_t tagopt,
git_refspec *spec,
git_vector *refs,
const char *log_message)
{
git_refspec tagspec;
git_remote_head *head, oid_head;
git_vector update_heads;
int error = 0;
size_t i;
GIT_ASSERT_ARG(remote);
if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
return -1;
/* Make a copy of the transport's refs */
if (git_vector_init(&update_heads, 16, NULL) < 0)
return -1;
/* Update tips based on the remote heads */
git_vector_foreach(refs, i, head) {
if (update_one_tip(&update_heads, remote, spec, head, &tagspec, tagopt, log_message, callbacks) < 0)
goto on_error;
}
/* Handle specified oid sources */
if (git_oid__is_hexstr(spec->src, GIT_OID_SHA1)) {
git_oid id;
if ((error = git_oid__fromstr(&id, spec->src, GIT_OID_SHA1)) < 0)
goto on_error;
if (spec->dst &&
(error = update_ref(remote, spec->dst, &id, log_message, callbacks)) < 0)
goto on_error;
git_oid_cpy(&oid_head.oid, &id);
oid_head.name = spec->src;
if ((error = git_vector_insert(&update_heads, &oid_head)) < 0)
goto on_error;
}
if (update_fetchhead &&
(error = git_remote_write_fetchhead(remote, spec, &update_heads)) < 0)
goto on_error;
git_refspec__dispose(&tagspec);
git_vector_free(&update_heads);
return 0;
on_error:
git_refspec__dispose(&tagspec);
git_vector_free(&update_heads);
return -1;
}
/**
* Iteration over the three vectors, with a pause whenever we find a match
*
* On each stop, we store the iteration stat in the inout i,j,k
* parameters, and return the currently matching passive refspec as
* well as the head which we matched.
*/
static int next_head(const git_remote *remote, git_vector *refs,
git_refspec **out_spec, git_remote_head **out_head,
size_t *out_i, size_t *out_j, size_t *out_k)
{
const git_vector *active, *passive;
git_remote_head *head;
git_refspec *spec, *passive_spec;
size_t i, j, k;
int valid;
active = &remote->active_refspecs;
passive = &remote->passive_refspecs;
i = *out_i;
j = *out_j;
k = *out_k;
for (; i < refs->length; i++) {
head = git_vector_get(refs, i);
if (git_reference_name_is_valid(&valid, head->name) < 0)
return -1;
if (!valid)
continue;
for (; j < active->length; j++) {
spec = git_vector_get(active, j);
if (!git_refspec_src_matches(spec, head->name))
continue;
for (; k < passive->length; k++) {
passive_spec = git_vector_get(passive, k);
if (!git_refspec_src_matches(passive_spec, head->name))
continue;
*out_spec = passive_spec;
*out_head = head;
*out_i = i;
*out_j = j;
*out_k = k + 1;
return 0;
}
k = 0;
}
j = 0;
}
return GIT_ITEROVER;
}
static int opportunistic_updates(
const git_remote *remote,
const git_remote_callbacks *callbacks,
git_vector *refs,
const char *msg)
{
size_t i, j, k;
git_refspec *spec;
git_remote_head *head;
git_str refname = GIT_STR_INIT;
int error = 0;
i = j = k = 0;
/* Handle refspecs matching remote heads */
while ((error = next_head(remote, refs, &spec, &head, &i, &j, &k)) == 0) {
/*
* If we got here, there is a refspec which was used
* for fetching which matches the source of one of the
* passive refspecs, so we should update that
* remote-tracking branch, but not add it to
* FETCH_HEAD
*/
git_str_clear(&refname);
if ((error = git_refspec__transform(&refname, spec, head->name)) < 0 ||
(error = update_ref(remote, refname.ptr, &head->oid, msg, callbacks)) < 0)
goto cleanup;
}
if (error != GIT_ITEROVER)
goto cleanup;
error = 0;
cleanup:
git_str_dispose(&refname);
return error;
}
static int truncate_fetch_head(const char *gitdir)
{
git_str path = GIT_STR_INIT;
int error;
if ((error = git_str_joinpath(&path, gitdir, GIT_FETCH_HEAD_FILE)) < 0)
return error;
error = git_futils_truncate(path.ptr, GIT_REFS_FILE_MODE);
git_str_dispose(&path);
return error;
}
int git_remote_update_tips(
git_remote *remote,
const git_remote_callbacks *callbacks,
int update_fetchhead,
git_remote_autotag_option_t download_tags,
const char *reflog_message)
{
git_refspec *spec, tagspec;
git_vector refs = GIT_VECTOR_INIT;
git_remote_autotag_option_t tagopt;
int error;
size_t i;
/* push has its own logic hidden away in the push object */
if (remote->push) {
return git_push_update_tips(remote->push, callbacks);
}
if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
return -1;
if ((error = ls_to_vector(&refs, remote)) < 0)
goto out;
if (download_tags == GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED)
tagopt = remote->download_tags;
else
tagopt = download_tags;
if ((error = truncate_fetch_head(git_repository_path(remote->repo))) < 0)
goto out;
if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, &tagspec, &refs, reflog_message)) < 0)
goto out;
}
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, spec, &refs, reflog_message)) < 0)
goto out;
}
/* Only try to do opportunistic updates if the refspec lists differ. */
if (remote->passed_refspecs)
error = opportunistic_updates(remote, callbacks, &refs, reflog_message);
out:
git_vector_free(&refs);
git_refspec__dispose(&tagspec);
return error;
}
int git_remote_connected(const git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (!remote->transport || !remote->transport->is_connected)
return 0;
/* Ask the transport if it's connected. */
return remote->transport->is_connected(remote->transport);
}
int git_remote_stop(git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (remote->transport && remote->transport->cancel)
remote->transport->cancel(remote->transport);
return 0;
}
int git_remote_disconnect(git_remote *remote)
{
GIT_ASSERT_ARG(remote);
if (git_remote_connected(remote))
remote->transport->close(remote->transport);
return 0;
}
static void free_heads(git_vector *heads)
{
git_remote_head *head;
size_t i;
git_vector_foreach(heads, i, head) {
git__free(head->name);
git__free(head);
}
}
void git_remote_free(git_remote *remote)
{
if (remote == NULL)
return;
if (remote->transport != NULL) {
git_remote_disconnect(remote);
remote->transport->free(remote->transport);
remote->transport = NULL;
}
git_vector_free(&remote->refs);
free_refspecs(&remote->refspecs);
git_vector_free(&remote->refspecs);
free_refspecs(&remote->active_refspecs);
git_vector_free(&remote->active_refspecs);
free_refspecs(&remote->passive_refspecs);
git_vector_free(&remote->passive_refspecs);
free_heads(&remote->local_heads);
git_vector_free(&remote->local_heads);
git_push_free(remote->push);
git__free(remote->url);
git__free(remote->pushurl);
git__free(remote->name);
git__free(remote);
}
static int remote_list_cb(const git_config_entry *entry, void *payload)
{
git_vector *list = payload;
const char *name = entry->name + strlen("remote.");
size_t namelen = strlen(name);
char *remote_name;
/* we know name matches "remote.<stuff>.(push)?url" */
if (!strcmp(&name[namelen - 4], ".url"))
remote_name = git__strndup(name, namelen - 4); /* strip ".url" */
else
remote_name = git__strndup(name, namelen - 8); /* strip ".pushurl" */
GIT_ERROR_CHECK_ALLOC(remote_name);
return git_vector_insert(list, remote_name);
}
int git_remote_list(git_strarray *remotes_list, git_repository *repo)
{
int error;
git_config *cfg;
git_vector list = GIT_VECTOR_INIT;
if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
return error;
if ((error = git_vector_init(&list, 4, git__strcmp_cb)) < 0)
return error;
error = git_config_foreach_match(
cfg, "^remote\\..*\\.(push)?url$", remote_list_cb, &list);
if (error < 0) {
git_vector_free_deep(&list);
return error;
}
git_vector_uniq(&list, git__free);
remotes_list->strings =
(char **)git_vector_detach(&remotes_list->count, NULL, &list);
return 0;
}
const git_indexer_progress *git_remote_stats(git_remote *remote)
{
GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
return &remote->stats;
}
git_remote_autotag_option_t git_remote_autotag(const git_remote *remote)
{
return remote->download_tags;
}
int git_remote_set_autotag(git_repository *repo, const char *remote, git_remote_autotag_option_t value)
{
git_str var = GIT_STR_INIT;
git_config *config;
int error;
GIT_ASSERT_ARG(repo && remote);
if ((error = ensure_remote_name_is_valid(remote)) < 0)
return error;
if ((error = git_repository_config__weakptr(&config, repo)) < 0)
return error;
if ((error = git_str_printf(&var, CONFIG_TAGOPT_FMT, remote)))
return error;
switch (value) {
case GIT_REMOTE_DOWNLOAD_TAGS_NONE:
error = git_config_set_string(config, var.ptr, "--no-tags");
break;
case GIT_REMOTE_DOWNLOAD_TAGS_ALL:
error = git_config_set_string(config, var.ptr, "--tags");
break;
case GIT_REMOTE_DOWNLOAD_TAGS_AUTO:
error = git_config_delete_entry(config, var.ptr);
if (error == GIT_ENOTFOUND)
error = 0;
break;
default:
git_error_set(GIT_ERROR_INVALID, "invalid value for the tagopt setting");
error = -1;
}
git_str_dispose(&var);
return error;
}
int git_remote_prune_refs(const git_remote *remote)
{
return remote->prune_refs;
}
static int rename_remote_config_section(
git_repository *repo,
const char *old_name,
const char *new_name)
{
git_str old_section_name = GIT_STR_INIT,
new_section_name = GIT_STR_INIT;
int error = -1;
if (git_str_printf(&old_section_name, "remote.%s", old_name) < 0)
goto cleanup;
if (new_name &&
(git_str_printf(&new_section_name, "remote.%s", new_name) < 0))
goto cleanup;
error = git_config_rename_section(
repo,
git_str_cstr(&old_section_name),
new_name ? git_str_cstr(&new_section_name) : NULL);
cleanup:
git_str_dispose(&old_section_name);
git_str_dispose(&new_section_name);
return error;
}
struct update_data {
git_config *config;
const char *old_remote_name;
const char *new_remote_name;
};
static int update_config_entries_cb(
const git_config_entry *entry,
void *payload)
{
struct update_data *data = (struct update_data *)payload;
if (strcmp(entry->value, data->old_remote_name))
return 0;
return git_config_set_string(
data->config, entry->name, data->new_remote_name);
}
static int update_branch_remote_config_entry(
git_repository *repo,
const char *old_name,
const char *new_name)
{
int error;
struct update_data data = { NULL };
if ((error = git_repository_config__weakptr(&data.config, repo)) < 0)
return error;
data.old_remote_name = old_name;
data.new_remote_name = new_name;
return git_config_foreach_match(
data.config, "branch\\..+\\.remote", update_config_entries_cb, &data);
}
static int rename_one_remote_reference(
git_reference *reference_in,
const char *old_remote_name,
const char *new_remote_name)
{
int error;
git_reference *ref = NULL, *dummy = NULL;
git_str namespace = GIT_STR_INIT, old_namespace = GIT_STR_INIT;
git_str new_name = GIT_STR_INIT;
git_str log_message = GIT_STR_INIT;
size_t pfx_len;
const char *target;
if ((error = git_str_printf(&namespace, GIT_REFS_REMOTES_DIR "%s/", new_remote_name)) < 0)
return error;
pfx_len = strlen(GIT_REFS_REMOTES_DIR) + strlen(old_remote_name) + 1;
git_str_puts(&new_name, namespace.ptr);
if ((error = git_str_puts(&new_name, git_reference_name(reference_in) + pfx_len)) < 0)
goto cleanup;
if ((error = git_str_printf(&log_message,
"renamed remote %s to %s",
old_remote_name, new_remote_name)) < 0)
goto cleanup;
if ((error = git_reference_rename(&ref, reference_in, git_str_cstr(&new_name), 1,
git_str_cstr(&log_message))) < 0)
goto cleanup;
if (git_reference_type(ref) != GIT_REFERENCE_SYMBOLIC)
goto cleanup;
/* Handle refs like origin/HEAD -> origin/master */
target = git_reference_symbolic_target(ref);
if ((error = git_str_printf(&old_namespace, GIT_REFS_REMOTES_DIR "%s/", old_remote_name)) < 0)
goto cleanup;
if (git__prefixcmp(target, old_namespace.ptr))
goto cleanup;
git_str_clear(&new_name);
git_str_puts(&new_name, namespace.ptr);
if ((error = git_str_puts(&new_name, target + pfx_len)) < 0)
goto cleanup;
error = git_reference_symbolic_set_target(&dummy, ref, git_str_cstr(&new_name),
git_str_cstr(&log_message));
git_reference_free(dummy);
cleanup:
git_reference_free(reference_in);
git_reference_free(ref);
git_str_dispose(&namespace);
git_str_dispose(&old_namespace);
git_str_dispose(&new_name);
git_str_dispose(&log_message);
return error;
}
static int rename_remote_references(
git_repository *repo,
const char *old_name,
const char *new_name)
{
int error;
git_str buf = GIT_STR_INIT;
git_reference *ref;
git_reference_iterator *iter;
if ((error = git_str_printf(&buf, GIT_REFS_REMOTES_DIR "%s/*", old_name)) < 0)
return error;
error = git_reference_iterator_glob_new(&iter, repo, git_str_cstr(&buf));
git_str_dispose(&buf);
if (error < 0)
return error;
while ((error = git_reference_next(&ref, iter)) == 0) {
if ((error = rename_one_remote_reference(ref, old_name, new_name)) < 0)
break;
}
git_reference_iterator_free(iter);
return (error == GIT_ITEROVER) ? 0 : error;
}
static int rename_fetch_refspecs(git_vector *problems, git_remote *remote, const char *new_name)
{
git_config *config;
git_str base = GIT_STR_INIT, var = GIT_STR_INIT, val = GIT_STR_INIT;
const git_refspec *spec;
size_t i;
int error = 0;
if ((error = git_repository_config__weakptr(&config, remote->repo)) < 0)
return error;
if ((error = git_vector_init(problems, 1, NULL)) < 0)
return error;
if ((error = default_fetchspec_for_name(&base, remote->name)) < 0)
return error;
git_vector_foreach(&remote->refspecs, i, spec) {
if (spec->push)
continue;
/* Does the dst part of the refspec follow the expected format? */
if (strcmp(git_str_cstr(&base), spec->string)) {
char *dup;
dup = git__strdup(spec->string);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(problems, dup)) < 0)
break;
continue;
}
/* If we do want to move it to the new section */
git_str_clear(&val);
git_str_clear(&var);
if (default_fetchspec_for_name(&val, new_name) < 0 ||
git_str_printf(&var, "remote.%s.fetch", new_name) < 0)
{
error = -1;
break;
}
if ((error = git_config_set_string(
config, git_str_cstr(&var), git_str_cstr(&val))) < 0)
break;
}
git_str_dispose(&base);
git_str_dispose(&var);
git_str_dispose(&val);
if (error < 0) {
char *str;
git_vector_foreach(problems, i, str)
git__free(str);
git_vector_free(problems);
}
return error;
}
int git_remote_rename(git_strarray *out, git_repository *repo, const char *name, const char *new_name)
{
int error;
git_vector problem_refspecs = GIT_VECTOR_INIT;
git_remote *remote = NULL;
GIT_ASSERT_ARG(out && repo && name && new_name);
if ((error = git_remote_lookup(&remote, repo, name)) < 0)
return error;
if ((error = ensure_remote_name_is_valid(new_name)) < 0)
goto cleanup;
if ((error = ensure_remote_doesnot_exist(repo, new_name)) < 0)
goto cleanup;
if ((error = rename_remote_config_section(repo, name, new_name)) < 0)
goto cleanup;
if ((error = update_branch_remote_config_entry(repo, name, new_name)) < 0)
goto cleanup;
if ((error = rename_remote_references(repo, name, new_name)) < 0)
goto cleanup;
if ((error = rename_fetch_refspecs(&problem_refspecs, remote, new_name)) < 0)
goto cleanup;
out->count = problem_refspecs.length;
out->strings = (char **) problem_refspecs.contents;
cleanup:
if (error < 0)
git_vector_free(&problem_refspecs);
git_remote_free(remote);
return error;
}
int git_remote_name_is_valid(int *valid, const char *remote_name)
{
git_str buf = GIT_STR_INIT;
git_refspec refspec = {0};
int error;
GIT_ASSERT(valid);
*valid = 0;
if (!remote_name || *remote_name == '\0')
return 0;
if ((error = git_str_printf(&buf, "refs/heads/test:refs/remotes/%s/test", remote_name)) < 0)
goto done;
error = git_refspec__parse(&refspec, git_str_cstr(&buf), true);
if (!error)
*valid = 1;
else if (error == GIT_EINVALIDSPEC)
error = 0;
done:
git_str_dispose(&buf);
git_refspec__dispose(&refspec);
return error;
}
git_refspec *git_remote__matching_refspec(git_remote *remote, const char *refname)
{
git_refspec *spec;
size_t i;
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if (git_refspec_src_matches(spec, refname))
return spec;
}
return NULL;
}
git_refspec *git_remote__matching_dst_refspec(git_remote *remote, const char *refname)
{
git_refspec *spec;
size_t i;
git_vector_foreach(&remote->active_refspecs, i, spec) {
if (spec->push)
continue;
if (git_refspec_dst_matches(spec, refname))
return spec;
}
return NULL;
}
int git_remote_add_fetch(git_repository *repo, const char *remote, const char *refspec)
{
return write_add_refspec(repo, remote, refspec, true);
}
int git_remote_add_push(git_repository *repo, const char *remote, const char *refspec)
{
return write_add_refspec(repo, remote, refspec, false);
}
static int copy_refspecs(git_strarray *array, const git_remote *remote, unsigned int push)
{
size_t i;
git_vector refspecs;
git_refspec *spec;
char *dup;
if (git_vector_init(&refspecs, remote->refspecs.length, NULL) < 0)
return -1;
git_vector_foreach(&remote->refspecs, i, spec) {
if (spec->push != push)
continue;
if ((dup = git__strdup(spec->string)) == NULL)
goto on_error;
if (git_vector_insert(&refspecs, dup) < 0) {
git__free(dup);
goto on_error;
}
}
array->strings = (char **)refspecs.contents;
array->count = refspecs.length;
return 0;
on_error:
git_vector_free_deep(&refspecs);
return -1;
}
int git_remote_get_fetch_refspecs(git_strarray *array, const git_remote *remote)
{
return copy_refspecs(array, remote, false);
}
int git_remote_get_push_refspecs(git_strarray *array, const git_remote *remote)
{
return copy_refspecs(array, remote, true);
}
size_t git_remote_refspec_count(const git_remote *remote)
{
return remote->refspecs.length;
}
const git_refspec *git_remote_get_refspec(const git_remote *remote, size_t n)
{
return git_vector_get(&remote->refspecs, n);
}
int git_remote_init_callbacks(git_remote_callbacks *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_remote_callbacks, GIT_REMOTE_CALLBACKS_INIT);
return 0;
}
/* asserts a branch.<foo>.remote format */
static const char *name_offset(size_t *len_out, const char *name)
{
size_t prefix_len;
const char *dot;
prefix_len = strlen("remote.");
dot = strchr(name + prefix_len, '.');
GIT_ASSERT_ARG_WITH_RETVAL(dot, NULL);
*len_out = dot - name - prefix_len;
return name + prefix_len;
}
static int remove_branch_config_related_entries(
git_repository *repo,
const char *remote_name)
{
int error;
git_config *config;
git_config_entry *entry;
git_config_iterator *iter;
git_str buf = GIT_STR_INIT;
if ((error = git_repository_config__weakptr(&config, repo)) < 0)
return error;
if ((error = git_config_iterator_glob_new(&iter, config, "branch\\..+\\.remote")) < 0)
return error;
/* find any branches with us as upstream and remove that config */
while ((error = git_config_next(&entry, iter)) == 0) {
const char *branch;
size_t branch_len;
if (strcmp(remote_name, entry->value))
continue;
if ((branch = name_offset(&branch_len, entry->name)) == NULL) {
error = -1;
break;
}
git_str_clear(&buf);
if ((error = git_str_printf(&buf, "branch.%.*s.merge", (int)branch_len, branch)) < 0)
break;
if ((error = git_config_delete_entry(config, git_str_cstr(&buf))) < 0) {
if (error != GIT_ENOTFOUND)
break;
git_error_clear();
}
git_str_clear(&buf);
if ((error = git_str_printf(&buf, "branch.%.*s.remote", (int)branch_len, branch)) < 0)
break;
if ((error = git_config_delete_entry(config, git_str_cstr(&buf))) < 0) {
if (error != GIT_ENOTFOUND)
break;
git_error_clear();
}
}
if (error == GIT_ITEROVER)
error = 0;
git_str_dispose(&buf);
git_config_iterator_free(iter);
return error;
}
static int remove_refs(git_repository *repo, const git_refspec *spec)
{
git_reference_iterator *iter = NULL;
git_vector refs;
const char *name;
char *dup;
int error;
size_t i;
if ((error = git_vector_init(&refs, 8, NULL)) < 0)
return error;
if ((error = git_reference_iterator_new(&iter, repo)) < 0)
goto cleanup;
while ((error = git_reference_next_name(&name, iter)) == 0) {
if (!git_refspec_dst_matches(spec, name))
continue;
dup = git__strdup(name);
if (!dup) {
error = -1;
goto cleanup;
}
if ((error = git_vector_insert(&refs, dup)) < 0)
goto cleanup;
}
if (error == GIT_ITEROVER)
error = 0;
if (error < 0)
goto cleanup;
git_vector_foreach(&refs, i, name) {
if ((error = git_reference_remove(repo, name)) < 0)
break;
}
cleanup:
git_reference_iterator_free(iter);
git_vector_foreach(&refs, i, dup) {
git__free(dup);
}
git_vector_free(&refs);
return error;
}
static int remove_remote_tracking(git_repository *repo, const char *remote_name)
{
git_remote *remote;
int error;
size_t i, count;
/* we want to use what's on the config, regardless of changes to the instance in memory */
if ((error = git_remote_lookup(&remote, repo, remote_name)) < 0)
return error;
count = git_remote_refspec_count(remote);
for (i = 0; i < count; i++) {
const git_refspec *refspec = git_remote_get_refspec(remote, i);
/* shouldn't ever actually happen */
if (refspec == NULL)
continue;
if ((error = remove_refs(repo, refspec)) < 0)
break;
}
git_remote_free(remote);
return error;
}
int git_remote_delete(git_repository *repo, const char *name)
{
int error;
GIT_ASSERT_ARG(repo);
GIT_ASSERT_ARG(name);
if ((error = remove_branch_config_related_entries(repo, name)) < 0 ||
(error = remove_remote_tracking(repo, name)) < 0 ||
(error = rename_remote_config_section(repo, name, NULL)) < 0)
return error;
return 0;
}
int git_remote_default_branch(git_buf *out, git_remote *remote)
{
GIT_BUF_WRAP_PRIVATE(out, git_remote__default_branch, remote);
}
int git_remote__default_branch(git_str *out, git_remote *remote)
{
const git_remote_head **heads;
const git_remote_head *guess = NULL;
const git_oid *head_id;
size_t heads_len, i;
git_str local_default = GIT_STR_INIT;
int error;
GIT_ASSERT_ARG(out);
if ((error = git_remote_ls(&heads, &heads_len, remote)) < 0)
goto done;
if (heads_len == 0 || strcmp(heads[0]->name, GIT_HEAD_FILE)) {
error = GIT_ENOTFOUND;
goto done;
}
/* the first one must be HEAD so if that has the symref info, we're done */
if (heads[0]->symref_target) {
error = git_str_puts(out, heads[0]->symref_target);
goto done;
}
/*
* If there's no symref information, we have to look over them
* and guess. We return the first match unless the default
* branch is a candidate. Then we return the default branch.
*/
if ((error = git_repository_initialbranch(&local_default, remote->repo)) < 0)
goto done;
head_id = &heads[0]->oid;
for (i = 1; i < heads_len; i++) {
if (git_oid_cmp(head_id, &heads[i]->oid))
continue;
if (git__prefixcmp(heads[i]->name, GIT_REFS_HEADS_DIR))
continue;
if (!guess) {
guess = heads[i];
continue;
}
if (!git__strcmp(local_default.ptr, heads[i]->name)) {
guess = heads[i];
break;
}
}
if (!guess) {
error = GIT_ENOTFOUND;
goto done;
}
error = git_str_puts(out, guess->name);
done:
git_str_dispose(&local_default);
return error;
}
GIT_INLINE(int) connect_opts_from_push_opts(
git_remote_connect_options *out,
git_remote *remote,
const git_push_options *push_opts)
{
git_remote_connect_options tmp = GIT_REMOTE_CONNECT_OPTIONS_INIT;
copy_opts(&tmp, push_opts);
return git_remote_connect_options_normalize(out, remote->repo, &tmp);
}
int git_remote_upload(
git_remote *remote,
const git_strarray *refspecs,
const git_push_options *opts)
{
git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
git_push *push;
git_refspec *spec;
size_t i;
int error;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if ((error = connect_opts_from_push_opts(&connect_opts, remote, opts)) < 0)
goto cleanup;
if ((error = connect_or_reset_options(remote, GIT_DIRECTION_PUSH, &connect_opts)) < 0)
goto cleanup;
free_refspecs(&remote->active_refspecs);
if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
goto cleanup;
if (remote->push) {
git_push_free(remote->push);
remote->push = NULL;
}
if ((error = git_push_new(&remote->push, remote, opts)) < 0)
goto cleanup;
push = remote->push;
if (refspecs && refspecs->count > 0) {
for (i = 0; i < refspecs->count; i++) {
if ((error = git_push_add_refspec(push, refspecs->strings[i])) < 0)
goto cleanup;
}
} else {
git_vector_foreach(&remote->refspecs, i, spec) {
if (!spec->push)
continue;
if ((error = git_push_add_refspec(push, spec->string)) < 0)
goto cleanup;
}
}
if ((error = git_push_finish(push)) < 0)
goto cleanup;
if (connect_opts.callbacks.push_update_reference &&
(error = git_push_status_foreach(push, connect_opts.callbacks.push_update_reference, connect_opts.callbacks.payload)) < 0)
goto cleanup;
cleanup:
git_remote_connect_options_dispose(&connect_opts);
return error;
}
int git_remote_push(
git_remote *remote,
const git_strarray *refspecs,
const git_push_options *opts)
{
git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
int error;
GIT_ASSERT_ARG(remote);
if (!remote->repo) {
git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
return -1;
}
if (connect_opts_from_push_opts(&connect_opts, remote, opts) < 0)
return -1;
if ((error = git_remote_upload(remote, refspecs, opts)) < 0)
goto done;
error = git_remote_update_tips(remote, &connect_opts.callbacks, 0, 0, NULL);
done:
git_remote_disconnect(remote);
git_remote_connect_options_dispose(&connect_opts);
return error;
}
#define PREFIX "url"
#define SUFFIX_FETCH "insteadof"
#define SUFFIX_PUSH "pushinsteadof"
static int apply_insteadof(char **out, git_config *config, const char *url, int direction, bool use_default_if_empty)
{
size_t match_length, prefix_length, suffix_length;
char *replacement = NULL;
const char *regexp;
git_str result = GIT_STR_INIT;
git_config_entry *entry;
git_config_iterator *iter;
GIT_ASSERT_ARG(out);
GIT_ASSERT_ARG(config);
GIT_ASSERT_ARG(url);
GIT_ASSERT_ARG(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH);
/* Add 1 to prefix/suffix length due to the additional escaped dot */
prefix_length = strlen(PREFIX) + 1;
if (direction == GIT_DIRECTION_FETCH) {
regexp = PREFIX "\\..*\\." SUFFIX_FETCH;
suffix_length = strlen(SUFFIX_FETCH) + 1;
} else {
regexp = PREFIX "\\..*\\." SUFFIX_PUSH;
suffix_length = strlen(SUFFIX_PUSH) + 1;
}
if (git_config_iterator_glob_new(&iter, config, regexp) < 0)
return -1;
match_length = 0;
while (git_config_next(&entry, iter) == 0) {
size_t n, replacement_length;
/* Check if entry value is a prefix of URL */
if (git__prefixcmp(url, entry->value))
continue;
/* Check if entry value is longer than previous
* prefixes */
if ((n = strlen(entry->value)) <= match_length)
continue;
git__free(replacement);
match_length = n;
/* Cut off prefix and suffix of the value */
replacement_length =
strlen(entry->name) - (prefix_length + suffix_length);
replacement = git__strndup(entry->name + prefix_length,
replacement_length);
}
git_config_iterator_free(iter);
if (match_length == 0 && use_default_if_empty) {
*out = git__strdup(url);
return *out ? 0 : -1;
} else if (match_length == 0) {
*out = NULL;
return 0;
}
git_str_printf(&result, "%s%s", replacement, url + match_length);
git__free(replacement);
*out = git_str_detach(&result);
return 0;
}
/* Deprecated functions */
#ifndef GIT_DEPRECATE_HARD
int git_remote_is_valid_name(const char *remote_name)
{
int valid = 0;
git_remote_name_is_valid(&valid, remote_name);
return valid;
}
#endif
| libgit2-main | src/libgit2/remote.c |
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/types.h"
#include "git2/remote.h"
#include "git2/net.h"
#include "git2/transport.h"
#include "git2/sys/transport.h"
#include "fs_path.h"
typedef struct transport_definition {
char *prefix;
git_transport_cb fn;
void *param;
} transport_definition;
static git_smart_subtransport_definition http_subtransport_definition = { git_smart_subtransport_http, 1, NULL };
static git_smart_subtransport_definition git_subtransport_definition = { git_smart_subtransport_git, 0, NULL };
#ifdef GIT_SSH
static git_smart_subtransport_definition ssh_subtransport_definition = { git_smart_subtransport_ssh, 0, NULL };
#endif
static transport_definition local_transport_definition = { "file://", git_transport_local, NULL };
static transport_definition transports[] = {
{ "git://", git_transport_smart, &git_subtransport_definition },
{ "http://", git_transport_smart, &http_subtransport_definition },
{ "https://", git_transport_smart, &http_subtransport_definition },
{ "file://", git_transport_local, NULL },
#ifdef GIT_SSH
{ "ssh://", git_transport_smart, &ssh_subtransport_definition },
{ "ssh+git://", git_transport_smart, &ssh_subtransport_definition },
{ "git+ssh://", git_transport_smart, &ssh_subtransport_definition },
#endif
{ NULL, 0, 0 }
};
static git_vector custom_transports = GIT_VECTOR_INIT;
#define GIT_TRANSPORT_COUNT (sizeof(transports)/sizeof(transports[0])) - 1
static transport_definition * transport_find_by_url(const char *url)
{
size_t i = 0;
transport_definition *d;
/* Find a user transport who wants to deal with this URI */
git_vector_foreach(&custom_transports, i, d) {
if (strncasecmp(url, d->prefix, strlen(d->prefix)) == 0) {
return d;
}
}
/* Find a system transport for this URI */
for (i = 0; i < GIT_TRANSPORT_COUNT; ++i) {
d = &transports[i];
if (strncasecmp(url, d->prefix, strlen(d->prefix)) == 0) {
return d;
}
}
return NULL;
}
static int transport_find_fn(
git_transport_cb *out,
const char *url,
void **param)
{
transport_definition *definition = transport_find_by_url(url);
#ifdef GIT_WIN32
/* On Windows, it might not be possible to discern between absolute local
* and ssh paths - first check if this is a valid local path that points
* to a directory and if so assume local path, else assume SSH */
/* Check to see if the path points to a file on the local file system */
if (!definition && git_fs_path_exists(url) && git_fs_path_isdir(url))
definition = &local_transport_definition;
#endif
/* For other systems, perform the SSH check first, to avoid going to the
* filesystem if it is not necessary */
/* It could be a SSH remote path. Check to see if there's a : */
if (!definition && strrchr(url, ':')) {
/* re-search transports again with ssh:// as url
* so that we can find a third party ssh transport */
definition = transport_find_by_url("ssh://");
}
#ifndef GIT_WIN32
/* Check to see if the path points to a file on the local file system */
if (!definition && git_fs_path_exists(url) && git_fs_path_isdir(url))
definition = &local_transport_definition;
#endif
if (!definition)
return GIT_ENOTFOUND;
*out = definition->fn;
*param = definition->param;
return 0;
}
/**************
* Public API *
**************/
int git_transport_new(git_transport **out, git_remote *owner, const char *url)
{
git_transport_cb fn;
git_transport *transport;
void *param;
int error;
if ((error = transport_find_fn(&fn, url, ¶m)) == GIT_ENOTFOUND) {
git_error_set(GIT_ERROR_NET, "unsupported URL protocol");
return -1;
} else if (error < 0)
return error;
if ((error = fn(&transport, owner, param)) < 0)
return error;
GIT_ERROR_CHECK_VERSION(transport, GIT_TRANSPORT_VERSION, "git_transport");
*out = transport;
return 0;
}
int git_transport_register(
const char *scheme,
git_transport_cb cb,
void *param)
{
git_str prefix = GIT_STR_INIT;
transport_definition *d, *definition = NULL;
size_t i;
int error = 0;
GIT_ASSERT_ARG(scheme);
GIT_ASSERT_ARG(cb);
if ((error = git_str_printf(&prefix, "%s://", scheme)) < 0)
goto on_error;
git_vector_foreach(&custom_transports, i, d) {
if (strcasecmp(d->prefix, prefix.ptr) == 0) {
error = GIT_EEXISTS;
goto on_error;
}
}
definition = git__calloc(1, sizeof(transport_definition));
GIT_ERROR_CHECK_ALLOC(definition);
definition->prefix = git_str_detach(&prefix);
definition->fn = cb;
definition->param = param;
if (git_vector_insert(&custom_transports, definition) < 0)
goto on_error;
return 0;
on_error:
git_str_dispose(&prefix);
git__free(definition);
return error;
}
int git_transport_unregister(const char *scheme)
{
git_str prefix = GIT_STR_INIT;
transport_definition *d;
size_t i;
int error = 0;
GIT_ASSERT_ARG(scheme);
if ((error = git_str_printf(&prefix, "%s://", scheme)) < 0)
goto done;
git_vector_foreach(&custom_transports, i, d) {
if (strcasecmp(d->prefix, prefix.ptr) == 0) {
if ((error = git_vector_remove(&custom_transports, i)) < 0)
goto done;
git__free(d->prefix);
git__free(d);
if (!custom_transports.length)
git_vector_free(&custom_transports);
error = 0;
goto done;
}
}
error = GIT_ENOTFOUND;
done:
git_str_dispose(&prefix);
return error;
}
int git_transport_init(git_transport *opts, unsigned int version)
{
GIT_INIT_STRUCTURE_FROM_TEMPLATE(
opts, version, git_transport, GIT_TRANSPORT_INIT);
return 0;
}
| libgit2-main | src/libgit2/transport.c |
Subsets and Splits